# ARCHITECTURE.md — VYNDR v1.0

---

## Section 1: The Mission

VYNDR is a bet on advancement. Sports betting intelligence SaaS built to reverse the flow of a multi-trillion dollar industry.

Three tiers:
- **Free** — 5 scans
- **Analyst** — $19.99/mo ($14.99 founder price)
- **Desk** — $49.99/mo ($34.99 founder price)

The house has data scientists. We give everyone else the same firepower.

---

## Section 2: What Was Already Built (Phase 0)

11 features shipped. 237 tests passing.

### Phase 1 — Core Engine
- **Odds API integration** — live odds ingestion from The Odds API
- **NBA stats wrapper** — Python FastAPI microservice wrapping nba_api
- **Prop analysis engine** — 6-step grading pipeline (season avg, recent form, situational, line comparison, kill conditions, grade)
- **Database schema** — 9 tables with row-level security
- **Bet submission** — 3 methods (manual, scan-to-save, quick pick)

### Phase 2 — Intelligence Layer
- **Parlay scan** — correlation detection across 5 types, monetization hooks
- **Line movement + cascade detection** — baseline capture, movement alerts, scratch-and-regrade

### Phase 3 — User-Facing Product
- **Landing page** — Next.js with Tailwind, cyan design system
- **Scan UI** — mobile-first prop scanning interface
- **Bet tracker** — portfolio-style bet management
- **Stripe integration** — checkout, webhooks, portal, founder code system

### Stack
- **Backend:** Node.js / Express
- **Database:** Supabase (PostgreSQL) with RLS on all tables
- **Frontend:** Next.js, Tailwind CSS, cyan design system
- **Caching:** Redis — 15min odds, 24hr season averages, 1hr recent games
- **Payments:** Stripe
- **Data:** The Odds API ($30/mo), nba_api (free, Python wrapper)

---

## Section 3: Phase 1 Additions (Current Session)

12 additions built in a single session:

| # | Addition | What It Does |
|---|----------|-------------|
| 1 | Founder's Note | Immutable constant, tested for integrity |
| 2 | Mission Header | X-VYNDR-Mission on all API responses |
| 3 | Stats Endpoints | /api/stats/parlays-graded, /api/stats/public, /api/props/live |
| 4 | Dynamic Role Profile System | 8 functional roles, Shannon entropy variance, conditional profiles, lineup profiles |
| 5 | Player Selector | 4-step mobile-first flow (placeholder — frontend handled by Cowork) |
| 6 | Parlay Probability | Per-leg probability, combined, phi coefficient correlation, juice-adjusted EV |
| 7 | MLB Prop Grading | 14 stat types, 10 kill conditions, 30 park coordinates, weather API |
| 8 | Intelligence Engine | Similarity, evolution/PELT, line discrepancy, alt line scanner, Bayesian, model trainer |
| 9 | Lineup Watch Speed | Role activation detection, 60-second alert window |
| 10 | Design System Update | Forest green variables, DemoScan result card, Hero tagline, live props strip |
| 11 | Accuracy Ledger + Marketplace | /ledger page and /marketplace page |
| 12 | Architecture Documentation | This file |

---

## Section 4: All Services and Data Flow

### Backend Services

#### Odds + Data Ingestion
- **oddsService.js** — fetches from Odds API, caches in Redis (15min TTL)
- **nbaStatsClient.js** — Python FastAPI wrapper for NBA season/game stats
- **mlbStatsClient.js** — MLB Stats API wrapper

#### Grading Pipeline
- **propAnalyzer.js** — 6-step grading pipeline (season avg, recent form, situational, line comparison, kill conditions, grade)
- **grader.js** — composite score to grade (A/B/C/D) with confidence
- **killConditions.js** — 6 NBA kill conditions
- **mlbGrader.js** — MLB-specific grading with adjusted thresholds
- **mlbKillConditions.js** — 10 MLB kill conditions + weather API integration

#### Parlay + Correlation
- **correlationEngine.js** — parlay correlation detection (5 correlation types)
- **parlayGrader.js** — parlay-level grading derived from leg grades
- **parlayScanService.js** — orchestrates full scan flow
- **correlationMath.js** — phi coefficient calculation, EV computation

