import { describe, expect, test } from 'bun:test'; import { parseCanonicalRunResult } from '@stock-bot/research/results'; import { parseFinancialDecimal } from '@stock-bot/types'; import { canonicalResultFixture } from '../fixtures/canonical-result'; describe('shared complete canonical result contract', () => { test('preserves the original native payload, exact money and unavailable analytics', () => { const value = canonicalResultFixture(); const before = JSON.stringify(value); const parsed = parseCanonicalRunResult(value, value.runId); expect(parsed).toBe(value); expect(JSON.stringify(value)).toBe(before); expect(parsed.financial.projection.valuation.equity).toBe('9969.30000000'); expect(parsed.financial.projection.valuation.fees).toBe('0.70000000'); expect(parsed.financial.projection.fills).toHaveLength(2); expect(parsed.analytics.metrics.roundTripCount).toBeNull(); expect(parsed.analytics.unavailable.roundTripCount).toBe('unsupported-round-trips'); }); test('rejects foreign identities, native policies and inconsistent statistical evidence', () => { const value = canonicalResultFixture(); const other = '11111111-1111-4111-8111-111111111111'; const mutations: ((copy: typeof value) => void)[] = [ copy => { copy.runId = other; }, copy => { copy.backtestId = other; }, copy => { copy.request.runId = other; }, copy => { copy.request.backtestId = other; }, copy => { copy.strategyExecution = 'typescript-isolated-candidate/v1'; }, copy => { copy.completedAt = 'not-a-date'; }, copy => { copy.executionTime = -1; }, copy => { copy.financial.identity.sessionId = other; }, copy => { copy.financial.identity.datasetHash = 'f'.repeat(64); }, copy => { copy.financial.policy.matching.risk.feeRate = parseFinancialDecimal('0.02'); }, copy => { copy.analytics.metrics.totalReturn = 99; }, copy => { copy.analytics.fillCount++; }, copy => { copy.analytics.unavailable.roundTripCount = 'insufficient-periods'; }, ]; for (const mutate of mutations) { const copy = structuredClone(value); mutate(copy); expect(() => parseCanonicalRunResult(copy, value.runId)).toThrow(); } expect(() => parseCanonicalRunResult(value, other)).toThrow(); for (const input of [ null, {}, { ...value, kind: 'legacy' }, { ...value, financialEngine: 'native' }, { ...value, status: 'failed' }, ]) { expect(() => parseCanonicalRunResult(input, value.runId)).toThrow(); } }); });