Session 55: Self-learning loop + real-time layer (2274 tests)

Product overhaul core — the two transformative, differentiated systems:

Self-learning loop (Phase 2): outcomeService settles locked snapshot grades
against real MLB Stats API results → hit/miss/push, rolling accuracy by grade
tier (30d window). Idempotent, injectable, unit-tested. New GET /api/accuracy +
/api/ledger/accuracy + internal settle triggers + cron hook. AccuracyBadge
(dashboard/scan/landing) is honest — "LEARNING" below MIN_SAMPLE, never a fake
number. Settled HIT/MISS chips overlay the live slate.

Real-time layer (Phase 1): Slate silent 60s auto-refresh (no flash, no wipe on
transient blips) + "SIGNAL LIVE · UPDATED Xs ago" freshness strip; Ticker LIVE
badge that flashes on fresh events.

Landing (Phase 3): TopSignals shows tonight's real top-3 A-rated grades + live
accuracy — the product shown, not described.

Founder pricing: FOUNDER_CODE_EXPIRY default 2026-06-30 → 2026-12-31 (had
lapsed, disabling every founder code + the ClaimMeter pitch). That expiry — not
a tier change — was the real cause of the 4 stripe test failures.

Backend 2255 (4 failing) → 2274 (all green; +19 new, +4 fixed). Web build exit 0.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Kev
2026-07-10 15:39:13 -04:00
parent 8629021774
commit d09a06c054
27 changed files with 1285 additions and 17 deletions
+30
View File
@@ -0,0 +1,30 @@
'use strict';
/**
* GET /api/accuracy (Session 55) — the system's track record.
*
* Public, cache-only read of the rolling accuracy record written by
* outcomeService (settled snapshot grades vs real results). Powers the
* dashboard "A-rated: 68% hit rate" pill and the grade-card accuracy line.
* NEVER triggers settlement (that's the internal cron) → no API credits spent.
*/
const express = require('express');
const { createRateLimit } = require('../middleware/rateLimit');
const outcomeService = require('../services/outcomeService');
const router = express.Router();
router.use(createRateLimit({ windowMs: 60_000, max: 60 }));
router.get('/', async (req, res) => {
try {
const acc = await outcomeService.getAccuracy();
res.set('Cache-Control', 'public, max-age=300');
return res.json(acc);
} catch (err) {
console.error('[accuracy]', err.message);
return res.status(200).json({ overall: null, sports: {}, min_sample: outcomeService.MIN_SAMPLE, updated_at: null });
}
});
module.exports = router;
+31
View File
@@ -159,4 +159,35 @@ router.post('/snapshot/:sport', async (req, res) => {
}
});
/**
* POST /api/internal/outcomes/all (Session 55) — settle every sport's latest
* snapshot against real results + recompute the overall accuracy record. This
* is the self-learning loop's write path (the public /api/accuracy is read-only).
* Registered BEFORE /outcomes/:sport so "all" isn't captured as a sport.
*/
router.post('/outcomes/all', async (req, res) => {
const outcomes = require('../services/outcomeService');
try {
const results = await outcomes.settleAllOutcomes();
return res.json({ ok: true, results });
} catch (err) {
const message = err && err.message ? err.message : String(err);
console.error('[internal/outcomes/all] failed:', message);
return res.status(500).json({ ok: false, error: message });
}
});
router.post('/outcomes/:sport', async (req, res) => {
const outcomes = require('../services/outcomeService');
try {
const summary = await outcomes.settleSnapshot(req.params.sport);
await outcomes.recomputeOverall();
return res.json({ ok: true, summary: { sport: summary.sport, settled: summary.settled, pending: summary.pending, accuracy: summary.accuracy } });
} catch (err) {
const message = err && err.message ? err.message : String(err);
console.error('[internal/outcomes] failed:', message);
return res.status(500).json({ ok: false, error: message });
}
});
module.exports = router;
+30
View File
@@ -0,0 +1,30 @@
'use strict';
/**
* GET /api/ledger/accuracy (Session 55) — grade-tier buckets for the ledger UI.
*
* The Next proxy `web/src/app/api/ledger/accuracy` has expected a `{ buckets }`
* shape since before a writer existed; the self-learning loop now fills it.
* Public, cache-only (reads outcomeService's persisted accuracy record).
*/
const express = require('express');
const { createRateLimit } = require('../middleware/rateLimit');
const outcomeService = require('../services/outcomeService');
const router = express.Router();
router.use(createRateLimit({ windowMs: 60_000, max: 60 }));
router.get('/accuracy', async (req, res) => {
try {
const acc = await outcomeService.getAccuracy();
const buckets = outcomeService.accuracyBuckets(acc.overall);
res.set('Cache-Control', 'public, max-age=300');
return res.json({ buckets, overall: acc.overall && acc.overall.overall, updated_at: acc.updated_at });
} catch (err) {
console.error('[ledger/accuracy]', err.message);
return res.status(200).json({ buckets: [] });
}
});
module.exports = router;
+27 -3
View File
@@ -12,23 +12,47 @@
const express = require('express');
const { createRateLimit } = require('../middleware/rateLimit');
const { cacheGet } = require('../utils/redis');
const { nameKey } = require('../utils/playerName');
const router = express.Router();
router.use(createRateLimit({ windowMs: 60_000, max: 60 }));
// Session 55 — overlay settled outcomes (self-learning loop) onto the grades so
// a completed prop can render "✅ HIT (2)" / "❌ MISS". Keyed by player+stat+line+side.
function outcomeIndex(log) {
const map = {};
for (const o of Array.isArray(log) ? log : []) {
const side = String(o.side || 'O').toUpperCase() === 'U' ? 'U' : 'O';
map[`${nameKey(o.player)}|${String(o.stat).toLowerCase()}|${o.line}|${side}`] = o;
}
return map;
}
function attachOutcomes(grades, index) {
if (!index || Object.keys(index).length === 0) return grades;
return grades.map((g) => {
const side = String(g.direction || 'over').toLowerCase() === 'under' ? 'U' : 'O';
const o = index[`${nameKey(g.player || g.player_name)}|${String(g.stat_type || g.stat || '').toLowerCase()}|${g.line}|${side}`];
return o ? { ...g, outcome: { result: o.result, actual: o.actual } } : g;
});
}
router.get('/:sport', async (req, res) => {
const sport = String(req.params.sport || '').toLowerCase();
try {
const snap = await cacheGet(`snapshot:${sport}:latest`);
const [snap, outcomeLog] = await Promise.all([
cacheGet(`snapshot:${sport}:latest`),
cacheGet(`outcomes:${sport}:log`),
]);
const idx = outcomeIndex(outcomeLog);
if (snap && Array.isArray(snap.grades)) {
res.set('Cache-Control', 'public, max-age=30');
return res.json({ sport, updated_at: snap.updated_at, grades: snap.grades, deltas: snap.deltas || [] });
return res.json({ sport, updated_at: snap.updated_at, grades: attachOutcomes(snap.grades, idx), deltas: snap.deltas || [] });
}
// Fallback: the grades envelope (no deltas yet).
const env = await cacheGet(`grades:${sport}`);
const grades = env && Array.isArray(env.grades) ? env.grades : [];
res.set('Cache-Control', 'public, max-age=30');
return res.json({ sport, updated_at: env && env.updated_at, grades, deltas: [] });
return res.json({ sport, updated_at: env && env.updated_at, grades: attachOutcomes(grades, idx), deltas: [] });
} catch (err) {
console.error('[snapshot]', err.message);
return res.status(200).json({ sport, grades: [], deltas: [] });