feat(research): cut over canonical runtime and enforce agent budgets
This commit is contained in:
parent
ab08db82fd
commit
bbf0dd4453
103 changed files with 6138 additions and 3112 deletions
123
test/integration/async-strategy-replay.test.ts
Normal file
123
test/integration/async-strategy-replay.test.ts
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import {
|
||||
NativeReplaySession,
|
||||
prepareReplayLoad,
|
||||
runReplaySessionAsync,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
||||
import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
||||
import type { ReplayResultFormat } from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
import { StrategyController } from '../../apps/stock/orchestrator/src/strategies/strategy-controller';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
function setup() {
|
||||
const fixture = nativeReplayFixture(8, 1, ['A', 'B']);
|
||||
const load = prepareReplayLoad(fixture.dataset, fixture.config);
|
||||
const programs: StrategyProgram<number>[] = ['A', 'B'].map(ownerId => ({
|
||||
ownerId,
|
||||
strategyId: 'async-parity',
|
||||
strategyVersion: '1',
|
||||
mode: 'target',
|
||||
seed: ownerId === 'A' ? 12 : 34,
|
||||
initialState: 0,
|
||||
decide(context) {
|
||||
expect(context.observations.every(bar => bar.available_at <= context.now)).toBe(true);
|
||||
expect(context.positions.every(position => position.ownerId === ownerId)).toBe(true);
|
||||
expect(context.previousAdmission?.decision.ownerId ?? ownerId).toBe(ownerId);
|
||||
return {
|
||||
nextState: context.state + 1,
|
||||
intent: {
|
||||
mode: 'target',
|
||||
targets: [
|
||||
{
|
||||
instrumentId: 'X0.US',
|
||||
quantity: parseFinancialDecimal(context.random() > 0.5 ? '1' : '0'),
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
},
|
||||
}));
|
||||
const controller = new StrategyController(load.identity, programs, load.config);
|
||||
return { load, programs, controller };
|
||||
}
|
||||
|
||||
for (const resultFormat of ['trace', 'projection', 'report'] satisfies ReplayResultFormat[]) {
|
||||
test(`async controller preserves synchronous ${resultFormat} economics, state and admission order`, async () => {
|
||||
const { load, programs, controller } = setup();
|
||||
const synchronous = runStrategyReplay(load, programs, { resultFormat, eventBudget: 1 });
|
||||
const phases: string[] = [];
|
||||
const asynchronous = await runReplaySessionAsync(
|
||||
new NativeReplaySession(load),
|
||||
{
|
||||
async stage(context, observations) {
|
||||
phases.push('stage');
|
||||
await Promise.resolve();
|
||||
expect(Object.isFrozen(context.view)).toBe(true);
|
||||
expect(Object.isFrozen(observations)).toBe(true);
|
||||
return controller.stage(context, observations);
|
||||
},
|
||||
async committed(outcome) {
|
||||
phases.push('commit');
|
||||
await Promise.resolve();
|
||||
controller.committed(outcome);
|
||||
},
|
||||
},
|
||||
{ resultFormat, eventBudget: 256 }
|
||||
);
|
||||
expect(asynchronous.result).toEqual(synchronous.result);
|
||||
expect(controller.snapshot()).toEqual(synchronous.diagnostics);
|
||||
expect(phases).toEqual(Array.from({ length: 7 }, () => ['stage', 'commit']).flat());
|
||||
expect(asynchronous.metrics.submitCalls).toBe(synchronous.metrics.submitCalls);
|
||||
});
|
||||
}
|
||||
|
||||
for (const phase of ['stage', 'commit'] as const) {
|
||||
test(`async ${phase} rejection disposes the native session and preserves only acknowledged diagnostics`, async () => {
|
||||
const { load, controller } = setup();
|
||||
const session = new NativeReplaySession(load);
|
||||
const dispose = session.dispose.bind(session);
|
||||
let disposals = 0;
|
||||
session.dispose = () => {
|
||||
disposals++;
|
||||
dispose();
|
||||
};
|
||||
await expect(
|
||||
runReplaySessionAsync(session, {
|
||||
async stage(context, observations) {
|
||||
await Promise.resolve();
|
||||
if (phase === 'stage') {
|
||||
throw new Error('isolated stage lost');
|
||||
}
|
||||
return controller.stage(context, observations);
|
||||
},
|
||||
async committed() {
|
||||
await Promise.resolve();
|
||||
throw new Error('isolated commit lost');
|
||||
},
|
||||
})
|
||||
).rejects.toThrow(`isolated ${phase} lost`);
|
||||
expect(disposals).toBe(1);
|
||||
expect(controller.snapshot().committedBarriers).toBe(0);
|
||||
expect(() => session.advance(1)).toThrow();
|
||||
});
|
||||
}
|
||||
|
||||
test('async malformed financial decisions fail before an acknowledgement and still dispose', async () => {
|
||||
const { load } = setup();
|
||||
const session = new NativeReplaySession(load);
|
||||
let acknowledged = false;
|
||||
await expect(
|
||||
runReplaySessionAsync(session, {
|
||||
async stage() {
|
||||
return [{ intent: { mode: 'target', targets: [] } }] as never;
|
||||
},
|
||||
async committed() {
|
||||
acknowledged = true;
|
||||
},
|
||||
})
|
||||
).rejects.toThrow();
|
||||
expect(acknowledged).toBe(false);
|
||||
expect(() => session.advance(1)).toThrow();
|
||||
});
|
||||
|
|
@ -45,6 +45,13 @@ const timers = new Map<
|
|||
{ at: number; delay: number; callback: () => void; repeat: boolean }
|
||||
>();
|
||||
|
||||
function submittedBody(request: { body?: string }): string {
|
||||
if (typeof request.body !== 'string') {
|
||||
throw new Error('Submission body is missing');
|
||||
}
|
||||
return request.body;
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason: Error) => void;
|
||||
|
|
@ -68,7 +75,9 @@ function request(path: string, method = 'GET') {
|
|||
const found = requests.find(
|
||||
item => item.path === path && item.method === method && !item.settled
|
||||
);
|
||||
if (!found) throw new Error(`No pending ${method} ${path}`);
|
||||
if (!found) {
|
||||
throw new Error(`No pending ${method} ${path}`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function reply(pending: Request, body: unknown, status = 200) {
|
||||
|
|
@ -115,18 +124,21 @@ const results = (id: string): RunResult => ({
|
|||
winRate: 0,
|
||||
totalTrades: 0,
|
||||
profitFactor: null,
|
||||
avgWin: 0,
|
||||
avgLoss: 0,
|
||||
},
|
||||
equity: [],
|
||||
ohlcData: {},
|
||||
positions: [],
|
||||
trades: [],
|
||||
analytics: {},
|
||||
analytics: { exposureTime: null },
|
||||
executionTime: 0,
|
||||
});
|
||||
const definition = {
|
||||
id: 'definition',
|
||||
name: 'Fixture',
|
||||
strategy: 'sma',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: 'version-one',
|
||||
symbols: ['A.US'],
|
||||
startDate: '2024-01-01',
|
||||
endDate: '2024-02-01',
|
||||
|
|
@ -174,9 +186,13 @@ async function advance(ms: number) {
|
|||
const due = [...timers].filter(([, timer]) => timer.at <= now);
|
||||
await flush(() => {
|
||||
for (const [id, timer] of due) {
|
||||
if (!timers.has(id)) continue;
|
||||
if (!timers.has(id)) {
|
||||
continue;
|
||||
}
|
||||
timers.delete(id);
|
||||
if (timer.repeat) timers.set(id, { ...timer, at: now + timer.delay });
|
||||
if (timer.repeat) {
|
||||
timers.set(id, { ...timer, at: now + timer.delay });
|
||||
}
|
||||
timer.callback();
|
||||
}
|
||||
});
|
||||
|
|
@ -187,7 +203,9 @@ function click(label: string) {
|
|||
const button =
|
||||
buttons.find(item => item.textContent?.trim() === label) ??
|
||||
buttons.find(item => item.getAttribute('aria-label') === label);
|
||||
if (!button) throw new Error(`Missing button ${label}`);
|
||||
if (!button) {
|
||||
throw new Error(`Missing button ${label}`);
|
||||
}
|
||||
button.click();
|
||||
}
|
||||
function HookHost({ socket = false }: { socket?: boolean }) {
|
||||
|
|
@ -196,7 +214,9 @@ function HookHost({ socket = false }: { socket?: boolean }) {
|
|||
useWebSocket({
|
||||
runId: socket ? (latest.currentRun?.id ?? null) : null,
|
||||
onMessage: message => {
|
||||
if (message.type !== 'pong') void latest.refreshRun(message.runId);
|
||||
if (message.type !== 'pong') {
|
||||
void latest.refreshRun(message.runId);
|
||||
}
|
||||
},
|
||||
});
|
||||
return latest.currentRun
|
||||
|
|
@ -210,7 +230,13 @@ function HookHost({ socket = false }: { socket?: boolean }) {
|
|||
}
|
||||
async function mount(element: ReactElement = createElement(HookHost)) {
|
||||
root = createRoot(host);
|
||||
await flush(() => root!.render(element));
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
element.type === CreateBacktestDialog
|
||||
? createElement(router.MemoryRouter, null, element)
|
||||
: element
|
||||
)
|
||||
);
|
||||
}
|
||||
async function select(id: string) {
|
||||
await flush(() => {
|
||||
|
|
@ -260,8 +286,9 @@ beforeAll(async () => {
|
|||
WebSocket: TestSocket,
|
||||
ResizeObserver: browser.ResizeObserver,
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
}))
|
||||
})) {
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
({ createRoot } = await import('react-dom/client'));
|
||||
({ useBacktestV2 } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2'
|
||||
|
|
@ -291,6 +318,9 @@ beforeEach(() => {
|
|||
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
||||
browser.document.body.append(host as never);
|
||||
browser.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
if (new URL(String(input)).pathname.endsWith('/canonical-capability')) {
|
||||
return Promise.resolve(Response.json({ available: true, reason: null }));
|
||||
}
|
||||
const pending: Request = {
|
||||
...deferred<Response>(),
|
||||
path: new URL(String(input)).pathname,
|
||||
|
|
@ -304,10 +334,12 @@ beforeEach(() => {
|
|||
requests.push(pending);
|
||||
// Deliberately ignore abort: guards must also reject a late server continuation.
|
||||
return pending.promise;
|
||||
}) as typeof browser.fetch;
|
||||
}) as unknown as typeof browser.fetch;
|
||||
const schedule = (repeat: boolean, original: typeof setTimeout) =>
|
||||
((callback: () => void, delay?: number, ...args: unknown[]) => {
|
||||
if (![1000, 3000, 30000].includes(delay ?? 0)) return original(callback, delay, ...args);
|
||||
if (![1000, 3000, 30000].includes(delay ?? 0)) {
|
||||
return original(callback, delay, ...args);
|
||||
}
|
||||
const id = ++timerId;
|
||||
timers.set(id, { at: now + delay!, delay: delay!, callback, repeat });
|
||||
return id;
|
||||
|
|
@ -315,16 +347,22 @@ beforeEach(() => {
|
|||
globalThis.setTimeout = schedule(false, realTimeout);
|
||||
globalThis.setInterval = schedule(true, realInterval as typeof setTimeout) as typeof setInterval;
|
||||
globalThis.clearTimeout = ((id: number) => {
|
||||
if (!timers.delete(id)) realClearTimeout(id);
|
||||
if (!timers.delete(id)) {
|
||||
realClearTimeout(id);
|
||||
}
|
||||
}) as typeof clearTimeout;
|
||||
globalThis.clearInterval = ((id: number) => {
|
||||
if (!timers.delete(id)) realClearInterval(id);
|
||||
if (!timers.delete(id)) {
|
||||
realClearInterval(id);
|
||||
}
|
||||
}) as typeof clearInterval;
|
||||
});
|
||||
afterEach(async () => {
|
||||
let leakedTimers = 0;
|
||||
try {
|
||||
if (root) await flush(() => root!.unmount());
|
||||
if (root) {
|
||||
await flush(() => root!.unmount());
|
||||
}
|
||||
leakedTimers = timers.size;
|
||||
} finally {
|
||||
root = undefined;
|
||||
|
|
@ -343,8 +381,11 @@ afterAll(async () => {
|
|||
} finally {
|
||||
for (const key of globals) {
|
||||
const descriptor = savedGlobals.get(key);
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
if (descriptor) {
|
||||
Object.defineProperty(globalThis, key, descriptor);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
@ -607,6 +648,45 @@ describe('actual detail page result states', () => {
|
|||
});
|
||||
|
||||
async function nameBacktest() {
|
||||
const family = { id: 'family', name: 'Test strategy', archived: false };
|
||||
const version = {
|
||||
id: 'version-one',
|
||||
strategyId: 'family',
|
||||
ordinal: 1,
|
||||
origin: 'builtin',
|
||||
package: {
|
||||
parameterSchema: {
|
||||
type: 'object',
|
||||
properties: {},
|
||||
required: [],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
await flush(() => reply(request('/api/v2/strategies'), { strategies: [family] }));
|
||||
const choose = (label: string, value: string) => {
|
||||
const select = host.querySelector(`select[aria-label="${label}"]`)!;
|
||||
Object.getOwnPropertyDescriptor(browser.HTMLSelectElement.prototype, 'value')!.set!.call(
|
||||
select,
|
||||
value
|
||||
);
|
||||
select.dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event);
|
||||
};
|
||||
await flush(() => choose('Strategy family', 'family'));
|
||||
await flush(() => reply(request('/api/v2/strategies/family/versions'), { versions: [version] }));
|
||||
await flush(() => choose('Immutable strategy version', 'version-one'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one'), { version, reviews: [] })
|
||||
);
|
||||
await flush(() => reply(request('/api/v2/strategies/family'), { strategy: family }));
|
||||
await flush(() => click('Validate parameters'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), {
|
||||
parameters: {},
|
||||
runnable: false,
|
||||
reason: 'Configure canonical settings',
|
||||
})
|
||||
);
|
||||
await flush(() => {
|
||||
const input = host.querySelector('input[placeholder="My Strategy Backtest"]')!;
|
||||
Object.getOwnPropertyDescriptor(browser.HTMLInputElement.prototype, 'value')!.set!.call(
|
||||
|
|
@ -643,175 +723,109 @@ describe('explicit save and repeat-safe run submission', () => {
|
|||
});
|
||||
const saving = request('/api/v2/backtests', 'POST');
|
||||
expect(JSON.parse(saving.body!).autoStart).toBe(false);
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'POST')
|
||||
).toHaveLength(1);
|
||||
await flush(() => reply(saving, definition));
|
||||
expect(created).toEqual([definition]);
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
expect(
|
||||
requests.filter(item => item.path.endsWith('/runs') && item.method === 'POST')
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
for (const failure of ['rejection', 'lost successful response'] as const) {
|
||||
test(`save_and_run_failure: ${failure} retries the saved definition, frozen body and key`, async () => {
|
||||
const created: { definition: Backtest; run?: Run }[] = [];
|
||||
await mount(
|
||||
createElement(CreateBacktestDialog, {
|
||||
onClose: () => {},
|
||||
onCreated: (value, submitted) => created.push({ definition: value, run: submitted }),
|
||||
})
|
||||
);
|
||||
await nameBacktest();
|
||||
await flush(() => {
|
||||
click('Save and run');
|
||||
click('Save and run');
|
||||
});
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
const first = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(first.headers.get('Idempotency-Key')).toBeTruthy();
|
||||
expect(JSON.parse(first.body!)).toEqual({ speedMultiplier: null });
|
||||
// In the lost-response case the server has accepted A; the transport fails.
|
||||
await flush(() =>
|
||||
failure === 'rejection'
|
||||
? reply(first, { error: 'Submission unavailable' }, 503)
|
||||
: fail(first)
|
||||
);
|
||||
expect(created).toHaveLength(0);
|
||||
expect(host.textContent).toContain('Backtest saved, but run submission failed');
|
||||
expect(host.querySelector('fieldset')!.disabled).toBe(true);
|
||||
await flush(() => {
|
||||
click('Retry submission');
|
||||
click('Retry submission');
|
||||
});
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(retry.body).toBe(first.body);
|
||||
expect(requests.filter(item => item.path === '/api/v2/backtests')).toHaveLength(1);
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(3);
|
||||
await flush(() => reply(retry, run('A', 'pending'), 202));
|
||||
expect(created).toEqual([{ definition, run: run('A', 'pending') }]);
|
||||
});
|
||||
}
|
||||
test('new dialog cannot submit legacy or unconfigured execution', async () => {
|
||||
await mount(createElement(CreateBacktestDialog, { onClose: () => {}, onCreated: () => {} }));
|
||||
expect(host.querySelector('[aria-label="Strategy mode"]')).toBeNull();
|
||||
await nameBacktest();
|
||||
await flush(() => click('Save and run'));
|
||||
expect(requests.some(item => item.path === '/api/v2/backtests' && item.method === 'POST')).toBe(
|
||||
false
|
||||
);
|
||||
expect(host.textContent).toContain('financial policies before running');
|
||||
});
|
||||
|
||||
for (const boundary of ['definition', 'submission'] as const) {
|
||||
test(`dialog unmount during ${boundary} ignores late completion and navigation`, async () => {
|
||||
let navigated = false;
|
||||
await mount(
|
||||
createElement(CreateBacktestDialog, {
|
||||
onClose: () => {},
|
||||
onCreated: () => {
|
||||
navigated = true;
|
||||
},
|
||||
})
|
||||
);
|
||||
await nameBacktest();
|
||||
await flush(() => click('Save and run'));
|
||||
if (boundary === 'submission') {
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
}
|
||||
await flush(() => root!.unmount());
|
||||
root = undefined;
|
||||
await flush(() =>
|
||||
reply(
|
||||
request(
|
||||
boundary === 'definition' ? '/api/v2/backtests' : '/api/v2/backtests/definition/runs',
|
||||
'POST'
|
||||
),
|
||||
boundary === 'definition' ? definition : run('A')
|
||||
)
|
||||
);
|
||||
expect(navigated).toBe(false);
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(
|
||||
boundary === 'definition' ? 1 : 2
|
||||
);
|
||||
});
|
||||
}
|
||||
test('dialog unmount during save ignores late completion and navigation', async () => {
|
||||
let navigated = false;
|
||||
await mount(
|
||||
createElement(CreateBacktestDialog, {
|
||||
onClose: () => {},
|
||||
onCreated: () => {
|
||||
navigated = true;
|
||||
},
|
||||
})
|
||||
);
|
||||
await nameBacktest();
|
||||
await flush(() => click('Save'));
|
||||
await flush(() => root!.unmount());
|
||||
root = undefined;
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
expect(navigated).toBe(false);
|
||||
expect(requests.some(item => item.path.endsWith('/runs') && item.method === 'POST')).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test('closing cannot race the definition write and refresh a list before the row exists', async () => {
|
||||
await mount(createElement(router.MemoryRouter, null, createElement(BacktestListPageV2)));
|
||||
test('save rejects double clicks and close while pending, then navigates to configure', async () => {
|
||||
await mount(
|
||||
createElement(
|
||||
router.MemoryRouter,
|
||||
{ initialEntries: ['/backtests'] },
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/backtests',
|
||||
element: createElement(BacktestListPageV2),
|
||||
}),
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id',
|
||||
element: createElement('p', null, 'Saved definition'),
|
||||
})
|
||||
),
|
||||
createElement(LocationProbe)
|
||||
)
|
||||
);
|
||||
await flush(() => reply(request('/api/v2/backtests'), []));
|
||||
await flush(() => click('New Backtest'));
|
||||
await nameBacktest();
|
||||
// The ref guard must work before the disabled state has rendered.
|
||||
await flush(() => {
|
||||
click('Save and run');
|
||||
click('Save');
|
||||
click('Save');
|
||||
click('Close backtest dialog');
|
||||
click('Close');
|
||||
});
|
||||
expect(host.querySelector('[aria-label="Close backtest dialog"]')).not.toBeNull();
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET')
|
||||
).toHaveLength(1);
|
||||
await flush(() => click('Close'));
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET')
|
||||
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'POST')
|
||||
).toHaveLength(1);
|
||||
expect(pageLocation).toBe('/backtests');
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
const submitting = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
await flush(() => click('Close'));
|
||||
await flush(() => reply(request('/api/v2/backtests'), [definition]));
|
||||
await flush(() => reply(submitting, run('A', 'pending'), 202));
|
||||
expect(host.textContent).toContain('Create and manage backtest configurations');
|
||||
expect(host.querySelector('[aria-label="Close backtest dialog"]')).toBeNull();
|
||||
expect(pageLocation).toBe('/backtests/definition');
|
||||
expect(requests.some(item => item.path.endsWith('/runs') && item.method === 'POST')).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test('closing saved-but-failed dialog reloads the real list without navigating', async () => {
|
||||
await mount(createElement(router.MemoryRouter, null, createElement(BacktestListPageV2)));
|
||||
await flush(() => reply(request('/api/v2/backtests'), []));
|
||||
await flush(() => click('New Backtest'));
|
||||
await nameBacktest();
|
||||
await flush(() => click('Save and run'));
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
await flush(() => fail(request('/api/v2/backtests/definition/runs', 'POST')));
|
||||
await flush(() => click('Close'));
|
||||
await flush(() => reply(request('/api/v2/backtests'), [definition]));
|
||||
// Virtualized rows need real layout (W04). Here verify the refetch and that
|
||||
// the real list, not a detail route, remains mounted after closing.
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET')
|
||||
).toHaveLength(2);
|
||||
expect(host.textContent).toContain('Create and manage backtest configurations');
|
||||
expect(host.textContent).not.toContain('Retry submission');
|
||||
});
|
||||
|
||||
for (const intent of ['Save', 'Save and run'] as const) {
|
||||
test(`real list ${intent} navigates only after the requested operation succeeds`, async () => {
|
||||
await mount(
|
||||
createElement(
|
||||
router.MemoryRouter,
|
||||
{ initialEntries: ['/backtests'] },
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/backtests',
|
||||
element: createElement(BacktestListPageV2),
|
||||
}),
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id',
|
||||
element: createElement('p', null, 'Saved definition'),
|
||||
}),
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id/run/:runId',
|
||||
element: createElement('p', null, 'Submitted run'),
|
||||
})
|
||||
),
|
||||
createElement(LocationProbe)
|
||||
)
|
||||
);
|
||||
await flush(() => reply(request('/api/v2/backtests'), []));
|
||||
await flush(() => click('New Backtest'));
|
||||
await nameBacktest();
|
||||
await flush(() => click(intent));
|
||||
expect(pageLocation).toBe('/backtests');
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
if (intent === 'Save and run') {
|
||||
expect(pageLocation).toBe('/backtests');
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/backtests/definition/runs', 'POST'), run('A', 'pending'), 202)
|
||||
);
|
||||
}
|
||||
expect(pageLocation).toBe(
|
||||
`/backtests/definition${intent === 'Save and run' ? '/run/A' : ''}`
|
||||
);
|
||||
test('legacy template stays readable but never creates a new run', async () => {
|
||||
await mount();
|
||||
await flush(() => {
|
||||
void latest.loadBacktest('definition');
|
||||
});
|
||||
}
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/definition'), {
|
||||
...definition,
|
||||
strategy: 'sma',
|
||||
strategyVersionId: null,
|
||||
});
|
||||
reply(request('/api/v2/backtests/definition/runs'), []);
|
||||
});
|
||||
await flush(() => {
|
||||
void latest.createRun();
|
||||
});
|
||||
expect(latest.submissionError).toContain('Legacy execution is retired');
|
||||
expect(requests.some(item => item.method === 'POST')).toBe(false);
|
||||
expect(latest.backtest?.name).toBe('Fixture');
|
||||
});
|
||||
|
||||
test('closing new-run confirmation prevents late successful submission from navigating', async () => {
|
||||
await mountPage('failed');
|
||||
|
|
@ -852,7 +866,7 @@ describe('explicit save and repeat-safe run submission', () => {
|
|||
expect(host.textContent).toContain('Run failed: B failure');
|
||||
await flush(() => click('Retry submission'));
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.body).toBe(submitting.body);
|
||||
expect(submittedBody(retry)).toBe(submittedBody(submitting));
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(submitting.headers.get('Idempotency-Key'));
|
||||
});
|
||||
|
||||
|
|
@ -880,7 +894,7 @@ describe('explicit save and repeat-safe run submission', () => {
|
|||
void latest.createRun(9);
|
||||
});
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.body).toBe(first.body);
|
||||
expect(submittedBody(retry)).toBe(submittedBody(first));
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(retry, run('A', 'pending'), 202));
|
||||
expect(latest.runs.filter(item => item.id === 'A')).toHaveLength(1);
|
||||
|
|
@ -889,7 +903,7 @@ describe('explicit save and repeat-safe run submission', () => {
|
|||
});
|
||||
const next = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(next.headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(JSON.parse(next.body!)).toEqual({ speedMultiplier: 9 });
|
||||
expect(JSON.parse(next.body!)).toEqual({ speedMultiplier: null });
|
||||
await flush(() => reply(next, run('B', 'pending'), 202));
|
||||
expect(latest.runs.map(item => item.id)).toEqual(['B', 'A']);
|
||||
});
|
||||
|
|
@ -913,7 +927,7 @@ describe('explicit save and repeat-safe run submission', () => {
|
|||
await flush(() => click('Retry submission'));
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(retry.body).toBe(first.body);
|
||||
expect(submittedBody(retry)).toBe(submittedBody(first));
|
||||
});
|
||||
|
||||
for (const change of ['selection', 'backtest', 'unmount'] as const) {
|
||||
|
|
@ -1051,7 +1065,7 @@ describe('template archive and restore', () => {
|
|||
void latest.createRun(9);
|
||||
});
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.body).toBe(first.body);
|
||||
expect(submittedBody(retry)).toBe(submittedBody(first));
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(retry, run('A', 'completed'), 202));
|
||||
expect(latest.hasPendingSubmission).toBe(false);
|
||||
|
|
@ -1074,7 +1088,7 @@ describe('template archive and restore', () => {
|
|||
});
|
||||
const fresh = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(fresh.headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(JSON.parse(fresh.body!)).toEqual({ speedMultiplier: 9 });
|
||||
expect(JSON.parse(fresh.body!)).toEqual({ speedMultiplier: null });
|
||||
await flush(() => reply(fresh, run('B', 'pending'), 202));
|
||||
expect(latest.runResults).toBe(savedResults);
|
||||
});
|
||||
|
|
@ -1090,7 +1104,7 @@ describe('template archive and restore', () => {
|
|||
expect(button('Retry submission').disabled).toBe(false);
|
||||
await flush(() => click('Retry submission'));
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.body).toBe(first.body);
|
||||
expect(submittedBody(retry)).toBe(submittedBody(first));
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(retry, run('A', 'running'), 202));
|
||||
expect(button('Run current settings').disabled).toBe(true);
|
||||
|
|
@ -1132,6 +1146,9 @@ describe('template archive and restore', () => {
|
|||
409
|
||||
)
|
||||
);
|
||||
if (typeof failure !== 'string') {
|
||||
throw new Error('Expected a retained-history refusal');
|
||||
}
|
||||
expect(failure).toContain('Archive it');
|
||||
expect(latest.error).toBe(failure);
|
||||
expect(latest.backtest?.id).toBe('definition');
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,201 +1,10 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type { HistoricalDatasetV2 } from '@stock-bot/types';
|
||||
import { builtinCatalogDescriptors } from '../../apps/stock/config/src/contracts/strategy';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import {
|
||||
BacktestCancelledError,
|
||||
type BacktestExecutionEngine,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import {
|
||||
BacktestLeaseLostError,
|
||||
type BacktestRunRepository,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
|
||||
const logger = { error() {} };
|
||||
function setup() {
|
||||
const versionId = randomUUID(),
|
||||
runId = randomUUID(),
|
||||
ownerId = `strategy:${versionId}`;
|
||||
const { dataset, config, selections } = canonicalSmaFixture([ownerId]);
|
||||
config.matching.risk.ledger.sessionId = runId;
|
||||
config.matching.risk.ledger.accountId = `research:${runId}`;
|
||||
const descriptor = builtinCatalogDescriptors.find(d => d.program.strategyId === 'sma_crossover')!;
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId,
|
||||
backtestId: randomUUID(),
|
||||
name: 'Runner boundary',
|
||||
strategy: {
|
||||
familyId: randomUUID(),
|
||||
versionId,
|
||||
origin: 'builtin',
|
||||
reviewId: randomUUID(),
|
||||
selection: selections[0],
|
||||
package: {
|
||||
version: 1,
|
||||
program: descriptor.program,
|
||||
parameterSchema: descriptor.parameterSchema,
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: descriptor.entryExport,
|
||||
content: 'not executed by this lifecycle fixture',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) },
|
||||
source: { revision: 'c'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: 'fixture', target: 'browser' },
|
||||
},
|
||||
},
|
||||
datasetHash: dataset.manifest.hash,
|
||||
policy: config,
|
||||
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
||||
modelArtifacts: [],
|
||||
build: {
|
||||
version: 1,
|
||||
workerSha256: 'd'.repeat(64),
|
||||
engineWrapperSha256: 'e'.repeat(64),
|
||||
engineBinarySha256: 'f'.repeat(64),
|
||||
dependencyLockSha256: 'b'.repeat(64),
|
||||
runtime: 'bun',
|
||||
runtimeVersion: 'fixture',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
},
|
||||
});
|
||||
const events: string[] = [];
|
||||
let result: CanonicalRunResult | undefined;
|
||||
let heartbeatFailure = false;
|
||||
let status = 'pending';
|
||||
const repo: BacktestRunRepository = {
|
||||
async start() {
|
||||
throw new Error('legacy claim must not run');
|
||||
},
|
||||
async startCanonical(input) {
|
||||
events.push('claim');
|
||||
status = 'running';
|
||||
return {
|
||||
runId,
|
||||
backtestId: request.backtestId,
|
||||
attemptId: 'attempt',
|
||||
config: structuredClone(input),
|
||||
};
|
||||
},
|
||||
async load() {
|
||||
return { status, config: structuredClone(request) };
|
||||
},
|
||||
async rejectPending() {
|
||||
events.push('reject');
|
||||
status = 'failed';
|
||||
},
|
||||
async heartbeat() {
|
||||
events.push('heartbeat');
|
||||
if (heartbeatFailure) {
|
||||
throw new Error('lost');
|
||||
}
|
||||
return { cancelRequested: false };
|
||||
},
|
||||
async loadDataset() {
|
||||
throw new Error('v1 data must not run');
|
||||
},
|
||||
async freezeDataset() {
|
||||
throw new Error('provider freeze must not run');
|
||||
},
|
||||
async loadCanonicalDataset(_id, _attempt, hash) {
|
||||
expect(hash).toBe(dataset.manifest.hash);
|
||||
events.push('dataset');
|
||||
return dataset;
|
||||
},
|
||||
async complete() {
|
||||
throw new Error('legacy completion must not run');
|
||||
},
|
||||
async completeCanonical(input) {
|
||||
events.push('complete');
|
||||
result = input;
|
||||
status = 'completed';
|
||||
},
|
||||
async updateProgress() {
|
||||
events.push('progress');
|
||||
},
|
||||
async fail() {
|
||||
events.push('fail');
|
||||
status = 'failed';
|
||||
},
|
||||
async cancel() {
|
||||
events.push('cancel');
|
||||
status = 'cancelled';
|
||||
},
|
||||
async updateControl() {},
|
||||
};
|
||||
const engine = Object.assign(new EventEmitter(), {
|
||||
async runBacktest(): Promise<never> {
|
||||
throw new Error('legacy simulator must not run');
|
||||
},
|
||||
async runCanonical(
|
||||
_input: typeof request,
|
||||
resolve: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
|
||||
) {
|
||||
await resolve(new AbortController().signal);
|
||||
events.push('execute');
|
||||
// Economic validation belongs to the actual worker/SQL fixtures; this fixture probes lifecycle only.
|
||||
return {
|
||||
financial: {} as CanonicalRunResult['financial'],
|
||||
analytics: {} as CanonicalRunResult['analytics'],
|
||||
};
|
||||
},
|
||||
async stopBacktest() {
|
||||
events.push('stop');
|
||||
},
|
||||
async pauseBacktest() {},
|
||||
async resumeBacktest() {},
|
||||
setSpeedMultiplier() {},
|
||||
getStatus() {
|
||||
return { isRunning: false, isPaused: false, progress: 0, currentTime: 0 };
|
||||
},
|
||||
async shutdown() {},
|
||||
}) satisfies BacktestExecutionEngine;
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
repository: repo,
|
||||
engineName: 'native',
|
||||
logger,
|
||||
heartbeatMs: 5,
|
||||
heartbeatTimeoutMs: 50,
|
||||
async prepare() {
|
||||
throw new Error('legacy preparation must not run');
|
||||
},
|
||||
});
|
||||
return {
|
||||
request,
|
||||
dataset,
|
||||
repo,
|
||||
engine,
|
||||
runner,
|
||||
events,
|
||||
get result() {
|
||||
return result;
|
||||
},
|
||||
loseLease() {
|
||||
heartbeatFailure = true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<T>((a, b) => {
|
||||
resolve = a;
|
||||
reject = b;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
||||
import { deferred, canonicalRunnerFixture as setup } from '../fixtures/canonical-runner';
|
||||
|
||||
describe('canonical jobs share the durable runner lifecycle', () => {
|
||||
test('queued canonical result preserves admitted request and bypasses every legacy seam', async () => {
|
||||
|
|
|
|||
150
test/integration/canonical-worker-lifecycle.test.ts
Normal file
150
test/integration/canonical-worker-lifecycle.test.ts
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import {
|
||||
BacktestCancelledError,
|
||||
BacktestTimeoutError,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { canonicalRunnerFixture, deferred } from '../fixtures/canonical-runner';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const workerUrl = new URL('../fixtures/native-backtest-worker.ts', import.meta.url);
|
||||
function start(behavior: string) {
|
||||
const fixture = nativeReplayFixture(),
|
||||
ready = deferred<number>(),
|
||||
controller = new AbortController();
|
||||
fixture.config.matching.risk.ledger.sessionId = `fixture:${behavior}`;
|
||||
const worker = new NativeBacktestWorker(workerUrl);
|
||||
const result = worker
|
||||
.execute(
|
||||
{
|
||||
type: 'runReplayTrace',
|
||||
version: 1,
|
||||
dataset: fixture.dataset,
|
||||
config: fixture.config,
|
||||
trace: [1, 2].map(offset => ({
|
||||
at: fixture.start + offset * fixture.minute,
|
||||
ownerId: 'A',
|
||||
intent: { mode: 'target' as const, targets: [] },
|
||||
})),
|
||||
resultFormat: 'report',
|
||||
eventBudget: 1,
|
||||
},
|
||||
controller.signal,
|
||||
progress => {
|
||||
if (progress.message.startsWith('Fixture worker ready:')) {
|
||||
ready.resolve(Number(progress.message.split(':')[1]));
|
||||
}
|
||||
}
|
||||
)
|
||||
.catch(error => {
|
||||
ready.reject(error);
|
||||
return error;
|
||||
});
|
||||
return { result, ready: ready.promise, controller };
|
||||
}
|
||||
function exited(pid: number) {
|
||||
expect(pid).toBeGreaterThan(0);
|
||||
expect(() => process.kill(pid, 0)).toThrow();
|
||||
}
|
||||
test.each(['crash', 'no-result', 'malformed', 'invalid-result', 'reported-error'])(
|
||||
'canonical worker %s cannot publish a result and is reaped before rejection',
|
||||
async behavior => {
|
||||
const execution = start(behavior),
|
||||
pid = await execution.ready;
|
||||
expect(await execution.result).toBeInstanceOf(Error);
|
||||
exited(pid);
|
||||
}
|
||||
);
|
||||
test('blocking canonical worker can be killed without blocking the parent event loop', async () => {
|
||||
const execution = start('block'),
|
||||
pid = await execution.ready;
|
||||
let tick = false;
|
||||
await new Promise<void>(resolve =>
|
||||
setTimeout(() => {
|
||||
tick = true;
|
||||
resolve();
|
||||
}, 5)
|
||||
);
|
||||
expect(tick).toBe(true);
|
||||
execution.controller.abort(new BacktestCancelledError());
|
||||
expect(await execution.result).toBeInstanceOf(BacktestCancelledError);
|
||||
exited(pid);
|
||||
});
|
||||
test('a deadline kills a noncooperative worker and preserves its timeout reason', async () => {
|
||||
const execution = start('block'),
|
||||
pid = await execution.ready;
|
||||
execution.controller.abort(new BacktestTimeoutError(10));
|
||||
expect(await execution.result).toBeInstanceOf(BacktestTimeoutError);
|
||||
exited(pid);
|
||||
});
|
||||
test('valid financial result is not accepted while the child is still alive', async () => {
|
||||
const execution = start('result-then-block'),
|
||||
pid = await execution.ready;
|
||||
let settled = false;
|
||||
execution.result.then(() => {
|
||||
settled = true;
|
||||
});
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
expect(settled).toBe(false);
|
||||
execution.controller.abort(new BacktestCancelledError());
|
||||
expect(await execution.result).toBeInstanceOf(BacktestCancelledError);
|
||||
exited(pid);
|
||||
});
|
||||
test('canonical adapter cancellation during retained dataset reads prevents a late worker', async () => {
|
||||
const f = canonicalRunnerFixture(),
|
||||
entered = deferred<void>(),
|
||||
release = deferred<void>();
|
||||
let providerReads = 0,
|
||||
progress = 0;
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger: { error() {} },
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
providerReads++;
|
||||
return [];
|
||||
},
|
||||
},
|
||||
});
|
||||
engine.on('progress', () => progress++);
|
||||
const result = engine
|
||||
.runCanonical(f.request, async () => {
|
||||
entered.resolve();
|
||||
await release.promise;
|
||||
return f.dataset;
|
||||
})
|
||||
.catch(error => error);
|
||||
await entered.promise;
|
||||
await engine.stopBacktest();
|
||||
expect(await result).toBeInstanceOf(BacktestCancelledError);
|
||||
release.resolve();
|
||||
await Promise.resolve();
|
||||
expect(providerReads).toBe(0);
|
||||
expect(progress).toBe(0);
|
||||
expect(engine.getStatus().isRunning).toBe(false);
|
||||
await engine.shutdown();
|
||||
await f.runner.shutdown();
|
||||
});
|
||||
test('canonical adapter timeout covers retained input loading and shutdown closes later work', async () => {
|
||||
const f = canonicalRunnerFixture();
|
||||
const engine = new RustBacktestAdapter(
|
||||
{
|
||||
logger: { error() {} },
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
throw new Error('provider must not run');
|
||||
},
|
||||
},
|
||||
},
|
||||
{ timeoutMs: 20 }
|
||||
);
|
||||
await expect(
|
||||
engine.runCanonical(f.request, async () => new Promise(() => {}))
|
||||
).rejects.toBeInstanceOf(BacktestTimeoutError);
|
||||
expect(engine.getStatus().isRunning).toBe(false);
|
||||
await engine.shutdown();
|
||||
await expect(engine.runCanonical(f.request, async () => f.dataset)).rejects.toThrow(
|
||||
'shutting down'
|
||||
);
|
||||
await f.runner.shutdown();
|
||||
});
|
||||
|
|
@ -20,8 +20,25 @@ import type {
|
|||
} from '@stock-bot/stock-config/experiments';
|
||||
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
|
||||
import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
|
||||
import { parseValidationDetail } from '../../apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
test('saved validation decodes explicit research agent actors without accepting malformed identities', () => {
|
||||
const value = document('reported');
|
||||
if (!value.selection || !value.report) {
|
||||
throw new Error('Reported fixture needs immutable selection and report');
|
||||
}
|
||||
const actor = 'agent:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
|
||||
value.selection.principal = actor;
|
||||
value.report.principal = actor;
|
||||
const parsed = parseValidationDetail(value);
|
||||
expect(parsed.selection?.principal).toBe(actor);
|
||||
expect(parsed.report?.principal).toBe(actor);
|
||||
expect(() =>
|
||||
parseValidationDetail({ ...value, report: { ...value.report, principal: 'agent:operator' } })
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const keys = ['window', 'document', 'Event', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
||||
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
||||
|
|
|
|||
|
|
@ -717,7 +717,7 @@ describe('immutable retry failure history', () => {
|
|||
expect(host.textContent).toContain('Retry 1 · previous attempt 1');
|
||||
expect(host.textContent).not.toContain('No accepted manual retries');
|
||||
});
|
||||
test('history is lazy and renders empty/loading states then exact nullable failure snapshots', async () => {
|
||||
test('history renders loading/empty states, exact nullable failure snapshots and research agent authorship', async () => {
|
||||
const value = failure(0, 0);
|
||||
value.trials[0]!.error = null;
|
||||
await show(value);
|
||||
|
|
@ -728,6 +728,7 @@ describe('immutable retry failure history', () => {
|
|||
expect(host.textContent).toContain('No accepted manual retries for this trial');
|
||||
await flush(() => button('Refresh retry history for trial 1').click());
|
||||
const saved = receipt(value);
|
||||
saved.principal = 'agent:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
|
||||
await flush(() => reply(request(historyPath()), { retries: [saved] }));
|
||||
expect(host.textContent).toContain('Retry 1 · previous attempt 0');
|
||||
expect(host.textContent).toContain('No error was recorded for this failure');
|
||||
|
|
@ -736,6 +737,7 @@ describe('immutable retry failure history', () => {
|
|||
expect(host.textContent).toContain(saved.completedAt!);
|
||||
expect(host.textContent).toContain(saved.recordedAt);
|
||||
expect(host.textContent).toContain(saved.reviewId);
|
||||
expect(host.textContent).toContain(saved.principal);
|
||||
expect(host.textContent).toContain('not a complete history of automatic recovery attempts');
|
||||
});
|
||||
test.each(['partial', 'foreign', 'unordered', 'duplicate', 'http'] as const)(
|
||||
|
|
|
|||
|
|
@ -266,7 +266,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
validateDataset(first, { ...datasetConfig(), datasetHash: 'f'.repeat(64) })
|
||||
).toThrow('does not match');
|
||||
});
|
||||
test('replays stored provider fixtures and produces identical trades and metrics', async () => {
|
||||
test('stored provider fixtures normalize into identical frozen inputs before admission', async () => {
|
||||
const { documents, mongodb } = memoryStore();
|
||||
await persistEodPrices(mongodb, identity, fixture);
|
||||
await persistEodPrices(mongodb, identity, fixture);
|
||||
|
|
@ -287,16 +287,11 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
slippage: 0,
|
||||
config: { fastPeriod: 3, slowPeriod: 7 },
|
||||
});
|
||||
const engine = new RustBacktestAdapter({ logger, storage });
|
||||
const first = await engine.runBacktest(config);
|
||||
const second = await engine.runBacktest(config);
|
||||
expect(first.status).toBe('completed');
|
||||
expect(first.trades.length).toBeGreaterThan(0);
|
||||
expect(first.trades).toEqual(second.trades);
|
||||
expect(first.metrics).toEqual(second.metrics);
|
||||
expect(first.equity).toEqual(second.equity);
|
||||
expect(first.metrics.totalReturn).toBeFinite();
|
||||
expect(engine.getStatus().isRunning).toBe(false);
|
||||
const first = await loadDataset(storage, config);
|
||||
const second = await loadDataset(storage, config);
|
||||
expect(first).toEqual(second);
|
||||
expect(first.bars).toHaveLength(fixture.length);
|
||||
expect(first.manifest.hash).toBe(second.manifest.hash);
|
||||
});
|
||||
|
||||
test('all listings retain their first same-timestamp bar and deterministic tie ordering', async () => {
|
||||
|
|
@ -310,16 +305,14 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
config: { fastPeriod: 3, slowPeriod: 7 },
|
||||
};
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
const engine = new RustBacktestAdapter({ logger, storage });
|
||||
const first = await engine.runBacktest(config);
|
||||
const second = await engine.runBacktest(config);
|
||||
const first = await loadDataset(storage, config);
|
||||
const second = await loadDataset(storage, config);
|
||||
for (const id of config.symbols) {
|
||||
expect(first.ohlcData[id]).toHaveLength(fixture.length);
|
||||
expect(first.ohlcData[id]?.[0]?.timestamp).toBe(start.getTime());
|
||||
const bars = first.bars.filter(bar => bar.symbol === id);
|
||||
expect(bars).toHaveLength(fixture.length);
|
||||
expect(bars[0]?.timestamp).toBe(start.getTime());
|
||||
}
|
||||
expect(first.trades).toEqual(second.trades);
|
||||
expect(first.metrics).toEqual(second.metrics);
|
||||
expect(first.equity).toEqual(second.equity);
|
||||
expect(first).toEqual(second);
|
||||
});
|
||||
|
||||
test('rejects malformed provider records before writing anything', async () => {
|
||||
|
|
@ -347,7 +340,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
);
|
||||
});
|
||||
|
||||
test('empty storage and unknown strategies fail without leaving the engine running', async () => {
|
||||
test('retired provider-at-execution entry refuses before storage or native strategy resolution', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
const engine = new RustBacktestAdapter({ logger, storage });
|
||||
|
|
@ -360,9 +353,11 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
});
|
||||
await expect(engine.runBacktest(config)).rejects.toThrow('No historical data');
|
||||
await expect(engine.runBacktest(config)).rejects.toThrow(
|
||||
'Legacy backtest execution is retired'
|
||||
);
|
||||
await expect(engine.runBacktest({ ...config, strategy: 'does-not-exist' })).rejects.toThrow(
|
||||
'Unknown native strategy'
|
||||
'Legacy backtest execution is retired'
|
||||
);
|
||||
expect(engine.getStatus().isRunning).toBe(false);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -118,7 +118,7 @@ const config = () =>
|
|||
});
|
||||
|
||||
describe('EOD intraday ingestion → research storage', () => {
|
||||
test('ingest_5m_freeze_replay: real writer/admission, v2 freeze and legacy native replay', async () => {
|
||||
test('ingest_5m_freeze: real writer, v2 freeze and historical v1 compatibility', async () => {
|
||||
const store = memoryStore();
|
||||
const response = intradayResponse();
|
||||
expect(await ingest(store.mongodb, response)).toEqual({
|
||||
|
|
@ -166,7 +166,7 @@ describe('EOD intraday ingestion → research storage', () => {
|
|||
).toBe(true);
|
||||
expect(validateDatasetV2(JSON.parse(JSON.stringify(dataset)))).toEqual(dataset);
|
||||
|
||||
// V1 runtime stays V1. This checks storage compatibility, not future F06 replay correctness.
|
||||
// Historical V1 payloads remain readable; production execution requires V2 admission.
|
||||
const legacy = await loadDataset(storage, config());
|
||||
expect(
|
||||
legacy.bars.map(({ timestamp, open, high, low, close, volume }) => ({
|
||||
|
|
@ -182,19 +182,10 @@ describe('EOD intraday ingestion → research storage', () => {
|
|||
legacy.manifest.hash
|
||||
);
|
||||
const engine = new RustBacktestAdapter({ logger, storage });
|
||||
try {
|
||||
const first = await engine.runBacktest(config(), async () => legacy);
|
||||
const second = await engine.runBacktest(config(), async () => legacy);
|
||||
expect(first.status).toBe('completed');
|
||||
expect(first.ohlcData[identity.eodSearchCode]).toHaveLength(78);
|
||||
expect(first.ohlcData[identity.eodSearchCode]?.[0]?.timestamp).toBe(start.getTime());
|
||||
expect(first.trades.length).toBeGreaterThan(0);
|
||||
expect(first.trades).toEqual(second.trades);
|
||||
expect(first.equity).toEqual(second.equity);
|
||||
expect(first.metrics).toEqual(second.metrics);
|
||||
} finally {
|
||||
await engine.shutdown();
|
||||
}
|
||||
await expect(engine.runBacktest(config(), async () => legacy)).rejects.toThrow(
|
||||
'Legacy backtest execution is retired'
|
||||
);
|
||||
await engine.shutdown();
|
||||
});
|
||||
|
||||
test('supported collections, UTC seconds and half-open fractional boundaries', async () => {
|
||||
|
|
@ -210,7 +201,7 @@ describe('EOD intraday ingestion → research storage', () => {
|
|||
['1m', 'eodIntraday1M'],
|
||||
['5m', 'eodIntraday5M'],
|
||||
['1h', 'eodIntraday1H'],
|
||||
]) {
|
||||
] as const) {
|
||||
const bars = await storage.getHistoricalBars(
|
||||
identity.eodSearchCode,
|
||||
new Date(start.getTime() + 1),
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ test('canonical paper rejects invalid role/configuration before resolving servic
|
|||
config.matching.series[0]!.mode = 'Open';
|
||||
await expect(
|
||||
registerOrchestratorServices(container, {
|
||||
role: 'paper',
|
||||
canonicalPaper: config,
|
||||
})
|
||||
).rejects.toThrow('Quote execution only');
|
||||
|
|
@ -40,6 +41,6 @@ test('live defaults, research canonical configuration and missing custody fail b
|
|||
createContainer(config({ defaultMode: 'backtest', canonicalPaper: paperFeedConfiguration() }))
|
||||
).rejects.toThrow('requires a paper composition');
|
||||
await expect(
|
||||
createContainer(config({ canonicalPaper: paperFeedConfiguration() }))
|
||||
createContainer(config({ defaultMode: 'paper', canonicalPaper: paperFeedConfiguration() }))
|
||||
).rejects.toThrow('requires durable PostgreSQL');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -361,7 +361,8 @@ describe('canonical paper HTTP failure and legacy gateway isolation', () => {
|
|||
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',
|
||||
error:
|
||||
'Legacy account execution is retired; use the explicitly configured canonical paper runtime',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
203
test/integration/research-agents-api.test.ts
Normal file
203
test/integration/research-agents-api.test.ts
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { expect, mock, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import {
|
||||
createHttpSecurity,
|
||||
getCredentialHttpPrincipal,
|
||||
getResearchHttpPrincipal,
|
||||
} from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { createResearchAgentSchema } from '@stock-bot/stock-config/research-agents';
|
||||
import { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes';
|
||||
import { researchAgentDatabaseError } from '../../apps/stock/web-api/src/services/research-agent-budget';
|
||||
import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
|
||||
|
||||
const agent = `agent:${randomUUID()}` as const;
|
||||
const token = 'sb-research.fixture-token';
|
||||
const adminToken = 'operator-test-secret-12345678901234567890';
|
||||
const serviceToken = 'service-test-secret-123456789012345678901';
|
||||
const limits = {
|
||||
maxActiveTrials: 2,
|
||||
maxTrialsPerExperiment: 4,
|
||||
maxBarEvaluationsPerExperiment: 1000,
|
||||
maxAttemptWallMs: 1000,
|
||||
maxAttempts: 2,
|
||||
};
|
||||
function boundary(disabled = false, resolver = true) {
|
||||
const resolve = mock(async () => ({ principal: agent }));
|
||||
const security = createHttpSecurity({
|
||||
adminToken,
|
||||
serviceToken,
|
||||
disabled,
|
||||
environment: 'test',
|
||||
browserSessions: true,
|
||||
...(resolver ? { resolveResearchCredential: resolve } : {}),
|
||||
});
|
||||
const app = new Hono();
|
||||
security.mount(app);
|
||||
app.all('/api/v2/experiments', c =>
|
||||
c.json({
|
||||
principal: getResearchHttpPrincipal(c.req.raw),
|
||||
privileged: getCredentialHttpPrincipal(c.req.raw) ?? null,
|
||||
})
|
||||
);
|
||||
return { app, security, resolve };
|
||||
}
|
||||
test('research HTTP identity is distinct; Origin and upgrades are fenced before asynchronous resolution', async () => {
|
||||
const f = boundary();
|
||||
for (const headers of [{ Origin: 'https://evil.invalid' }, { Upgrade: 'websocket' }] as Record<
|
||||
string,
|
||||
string
|
||||
>[]) {
|
||||
const response = await f.app.request('/api/v2/experiments', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}`, ...headers },
|
||||
});
|
||||
expect(response.status).toBe(403);
|
||||
expect(response.headers.get('cache-control')).toBe('no-store');
|
||||
}
|
||||
expect(f.resolve).toHaveBeenCalledTimes(0);
|
||||
const response = await f.app.request('/api/v2/experiments', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({ principal: agent, privileged: null });
|
||||
expect(
|
||||
f.security.authorize(
|
||||
new Request('http://localhost/api/v2/experiments', {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
)?.status
|
||||
).toBe(403);
|
||||
});
|
||||
test('research credential never becomes a privileged session or bypasses disabled/unrelated authentication', async () => {
|
||||
for (const f of [boundary(true), boundary(false, false)]) {
|
||||
const response = await f.app.request('/api/v2/experiments', {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
expect(response.status).toBe(403);
|
||||
expect(f.resolve).toHaveBeenCalledTimes(0);
|
||||
expect(f.security.researchEnabled).toBe(false);
|
||||
const login = await f.app.request('/api/auth/session', {
|
||||
method: 'POST',
|
||||
headers: { Origin: 'http://localhost', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
expect(login.status).toBe(403);
|
||||
expect(login.headers.get('set-cookie')).toBeNull();
|
||||
}
|
||||
const f = boundary();
|
||||
const login = await f.app.request('/api/auth/session', {
|
||||
method: 'POST',
|
||||
headers: { Origin: 'http://localhost', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
expect(login.status).toBe(403);
|
||||
expect(login.headers.get('set-cookie')).toBeNull();
|
||||
});
|
||||
test('operator-only provisioning fails closed without enabled research authentication before storage', async () => {
|
||||
const query = mock(async () => {
|
||||
throw new Error('denied operation touched storage');
|
||||
});
|
||||
const container = {
|
||||
postgres: { query },
|
||||
logger: { error: mock(() => {}) },
|
||||
} as unknown as IServiceContainer;
|
||||
for (const disabled of [false, true]) {
|
||||
const f = boundary(disabled);
|
||||
f.app.route('/', createResearchAgentRoutes(container, f.security.researchEnabled));
|
||||
for (const bearer of [token, serviceToken, ...(disabled ? [adminToken] : [])]) {
|
||||
const response = await f.app.request('/api/v2/research-agents', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${bearer}`, 'Content-Type': 'application/json' },
|
||||
body: '{}',
|
||||
});
|
||||
expect(response.status).toBe(403);
|
||||
}
|
||||
}
|
||||
expect(query).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
test('resolver exact write capabilities refuse trading, operators, foreign evidence and ownership impersonation', async () => {
|
||||
const projectId = randomUUID(),
|
||||
experimentId = randomUUID(),
|
||||
familyId = randomUUID();
|
||||
const query = mock(async (sql: string) => ({
|
||||
rows: sql.includes('token_hash')
|
||||
? [{ id: agent, enabled: true, policy: { allowedProjectIds: [projectId] } }]
|
||||
: [{ submission_principal: 'operator', owner_principal: 'operator', project_id: projectId }],
|
||||
}));
|
||||
const service = new ResearchAgentsService({
|
||||
postgres: { query },
|
||||
} as unknown as IServiceContainer);
|
||||
const check = (path: string, method = 'POST') =>
|
||||
service.authenticate(
|
||||
new Request(`http://localhost${path}`, {
|
||||
method,
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
);
|
||||
for (const path of [
|
||||
'/api/v2/research-agents',
|
||||
'/api/v2/backtests',
|
||||
'/api/v2/datasets/retain',
|
||||
'/api/v2/strategy-versions/' + familyId + '/review',
|
||||
'/api/operations/start',
|
||||
'/api/v2/runs/' + experimentId + '/reproduce',
|
||||
`/api/v2/experiments/${experimentId}/cancel`,
|
||||
`/api/v2/strategies/${familyId}/versions`,
|
||||
`/api/v2/research-projects/${randomUUID()}/hypotheses`,
|
||||
]) {
|
||||
expect(await check(path)).toBeInstanceOf(Response);
|
||||
expect(((await check(path)) as Response).status).toBe(403);
|
||||
}
|
||||
expect(await check(`/api/v2/research-projects/${projectId}/hypotheses`)).toEqual({
|
||||
principal: agent,
|
||||
});
|
||||
expect(await check('/api/v2/experiments/preview')).toEqual({ principal: agent });
|
||||
expect(await check(`/api/v2/experiments/${experimentId}`, 'GET')).toEqual({ principal: agent });
|
||||
expect(await check('/api/v2/research-agents', 'GET')).toBeInstanceOf(Response);
|
||||
});
|
||||
test('quota diagnostics remain distinguishable from arbitrary database failures; policy is strict and bounded', () => {
|
||||
expect(
|
||||
researchAgentDatabaseError({ code: 'P0001', message: 'research_budget:capacity' })?.status
|
||||
).toBe(429);
|
||||
expect(
|
||||
researchAgentDatabaseError({ code: 'P0001', message: 'research_access:denied' })?.status
|
||||
).toBe(403);
|
||||
expect(researchAgentDatabaseError(new Error('database unavailable'))).toBeNull();
|
||||
expect(
|
||||
researchAgentDatabaseError({ code: '23514', message: 'research_budget:spoof' })
|
||||
).toBeNull();
|
||||
expect(
|
||||
createResearchAgentSchema.parse({
|
||||
name: 'Agent',
|
||||
allowedProjectIds: [],
|
||||
allowedBacktestIds: [],
|
||||
limits,
|
||||
}).limits
|
||||
).toEqual(limits);
|
||||
for (const bad of [
|
||||
{ ...limits, maxAttempts: 4 },
|
||||
{ ...limits, maxActiveTrials: 0 },
|
||||
{ ...limits, maxAttemptWallMs: 2147483648 },
|
||||
]) {
|
||||
expect(
|
||||
createResearchAgentSchema.safeParse({
|
||||
name: 'Agent',
|
||||
allowedProjectIds: [],
|
||||
allowedBacktestIds: [],
|
||||
limits: bad,
|
||||
}).success
|
||||
).toBe(false);
|
||||
}
|
||||
expect(
|
||||
createResearchAgentSchema.safeParse({
|
||||
name: 'Agent',
|
||||
allowedProjectIds: [],
|
||||
allowedBacktestIds: [],
|
||||
limits,
|
||||
ownerPrincipal: 'operator',
|
||||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
345
test/integration/research-agents-ui.test.tsx
Normal file
345
test/integration/research-agents-ui.test.tsx
Normal file
|
|
@ -0,0 +1,345 @@
|
|||
import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test';
|
||||
import { GlobalWindow } from 'happy-dom';
|
||||
import { act, createElement } from 'react';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import type { ResearchAgentRecord } from '@stock-bot/stock-config/research-agents';
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const names = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
||||
const globals = names.map(
|
||||
name => [name, Object.getOwnPropertyDescriptor(globalThis, name)] as const
|
||||
);
|
||||
let createRoot: typeof import('react-dom/client').createRoot;
|
||||
let router: typeof import('react-router-dom');
|
||||
let Page: typeof import('../../apps/stock/web-app/src/features/research/ResearchAgentsPage').ResearchAgentsPage;
|
||||
let api: typeof import('../../apps/stock/web-app/src/features/research/services/researchAgentsApi').researchAgentsApi;
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement;
|
||||
const agentId = 'agent:11111111-1111-4111-8111-111111111111';
|
||||
const projectId = '22222222-2222-4222-8222-222222222222';
|
||||
const backtestId = '33333333-3333-4333-8333-333333333333';
|
||||
const record = (extra: Partial<ResearchAgentRecord> = {}): ResearchAgentRecord => ({
|
||||
id: agentId,
|
||||
name: 'Research worker',
|
||||
enabled: true,
|
||||
revision: 1,
|
||||
allowedProjectIds: [projectId],
|
||||
grants: [{ backtestId, policyHash: 'a'.repeat(64) }],
|
||||
limits: {
|
||||
maxActiveTrials: 1,
|
||||
maxTrialsPerExperiment: 10,
|
||||
maxBarEvaluationsPerExperiment: 100000,
|
||||
maxAttemptWallMs: 60000,
|
||||
maxAttempts: 3,
|
||||
},
|
||||
createdAt: '2026-10-24T12:00:00.000Z',
|
||||
updatedAt: '2026-10-24T12:00:00.000Z',
|
||||
...extra,
|
||||
});
|
||||
type Pending = {
|
||||
path: string;
|
||||
method: string;
|
||||
body: unknown;
|
||||
resolve: (response: Response) => void;
|
||||
reject: (error: Error) => void;
|
||||
settled: boolean;
|
||||
};
|
||||
const calls: Pending[] = [];
|
||||
function pending(path = '', method = 'GET') {
|
||||
const value = calls.find(
|
||||
call =>
|
||||
!call.settled && call.path === `/api/v2/research-agents${path}` && call.method === method
|
||||
);
|
||||
if (!value) {
|
||||
throw new Error(`Missing request ${method} ${path}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function reply(call: Pending, body: unknown, status = 200) {
|
||||
call.settled = true;
|
||||
call.resolve(Response.json(body, { status }));
|
||||
}
|
||||
async function flush(action: () => void = () => {}) {
|
||||
await act(async () => {
|
||||
action();
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
function button(text: string) {
|
||||
const value = [...host.querySelectorAll('button')].find(
|
||||
item => item.textContent?.trim() === text
|
||||
);
|
||||
if (!value) {
|
||||
throw new Error(`Missing button ${text}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
async function fill(label: string, value: string) {
|
||||
await flush(() => {
|
||||
const input = host.querySelector(`[aria-label="${label}"]`)!;
|
||||
const prototype =
|
||||
input.tagName === 'TEXTAREA'
|
||||
? browser.HTMLTextAreaElement.prototype
|
||||
: browser.HTMLInputElement.prototype;
|
||||
Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value);
|
||||
input.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event);
|
||||
});
|
||||
}
|
||||
async function mount(agents: ResearchAgentRecord[] = []) {
|
||||
root = createRoot(host);
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(
|
||||
router.MemoryRouter,
|
||||
{ initialEntries: [`/research/agents?projectId=${projectId}`] },
|
||||
createElement(Page)
|
||||
)
|
||||
)
|
||||
);
|
||||
await flush(() => reply(pending(), { agents }));
|
||||
}
|
||||
async function draft() {
|
||||
await fill('Agent name', 'Research worker');
|
||||
await fill('Allowed backtest IDs', backtestId);
|
||||
}
|
||||
beforeAll(async () => {
|
||||
for (const [name, value] of Object.entries({
|
||||
window: browser,
|
||||
document: browser.document,
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
})) {
|
||||
Object.defineProperty(globalThis, name, { configurable: true, writable: true, value });
|
||||
}
|
||||
({ createRoot } = await import('react-dom/client'));
|
||||
router = await import('react-router-dom');
|
||||
({ ResearchAgentsPage: Page } = await import(
|
||||
'../../apps/stock/web-app/src/features/research/ResearchAgentsPage'
|
||||
));
|
||||
({ researchAgentsApi: api } = await import(
|
||||
'../../apps/stock/web-app/src/features/research/services/researchAgentsApi'
|
||||
));
|
||||
});
|
||||
beforeEach(() => {
|
||||
calls.length = 0;
|
||||
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
||||
browser.document.body.append(host as never);
|
||||
browser.fetch = ((input: RequestInfo | URL, init?: RequestInit) =>
|
||||
new Promise<Response>((resolve, reject) => {
|
||||
calls.push({
|
||||
path: new URL(String(input)).pathname,
|
||||
method: init?.method ?? 'GET',
|
||||
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
||||
resolve,
|
||||
reject,
|
||||
settled: false,
|
||||
});
|
||||
})) as unknown as typeof browser.fetch;
|
||||
});
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await flush(() => root!.unmount());
|
||||
}
|
||||
root = undefined;
|
||||
host.remove();
|
||||
});
|
||||
afterAll(() => {
|
||||
browser.happyDOM.abort();
|
||||
for (const [name, descriptor] of globals) {
|
||||
if (descriptor) {
|
||||
Object.defineProperty(globalThis, name, descriptor);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, name);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('explicit scoped creation posts one bounded policy, shows credential once and never starts work', async () => {
|
||||
await mount();
|
||||
expect(host.textContent).toContain('No research agents configured.');
|
||||
expect(
|
||||
(host.querySelector('[aria-label="Allowed project IDs"]') as HTMLTextAreaElement).value
|
||||
).toBe(projectId);
|
||||
await draft();
|
||||
await flush(() => {
|
||||
button('Create credential').click();
|
||||
button('Create credential').click();
|
||||
});
|
||||
const request = pending('', 'POST');
|
||||
expect(request.body).toEqual({
|
||||
name: 'Research worker',
|
||||
allowedProjectIds: [projectId],
|
||||
allowedBacktestIds: [backtestId],
|
||||
limits: record().limits,
|
||||
});
|
||||
expect(calls.filter(call => call.method === 'POST')).toHaveLength(1);
|
||||
await flush(() =>
|
||||
reply(request, { agent: record(), token: 'fixture-generated-credential' }, 201)
|
||||
);
|
||||
expect(
|
||||
(host.querySelector('[aria-label="New research token"]') as HTMLTextAreaElement).value
|
||||
).toBe('fixture-generated-credential');
|
||||
expect(button('Create credential').disabled).toBe(true);
|
||||
expect(host.textContent).toContain('Revision 1');
|
||||
expect(host.textContent).toContain('a'.repeat(64));
|
||||
await flush(() => button('I have saved the credential').click());
|
||||
expect(host.querySelector('[aria-label="New research token"]')).toBeNull();
|
||||
expect(calls.some(call => /runs|experiments|paper/.test(call.path))).toBe(false);
|
||||
});
|
||||
|
||||
test('malformed scope and invalid budgets preserve draft without writing', async () => {
|
||||
await mount();
|
||||
await draft();
|
||||
await fill('Maximum active trials', '0');
|
||||
await flush(() =>
|
||||
host
|
||||
.querySelector('form')!
|
||||
.dispatchEvent(
|
||||
new browser.Event('submit', { bubbles: true, cancelable: true }) as unknown as Event
|
||||
)
|
||||
);
|
||||
expect(host.textContent).toContain('limits.maxActiveTrials');
|
||||
expect(calls.some(call => call.method === 'POST')).toBe(false);
|
||||
await fill('Maximum active trials', '1');
|
||||
await fill('Allowed project IDs', 'not-a-uuid');
|
||||
await flush(() => button('Create credential').click());
|
||||
expect(host.textContent).toContain('allowedProjectIds');
|
||||
expect(calls.some(call => call.method === 'POST')).toBe(false);
|
||||
expect((host.querySelector('[aria-label="Agent name"]') as HTMLInputElement).value).toBe(
|
||||
'Research worker'
|
||||
);
|
||||
});
|
||||
|
||||
test('ambiguous creation forbids blind retry and permits inspecting and disabling the retained credential', async () => {
|
||||
await mount();
|
||||
await draft();
|
||||
await flush(() => button('Create credential').click());
|
||||
const request = pending('', 'POST');
|
||||
await flush(() => {
|
||||
request.settled = true;
|
||||
request.reject(new Error('Response lost'));
|
||||
});
|
||||
expect(host.textContent).toContain('token cannot be recovered');
|
||||
expect(button('Create credential').disabled).toBe(true);
|
||||
expect(button('I have checked the saved agents').disabled).toBe(true);
|
||||
await flush(() => button('I have checked the saved agents').click());
|
||||
expect(button('Create credential').disabled).toBe(true);
|
||||
await flush(() => button('Create credential').click());
|
||||
expect(calls.filter(call => call.method === 'POST')).toHaveLength(1);
|
||||
await flush(() => button('Check saved agents').click());
|
||||
await flush(() => reply(pending(), { error: 'List unavailable' }, 503));
|
||||
expect(button('I have checked the saved agents').disabled).toBe(true);
|
||||
await flush(() => button('Check saved agents').click());
|
||||
expect(button('I have checked the saved agents').disabled).toBe(true);
|
||||
await flush(() => reply(pending(), { agents: [record()] }));
|
||||
expect(button('I have checked the saved agents').disabled).toBe(false);
|
||||
await flush(() => button('Disable Research worker').click());
|
||||
expect(pending(`/${encodeURIComponent(agentId)}`, 'PATCH').body).toEqual({
|
||||
expectedRevision: 1,
|
||||
enabled: false,
|
||||
});
|
||||
await flush(() =>
|
||||
reply(pending(`/${encodeURIComponent(agentId)}`, 'PATCH'), {
|
||||
agent: record({ enabled: false, revision: 2 }),
|
||||
})
|
||||
);
|
||||
expect(host.textContent).toContain('Disabled');
|
||||
expect(button('Create credential').disabled).toBe(true);
|
||||
await flush(() => button('I have checked the saved agents').click());
|
||||
expect(button('Create credential').disabled).toBe(false);
|
||||
});
|
||||
|
||||
test('failed list is explicit and refresh recovers; obsolete budget response cannot replace refreshed state', async () => {
|
||||
await mount([record()]);
|
||||
await flush(() => button('Check budget for Research worker').click());
|
||||
const old = pending(`/${encodeURIComponent(agentId)}/budget`);
|
||||
await flush(() => button('Refresh agents').click());
|
||||
await flush(() => reply(pending(), { error: 'Store unavailable' }, 503));
|
||||
expect(host.textContent).toContain('Store unavailable');
|
||||
expect(host.textContent).not.toContain('No research agents configured');
|
||||
await flush(() => button('Refresh agents').click());
|
||||
await flush(() => reply(pending(), { agents: [record()] }));
|
||||
await flush(() => reply(old, { agent: record(), activeTrials: 1, remainingActiveTrials: 0 }));
|
||||
expect(host.textContent).not.toContain('Active trials:');
|
||||
await flush(() => button('Check budget for Research worker').click());
|
||||
await flush(() =>
|
||||
reply(pending(`/${encodeURIComponent(agentId)}/budget`), {
|
||||
agent: record(),
|
||||
activeTrials: 1,
|
||||
remainingActiveTrials: 0,
|
||||
})
|
||||
);
|
||||
expect(host.textContent).toContain('Active trials: 1; available slots: 0');
|
||||
});
|
||||
|
||||
test('policy conflict refreshes rather than overwriting the newer revision', async () => {
|
||||
await mount([record()]);
|
||||
await flush(() => button('Disable Research worker').click());
|
||||
await flush(() =>
|
||||
reply(pending(`/${encodeURIComponent(agentId)}`, 'PATCH'), { error: 'Revision changed' }, 409)
|
||||
);
|
||||
expect(host.textContent).toContain('Refresh to verify');
|
||||
await flush(() => reply(pending(), { agents: [record({ revision: 3, enabled: false })] }));
|
||||
expect(host.textContent).toContain('Revision 3');
|
||||
expect(calls.filter(call => call.method === 'PATCH')).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('budget identity/capacity and update identity/revision mismatches reject', async () => {
|
||||
const budget = api.budget(agentId);
|
||||
reply(pending(`/${encodeURIComponent(agentId)}/budget`), {
|
||||
agent: record(),
|
||||
activeTrials: 1,
|
||||
remainingActiveTrials: 1,
|
||||
});
|
||||
await expect(budget).rejects.toThrow('capacity mismatch');
|
||||
const update = api.update(agentId, { expectedRevision: 1, enabled: false });
|
||||
reply(pending(`/${encodeURIComponent(agentId)}`, 'PATCH'), {
|
||||
agent: record({ revision: 1, enabled: false }),
|
||||
});
|
||||
await expect(update).rejects.toThrow('revision mismatch');
|
||||
});
|
||||
|
||||
test('unmount fences late credential response', async () => {
|
||||
await mount();
|
||||
await draft();
|
||||
await flush(() => button('Create credential').click());
|
||||
const request = pending('', 'POST');
|
||||
await flush(() => root!.unmount());
|
||||
root = undefined;
|
||||
await flush(() => reply(request, { agent: record(), token: 'fixture-late-credential' }, 201));
|
||||
expect(host.textContent).toBe('');
|
||||
});
|
||||
|
||||
test('per-agent budget request order fences older success and failure responses', async () => {
|
||||
await mount([record()]);
|
||||
const path = `/${encodeURIComponent(agentId)}/budget`;
|
||||
const newerRequest = () => {
|
||||
const value = calls
|
||||
.filter(call => !call.settled && call.path === `/api/v2/research-agents${path}`)
|
||||
.at(-1);
|
||||
if (!value) {
|
||||
throw new Error('Missing newer budget request');
|
||||
}
|
||||
return value;
|
||||
};
|
||||
await flush(() => button('Check budget for Research worker').click());
|
||||
const olderSuccess = pending(path);
|
||||
await flush(() => button('Check budget for Research worker').click());
|
||||
const newestSuccess = newerRequest();
|
||||
expect(newestSuccess).not.toBe(olderSuccess);
|
||||
await flush(() =>
|
||||
reply(newestSuccess, { agent: record(), activeTrials: 0, remainingActiveTrials: 1 })
|
||||
);
|
||||
await flush(() =>
|
||||
reply(olderSuccess, { agent: record(), activeTrials: 1, remainingActiveTrials: 0 })
|
||||
);
|
||||
expect(host.textContent).toContain('Active trials: 0; available slots: 1');
|
||||
await flush(() => button('Check budget for Research worker').click());
|
||||
const olderFailure = pending(path);
|
||||
await flush(() => button('Check budget for Research worker').click());
|
||||
await flush(() =>
|
||||
reply(newerRequest(), { agent: record(), activeTrials: 1, remainingActiveTrials: 0 })
|
||||
);
|
||||
await flush(() => reply(olderFailure, { error: 'Obsolete unavailable response' }, 503));
|
||||
expect(host.textContent).toContain('Active trials: 1; available slots: 0');
|
||||
expect(host.textContent).not.toContain('Obsolete unavailable response');
|
||||
});
|
||||
|
|
@ -2,19 +2,19 @@ import { asFunction, asValue, createContainer as createDiContainer } from 'awili
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { ServiceContainerBuilder, type ServiceCradle } from '@stock-bot/di';
|
||||
import type { StockAppConfig } from '@stock-bot/stock-config';
|
||||
import { BacktestEngine } from '../../apps/stock/orchestrator/src/backtest/BacktestEngine';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
|
||||
import { defaultRiskLimits } from '../../apps/stock/orchestrator/src/execution/model';
|
||||
import { createRoutes } from '../../apps/stock/orchestrator/src/routes/create-routes';
|
||||
import { createContainer } from '../../apps/stock/orchestrator/src/simple-container';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { config, logger, makeExecution } from '../fixtures/execution';
|
||||
import { logger } from '../fixtures/execution';
|
||||
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) await close();
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
async function compose(options: Parameters<typeof registerOrchestratorServices>[1] = {}) {
|
||||
const container = await new ServiceContainerBuilder()
|
||||
.withOptions({
|
||||
|
|
@ -30,42 +30,44 @@ async function compose(options: Parameters<typeof registerOrchestratorServices>[
|
|||
const services: OrchestratorServices = { logger };
|
||||
container.register({ serviceContainer: asValue(services) });
|
||||
await registerOrchestratorServices(container, options);
|
||||
const runtime = services.custom!;
|
||||
cleanup.push(async () => {
|
||||
await runtime.BacktestRunner!.shutdown();
|
||||
await runtime.ModeManager!.shutdown();
|
||||
await runtime.StrategyManager!.shutdown();
|
||||
await services.custom!.BacktestRunner!.shutdown();
|
||||
await container.dispose();
|
||||
});
|
||||
return runtime;
|
||||
return { services, container };
|
||||
}
|
||||
|
||||
describe('research runtime composition admission', () => {
|
||||
test.each([true, false])(
|
||||
'legacy_paper_combination_rejected_before_prepare (initializeMode=%s)',
|
||||
async initializeMode => {
|
||||
describe('canonical research-only default composition', () => {
|
||||
test.each(['paper', 'research-only'] as const)(
|
||||
'%s refuses retired TypeScript financial execution before resolving services',
|
||||
async role => {
|
||||
let resolved = 0;
|
||||
const container = createDiContainer<ServiceCradle>();
|
||||
container.register({
|
||||
serviceContainer: asFunction(() => {
|
||||
resolved++;
|
||||
throw new Error('Runtime services must not be resolved');
|
||||
throw new Error('must not resolve');
|
||||
}),
|
||||
});
|
||||
await expect(
|
||||
registerOrchestratorServices(container, { useRustEngine: false, initializeMode })
|
||||
).rejects.toThrow('TypeScript backtests require a research-only composition');
|
||||
registerOrchestratorServices(container, { role, useRustEngine: false })
|
||||
).rejects.toThrow('Legacy financial execution is retired');
|
||||
expect(resolved).toBe(0);
|
||||
}
|
||||
);
|
||||
|
||||
test('unsafe application startup fails before connection setup', async () => {
|
||||
const config = {
|
||||
services: { orchestrator: { backtesting: { useRustEngine: false } } },
|
||||
} as StockAppConfig;
|
||||
await expect(createContainer(config)).rejects.toThrow('Unsupported runtime combination');
|
||||
test('paper requires explicit canonical configuration before connections, including initializeMode false', async () => {
|
||||
const container = createDiContainer<ServiceCradle>();
|
||||
await expect(
|
||||
registerOrchestratorServices(container, { role: 'paper', initializeMode: false })
|
||||
).rejects.toThrow('explicit canonicalPaper');
|
||||
await expect(
|
||||
createContainer({ services: { orchestrator: { defaultMode: 'paper' } } } as StockAppConfig)
|
||||
).rejects.toThrow('explicit canonicalPaper');
|
||||
await expect(
|
||||
createContainer({
|
||||
services: { orchestrator: { backtesting: { useRustEngine: false } } },
|
||||
} as StockAppConfig)
|
||||
).rejects.toThrow('Legacy financial execution is retired');
|
||||
});
|
||||
|
||||
test('unchecked role and backend options fail closed before service resolution', async () => {
|
||||
const container = createDiContainer<ServiceCradle>();
|
||||
for (const options of [
|
||||
|
|
@ -82,70 +84,45 @@ describe('research runtime composition admission', () => {
|
|||
).rejects.toThrow('role' in options ? 'Unsupported runtime role' : 'must be a boolean');
|
||||
}
|
||||
});
|
||||
|
||||
test('standalone_legacy_research_allowed without automatic paper initialization', async () => {
|
||||
const runtime = await compose({
|
||||
role: 'research-only',
|
||||
useRustEngine: false,
|
||||
allowSyntheticData: true,
|
||||
syntheticSeed: 42,
|
||||
});
|
||||
expect(runtime.BacktestEngine).toBeInstanceOf(BacktestEngine);
|
||||
expect(runtime.ModeManager!.getConfig()).toBeNull();
|
||||
await runtime.ModeManager!.initializeMode(config);
|
||||
const result = await runtime.BacktestEngine!.runBacktest(config);
|
||||
expect(result.status).toBe('completed');
|
||||
expect(result.trades.length).toBeGreaterThan(0);
|
||||
expect(runtime.ModeManager!.getConfig()).toEqual(config);
|
||||
});
|
||||
|
||||
test('research_only_paper_activation_denied through every exposed initializer', async () => {
|
||||
const runtime = await compose({ role: 'research-only', useRustEngine: false });
|
||||
const mode = runtime.ModeManager!;
|
||||
const execution = runtime.ExecutionService!;
|
||||
await mode.initializeMode(config);
|
||||
const engine = mode.getTradingEngine();
|
||||
const account = await execution.getAccount();
|
||||
const paper = { mode: 'paper' as const, startingCapital: 123 };
|
||||
let shutdowns = 0;
|
||||
mode.on('shutdown', () => shutdowns++);
|
||||
|
||||
await expect(mode.initializeMode(paper)).rejects.toThrow('only permits backtest');
|
||||
await expect(mode.transitionMode('backtest', 'paper', paper)).rejects.toThrow(
|
||||
'only permits backtest'
|
||||
test.each([{}, { role: 'research-only' as const }])(
|
||||
'default and explicit research compose one canonical engine without any account/feed/mode gateway',
|
||||
async options => {
|
||||
const { services, container } = await compose(options);
|
||||
expect(services.custom!.BacktestEngine).toBeInstanceOf(RustBacktestAdapter);
|
||||
for (const key of [
|
||||
'ModeManager',
|
||||
'ExecutionService',
|
||||
'MarketDataService',
|
||||
'StrategyManager',
|
||||
'PaperTradingManager',
|
||||
'CanonicalPaperRuntime',
|
||||
]) {
|
||||
expect(services.custom).not.toHaveProperty(key);
|
||||
expect(container.hasRegistration(key)).toBe(false);
|
||||
}
|
||||
const app = createRoutes(services);
|
||||
expect(await (await app.request('/health')).json()).toMatchObject({
|
||||
mode: 'research-only',
|
||||
execution: 'canonical-research',
|
||||
});
|
||||
expect((await app.request('/api/recovery')).status).toBe(503);
|
||||
for (const path of ['/api/orders', '/api/positions']) {
|
||||
expect((await app.request(path, { method: 'POST' })).status).toBe(409);
|
||||
}
|
||||
expect(await (await app.request('/api/paper/readiness')).json()).toMatchObject({
|
||||
configured: false,
|
||||
active: false,
|
||||
ready: false,
|
||||
operatorHalted: true,
|
||||
accountId: null,
|
||||
});
|
||||
}
|
||||
);
|
||||
test('cannot overlay the canonical graph on a legacy account runtime', async () => {
|
||||
const container = createDiContainer<ServiceCradle>();
|
||||
container.register({ serviceContainer: asValue({ logger, custom: { ExecutionService: {} } }) });
|
||||
await expect(registerOrchestratorServices(container)).rejects.toThrow(
|
||||
'fresh runtime composition'
|
||||
);
|
||||
await expect(execution.initialize(paper, engine)).rejects.toThrow('only permits backtest');
|
||||
const live = {
|
||||
mode: 'live' as const,
|
||||
broker: 'ib',
|
||||
accountId: 'not-a-real-account',
|
||||
accountType: 'cash' as const,
|
||||
riskLimits: { ...defaultRiskLimits },
|
||||
};
|
||||
await expect(mode.initializeMode(live)).rejects.toThrow('Live trading is disabled');
|
||||
await expect(execution.initialize(live, engine)).rejects.toThrow('Live trading is disabled');
|
||||
expect(shutdowns).toBe(0);
|
||||
expect(mode.getTradingEngine()).toBe(engine);
|
||||
expect(mode.getConfig()).toEqual(config);
|
||||
expect(await execution.getAccount()).toEqual(account);
|
||||
});
|
||||
|
||||
test('paper composition defaults to native and cannot be switched to a legacy shared mode', async () => {
|
||||
const runtime = await compose({ initializeMode: false });
|
||||
expect(runtime.BacktestEngine).toBeInstanceOf(RustBacktestAdapter);
|
||||
await expect(runtime.ModeManager!.initializeMode(config)).rejects.toThrow('only permits paper');
|
||||
await expect(
|
||||
runtime.ExecutionService!.initialize(config, makeExecution().engine)
|
||||
).rejects.toThrow('only permits paper');
|
||||
expect(runtime.ModeManager!.getConfig()).toBeNull();
|
||||
});
|
||||
|
||||
test('research-only native composition also forbids paper startup and activation', async () => {
|
||||
const runtime = await compose({ role: 'research-only' });
|
||||
expect(runtime.BacktestEngine).toBeInstanceOf(RustBacktestAdapter);
|
||||
expect(runtime.ModeManager!.getConfig()).toBeNull();
|
||||
await expect(
|
||||
runtime.ModeManager!.initializeMode({ mode: 'paper', startingCapital: 10000 })
|
||||
).rejects.toThrow('only permits backtest');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -23,9 +23,35 @@ import {
|
|||
import { buildExperimentPreview } from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import { prepareChronologicalValidation } from '../../apps/stock/web-api/src/services/validation-preview';
|
||||
import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
|
||||
import { parseWalkForwardDetail } from '../../apps/stock/web-app/src/features/experiments/services/walkForwardApi';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
import { walkForwardDataset } from '../fixtures/walk-forward';
|
||||
|
||||
test('saved walk-forward report preserves agent authorship across nested validation evidence', () => {
|
||||
const value = document('reported');
|
||||
if (!value.report) {
|
||||
throw new Error('Reported fixture needs its immutable report');
|
||||
}
|
||||
const actor = 'agent:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
|
||||
value.report.principal = actor;
|
||||
for (const window of value.windows) {
|
||||
if (!window.validation?.selection || !window.validation.report) {
|
||||
throw new Error('Reported window needs its selection and report');
|
||||
}
|
||||
window.validation.selection.principal = actor;
|
||||
window.validation.report.principal = actor;
|
||||
}
|
||||
const parsed = parseWalkForwardDetail(value);
|
||||
expect(parsed.report?.principal).toBe(actor);
|
||||
expect(parsed.windows.map(window => window.validation?.report?.principal)).toEqual([
|
||||
actor,
|
||||
actor,
|
||||
]);
|
||||
expect(() =>
|
||||
parseWalkForwardDetail({ ...value, report: { ...value.report, principal: 'agent:operator' } })
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const keys = ['window', 'document', 'Event', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
||||
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue