feat(paper): gate canonical execution on durable feed readiness

This commit is contained in:
Boki 2026-10-23 16:50:35 -04:00
parent c01e96e4dd
commit 75abae2cfc
24 changed files with 3720 additions and 66 deletions

View file

@ -0,0 +1,45 @@
import { asFunction, createContainer as createDiContainer } from 'awilix';
import { expect, test } from 'bun:test';
import type { ServiceCradle } from '@stock-bot/di';
import type { StockAppConfig } from '@stock-bot/stock-config';
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
import { createContainer } from '../../apps/stock/orchestrator/src/simple-container';
import { paperFeedConfiguration } from '../fixtures/paper-feed';
test('canonical paper rejects invalid role/configuration before resolving services', async () => {
let resolved = 0;
const container = createDiContainer<ServiceCradle>();
container.register({
serviceContainer: asFunction(() => {
resolved++;
throw new Error('Unexpected service resolution');
}),
});
const config = paperFeedConfiguration();
await expect(
registerOrchestratorServices(container, {
role: 'research-only',
canonicalPaper: config,
})
).rejects.toThrow('requires a paper composition');
config.matching.series[0]!.mode = 'Open';
await expect(
registerOrchestratorServices(container, {
canonicalPaper: config,
})
).rejects.toThrow('Quote execution only');
expect(resolved).toBe(0);
});
test('live defaults, research canonical configuration and missing custody fail before connections', async () => {
const config = (orchestrator: unknown) => ({ services: { orchestrator } }) as StockAppConfig;
await expect(createContainer(config({ defaultMode: 'live' }))).rejects.toThrow(
'Live trading is disabled'
);
await expect(
createContainer(config({ defaultMode: 'backtest', canonicalPaper: paperFeedConfiguration() }))
).rejects.toThrow('requires a paper composition');
await expect(
createContainer(config({ canonicalPaper: paperFeedConfiguration() }))
).rejects.toThrow('requires durable PostgreSQL');
});

View file

@ -0,0 +1,467 @@
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<CanonicalAccount, 'checkpoint' | 'observed' | 'latestObservations'> => ({
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<string>(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);
});
});

View file

