Session B (night2): streaks/hot-list engine — producer + form heat + THE LENS
RESURRECT verdict: the Session-23 engine existed, was pure, tested, and
mounted — it starved because every producer was external and unarmed
(tank01-prefetch via n8n, offline Python flow). The snapshot pipeline is
now the producer: each run merges slate players' real game logs (already
fetched for archetypes — zero extra calls) into rosterlogs:{sport}.
- computeFormHeat: hot hitters (7d AVG), hot sluggers (SLG), hot shooters
(FG%) — correct sum/sum rate math, season baseline else prior stretch,
min-sample refusals, never extrapolated.
- streakLens: no raw streak renders alone — built-vs opponents, tonight's
matchup + opposing SP w/ ERA, step-up/step-down difficulty, one-line
read. Absent context = say less, never invent.
- /api/streaks/:sport: heat merged into the feed, lens applied from cached
schedule + pitchers (time-bounded, can never hang the route), snapshot
grade letters joined.
- ACCEPTANCE (live statsapi, real 2026 logs): 32 rows found — Turang
12-gm on-base, Reynolds 8-gm on-base, Pratt 7-gm on-base + 3-gm
multi-hit, Meidroth 5-gm on-base, Cortes 5-gm on-base.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -191,7 +191,7 @@ function computePlayerStreaks(player, sport, opts = {}) {
|
||||
continue;
|
||||
}
|
||||
const run = consecutiveRun(games, spec.value, spec.threshold);
|
||||
if (run >= MIN_STREAK) found.push(makeStreak(player, sport, spec, run));
|
||||
if (run >= MIN_STREAK) found.push(makeStreak(player, sport, spec, run, undefined, games));
|
||||
}
|
||||
|
||||
// Collapse tiered specs (e.g. 25+ and 20+ points) to one entry per
|
||||
@@ -210,7 +210,12 @@ function computePlayerStreaks(player, sport, opts = {}) {
|
||||
return Array.from(best.values()).map(({ _collapse, ...rest }) => rest);
|
||||
}
|
||||
|
||||
function makeStreak(player, sport, spec, run, rateValue) {
|
||||
function makeStreak(player, sport, spec, run, rateValue, games) {
|
||||
// Session 60 (night2/B) — the opponents the streak was BUILT against
|
||||
// (unique, streak-window only). Lens fuel: "built vs OAK, LAA, SEA".
|
||||
const opponents = Array.isArray(games)
|
||||
? [...new Set(games.slice(0, run).map((g) => g && g.opponent).filter(Boolean))]
|
||||
: [];
|
||||
return {
|
||||
sport,
|
||||
player: player.name || player.player || null,
|
||||
@@ -222,6 +227,7 @@ function makeStreak(player, sport, spec, run, rateValue) {
|
||||
currentStreak: run,
|
||||
rate: rateValue ?? null,
|
||||
description: describe(spec, run),
|
||||
opponents,
|
||||
active: true,
|
||||
_collapse: spec.collapse || spec.key, // internal — stripped before return
|
||||
};
|
||||
@@ -245,9 +251,114 @@ function computeStreaks(players, sport, opts = {}) {
|
||||
return all;
|
||||
}
|
||||
|
||||
// ---- Session 60 (night2/B): FORM HEAT — 7-day rate vs baseline ----------
|
||||
// Hot hitters (AVG), hot sluggers (SLG/ISO), hot shooters (FG%). Rates are
|
||||
// computed the correct way (Σmakes/Σattempts over the window, NOT a mean of
|
||||
// per-game rates). Baseline = the player's season rate when the roster blob
|
||||
// carries one, else the pre-window games — labeled accordingly, never faked.
|
||||
|
||||
const fmt3 = (n) => {
|
||||
const s = n.toFixed(3);
|
||||
return s.startsWith('0.') ? s.slice(1) : s; // .412, not 0.412
|
||||
};
|
||||
|
||||
function windowSplit(games, now, windowDays = 7) {
|
||||
const cutoff = (now || Date.now()) - windowDays * 86_400_000;
|
||||
const dated = games.filter((g) => g && g.date && Number.isFinite(new Date(g.date).getTime()));
|
||||
if (dated.length === 0) return { recent: games.slice(0, 5), rest: games.slice(5) };
|
||||
return {
|
||||
recent: dated.filter((g) => new Date(g.date).getTime() >= cutoff),
|
||||
rest: dated.filter((g) => new Date(g.date).getTime() < cutoff),
|
||||
};
|
||||
}
|
||||
|
||||
const sumOf = (rows, ...keys) => rows.reduce((acc, r) => acc + num(r, ...keys), 0);
|
||||
|
||||
// Rate over a set of games: { made, att, rate|null }.
|
||||
function ratio(rows, madeKeys, attKeys) {
|
||||
const made = sumOf(rows, ...madeKeys);
|
||||
const att = sumOf(rows, ...attKeys);
|
||||
return { made, att, rate: att > 0 ? made / att : null };
|
||||
}
|
||||
|
||||
const HEAT_SPECS = {
|
||||
mlb: [
|
||||
{
|
||||
type: 'hot_hitter', category: 'hits', label: 'AVG',
|
||||
made: ['hits', 'H', 'h'], att: ['atBats', 'ab', 'AB'],
|
||||
seasonKey: 'avg', minAtt: 15, minDelta: 0.05, fmt: fmt3,
|
||||
line: (r, b, src) => `hitting ${fmt3(r)} over the last 7 days (${src} ${fmt3(b)})`,
|
||||
},
|
||||
{
|
||||
type: 'hot_slugger', category: 'total_bases', label: 'SLG',
|
||||
made: ['totalBases', 'TB', 'total_bases'], att: ['atBats', 'ab', 'AB'],
|
||||
seasonKey: 'slg', minAtt: 15, minDelta: 0.09, fmt: fmt3,
|
||||
line: (r, b, src) => `slugging ${fmt3(r)} over the last 7 days (${src} ${fmt3(b)})`,
|
||||
},
|
||||
],
|
||||
wnba: [
|
||||
{
|
||||
type: 'hot_shooter', category: 'points', label: 'FG%',
|
||||
made: ['fgm', 'field_goals_made', 'fieldGoalsMade'], att: ['fga', 'field_goals_attempted', 'fieldGoalsAttempted'],
|
||||
seasonKey: 'fgPct', minAtt: 20, minDelta: 0.05, fmt: (n) => `${Math.round(n * 100)}%`,
|
||||
line: (r, b, src) => `shooting ${Math.round(r * 100)}% over the last 7 days (${src} ${Math.round(b * 100)}%)`,
|
||||
},
|
||||
],
|
||||
};
|
||||
HEAT_SPECS.nba = HEAT_SPECS.wnba;
|
||||
|
||||
/**
|
||||
* Form-heat rows in the streak shape (they merge into the same feed).
|
||||
* players = [{ name, playerId, team, games, seasonRaw? }] — games
|
||||
* most-recent-first with date fields.
|
||||
*/
|
||||
function computeFormHeat(players, sport, opts = {}) {
|
||||
const specs = HEAT_SPECS[String(sport || '').toLowerCase()] || [];
|
||||
if (specs.length === 0 || !Array.isArray(players)) return [];
|
||||
const out = [];
|
||||
for (const p of players) {
|
||||
const games = Array.isArray(p?.games) ? p.games.slice() : [];
|
||||
if (opts.chronological) games.reverse();
|
||||
if (games.length === 0) continue;
|
||||
const { recent, rest } = windowSplit(games, opts.now, opts.windowDays || 7);
|
||||
for (const spec of specs) {
|
||||
const cur = ratio(recent, spec.made, spec.att);
|
||||
if (cur.rate == null || cur.att < spec.minAtt) continue;
|
||||
// Baseline: season rate from the blob when present, else prior games.
|
||||
let baseline = null;
|
||||
let baselineSrc = 'season';
|
||||
const seasonVal = p.seasonRaw && Number(p.seasonRaw[spec.seasonKey]);
|
||||
if (Number.isFinite(seasonVal) && seasonVal > 0) baseline = seasonVal;
|
||||
else {
|
||||
const prior = ratio(rest, spec.made, spec.att);
|
||||
if (prior.rate != null && prior.att >= spec.minAtt) { baseline = prior.rate; baselineSrc = 'prior stretch'; }
|
||||
}
|
||||
if (baseline == null || cur.rate - baseline < spec.minDelta) continue;
|
||||
out.push({
|
||||
sport: String(sport).toLowerCase(),
|
||||
player: p.name || p.player || null,
|
||||
playerId: p.playerId ?? p.id ?? null,
|
||||
team: p.team || null,
|
||||
type: spec.type,
|
||||
category: spec.category,
|
||||
threshold: null,
|
||||
currentStreak: recent.length,
|
||||
rate: Math.round(cur.rate * 1000) / 1000,
|
||||
baseline: Math.round(baseline * 1000) / 1000,
|
||||
description: spec.line(cur.rate, baseline, baselineSrc),
|
||||
opponents: [...new Set(recent.map((g) => g && g.opponent).filter(Boolean))],
|
||||
active: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
out.sort((a, b) => (b.rate - b.baseline) - (a.rate - a.baseline));
|
||||
return opts.limit && opts.limit > 0 ? out.slice(0, opts.limit) : out;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
computeStreaks,
|
||||
computePlayerStreaks,
|
||||
computeFormHeat,
|
||||
specsFor,
|
||||
__internals: { consecutiveRun, rateOverWindow, nba, mlb, nfl, soccer, MIN_STREAK },
|
||||
__internals: { consecutiveRun, rateOverWindow, windowSplit, ratio, nba, mlb, nfl, soccer, MIN_STREAK, HEAT_SPECS },
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user