Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
# Vyay — Environment Config Template
# Day 4: Reports ko save aur share karne ke liye Supabase setup zaroori hai.
# Copy this file to .env and fill in real values before running locally.

# Supabase
VITE_SUPABASE_URL=your_supabase_project_url
VITE_SUPABASE_ANON_KEY=your_supabase_anon_public_key

# Day 5: AI-based "Executive Summary" ke liye Gemini API key chahiye hogi.
# Gemini AI
VITE_GEMINI_API_KEY=your_google_gemini_api_key

# Transactional Emails
# Transactional Email (Resend)
VITE_RESEND_API_KEY=your_resend_api_key
# Optional sender email. Sandbox mode requires 'onboarding@resend.dev'.
VITE_FROM_EMAIL=onboarding@resend.dev

# Production URL — used in serverless functions to generate email re-audit links.
# Set to your deployed domain. Must NOT have a trailing slash.
VITE_APP_URL=https://your-app.vercel.app

# Optional Analytics
# VITE_GA_ID=your_google_analytics_id
# GitHub Actions secret (set in repo Settings → Secrets → Actions):
# VYAY_PRODUCTION_URL = https://your-app.vercel.app
# Used by .github/workflows/scheduled-detect-changes.yml
25 changes: 25 additions & 0 deletions .github/workflows/scheduled-detect-changes.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: Scheduled Change Detection

on:
schedule:
- cron: '0 0 * * *' # Daily at midnight UTC
workflow_dispatch: # Allows manual trigger from the Actions tab

jobs:
detect-changes:
runs-on: ubuntu-latest
steps:
- name: Trigger Change Detection API
env:
VYAY_PRODUCTION_URL: ${{ secrets.VYAY_PRODUCTION_URL }}
run: |
if [ -z "$VYAY_PRODUCTION_URL" ]; then
echo "Error: VYAY_PRODUCTION_URL secret is not configured."
exit 1
fi

echo "Triggering change detection at $VYAY_PRODUCTION_URL/api/detect-changes..."
curl -f -X POST "$VYAY_PRODUCTION_URL/api/detect-changes" \
-H "Content-Type: application/json" \
-d '{"dryRun": false}'

153 changes: 100 additions & 53 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,75 +2,122 @@

# Vyay System Architecture

This document delineates the technical architecture, data flow specifications, and scaling strategies for the Vyay platform.
This document details the system design, data models, processing flows, and design decisions behind Vyay's persistent re-audit and change detection engine.

## System Infrastructure Overview
---

## 1. System Infrastructure & Flow Overview

```mermaid
graph TD
User((User)) -->|Data Ingestion| WebApp[React/Vite Frontend]
WebApp -->|Zustand State| FormLogic[Multi-Stage Audit Interface]
FormLogic -->|Execution| AuditEngine[Deterministic Rule Engine]
AuditEngine -->|Evaluation| Results[Audit Result Set]
Results -->|Persistence| Supabase[(Supabase Database)]
Results -->|Presentation| ResultPage[Reporting Interface]

AuditEngine -.->|Analytical Processing| Gemini[Gemini 2.5 Flash API]
ResultPage -->|Distribution| PublicLink[Public Report URL]
ResultPage -->|Notification| Resend[Resend Service]
subgraph Client-Side (React/Vite)
User[Founder / VP Eng] -->|1. Inputs Stack| AuditForm[Multi-Stage Form]
AuditForm -->|2. Runs Rules| AuditEngine[Deterministic Rule Engine]
AuditEngine -->|3. Serializes| Snapshot[Pricing Snapshot]
ResultUI[Result & Diff Views]
end

subgraph Serverless Edge Layer (Vercel)
API_Changes[POST /api/detect-changes] -->|Triggers| ReauditService[reauditService.ts]
API_OG[GET /api/og] -->|Dynamic Previews| OG_Image
end

subgraph Data & Messaging (Supabase & Resend)
Supabase[(Supabase DB)]
Resend[Resend SMTP]
end

AuditEngine -->|4. Persists Snapshot + Audit| Supabase
ReauditService -->|5. Fetches All Audits| Supabase
ReauditService -->|6. Recomputes & Checks Staleness| DiffEngine[diffEngine.ts]
ReauditService -->|7. Groups by Email| Batching[notificationBatchService.ts]
ReauditService -->|8. Sends Batch Emails| Resend
ResultUI -->|9. Pulls Diff Model| Supabase
```

## Data Flow Architecture
1. **Ingestion Phase**: User inputs tool usage data (subscriptions, seats, tiers) via a multi-stage React form. Form state is persisted locally using Zustand to prevent data loss on browser refresh.
2. **Analysis Phase**: The **Deterministic Audit Engine** processes inputs against a validated pricing dataset (`src/data/`). It executes a series of logic hooks to identify service redundancies and tier inefficiencies.
3. **AI Enhancement**: A structured summary of the audit input is transmitted to the **Gemini 2.5 Flash API** to generate a human-centric narrative of the findings.
4. **Persistence Phase**: The resulting audit object is stored in **Supabase**, generating a unique, non-guessable identifier for the public report.
5. **Distribution Phase**: The reporting interface resolves the report ID to display a high-fidelity, shareable dashboard.
---

## 2. Pricing Snapshot Lifecycle & Immutability

To guarantee historical report reproducibility, Vyay implements a versioned **Pricing Snapshot** design:

## Technology Stack Justification
1. **Serialization**: When an audit is compiled, the current catalog (`src/data/pricing.ts`) is serialized into an immutable JSON representation.
2. **Hash Binding**: A cryptographic SHA-256 hash is computed over the snapshot schema to uniquely identify the pricing version.
3. **Database Capture**:
* The snapshot is verified against a strict Zod schema (`PricingSnapshotSchema`).
* The snapshot is inserted into the `pricing_snapshots` table (deduplicated by its hash).
* The audit record is saved in `audits`, holding a foreign key reference (`pricing_snapshot_id`) and a complete embedded copy (`pricing_snapshot_json`).
4. **Time-Travel Guarantee**: When the original audit report is reloaded at `/result/:id`, the system loads `pricing_snapshot_json` to reconstruct the original pricing context. Subsequent code deployments modifying the live catalog do **not** alter historical figures.

| Component | Technology | Rationale |
| :--- | :--- | :--- |
| **Frontend Framework** | **React 18** | Industry standard for building reactive, component-based user interfaces with extensive ecosystem support for utility tools. |
| **Build Tooling** | **Vite** | Provides near-instantaneous Hot Module Replacement (HMR) and optimized production builds, critical for maintaining high development velocity. |
| **State Management** | **Zustand** | Offers a minimalist, high-performance state store without the complexity of Redux, ideal for managing the transient state of an audit form. |
| **Validation** | **Zod** | Ensures type-safe data handling from form input to database persistence, reducing runtime errors. |
| **Backend/DB** | **Supabase** | Provides a robust, scalable PostgreSQL infrastructure with built-in row-level security and rapid API generation, minimizing DevOps overhead. |
| **AI Integration** | **Gemini 2.5 Flash** | Selected for its exceptional performance-to-cost ratio and high speed in generating analytical summaries. |
---

## Scaling Strategy: 10,000 Audits Per Day
## 3. Recomputation Flow & Staleness Classification

To support a throughput of 10,000 audits per day (approximately 7 audits per minute with peak bursts), the following architectural optimizations are implemented:
```mermaid
sequenceDiagram
participant Cron as GitHub Actions / API
participant RS as reauditService.ts
participant DB as Supabase
participant DE as diffEngine.ts

Cron->>RS: POST /api/detect-changes
RS->>DB: Fetch all audits with pricing snapshots
DB-->>RS: Return stored audits
loop For each stored audit
RS->>DE: recomputeAuditFromSnapshot(storedAudit)
Note over DE: Runs stored inputs through current pricing
DE-->>RS: Return new AuditResult
RS->>DE: determineStaleness(storedAudit, newResult)
Note over DE: Check absolute ($5) & relative (5%) savings delta
DE-->>RS: Return StalenessResult (isStale, reason)
end
```

1. **Edge-Based Execution**: The core deterministic audit logic executes entirely on the client side. This offloads the primary computational burden from the server, allowing the infrastructure to scale linearly with user traffic.
2. **Database Concurrency**: Supabase (PostgreSQL) is architectured to handle thousands of concurrent connections. For 10k audits/day, the database load remains minimal, primarily involving simple `INSERT` and `SELECT` operations.
3. **API Rate Management**: AI and Email services (Gemini and Resend) are managed via a queue-based or debounce strategy in the frontend to prevent exceeding rate limits during high-traffic bursts.
4. **Static Optimization**: The frontend is deployed via Vercel's Global Edge Network, ensuring low-latency delivery of the application shell regardless of the user's geographic location.
5. **Caching Layer**: Public audit reports are cached at the edge using Vercel's CDN headers, ensuring that repeat views of the same report do not strain the database.
---

## Social Share & Asset Generation
## 4. Grouping & Notification Flow

CTOs and founders often generate multiple audits when exploring stack alternatives. To prevent inbox spam, Vyay aggregates stale notifications:

```mermaid
graph LR
subgraph Diffs Detected
D1[Audit A: Stale]
D2[Audit B: Stale]
D3[Audit C: Stale]
end

subgraph Batching Layer
BatchService[notificationBatchService.ts]
end

subgraph Recipient Inbox
CTO_Email[CTO @ acme.co]
end

D1 --> BatchService
D2 --> BatchService
D3 --> BatchService
BatchService -->|Group by userEmail| Batch[1 Consolidated Email]
Batch --> CTO_Email
```

1. **Deterministic OG Previews**: The platform utilizes a Vercel Edge Function (`/api/og`) to dynamically generate high-resolution Open Graph images. These images incorporate real-time audit metrics (Savings, Recommendations, Grade) to maximize click-through rates on X and LinkedIn.
2. **Executive PDF Export**: High-fidelity report generation is handled via `@react-pdf/renderer` on the client side. This ensures that sensitive financial data never leaves the browser environment for PDF processing.
- **Performance**: Heavy font assets (Inter, Playfair) are pre-loaded to minimize generation latency.
- **Security**: Deterministic values are passed directly from the audit state to the document template.
1. **Aggregation**: `groupAffectedAuditsByUser` gathers all stale audits.
2. **Deduplication**: If a user has three stale audits, they receive **exactly one** email.
3. **Consolidated Metrics**: The email lists each affected audit reference, summarizes the collective monthly savings delta, and links directly to custom side-by-side comparison dashboards (`/reaudit-diff/:id`).

## Widget Architecture: Embeddable Intelligence
---

The Vyay widget is a zero-dependency JavaScript payload (`/public/widget.js`) designed for cross-origin embedding.
- **Isolation**: Uses a custom namespace and scoped CSS to prevent collision with the host site's styling.
- **Dynamic Configuration**: Supports `data-theme` and `data-compact` attributes for aesthetic alignment with host blogs/platforms.
- **Lite Input Model**: Collects minimal engineering metrics (e.g., headcount) to generate a "Savings Preview" before deep-linking the user into the full audit experience.
## 5. Architectural Trade-offs & Decisions

## Referral & Growth System
### Why Live Scraping was Avoided
Scraping vendor pricing pages (e.g. OpenAI or Anthropic pricing tables) is highly fragile. Minor HTML shifts instantly break code. Standardizing vendor pricing into statically typed files (`src/data/pricing.ts`) ensures compile-time safety, 100% computational uptime, and bulletproof calculations.

A lightweight referral engine is integrated into the core service layer:
- **Generation**: Unique referral codes are generated for strategic partners and early adopters.
- **Tracking**: Inbound traffic via referral URLs is tracked to measure channel efficiency and reward high-impact advocates.
- **Atomic Operations**: Click and conversion counters are managed via Supabase RPC functions to ensure data consistency during concurrent access.
### Why Pricing Snapshots are Immutable
Vendor prices change unpredictably. If the pricing catalog was global and mutable, reloading an old audit report from 6 months ago would dynamically recalculate it using today's prices, distorting the original recommendations the user signed off on. Storing immutable snapshots keeps the historical truth locked in stone.

## Security & Abuse Protection
### Why Deterministic Recomputation is Preferred over LLMs
Using LLMs to parse and compute pricing models introduces non-determinism, hallucinations, and latency. A math engine must be 100% reproducible and defensible in front of a CFO. The recomputation logic is pure typescript rules. LLMs are constrained strictly to narrative summaries.

1. **Honeypot Integration**: Lead capture forms implement a silent "Honeypot" field to filter out automated bot submissions without disrupting the legitimate user experience.
2. **Rate Limiting**: API interactions with Gemini and Resend are governed by client-side debouncing and server-side rate limits provided by Supabase and Vercel.
3. **Data Stripping**: Public audit results undergo a "Sanitization Pass" before hydration to ensure that PII (Personally Identifiable Information) such as email addresses or specific company names are never exposed on shareable links.
### Why Notifications are Grouped by User
Sending an email alert for every single stale audit results in immediate spam classification. Grouping by user ensures a single high-signal message is delivered with all changed options, maximizing engagement.
2 changes: 1 addition & 1 deletion DEVLOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# 🛰️ Project Development Log Vyay
# 🛰️ Project Development Log - Vyay
> *Engineering the future of AI spend management.*

---
Expand Down
2 changes: 1 addition & 1 deletion LAUNCH_CONTENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ Recapture your growth capital:
**Headline**: Why we built a financial tool that doesn't 'hallucinate' savings.

(Summary):
In the rush to add AI to everything, the industry lost sight of accuracy. We argue that for infrastructure spend, founders don't want a "chatbot conversation"they want a calculated verdict. Vyay represents our philosophy of "AI for Narrative, Logic for Numbers."
In the rush to add AI to everything, the industry lost sight of accuracy. We argue that for infrastructure spend, founders don't want a "chatbot conversation" - they want a calculated verdict. Vyay represents our philosophy of "AI for Narrative, Logic for Numbers."