@ -0,0 +1,377 @@
import { describe, expect, mock, test } from 'bun:test';
import { Hono } from 'hono';
import type { Server as SocketIOServer } from 'socket.io';
import { createHttpSecurity } from '@stock-bot/di';
import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper';
import {
PaperRuntimeError,
type PaperConfigurationInput,
type PaperConnection,
type PaperFrameInput,
type PaperReadiness,
type PaperRuntime,
} from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/repository';
import { createRoutes } from '../../apps/stock/orchestrator/src/routes/create-routes';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { paperFeedFrame } from '../fixtures/paper-feed';
const tokens = {
operator: 'paper-routes-admin-fixture-not-a-real-secret-1234',
service: 'paper-routes-service-fixture-not-a-real-secret-1234',
read: 'paper-routes-read-fixture-not-a-real-secret-1234',
};
type Role = keyof typeof tokens;
const connection = { sourceId: 'trusted-fixture', connectionId: 'connection-1' };
const readiness = (): PaperReadiness => ({
configured: true,
accountId: 'paper-account',
sourceId: 'trusted-fixture',
active: false,
ready: true,
operatorHalted: true,
connected: true,
reasons: [],
lastReceivedAt: 1000,
lastAvailableAt: 1000,
requiresHistoricalRecovery: false,
pendingInput: null,
pendingBatch: null,
pendingDecisionSequence: null,
nativeStatus: 'Running',
risk: { dailyHalted: false, drawdownHalted: false },
});
function runtimeFixture() {
return {
initialize: mock(async (_input: PaperConfigurationInput) => {}),
status: mock(async () => readiness()),
connect: mock(async (_input: PaperConnection) => readiness()),
disconnect: mock(async (_input: PaperConnection) => readiness()),
ingest: mock(async (_input: PaperFrameInput) => ({
duplicate: false,
disposition: 'admitted' as const,
readiness: readiness(),
})),
activate: mock(async (_input: { recoverPending: boolean }) => readiness()),
halt: mock(async (_reason: string) => readiness()),
shutdown: mock(async () => {}),
} satisfies PaperRuntime;
}
function fixture(runtime: PaperRuntime | null = runtimeFixture(), allRoutes = false) {
const logger = {
info: mock(() => {}),
warn: mock(() => {}),
debug: mock(() => {}),
error: mock(() => {}),
};
const legacy = {
submitOrder: mock(async () => {
throw new Error('Legacy submit must be unreachable');
}),
cancelOrder: mock(async () => {
throw new Error('Legacy cancel must be unreachable');
}),
getPositions: mock(async () => {
throw new Error('Legacy positions must be unreachable');
}),
getRecoveryStatus: mock(async () => {
throw new Error('Legacy recovery must be unreachable');
}),
on: mock(() => {}),
};
const services = {
logger,
custom: {
...(runtime ? { CanonicalPaperRuntime: runtime } : {}),
ExecutionService: legacy,
BacktestRunner: {},
ModeManager: { getCurrentMode: mock(() => 'live') },
},
} as unknown as OrchestratorServices;
const io = { on: mock(() => {}) };
const app = new Hono();
createHttpSecurity({
adminToken: tokens.operator,
serviceToken: tokens.service,
readToken: tokens.read,
environment: 'test',
}).mount(app);
if (allRoutes) {
app.route('/', createRoutes(services, io as unknown as SocketIOServer));
} else {
app.route('/api/paper', createPaperRoutes(services));
}
return {
app,
logger,
legacy,
io,
request(path: string, role?: Role, body?: unknown, headers?: Record<string, string>) {
return app.request(`/api/paper${path}`, {
method: body === undefined ? 'GET' : 'POST',
headers: {
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
'Content-Type': 'application/json',
...headers,
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
},
};
}
const mutations = [
{ path: '/activate', method: 'activate', body: {}, feed: false },
{ path: '/halt', method: 'halt', body: { reason: 'operator-request' }, feed: false },
{ path: '/feed/connect', method: 'connect', body: connection, feed: true },
{ path: '/feed/disconnect', method: 'disconnect', body: connection, feed: true },
{ path: '/feed/frames', method: 'ingest', body: paperFeedFrame(), feed: true },
] as const;
describe('canonical paper HTTP authorization', () => {
test('real security distinguishes operator, service producer, reader and anonymous callers', async () => {
for (const role of ['operator', 'service', 'read', undefined] as const) {
const runtime = runtimeFixture();
const f = fixture(runtime);
const response = await f.request('/readiness', role);
expect(response.status).toBe(role ? 200 : 401);
expect(runtime.status.mock.calls).toHaveLength(role ? 1 : 0);
for (const endpoint of mutations) {
const allowed = role === 'operator' || (role === 'service' && endpoint.feed);
const mutation = await f.request(endpoint.path, role, endpoint.body);
expect(mutation.status).toBe(allowed ? 200 : role ? 403 : 401);
expect(runtime[endpoint.method].mock.calls).toHaveLength(allowed ? 1 : 0);
}
}
});
test('caller actor headers, query strings and body fields cannot manufacture operator authority', async () => {
const runtime = runtimeFixture();
const f = fixture(runtime);
const forged = { 'X-Actor': 'operator', 'X-Principal': 'operator', 'X-Role': 'admin' };
for (const role of ['service', 'read', undefined] as const) {
const response = await f.request(
'/activate?principal=operator&actor=admin',
role,
{},
forged
);
expect(response.status).toBe(role ? 403 : 401);
}
expect((await f.request('/activate', 'operator', { actor: 'operator' }, forged)).status).toBe(
400
);
expect(runtime.activate.mock.calls).toHaveLength(0);
expect((await f.request('/feed/connect', undefined, connection, forged)).status).toBe(401);
expect(runtime.connect.mock.calls).toHaveLength(0);
});
});
describe('canonical paper HTTP input and readiness contracts', () => {
test('activation defaults to no historical recovery and accepts only the explicit strict option', async () => {
const runtime = runtimeFixture();
const f = fixture(runtime);
expect((await f.request('/activate', 'operator', {})).status).toBe(200);
expect((await f.request('/activate', 'operator', { recoverPending: true })).status).toBe(200);
expect(runtime.activate.mock.calls).toEqual([
[{ recoverPending: false }],
[{ recoverPending: true }],
]);
for (const body of [
{ recoverPending: 'true' },
{ recoverPending: true, resetCapital: true },
null,
[],
]) {
expect((await f.request('/activate', 'operator', body)).status).toBe(400);
}
const malformed = await f.app.request('/api/paper/activate', {
method: 'POST',
headers: { Authorization: `Bearer ${tokens.operator}` },
body: '{',
});
expect(malformed.status).toBe(400);
expect(runtime.activate.mock.calls).toHaveLength(2);
});
test('halt and feed endpoints pass only validated normalized arguments to the runtime', async () => {
const runtime = runtimeFixture();
const f = fixture(runtime);
expect((await f.request('/halt', 'operator', { reason: ' stop requested ' })).status).toBe(
200
);
expect(runtime.halt.mock.calls).toEqual([['stop requested']]);
for (const body of [{ reason: '' }, { reason: ' ' }, { reason: 'stop', resetRisk: true }]) {
expect((await f.request('/halt', 'operator', body)).status).toBe(400);
}
for (const path of ['/feed/connect', '/feed/disconnect']) {
expect((await f.request(path, 'service', connection)).status).toBe(200);
expect((await f.request(path, 'service', { sourceId: connection.sourceId })).status).toBe(
400
);
expect((await f.request(path, 'service', { ...connection, actor: 'operator' })).status).toBe(
400
);
}
expect(runtime.connect.mock.calls).toEqual([[connection]]);
expect(runtime.disconnect.mock.calls).toEqual([[connection]]);
const frame = paperFeedFrame();
const admitted = await f.request('/feed/frames', 'service', frame);
expect(admitted.status).toBe(200);
expect(await admitted.json()).toEqual({
duplicate: false,
disposition: 'admitted',
readiness: readiness(),
});
expect(runtime.ingest.mock.calls[0]![0].quotes[0]!.bid).toBe('10.00000000');
for (const body of [
{ ...frame, unexpected: true },
{ ...frame, quotes: [] },
{ ...frame, quotes: [{ ...frame.quotes[0], brokerOrderId: 'forbidden' }] },
{ ...frame, observations: [{ ...frame.observations[0], futureFeature: 'forbidden' }] },
]) {
expect((await f.request('/feed/frames', 'service', body)).status).toBe(400);
}
expect(runtime.ingest.mock.calls).toHaveLength(1);
expect(runtime.initialize.mock.calls).toHaveLength(0);
});
test('malformed quote and observation decimals return400 before runtime admission', async () => {
const runtime = runtimeFixture();
const f = fixture(runtime);
for (const malformed of ['bad', 'NaN', '1e5', '1.000000001']) {
const quote = paperFeedFrame();
quote.quotes[0]!.bid = malformed;
expect((await f.request('/feed/frames', 'service', quote)).status).toBe(400);
const observation = paperFeedFrame();
const body = {
...observation,
observations: [{ ...observation.observations[0], close: malformed }],
};
expect((await f.request('/feed/frames', 'service', body)).status).toBe(400);
}
expect(runtime.ingest.mock.calls).toHaveLength(0);
});
test('unconfigured readiness reports explicit unavailable state and never invents an account', async () => {
const f = fixture(null);
const response = await f.request('/readiness', 'read');
expect(response.status).toBe(200);
expect(response.headers.get('Cache-Control')).toBe('no-store');
expect(await response.json()).toEqual({
configured: false,
accountId: null,
sourceId: null,
active: false,
ready: false,
operatorHalted: true,
connected: false,
reasons: ['not-configured'],
lastReceivedAt: null,
lastAvailableAt: null,
requiresHistoricalRecovery: false,
pendingInput: null,
pendingBatch: null,
pendingDecisionSequence: null,
nativeStatus: null,
risk: null,
});
const activate = await f.request('/activate', 'operator', {});
expect(activate.status).toBe(409);
expect(await activate.json()).toMatchObject({ code: 'not-ready' });
});
test('configured readiness preserves recovery and risk diagnostics without claiming activation', async () => {
const runtime = runtimeFixture();
const blocked: PaperReadiness = {
...readiness(),
ready: false,
active: false,
connected: false,
reasons: ['disconnected', 'pending-financial-work'],
requiresHistoricalRecovery: true,
pendingInput: 'input-7',
pendingBatch: 'batch-3',
pendingDecisionSequence: 8,
risk: { dailyHalted: true, drawdownHalted: false },
};
runtime.status.mockImplementation(async () => blocked);
const response = await fixture(runtime).request('/readiness', 'read');
expect(response.status).toBe(200);
expect(await response.json()).toEqual(blocked);
expect(response.headers.get('Cache-Control')).toBe('no-store');
});
});
describe('canonical paper HTTP failure and legacy gateway isolation', () => {
test('typed validation/readiness/conflict failures keep their public status classification', async () => {
const runtime = runtimeFixture();
const f = fixture(runtime);
for (const [error, expectedStatus, code] of [
[new PaperRuntimeError('invalid-input', 'Invalid physical quote'), 400, 'invalid-input'],
[new PaperRuntimeError('not-ready', 'Feed disconnected'), 409, 'not-ready'],
[new PaperRuntimeError('conflict', 'Frame conflicts'), 409, 'conflict'],
[new ExecutionConflictError('Account conflicts'), 409, 'conflict'],
] as const) {
runtime.activate.mockImplementation(async () => {
throw error;
});
const response = await f.request('/activate', 'operator', {});
expect(response.status).toBe(expectedStatus);
expect(await response.json()).toEqual({ error: error.message, code });
}
expect(f.logger.error.mock.calls).toHaveLength(0);
});
test('runtime failures return503 and never leak internal database or transport details', async () => {
const runtime = runtimeFixture();
const f = fixture(runtime);
const failure = new Error('sensitive database driver details');
runtime.status.mockImplementation(async () => {
throw failure;
});
const failedStatus = await f.request('/readiness', 'read');
expect(failedStatus.status).toBe(503);
expect(await failedStatus.json()).toEqual({ error: 'Canonical paper runtime unavailable' });
for (const endpoint of mutations) {
runtime[endpoint.method].mockImplementation(async () => {
throw failure;
});
const response = await f.request(endpoint.path, 'operator', endpoint.body);
expect(response.status).toBe(503);
expect(await response.json()).toEqual({ error: 'Canonical paper runtime unavailable' });
expect(response.headers.get('Cache-Control')).toBe('no-store');
}
expect(f.logger.error.mock.calls).toHaveLength(6);
});
test('canonical createRoutes blocks legacy account REST paths and does not register legacy WebSocket handlers', async () => {
const runtime = runtimeFixture();
const f = fixture(runtime, true);
const headers = { Authorization: `Bearer ${tokens.operator}` };
for (const path of [
'/api/orders',
'/api/orders/order-1',
'/api/positions',
'/api/positions/X',
]) {
for (const method of ['GET', 'POST', 'DELETE']) {
const response = await f.app.request(path, { method, headers });
expect(response.status).toBe(409);
expect(await response.json()).toEqual({
error: 'Legacy account gateway unavailable in canonical paper mode',
});
}
}
const recovery = await f.app.request('/api/recovery', { headers });
expect(await recovery.json()).toEqual({ engine: 'canonical-paper', ...readiness() });
const health = await f.app.request('/health');
expect(await health.json()).toMatchObject({ mode: 'paper', execution: 'canonical-paper' });
expect(f.io.on.mock.calls).toHaveLength(0);
for (const call of Object.values(f.legacy)) {
expect(call.mock.calls).toHaveLength(0);
}
});
});