Session 58: Phase 1 — Truth Infrastructure (2327 tests)

ledger_entries is live (migration 019 applied to prod, RLS + NULLS NOT
DISTINCT dedupe verified against the real database). Every grade now
persists, settles against the real result, and carries closing-line value.

- ledgerService: pipeline pre-grade upserts (public model record, user_id
  null, idempotent), closing capture on every snapshot (last write before
  game start = the close), settlement with SIGNED CLV (over = locked -
  closing; beat/faded/flat), 30d model aggregate with the hard n>=20 rule.
- Write paths: snapshotService -> ledger (priority path); Next /api/scan ->
  ledger for authenticated users only (anon never touches the public
  record). Refused reads write nothing and don't burn a scan.
- Honest refusal (work-order 1.5): no projection => insufficient_data,
  grade null, "INSUFFICIENT DATA - no read" UI. The web gradeAdapter no
  longer displays the line as the model projection (the audit's
  model==line / +0% edge degenerate); the card renders absent states.
  projectionFor is sport-aware (l5 -> l20 -> {stat}_per_90 -> xG).
- /ledger: MY READS | MODEL tabs; model header shows hit% + beat-close%
  only at n>=20, else RECORD BUILDING + live pending count. ModelRecord
  deferred-render strip on landing + player hero. CLV + outcome chips,
  revised_from_grade strikethrough (Phase 2.5 ready).
- SYNC (Task 5): thresholds vs SNAPSHOT_EXPECTED_INTERVAL (normal <1.5x,
  amber >=1.5x, STALE red >=3x) via /api/snapshot/summary.
- Phase 2.5 logged in specs/vyndr-roadmap.md (build after Phase 3).
- Data-semantics hardening: strict null-safe numeric parsing everywhere a
  market value is handled (Number(null)===0 would have fabricated lines).

Backend 2309 -> 2327 tests (201 suites), web build exit 0.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Kev
2026-07-10 21:34:26 -04:00
parent 2c79373a3b
commit d296e40cb6
29 changed files with 1578 additions and 223 deletions
+80 -1
View File
@@ -115,7 +115,21 @@ export async function POST(req: NextRequest) {
let scansRemaining: number | null = null;
if (user && sb) {
// Session 58 (work-order 1.5) — a refused read (no projection) writes
// NOTHING: no scan_history, no ledger row. No hollow rows anywhere.
const refused = data?.insufficient_data === true || !data?.grade;
if (user && sb && !refused) {
// Phase 1 — persist the read to the ledger (authenticated users only;
// anonymous scans are never written: a null user_id row would pollute
// the PUBLIC model record, which is pipeline-only). The line/book are
// the REAL book values the slate pre-filled; locked odds are enriched
// from the cached odds feed when the prop matches. Fire-and-forget —
// the scan response never waits on the ledger.
void writeLedgerEntry(sb, user.id, body, data);
}
if (user && sb && !refused) {
void sb.rpc('increment_parlay_leg_frequency', {
p_player: body.player,
p_stat: body.stat,
@@ -162,3 +176,68 @@ export async function POST(req: NextRequest) {
return jsonError(502, 'The engine hit a wall. Try that read again.');
}
}
/**
* Session 58 (Phase 1) — persist a completed user scan to ledger_entries.
*
* DATA SEMANTICS: `line`/`book` are the real book values the user scanned
* (the slate pre-fills them from the odds feed). `locked_odds` attaches ONLY
* when the cache-only snapshot carries the SAME line for this prop — odds
* from a different line would be a fabrication, so absent beats wrong.
* Upsert on the dedupe constraint: a double-tap never duplicates.
*/
async function writeLedgerEntry(
sb: NonNullable<ReturnType<typeof getServiceRoleSupabase>>,
userId: string,
body: ScanBody,
data: { grade?: string; projection?: number; confidence?: number; edge_pct?: number },
) {
try {
const { nameKey, normalizeName } = await import('@/lib/playerName');
const sport = body.sport.toLowerCase();
const playerKey = nameKey(body.player);
const gameDate = new Intl.DateTimeFormat('en-CA', {
timeZone: 'America/New_York', year: 'numeric', month: '2-digit', day: '2-digit',
}).format(new Date());
// Cache-only snapshot read (never triggers an odds fetch → no quota).
let lockedOdds: string | null = null;
try {
const snap = await fetch(`${BACKEND_URL}/api/snapshot/${sport}`, {
headers: { Accept: 'application/json' },
cache: 'no-store',
}).then((r) => (r.ok ? r.json() : null));
const match = (snap?.grades || []).find(
(g: { player?: string; player_name?: string; stat_type?: string; stat?: string; gradedAt?: { line?: number; odds?: number | string | null } }) =>
nameKey(g.player || g.player_name || '') === playerKey
&& String(g.stat_type || g.stat || '').toLowerCase() === body.stat.toLowerCase()
&& g.gradedAt && Number(g.gradedAt.line) === Number(body.line),
);
if (match?.gradedAt?.odds != null) lockedOdds = String(match.gradedAt.odds);
} catch { /* absent beats wrong */ }
await sb.from('ledger_entries').upsert(
{
user_id: userId,
player_key: playerKey,
player_name: normalizeName(body.player).display || body.player,
sport,
stat: body.stat.toLowerCase(),
line: body.line,
side: body.direction,
locked_odds: lockedOdds,
book: body.book ?? 'draftkings',
grade: data.grade,
edge: typeof data.edge_pct === 'number' ? data.edge_pct : null,
confidence: typeof data.confidence === 'number' ? data.confidence : null,
model_value: typeof data.projection === 'number' ? data.projection : null,
graded_at: new Date().toISOString(),
game_id: `manual:${sport}:${gameDate}:${playerKey}`,
game_date: gameDate,
},
{ onConflict: 'user_id,player_key,stat,line,side,game_id', ignoreDuplicates: true },
);
} catch (err) {
console.warn('[scan] ledger write failed', err);
}
}