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,214 @@
/**
* computeFeaturesForProp — the ONE permitted architectural addition of
* Session 7f. Bridges raw single-prop input (`{player, stat_type, line,
* direction, book, sport}`) to the feature-vector shape `engine1.gradeProp()`
* expects.
*
* The orchestrator does this same work inline, tied to its batch loop +
* grade_history persistence. This module lifts only the per-prop logic
* so single-prop callers (`/api/analyze/prop`, batch entries,
* `/api/scan/parlay` legs, `/api/bets/*`) can produce engine1 input
* without re-implementing the resolution chain.
*
* Never throws. Every step is independently fault-tolerant:
* - player_id_map miss → team/opponent unknown, features still partial
* - no game tonight → no gameId, gameId-dependent features omitted
* - feature fetch fails → features {} returned, engine1 lands C
* - trap fetch fails → trap defaults to no signals firing
* - game logs unavailable → consistency defaults to 'unknown'
*
* The caller (analyzeViaEngine1) reads the returned `errors` array and
* downgrades confidence accordingly via the adapter's reasoning string.
*/
const axios = require('axios');
const { getSportConfig } = require('../../config/sports');
const { getSupabaseServiceClient } = require('../../utils/supabase');
const { normalizeName } = require('../../utils/normalize');
const featureCache = require('./featureCache');
const trapDetection = require('./trapDetection');
const consistencyScore = require('./consistencyScore');
const gameLogService = require('./gameLogService');
const HTTP_TIMEOUT_MS = 8_000;
// Resolve a free-form player + sport to a roster row. Returns null on
// any failure so callers can still proceed with partial features.
async function lookupPlayer({ player, sport }) {
if (!player || !sport) return null;
try {
const supabase = getSupabaseServiceClient();
const norm = normalizeName(player);
const { data, error } = await supabase
.from('player_id_map')
.select('display_name, normalized_name, espn_id, team_abbr, sport')
.eq('sport', sport)
.eq('normalized_name', norm)
.limit(1)
.maybeSingle();
if (error || !data) return null;
return data;
} catch (err) {
console.warn('[computeFeatures] player lookup failed:', err.message);
return null;
}
}
// Pull today's scoreboard for the sport and find the game the player's
// team plays in. Returns { gameId, opponentAbbr, isHome } or null.
async function lookupTodayGame({ sport, teamAbbr }) {
if (!sport || !teamAbbr) return null;
let sportCfg;
try { sportCfg = getSportConfig(sport); } catch { return null; }
try {
const res = await axios.get(sportCfg.espnScoreboard, { timeout: HTTP_TIMEOUT_MS });
const events = res.data?.events || [];
for (const ev of events) {
const comp = ev?.competitions?.[0];
if (!comp) continue;
const competitors = comp.competitors || [];
const home = competitors.find((c) => c.homeAway === 'home');
const away = competitors.find((c) => c.homeAway === 'away');
const homeAbbr = home?.team?.abbreviation;
const awayAbbr = away?.team?.abbreviation;
if (homeAbbr === teamAbbr) {
return { gameId: String(ev.id), opponentAbbr: awayAbbr, isHome: true };
}
if (awayAbbr === teamAbbr) {
return { gameId: String(ev.id), opponentAbbr: homeAbbr, isHome: false };
}
}
return null;
} catch (err) {
console.warn('[computeFeatures] scoreboard fetch failed:', err.message);
return null;
}
}
async function safeGetFeatures(input) {
try {
const payload = await featureCache.getFeatures(input);
return payload?.features || {};
} catch (err) {
console.warn('[computeFeatures] feature fetch failed:', err.message);
return {};
}
}
async function safeGetTrap(input) {
const fallback = { composite: 0, signals: {}, active_count: 0, recommendation: 'proceed' };
try {
return (await trapDetection.getTrapScore(input)) || fallback;
} catch (err) {
console.warn('[computeFeatures] trap detection failed:', err.message);
return fallback;
}
}
async function safeGetConsistency({ playerName, sport, statType }) {
const fallback = { consistency: 'unknown', score: null, games: 0 };
try {
const logs = await gameLogService.getGameLogs(playerName, sport, 20);
if (!logs || logs.length === 0) return { result: fallback, gameLogs: [] };
const result = await consistencyScore.getConsistency({
playerName, sport, statType, gameLogs: logs,
});
return { result: result || fallback, gameLogs: logs };
} catch (err) {
console.warn('[computeFeatures] consistency failed:', err.message);
return { result: fallback, gameLogs: [] };
}
}
async function computeFeaturesForProp(rawProp = {}) {
const errors = [];
const player = rawProp.player;
const statType = rawProp.stat_type || rawProp.statType;
const line = Number(rawProp.line);
const direction = rawProp.direction || 'over';
const book = rawProp.book || 'unknown';
// Default to NBA when caller omits — matches what legacy analyzeProp does.
const sport = (rawProp.sport || 'nba').toLowerCase();
if (!player || !statType || !Number.isFinite(line)) {
errors.push('missing required fields (player, stat_type, or line)');
}
const roster = await lookupPlayer({ player, sport });
if (!roster) errors.push('player_not_found_in_id_map');
const teamAbbr = roster?.team_abbr ?? null;
const playerId = roster?.espn_id ?? null;
const game = teamAbbr ? await lookupTodayGame({ sport, teamAbbr }) : null;
if (!game) errors.push('no_game_scheduled_today');
const gameContext = {
home_away: game ? (game.isHome ? 'home' : 'away') : null,
};
const features = await safeGetFeatures({
playerId,
playerName: player,
statType,
sport,
teamAbbr,
opponentAbbr: game?.opponentAbbr ?? null,
gameId: game?.gameId ?? null,
gameContext,
});
if (!features || Object.keys(features).length === 0) {
errors.push('no_features_computed');
}
const trap = await safeGetTrap({
playerName: player,
statType,
sport,
gameId: game?.gameId ?? null,
gameContext,
features,
odds: { playerLine: line, consensus: null },
});
const { result: consistency, gameLogs } = await safeGetConsistency({
playerName: player, sport, statType,
});
return {
// Shape engine1.gradeProp() consumes.
features,
trap,
consistency,
prop: { line, direction },
// Extra context the wiring helper (Fix 2) uses to build human-readable
// reasoning sentences. Not consumed by engine1 itself.
meta: {
player,
statType,
line,
direction,
book,
sport,
teamAbbr,
playerId,
opponentAbbr: game?.opponentAbbr ?? null,
gameId: game?.gameId ?? null,
isHome: game?.isHome ?? null,
gameLogs,
errors,
},
};
}
module.exports = {
computeFeaturesForProp,
__internals: {
lookupPlayer,
lookupTodayGame,
safeGetFeatures,
safeGetTrap,
safeGetConsistency,
},
};