import { requireServices, type IServiceContainer } from '@stock-bot/services'; import { isCanonicalRunResult, type ResearchRunResult, } from '@stock-bot/stock-config/canonical-research'; import { parseResearchInput, researchEvidenceReferenceSchema, } from '@stock-bot/stock-config/research'; import type { CanonicalMetrics, ResearchEvidence, ResearchEvidenceReference, ResearchFindingSource, } from '@stock-bot/types'; import type { BacktestResultQuery } from './backtests/contracts'; import type { BacktestResults } from './backtests/results'; import { ResearchError } from './research-errors'; import { verifyResearchSource } from './research-source-evidence'; function unitOf(path: string): ResearchEvidence['unit'] { const name = path.split('.').at(-1); if (['fillCount', 'roundTripCount', 'totalTrades'].includes(name ?? '')) { return 'count'; } if (['avgWin', 'avgLoss'].includes(name ?? '')) { return 'currency'; } if ( ['sharpeRatio', 'sortinoRatio', 'profitFactor', 'beta', 'informationRatio'].includes(name ?? '') ) { return 'ratio'; } return 'fraction'; } /** Select existing scalar measurements only. No metric, accounting or validation recalculation. */ export function projectResearchEvidence( input: ResearchEvidenceReference, result: ResearchRunResult ): ResearchEvidence { const reference = parseResearchInput(researchEvidenceReferenceSchema, input); if (result.runId !== reference.runId || result.status !== 'completed') { throw new ResearchError(422, 'Evidence must refer to the completed retained run'); } let value: number | null | undefined; let unavailableReason: string | null; let details: Pick< ResearchEvidence, 'resultKind' | 'financialEngine' | 'datasetHash' | 'limitations' >; if (isCanonicalRunResult(result)) { if (reference.metricsVersion !== 'canonical-analytics/v1' || result.analytics.version !== 1) { throw new ResearchError(422, 'Metrics version does not match this retained result'); } if ( reference.strategyVersionId && reference.strategyVersionId !== result.request.strategy.versionId ) { throw new ResearchError(422, 'Strategy version is not bound by this run'); } const key = reference.metricPath.slice('analytics.metrics.'.length) as keyof CanonicalMetrics; value = reference.metricPath === 'analytics.fillCount' ? result.analytics.fillCount : result.analytics.metrics[key]; unavailableReason = value === null ? (result.analytics.unavailable[key] ?? 'not-reported') : null; details = { resultKind: 'canonical', financialEngine: 'rust', datasetHash: result.request.datasetHash, limitations: [...result.financial.limitations, ...result.financial.modelLimitations].map( message => ({ code: 'canonical-model-limitation', message }) ), }; } else { if (reference.metricsVersion !== 'legacy-display/v1' || reference.strategyVersionId) { throw new ResearchError( 422, 'Legacy results cannot certify this metrics or executable version' ); } value = reference.metricPath === 'analytics.exposureTime' ? result.analytics.exposureTime : result.metrics[reference.metricPath.slice('metrics.'.length)]; unavailableReason = value === null || value === undefined ? 'legacy-unavailable' : null; // Legacy v1 names this read-only display adapter, not an engine/economics version. details = { resultKind: 'legacy', financialEngine: result.engine, datasetHash: result.provenance?.datasetHash ?? null, limitations: [ { code: 'legacy-unverified-economics', message: 'Legacy display measurements are exploratory evidence; financial correctness and historical engine versions are not certified.', }, ...(result.provenance?.limitations ?? []), ], }; } if ( value !== null && value !== undefined && (typeof value !== 'number' || !Number.isFinite(value)) ) { throw new ResearchError(422, 'Retained metric is not a finite scalar measurement'); } if (value === undefined) { value = null; unavailableReason ??= 'not-reported'; } return { ...reference, backtestId: result.backtestId, value, unit: unitOf(reference.metricPath), availability: value === null ? 'unavailable' : 'available', unavailableReason, ...details, }; } export class ResearchEvidenceResolver { private readonly database; constructor( container: IServiceContainer, private readonly results: Pick ) { this.database = requireServices(container, 'postgres').postgres; } async resolveAll( references: ResearchEvidenceReference[], source: ResearchFindingSource | null, database: BacktestResultQuery ): Promise { if (!source) { const resolved: ResearchEvidence[] = []; for (const reference of references) { resolved.push(await this.resolve(reference, database)); } return resolved; } const results = await verifyResearchSource(source, references, database, (id, query) => this.results.getRunResults(id, query) ); return references.map(reference => { const result = results.get(reference.runId); if (!result) { throw new Error('Verified source result is missing'); } return projectResearchEvidence(reference, result); }); } async resolve( input: ResearchEvidenceReference, database: BacktestResultQuery = this.database ): Promise { const reference = parseResearchInput(researchEvidenceReferenceSchema, input); const run = ( await database.query<{ id: string; backtest_id: string; status: string }>( 'SELECT id,backtest_id,status FROM runs WHERE id=$1', [reference.runId] ) ).rows[0]; if (!run || run.status !== 'completed') { throw new ResearchError(422, 'Evidence requires a completed retained run'); } let result; try { result = await this.results.getRunResults(reference.runId, database); } catch (cause) { // Validation here concerns retained storage, not the caller's valid reference. // Preserve the cause for server diagnostics without returning a false HTTP 400. throw new Error('Retained research result could not be read', { cause }); } if (!result || result.runId !== run.id || result.backtestId !== run.backtest_id) { throw new ResearchError( 422, 'Retained evidence result is missing or has a different identity' ); } return projectResearchEvidence(reference, result); } }