import { describe, expect, test } from 'bun:test'; import { stageFinancialTransaction } from '@stock-bot/engine'; import { parseFinancialDecimal } from '@stock-bot/types'; import { parseFinancialTransactionResult, type CanonicalMatchingCommand, } from '../../apps/stock/orchestrator/src/contracts/canonical-execution'; import { PaperRuntimeError, type PaperConfigurationInput, type PaperFrameInput, } from '../../apps/stock/orchestrator/src/contracts/paper-runtime'; import type { CanonicalAccount } from '../../apps/stock/orchestrator/src/execution/canonical-paper'; import { planPaperFrame, validatePaperConfiguration, validatePaperFrame, } from '../../apps/stock/orchestrator/src/paper/feed'; import { paperFeedConfiguration, paperFeedFrame } from '../fixtures/paper-feed'; function fixture(input = paperFeedConfiguration()) { const config = validatePaperConfiguration(input); const identity = { accountId: config.matching.risk.ledger.accountId, sessionId: config.matching.risk.ledger.sessionId, }; let native = parseFinancialTransactionResult( stageFinancialTransaction( JSON.stringify({ version: 1, kind: 'initialize', identity, config: config.matching }) ), identity ); const account = (): Pick => ({ checkpoint: native.checkpoint, observed: 0, latestObservations: [], }); return { config, identity, account, current: () => native, plan: (frame = paperFeedFrame()) => planPaperFrame(config, validatePaperFrame(config, frame, frame.availableAt), account()), apply(command: CanonicalMatchingCommand) { native = parseFinancialTransactionResult( stageFinancialTransaction( JSON.stringify({ version: 1, kind: 'apply', identity, checkpoint: native.checkpoint, command, }) ), identity ); expect(native.checkpoint.status).toBe('Running'); return native; }, }; } function invalidFrame( change: (frame: PaperFrameInput) => void, config = validatePaperConfiguration(paperFeedConfiguration()) ) { const frame = paperFeedFrame(); change(frame); expect(() => validatePaperFrame(config, frame, 1000)).toThrow(); } describe('trusted canonical paper feed policy', () => { test('malformed decimal wire values remain input failures rather than server errors', () => { const raw = paperFeedConfiguration(); raw.matching.risk.ledger.initialCapital = 'bad'; try { validatePaperConfiguration(raw); throw new Error('Malformed configuration was accepted'); } catch (error) { expect(error).toBeInstanceOf(PaperRuntimeError); expect((error as PaperRuntimeError).kind).toBe('invalid-input'); } const config = validatePaperConfiguration(paperFeedConfiguration()); const frame = paperFeedFrame(); frame.quotes[0]!.bid = 'bad'; try { validatePaperFrame(config, frame, 1000); throw new Error('Malformed frame was accepted'); } catch (error) { expect(error).toBeInstanceOf(PaperRuntimeError); expect((error as PaperRuntimeError).kind).toBe('invalid-input'); } }); test('binds immutable built-in cohorts, observations and calendars without mutating caller input', () => { const raw = paperFeedConfiguration(['Y', 'X']); const before = JSON.stringify(raw); const config = validatePaperConfiguration(raw); expect(JSON.stringify(raw)).toBe(before); expect(config.matching.series.map(series => series.instrumentId)).toEqual(['X', 'Y']); expect(config.strategies.map(strategy => strategy.strategyId)).toEqual([ 'sma_crossover', 'sma_crossover', ]); expect(config.matching.risk.ledger.ownerIds).toEqual(['owner-X', 'owner-Y']); const changes: ((raw: PaperConfigurationInput) => void)[] = [ value => { value.matching.series[0]!.mode = 'Open'; }, value => { value.matching.owners[0]!.mode = 'Orders'; }, value => { value.policy.cadence[0]!.ownerId = 'unknown'; }, value => { value.policy.cadence[0]!.seriesIds = ['unknown']; }, value => { value.strategies[0]!.instrumentId = 'unknown'; }, value => { value.policy.observations[0]!.instrumentId = 'unknown'; }, value => { value.matching.risk.ledger.ownerIds = []; }, value => { value.policy.calendars[0]!.instrumentId = 'unknown'; }, value => { value.policy.calendars[0]!.sessions.push({ sessionId: 'overlap', opensAt: 9000, closesAt: 12000, }); }, value => { value.policy.riskBoundaries.push({ ...value.matching.risk.ledger.riskSession, sessionId: 'risk-2', calendarRevision: 'other', startsAt: 2000, }); }, value => { value.matching.series.push({ ...value.matching.series[0]!, seriesId: 'other' }); }, ]; for (const change of changes) { const candidate = paperFeedConfiguration(); change(candidate); expect(() => validatePaperConfiguration(candidate)).toThrow(); } }); test('rejects unknown, future, unaligned, crossed, impossible and observation-only frames', () => { for (const change of [ (value: PaperFrameInput) => { value.sourceId = 'other'; }, (value: PaperFrameInput) => { value.availableAt = 1001; }, (value: PaperFrameInput) => { value.quotes = []; }, (value: PaperFrameInput) => { value.quotes[0]!.instrumentId = 'unknown'; }, (value: PaperFrameInput) => { value.quotes[0]!.seriesId = 'X:bar'; }, (value: PaperFrameInput) => { value.quotes[0]!.observedAt = 1001; }, (value: PaperFrameInput) => { value.quotes[0]!.bid = '11'; }, (value: PaperFrameInput) => { value.quotes[0]!.ask = '0'; }, (value: PaperFrameInput) => { value.quotes[0]!.bidSize = '-1'; }, (value: PaperFrameInput) => { value.observations[0]!.series_id = 'unknown'; }, (value: PaperFrameInput) => { value.observations[0]!.event_time = 999; }, (value: PaperFrameInput) => { value.observations[0]!.interval_start = 1; }, (value: PaperFrameInput) => { value.observations[0]!.interval_end = 999; }, (value: PaperFrameInput) => { value.observations[0]!.available_at = 999; }, (value: PaperFrameInput) => { value.observations[0]!.available_at = 1001; }, (value: PaperFrameInput) => { value.observations[0]!.high = parseFinancialDecimal('9'); }, (value: PaperFrameInput) => { value.observations[0]!.volume = parseFinancialDecimal('-1'); }, ]) { invalidFrame(change); } const config = validatePaperConfiguration(paperFeedConfiguration()); const exhausted = paperFeedFrame(10000); expect(() => validatePaperFrame(config, exhausted, 10000)).toThrow('session coverage'); const beforeOpen = paperFeedFrame(-1); beforeOpen.sequence = 0; beforeOpen.quotes[0]!.sourceSequence = 0; beforeOpen.observations = []; expect(() => validatePaperFrame(config, beforeOpen, 1000)).toThrow('session coverage'); }); test('retains real timestamps and deduplicates only identical physical observations', () => { const config = validatePaperConfiguration(paperFeedConfiguration()); const raw = paperFeedFrame(); raw.quotes[0]!.observedAt = 990; raw.observations.push(structuredClone(raw.observations[0]!)); const before = JSON.stringify(raw); const frame = validatePaperFrame(config, raw, 1000); expect(JSON.stringify(raw)).toBe(before); expect(frame.quotes[0]!.observedAt).toBe(990); expect(frame.observations).toHaveLength(1); raw.observations[1]!.close = parseFinancialDecimal('9'); raw.observations[1]!.low = parseFinancialDecimal('9'); expect(() => validatePaperFrame(config, raw, 1000)).toThrow('Conflicting physical'); raw.observations = []; raw.quotes.push({ ...raw.quotes[0]! }); expect(() => validatePaperFrame(config, raw, 1000)).toThrow('physical quote'); raw.quotes[1]!.observedAt = 991; expect(() => validatePaperFrame(config, raw, 1000)).toThrow('quote event key'); }); }); describe('paper frame deterministic native command planning', () => { test('one multi-asset decision follows every quote and cannot fill until the next physical quotes', () => { const f = fixture(paperFeedConfiguration(['Y', 'X'])); const frame = paperFeedFrame(1000, ['Y', 'X']); const plan = f.plan(frame); expect(plan.map(input => input.command.body.kind)).toEqual([ 'openSession', 'openSession', 'execute', 'execute', ]); expect(plan.filter(input => input.decision)).toHaveLength(1); expect(plan.slice(0, -1).every(input => !input.observations.length)).toBe(true); const barrier = plan.at(-1)!.decision!; expect(barrier.ownerIds).toEqual(['owner-X', 'owner-Y']); expect(barrier.key).toEqual(plan.at(-1)!.command.key); expect(barrier.key).toEqual({ at: 1000, phase: 'Execution', instrumentId: 'Y', sourceSequence: 1000, }); for (const input of plan) { f.apply(input.command); } expect(f.current().view.portfolio.positions).toHaveLength(0); f.apply({ commandId: barrier.commandId, key: barrier.key, body: { kind: 'submit', decisions: ['X', 'Y'].map(instrumentId => ({ version: 1, sessionId: f.identity.sessionId, barrierId: barrier.barrierId, revision: f.current().checkpoint.revision, decision: { ownerId: `owner-${instrumentId}`, decisionId: `decision-${instrumentId}`, sequence: 0, }, intent: { mode: 'target', targets: [{ instrumentId, quantity: parseFinancialDecimal('2') }], }, })), }, }); expect(f.current().view.portfolio.positions).toHaveLength(0); expect(f.current().checkpoint.orders).toHaveLength(2); const next = paperFeedFrame(1001, ['Y', 'X']); next.observations = []; const nextPlan = f.plan(next); expect(nextPlan.every(input => !input.decision)).toBe(true); for (const input of nextPlan) { f.apply(input.command); } expect(f.current().view.portfolio.positions.map(position => position.quantity)).toEqual([ parseFinancialDecimal('2'), parseFinancialDecimal('2'), ]); expect(f.current().view.portfolio.cash).toBe('959.60000000'); expect(f.current().view.portfolio.fees).toEqual([ { ownerId: 'owner-X', amount: parseFinancialDecimal('0.2') }, { ownerId: 'owner-Y', amount: parseFinancialDecimal('0.2') }, ]); }); test('quote identities survive frame/connection renaming and reject retimed reuse or backwards physical time', () => { const f = fixture(); const first = f.plan(); const renamed = paperFeedFrame(); renamed.id = 'renamed'; renamed.connectionId = 'reconnected'; renamed.sequence = 9; expect(f.plan(renamed).at(-1)!.command.commandId).toBe(first.at(-1)!.command.commandId); for (const input of first) { f.apply(input.command); } const reused = paperFeedFrame(1001); reused.observations = []; reused.quotes[0]!.observedAt = 1000; reused.quotes[0]!.sourceSequence = 1000; expect(() => f.plan(reused)).toThrow('physical quote liquidity'); reused.quotes[0]!.sourceSequence = 1001; reused.quotes[0]!.observedAt = 999; expect(() => f.plan(reused)).toThrow('regresses'); reused.quotes[0]!.sourceSequence = 0; reused.quotes[0]!.observedAt = 1001; expect(f.plan(reused).at(-1)!.command.key.sourceSequence).toBe(0); }); test('a newly published auxiliary series neither creates liquidity nor wakes unrelated cadence owners', () => { const raw = paperFeedConfiguration(['X', 'Y']); raw.policy.observations.push({ seriesId: 'X:aux', instrumentId: 'X', intervalMs: 1000, staleAfterMs: 50, }); const f = fixture(raw); const frame = paperFeedFrame(1000, ['X', 'Y']); frame.observations = [{ ...frame.observations[0]!, series_id: 'X:aux' }]; const auxiliary = f.plan(frame); expect(auxiliary.filter(input => input.command.body.kind === 'execute')).toHaveLength(2); expect(auxiliary.filter(input => input.decision)).toHaveLength(0); frame.observations.push(paperFeedFrame().observations[0]!); const due = f.plan(frame).at(-1)!; expect(due.decision!.ownerIds).toEqual(['owner-X']); expect(due.decision!.inputs.find(input => input.series_id === 'Y:bar')!.availability).toBe( 'Missing' ); expect(due.decision!.inputs.find(input => input.series_id === 'X:aux')!.availability).toEqual({ Fresh: { event_time: 1000, available_at: 1000 }, }); }); test('accepts session-clipped complete bars and emits declared close/risk/open boundaries in native order', () => { const raw = paperFeedConfiguration(); raw.policy.calendars[0]!.sessions = [ { sessionId: 'half-day', opensAt: 0, closesAt: 1500 }, { sessionId: 'next-day', opensAt: 2000, closesAt: 3500 }, ]; raw.policy.riskBoundaries = [ { ...raw.matching.risk.ledger.riskSession, sessionId: 'risk-2', startsAt: 2000 }, ]; raw.policy.observations[0]!.staleAfterMs = 500; const f = fixture(raw); for (const input of f.plan()) { f.apply(input.command); } const frame = paperFeedFrame(2100); frame.observations[0] = { ...frame.observations[0]!, interval_start: 1000, interval_end: 1500, event_time: 1500, available_at: 2100, }; const plan = f.plan(frame); expect( plan.map(input => [ input.command.body.kind, input.command.key.at, input.command.key.sourceSequence, ]) ).toEqual([ ['closeSession', 1500, 0], ['riskSessionBoundary', 2000, 1], ['openSession', 2000, 2], ['execute', 2100, 2100], ]); expect(plan.at(-1)!.decision!.inputs[0]!.availability).toEqual({ Stale: { event_time: 1500, available_at: 2100 }, }); for (const input of plan) { f.apply(input.command); } expect(f.current().checkpoint.sessions).toEqual([ ['X', { sessionId: 'next-day', opensAt: 2000, closesAt: 3500 }], ]); const daily = structuredClone(raw); daily.policy.observations[0]!.intervalMs = 86400000; frame.observations[0]!.interval_start = 0; expect( validatePaperFrame(validatePaperConfiguration(daily), frame, 2100).observations[0]! .interval_end ).toBe(1500); frame.quotes[0]!.observedAt = 1499; expect(() => validatePaperFrame(f.config, frame, 2100)).toThrow('identity, time'); }); test('keeps newly available older observations, while unchanged latest does not create decisions', () => { const f = fixture(); const newest = validatePaperFrame(f.config, paperFeedFrame(2000), 2000).observations[0]!; const account = { ...f.account(), latestObservations: [newest], observed: 1 }; const delayed = paperFeedFrame(3000); delayed.observations = [{ ...paperFeedFrame().observations[0]!, available_at: 3000 }]; const before = JSON.stringify(account); const plan = planPaperFrame(f.config, validatePaperFrame(f.config, delayed, 3000), account); expect(plan.at(-1)!.observations[0]!.event_time).toBe(1000); expect(plan.at(-1)!.decision!.inputs[0]!.availability).toEqual({ Fresh: { event_time: 2000, available_at: 2000 }, }); expect(JSON.stringify(account)).toBe(before); delayed.observations = [newest]; expect( planPaperFrame(f.config, validatePaperFrame(f.config, delayed, 3000), account).at(-1)! .decision ).toBeUndefined(); delayed.observations = [{ ...newest, volume: parseFinancialDecimal('101') }]; expect(() => planPaperFrame(f.config, validatePaperFrame(f.config, delayed, 3000), account) ).toThrow('retained identity'); }); test('atomic plan keys and physical sequence order are deterministic and fail closed behind the cursor', () => { const f = fixture(); const frame = paperFeedFrame(); frame.quotes.push({ ...frame.quotes[0]!, observedAt: 999, sourceSequence: 999 }); expect( f .plan(frame) .filter(input => input.command.body.kind === 'execute') .map(input => input.command.key.sourceSequence) ).toEqual([999, 1000]); frame.quotes[1]!.observedAt = 1000; frame.quotes[0]!.observedAt = 999; expect(() => f.plan(frame)).toThrow('reverses'); for (const input of f.plan()) { f.apply(input.command); } const behind = paperFeedFrame(999); behind.observations = []; behind.quotes[0]!.observedAt = 999; expect(() => f.plan(behind)).toThrow(); const snapshot = f.account(); snapshot.checkpoint.status = 'Complete'; expect(() => planPaperFrame(f.config, validatePaperFrame(f.config, paperFeedFrame(2000), 2000), snapshot) ).toThrow(PaperRuntimeError); }); });