Sessions 7e+7f: Grade adapter, normalize consolidation, computeFeatures, analyzeViaEngine1, scan/parlay migrated to engine1

This commit is contained in:
Kev
2026-06-10 09:28:30 -04:00
parent 012c0ef47e
commit 4815ceac03
10 changed files with 952 additions and 11 deletions
@@ -0,0 +1,248 @@
/**
* analyzeViaEngine1 — the canonical single-prop analysis function.
*
* Composes the three pieces sessions 6c, 7e, and 7f built:
* computeFeaturesForProp → engine1.gradeProp → toLegacyShape
*
* Output matches the legacy `analyzeProp()` shape byte-for-byte (DemoScan
* + GradeCard read the same fields). The `reasoning.summary` here is built
* from real feature values (l5_avg, opp_rank_stat, etc.) so users still
* see concrete sentences, not abstract factor labels.
*
* Never throws. Every upstream failure mode is reflected as low-confidence
* grade + an explanatory reasoning summary.
*/
const { computeFeaturesForProp } = require('./computeFeatures');
const engine1 = require('./engine1');
const { toLegacyShape } = require('../../utils/gradeAdapter');
// Map an error code from computeFeaturesForProp.meta.errors into a human
// sentence the user will see in reasoning.summary.
const ERROR_EXPLANATIONS = Object.freeze({
player_not_found_in_id_map: "We couldn't find this player in our roster index.",
no_game_scheduled_today: "No game scheduled for this player tonight.",
no_features_computed: "Statistical features unavailable for this player tonight.",
});
function explainErrors(errors) {
if (!Array.isArray(errors) || errors.length === 0) return '';
return errors.map((e) => ERROR_EXPLANATIONS[e] || `Data gap: ${e}.`).join(' ');
}
// Build a human-readable reasoning summary + steps from the actual
// features (which carry real numbers) and engine1's grade.
function buildConcreteReasoning(features = {}, engine1Result = {}, meta = {}, prop = {}) {
const lines = [];
// Recent form vs the line — L5 and L20 are the orchestrator's
// canonical season-trend signals.
if (Number.isFinite(features.l5_avg)) {
lines.push(`${prop.player || 'Player'} is averaging ${features.l5_avg.toFixed(1)} ${prop.stat_type || ''} over his last 5 games.`);
}
if (Number.isFinite(features.l20_avg)) {
lines.push(`Last 20 games average: ${features.l20_avg.toFixed(1)}.`);
}
// Trend direction relative to the line.
if (Number.isFinite(features.l5_avg) && Number.isFinite(prop.line)) {
const diff = features.l5_avg - prop.line;
if (Math.abs(diff) >= 0.5) {
const dir = diff > 0 ? 'above' : 'below';
lines.push(`That's ${Math.abs(diff).toFixed(1)} ${dir} the line of ${prop.line}.`);
}
}
// Home / away.
if (features.home_away === 1.0) lines.push('Playing at home tonight.');
else if (features.home_away === 0.0) lines.push('Playing on the road tonight.');
// Opponent matchup. opp_rank_stat is 0..1 normalized
// (0 = best D, 1 = worst D) — translate to friendlier language.
if (Number.isFinite(features.opp_rank_stat) && meta.opponentAbbr) {
if (features.opp_rank_stat >= 0.7) {
lines.push(`${meta.opponentAbbr} is a bottom-tier defense vs this stat.`);
} else if (features.opp_rank_stat <= 0.3) {
lines.push(`${meta.opponentAbbr} is a top-tier defense vs this stat.`);
} else {
lines.push(`${meta.opponentAbbr} is a middling defense vs this stat.`);
}
}
// Rest / fatigue context.
if (features.rest_days === 0) lines.push('Back-to-back — fatigue concern.');
else if (Number.isFinite(features.rest_days) && features.rest_days >= 2) {
lines.push(`${features.rest_days} days of rest.`);
}
if (Number.isFinite(features.game_count_in_7d) && features.game_count_in_7d >= 4) {
lines.push(`Heavy workload — ${features.game_count_in_7d} games in the last week.`);
}
// Injury context.
if (Number.isFinite(features.injury_severity_score) && features.injury_severity_score > 0) {
lines.push(`${features.injury_severity_score} opponent starter(s) on the injury report.`);
}
// Trap composite — surfaced when meaningful.
// (Adapter handles the per-factor kill_conditions chips; this line
// gives the user the overall warning.)
if (engine1Result?.grade && engine1Result.grade.endsWith('-') === false
&& Array.isArray(engine1Result.all_factors)
&& engine1Result.all_factors.includes('trap_composite_high')) {
lines.push('Multiple trap signals firing — proceed with caution.');
}
// Engine-1 verdict capper.
const grade = engine1Result?.grade;
if (grade) {
const verb = grade.startsWith('A') ? 'favors the play'
: grade.startsWith('B') ? 'leans toward the play'
: grade.startsWith('C') ? 'is split'
: 'leans against the play';
lines.push(`Engine 1 graded ${grade}${verb}.`);
}
// Tack on any data-gap explanations.
const gapNote = explainErrors(meta.errors);
if (gapNote) lines.push(gapNote);
const summary = lines.join(' ').trim()
|| `Analysis complete. Grade: ${grade || 'C'}.`;
// Legacy-shaped steps so backward-compat callers (integration tests,
// anything pre-dating the engine swap) keep seeing the named
// sub-blocks. Each is populated from engine1 features where the data
// exists; missing sub-blocks contain null fields instead of being
// absent so callers can dot-access without optional chaining.
const seasonAvg = Number.isFinite(features.l20_avg) ? features.l20_avg : null;
const recentAvg = Number.isFinite(features.l5_avg) ? features.l5_avg : null;
const haContext = features.home_away === 1.0 ? 'home'
: features.home_away === 0.0 ? 'away' : null;
const restContext = features.rest_days === 0 ? 'b2b'
: Number.isFinite(features.rest_days) && features.rest_days >= 2 ? 'rested' : null;
return {
summary,
steps: {
season_avg: {
value: seasonAvg,
vs_line: seasonAvg != null && Number.isFinite(prop.line)
? Math.round((seasonAvg - prop.line) * 10) / 10 : null,
signal: null,
},
recent_form: {
value: recentAvg,
vs_line: recentAvg != null && Number.isFinite(prop.line)
? Math.round((recentAvg - prop.line) * 10) / 10 : null,
signal: null,
},
situational: {
home_away: { value: null, context: haContext, signal: null },
rest_days: { value: features.rest_days ?? null, context: restContext, signal: null },
vs_opponent: { value: null, games: null, signal: null },
},
line_comparison: {
best_line: null,
worst_line: null,
edge_from_best: 0,
signal: null,
},
kill_conditions: [],
final_grade: grade || null,
// Flat narrative bullets — kept under `steps` so legacy clients
// can still find them but they don't collide with the named
// sub-blocks above.
narrative: lines.map((line, i) => ({ step: i + 1, detail: line })),
},
};
}
// edge_pct in the legacy shape compares the relevant average to the line.
// We use l5_avg when present (matches legacy "recent form" weighting),
// fall back to l20_avg, otherwise return 0 so the field is always present.
function edgePctFor(features, prop) {
const ref = Number.isFinite(features?.l5_avg) ? features.l5_avg
: Number.isFinite(features?.l20_avg) ? features.l20_avg
: null;
if (ref == null || !Number.isFinite(prop?.line) || prop.line === 0) return 0;
const signed = prop.direction === 'over' ? (ref - prop.line) : (prop.line - ref);
return Math.round((signed / prop.line) * 1000) / 10;
}
// When computeFeatures fails so badly that even a partial feature vector
// is empty, return a legacy-shaped low-confidence result rather than
// asking engine1 to grade nothing.
function fallbackLegacyResult(rawProp, errors) {
return {
player: rawProp.player ?? null,
stat_type: rawProp.stat_type ?? null,
line: rawProp.line ?? null,
direction: rawProp.direction ?? null,
book: rawProp.book || 'unknown',
grade: 'C',
confidence: 10,
edge_pct: 0,
kill_conditions_triggered: [],
reasoning: {
summary: `Unable to compute full analysis. ${explainErrors(errors) || ''} Grade is provisional.`.trim(),
steps: [],
},
};
}
async function analyzeViaEngine1(rawProp = {}) {
const featureResult = await computeFeaturesForProp(rawProp);
const { features, trap, consistency, prop, meta } = featureResult;
// Hard fallback only when computeFeatures couldn't produce anything
// useful at all (no features AND no consistency input).
if ((!features || Object.keys(features).length === 0)
&& (!consistency || consistency.consistency === 'unknown')
&& (!Array.isArray(meta?.gameLogs) || meta.gameLogs.length === 0)) {
return fallbackLegacyResult(rawProp, meta?.errors);
}
// Engine 1: deterministic rule-based grade on the feature vector.
const engine1Result = engine1.gradeProp({ features, trap, consistency, prop });
// Translate engine1 output → legacy shape via the adapter from 7e.
// The adapter handles kill_conditions_triggered + the 4-letter grade
// collapse + the 0-100 confidence scale.
const summaryOverride = buildConcreteReasoning(features, engine1Result, meta, {
...rawProp,
line: prop.line,
}).summary;
const legacy = toLegacyShape(engine1Result, {
player: rawProp.player,
stat_type: rawProp.stat_type,
line: prop.line,
direction: prop.direction,
book: rawProp.book || 'unknown',
sport: meta.sport,
}, {
summaryOverride,
edgePct: edgePctFor(features, prop),
});
// The adapter's reasoning.steps was a single-element debug bag;
// replace it with the line-by-line breakdown we built above so the
// legacy UI's step list looks identical to before.
legacy.reasoning = buildConcreteReasoning(features, engine1Result, meta, {
...rawProp,
line: prop.line,
});
return legacy;
}
module.exports = {
analyzeViaEngine1,
__internals: {
buildConcreteReasoning,
edgePctFor,
fallbackLegacyResult,
explainErrors,
ERROR_EXPLANATIONS,
},
};