#### Line Intelligence
- **lineMovementService.js** — baseline capture + movement detection
- **cascadeService.js** — scratch detection + regrade triggers
- **alertService.js** — cascade alert management
- **lineDiscrepancyDetector.js** — sharp vs square book gap detection
- **altLineScanner.js** — optimal alternate line finding

#### Role + Profile System
- **roleProfileEngine.js** — role distribution calculation, elevation detection
- **roleStabilityEngine.js** — stability scoring with decay

#### Advanced Intelligence
- **similarityEngine.js** — 10-factor game similarity matching
- **evolutionEngine.js** — Node wrapper for Python PELT microservice
- **bayesianEngine.js** — correct distribution shape per stat type
- **modelTrainer.js** — walk-forward validation, CLV tracking, drift detection

#### Payments
- **stripeService.js** — checkout sessions, webhooks, customer portal, founder codes

### Python Microservices

| Service | Framework | Port | Purpose |
|---------|-----------|------|---------|
| NBA stats wrapper | FastAPI | 8000 | nba_api Python wrapper |
| Evolution engine | Flask | 5001 | PELT changepoint detection via ruptures |

### Data Flow

```
Odds API
    |
    v
oddsService.js --> Redis Cache (15min TTL)
    |
    v
propAnalyzer.js
    |-- nbaStatsClient.js --> FastAPI (port 8000) --> nba_api
    |-- mlbStatsClient.js --> MLB Stats API
    |-- roleProfileEngine.js
    |-- similarityEngine.js
    |-- bayesianEngine.js
    |
    v
grader.js / mlbGrader.js
    |-- killConditions.js / mlbKillConditions.js
    |
    v
parlayScanService.js
    |-- correlationEngine.js
    |-- parlayGrader.js
    |-- correlationMath.js (phi, EV)
    |
    v
Supabase (PostgreSQL)
    |
    v
lineMovementService.js --> cascadeService.js --> alertService.js
```

---

## Section 5: Database Schema

### Original Tables (Migrations 001, 002)
- **users** — auth, tier, founder status
- **picks** — individual prop picks with grades
- **scan_sessions** — scan history per user
- **cascade_alerts** — line movement alert records
- **line_baselines** — captured opening lines
- **line_movements** — detected line changes
- Plus standard auth tables (managed by Supabase)

### New Tables (Migration 003)
- **player_role_profiles** — per-player role distribution snapshots
- **lineup_role_profiles** — team lineup composition profiles
- **player_role_activations** — role elevation/change events
- **model_predictions_extended** — predictions with confidence and methodology
- **prediction_registry** — pre-registered predictions (public read, service write)
- **joint_outcomes** — correlated outcome tracking for phi coefficient
- **discrepancy_reliability_scores** — sharp/square gap reliability history

All tables enforce row-level security (RLS). The prediction_registry table has public read access and service-role-only write access.

---

## Section 6: Phase 2 Pending

- **Model learning loop** — Feature 4.1 spec exists in specs/
- **Player selector UI completion** — Cowork handles the design implementation
- **Full parlay probability UI integration** — connect backend math to scan results
- **Real-time lineup watch CRON** — scheduled job for role activation monitoring
- **Evolution watch UI on ledger page** — visualize PELT changepoints
- **Pre-registered predictions system activation** — public ledger goes live
- **Physical ledger fulfillment** — printed accuracy reports for Desk tier
- **Education library content** — betting strategy guides

---

## Section 7: Known Gaps and Next Actions

### Active Blockers
- **BLOCKER-003:** WSL2 DNS cannot resolve *.supabase.co — migration 003 must be applied manually via Supabase dashboard or a machine with direct DNS

### Environment Dependencies
- Python evolution microservice requires ruptures + numpy installed
- Seed script requires NBA API network access to populate role profiles
- Stripe environment variables (STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET) must be set
- Vercel deployment pending for Next.js frontend

### Next Actions
1. Apply migration 003 manually (blocked by DNS)
2. Install Python dependencies for evolution microservice
3. Set Stripe env vars and test payment flow end-to-end
4. Deploy frontend to Vercel
5. Begin Feature 4.1 (model learning loop)