---
"Built for founders, by engineers."
24 changes: 12 additions & 12 deletions PRODUCT_SPEC.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Vyay Full MVP + Bonus Implementation Specification
# Vyay - Full MVP + Bonus Implementation Specification

This document encapsulates the original vision, implementation requirements, and product principles that define **Vyay**. It serves as the definitive guide for maintaining the platform's strategic positioning and technical integrity.

Expand All @@ -19,37 +19,37 @@ Vyay audits AI subscription and API spend for small engineering teams and startu

## 2. Required MVP Features

### FEATURE 1 Spend Input Form
### FEATURE 1 - Spend Input Form
A highly polished, frictionless audit intake flow supporting:
- **Supported Tools**: Cursor, GitHub Copilot, Claude, ChatGPT, Anthropic API, OpenAI API, Gemini, Windsurf.
- **Input Requirements**: Selected plan, monthly spend, seat count.
- **Global Context**: Team size, primary use case (Coding, Writing, Data, Research, Mixed).
- **UX Details**: Dynamic tool cards, localStorage persistence, pricing hints, and validation warnings.

### FEATURE 2 Deterministic Audit Engine
### FEATURE 2 - Deterministic Audit Engine
A rule-based reasoning system that is 100% explainable and mathematically sound.
- **Logic**: Oversized plans, duplicate tooling, overlapping subscriptions, inefficient API spend, enterprise mismatch, and coding assistant redundancy.
- **Integrity**: If savings are low, the engine is honest about the stack's efficiency.
- **Structure**: Each recommendation includes current spend, action, estimated savings, confidence level, and reasoning.

### FEATURE 3 Audit Results Page
### FEATURE 3 - Audit Results Page
The primary visual anchor of the product, designed to be screenshot-worthy and shareable.
- **Sections**: Savings Hero (Monthly/Annual), Per-Tool Recommendations, "Already Optimized" handling, Lead Capture, and Share Section.
- **CTA Logic**: High savings (>$500/mo) trigger a Credex consultation CTA.

### FEATURE 4 AI-Generated Summary
### FEATURE 4 - AI-Generated Summary
Using **Gemini 2.5 Flash** for executive-style synthesis.
- **Role**: Translation of deterministic data into a human-readable strategic narrative.
- **Tone**: Calm, analytical, and professional.
- **Fallback**: A robust deterministic summary template if the AI service is unavailable.

### FEATURE 5 Lead Capture & Storage
### FEATURE 5 - Lead Capture & Storage
A non-gated conversion flow utilizing **Supabase** for persistence.
- **Persistence**: Audits and leads are stored securely.
- **Communication**: Integrated **Resend** transactional emails for report delivery.
- **Protection**: Honeypot-based abuse prevention.

### FEATURE 6 Shareable Result URLs
### FEATURE 6 - Shareable Result URLs
Publicly accessible results at `/result/:publicId`.
- **Privacy**: No exposure of PII (email, company name) in public reports.
- **Social**: Fully optimized Open Graph (OG) metadata and Twitter cards.
Expand All @@ -58,19 +58,19 @@ Publicly accessible results at `/result/:publicId`.

## 3. Bonus Features Implemented

### BONUS 1 PDF Export
### BONUS 1 - PDF Export
Downloadable, clean-formatted audit reports for institutional sharing.

### BONUS 2 Embeddable Widget
### BONUS 2 - Embeddable Widget
A lightweight `<script>` widget for third-party integration on blogs and startup sites.

### BONUS 3 Benchmark Mode
### BONUS 3 - Benchmark Mode
Contextual insights comparing user spend against peer-group averages (e.g., "28% above similar 5-15 person teams").

### BONUS 4 Referral Codes
### BONUS 4 - Referral Codes
A lightweight referral tracking system for community-driven growth.

### BONUS 5 Launch Content
### BONUS 5 - Launch Content
Pre-generated launch copy for Product Hunt, X/Twitter, and founder-focused blogs.

---
Expand Down
2 changes: 1 addition & 1 deletion PROMPTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ This document outlines the strategic use of AI in Vyay, specifically focusing on

At Vyay, we believe that financial audits must be verifiable and consistent.
- **Audit Logic**: 100% deterministic (TypeScript). If the same data is input twice, the same recommendations and savings calculations are returned.
- **AI Utility**: 0% decision making. AI is used exclusively for *narrative synthesis*taking raw data and turning it into a professional, human-readable executive brief.
- **AI Utility**: 0% decision making. AI is used exclusively for *narrative synthesis* - taking raw data and turning it into a professional, human-readable executive brief.

## Gemini 2.5 Flash System Prompt

Expand Down
Loading
Loading