feat(research): cut over canonical runtime and enforce agent budgets

This commit is contained in:
Boki 2026-10-24 16:47:19 -04:00
parent ab08db82fd
commit bbf0dd4453
103 changed files with 6138 additions and 3112 deletions

View file

@ -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');
});
});