stock-bot/scripts/test/architecture.test.ts
Boki 4cd6038063 refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack
- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched)
- Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations()
- Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation
- Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims
- Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution
- Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
2026-11-27 00:11:50 -05:00

368 lines
13 KiB
TypeScript

import { existsSync, readFileSync } from 'node:fs';
import { dirname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'bun:test';
import ts from 'typescript';
import { runtimeImports } from '../runtime-imports';
const root = fileURLToPath(new URL('../../apps/stock/orchestrator/src/', import.meta.url));
const files = [...new Bun.Glob('**/*.ts').scanSync({ cwd: root })].map(file => join(root, file));
const imports = new Map(files.map(file => [file, runtimeImports(file)]));
function localFile(from: string, specifier: string): string | undefined {
if (!specifier.startsWith('.')) {
return undefined;
}
const path = resolve(dirname(from), specifier);
const target = [path, `${path}.ts`, join(path, 'index.ts')].find(
file => existsSync(file) && imports.has(file)
);
if (!target) {
throw new Error(`Unresolved local runtime import: ${relative(root, from)} -> ${specifier}`);
}
return target;
}
const graph = new Map(
[...imports].map(([file, dependencies]) => [
file,
dependencies
.map(specifier => localFile(file, specifier))
.filter((file): file is string => !!file),
])
);
function reachable(file: string, seen = new Set<string>()): Set<string> {
if (seen.has(file)) {
return seen;
}
seen.add(file);
for (const next of graph.get(file) ?? []) {
reachable(next, seen);
}
return seen;
}
describe('orchestrator architecture boundaries', () => {
it('local runtime dependencies are acyclic', () => {
const done = new Set<string>();
function visit(file: string, stack: string[]) {
if (stack.includes(file)) {
throw new Error(
`Runtime dependency cycle: ${[...stack, file].map(file => relative(root, file)).join(' -> ')}`
);
}
if (done.has(file)) {
return;
}
for (const next of graph.get(file) ?? []) {
visit(next, [...stack, file]);
}
done.add(file);
}
for (const file of files) {
visit(file, []);
}
});
it('contracts and native worker protocol cannot load services, storage or server adapters', () => {
const contracts = files.filter(file => file.startsWith(join(root, 'contracts/')));
for (const entry of [
...contracts,
join(root, 'types.ts'),
join(root, 'backtest/native-worker-protocol.ts'),
]) {
for (const file of reachable(entry)) {
const path = relative(root, file);
expect(
path === 'types.ts' ||
path.startsWith('contracts/') ||
path === 'backtest/native-worker-protocol.ts'
).toBe(true);
for (const specifier of imports.get(file) ?? []) {
expect(
specifier.startsWith('.') ||
[
'zod',
'@stock-bot/types',
'@stock-bot/stock-config/backtest',
'@stock-bot/stock-config/strategy',
'@stock-bot/stock-config/canonical-replay',
'@stock-bot/stock-config/canonical-research',
'@stock-bot/stock-config/candidate-execution',
'@stock-bot/stock-config/paper-deployments',
'@stock-bot/stock-config/paper-runtime',
'@stock-bot/stock-config/canonical-execution',
'@stock-bot/calculations/analytics',
'@stock-bot/calculations/returns',
'@stock-bot/research/results',
'@stock-bot/research/strategy-api',
].includes(specifier)
).toBe(true);
}
}
}
});
it('the shared backtest contract loads no configuration manager, services or application runtime', async () => {
const entry = resolve(root, '../../config/src/contracts/backtest.ts');
expect(runtimeImports(entry).sort()).toEqual([
'./canonical-research',
'@stock-bot/types',
'zod',
]);
const bundle = await Bun.build({ entrypoints: [entry], target: 'browser' });
expect(bundle.success).toBe(true);
const code = await bundle.outputs[0]?.text();
expect(code).toBeDefined();
expect(code).not.toContain('config-instance');
expect(code).not.toContain('PostgresClient');
expect(code).not.toContain('engine.node');
});
it('shared strategy catalog contracts cannot import strategy execution or application services', async () => {
const directory = resolve(root, '../../config/src/contracts');
for (const name of [
'strategy.ts',
'builtin-strategy.ts',
'strategy-names.ts',
'canonical-research.ts',
'canonical-replay.ts',
'candidate-execution.ts',
'paper-deployments.ts',
'research.ts',
]) {
for (const specifier of runtimeImports(join(directory, name))) {
expect(
[
'zod',
'@stock-bot/types',
'./builtin-strategy',
'./strategy-names',
'./strategy',
'./canonical-replay',
'./candidate-execution',
'./research',
].includes(specifier)
).toBe(true);
}
}
const bundle = await Bun.build({
entrypoints: [join(directory, 'strategy.ts')],
target: 'browser',
plugins: [
{
name: 'current-contract-types',
setup(builder) {
builder.onResolve({ filter: /^@stock-bot\/types$/ }, () => ({
path: fileURLToPath(new URL('../../libs/core/types/src/index.ts', import.meta.url)),
}));
},
},
],
});
expect(bundle.success).toBe(true);
const code = await bundle.outputs[0]?.text();
expect(code).toBeDefined();
for (const forbidden of [
'config-instance',
'PostgresClient',
'engine.node',
'createBuiltinStrategy',
]) {
expect(code).not.toContain(forbidden);
}
});
it('backtest adapter collaborators are injected, not located or constructed internally', () => {
for (const file of ['backtest/RustBacktestAdapter.ts']) {
const source = readFileSync(join(root, file), 'utf8');
expect(source).not.toMatch(/\b(OrchestratorServices|IServiceContainer)\b/);
const tree = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
function visit(node: ts.Node) {
if (ts.isPropertyAccessExpression(node)) {
expect(node.name.text).not.toBe('custom');
}
if (ts.isElementAccessExpression(node) && ts.isStringLiteral(node.argumentExpression)) {
expect(node.argumentExpression.text).not.toBe('custom');
}
if (ts.isNewExpression(node)) {
expect(node.expression.getText(tree)).not.toBe('StorageService');
}
ts.forEachChild(node, visit);
}
visit(tree);
}
});
it('retired execution paths and strategy-local financial frameworks cannot return', () => {
const retired = [
'backtest/RustBacktestEngine.ts',
'backtest/BacktestEngine.ts',
'backtest/BacktestMarket.ts',
'backtest/MarketSimulator.ts',
'backtest/BacktestPlayback.ts',
'backtest/BacktestReport.ts',
'core/ModeManager.ts',
'execution/SimulationExecution.ts',
'execution/StrategyRecovery.ts',
'execution/PostgresExecutionRepository.ts',
'execution/BacktestExecutionRepository.ts',
'execution/model.ts',
'execution/repository.ts',
'paper/PaperTradingManager.ts',
'services/ExecutionService.ts',
'services/MarketDataService.ts',
'strategies/BaseStrategy.ts',
'strategies/StrategyManager.ts',
'strategies/StrategyRegistry.ts',
'strategies/RustStrategy.ts',
'strategies/StrategyExecutor.ts',
'api/rest/orders.ts',
'api/rest/positions.ts',
'api/websocket/index.ts',
];
for (const file of retired) {
expect(existsSync(join(root, file))).toBe(false);
}
for (const file of files) {
expect(relative(root, file)).not.toMatch(
/^strategies\/(builtin|experimental|examples|rust|position|risk|signals|indicators)\//
);
}
expect(readFileSync(join(root, 'backtest/native-worker-protocol.ts'), 'utf8')).not.toContain(
"z.literal('run')"
);
expect(readFileSync(join(root, 'backtest/BacktestRunner.ts'), 'utf8')).not.toContain(
'engine.runBacktest('
);
});
it('native backtest execution stays in the worker and strategies cannot submit orders directly', () => {
const nativeEntrypoints = files.filter(
file =>
relative(root, file).startsWith('backtest/') &&
imports.get(file)?.includes('@stock-bot/engine')
);
expect(nativeEntrypoints.map(file => relative(root, file)).sort()).toEqual([
'backtest/native-replay.ts',
]);
for (const file of files) {
const path = relative(root, file);
if (reachable(file).has(join(root, 'backtest/native-replay.ts'))) {
expect([
'backtest/native-replay.ts',
'backtest/native-worker.ts',
'backtest/strategy-runtime.ts',
]).toContain(path);
}
const source = ts.createSourceFile(
file,
readFileSync(file, 'utf8'),
ts.ScriptTarget.Latest,
true
);
function visit(node: ts.Node) {
if (
ts.isImportDeclaration(node) &&
ts.isStringLiteral(node.moduleSpecifier) &&
node.moduleSpecifier.text === '@stock-bot/engine' &&
!node.importClause?.isTypeOnly
) {
const bindings = node.importClause?.namedBindings;
if (bindings && ts.isNamedImports(bindings)) {
for (const binding of bindings.elements) {
if (
!binding.isTypeOnly &&
(binding.propertyName ?? binding.name).text === 'BacktestEngine'
) {
throw new Error(`Retired native simulator imported by ${path}`);
}
if (
!binding.isTypeOnly &&
(binding.propertyName ?? binding.name).text === 'FinancialReplaySession'
) {
expect(path).toBe('backtest/native-replay.ts');
}
if (
!binding.isTypeOnly &&
(binding.propertyName ?? binding.name).text === 'stageFinancialTransaction'
) {
expect(path).toBe('execution/CanonicalPaperExecution.ts');
}
}
}
}
if (ts.isCallExpression(node)) {
const callee = node.expression;
const method = ts.isPropertyAccessExpression(callee)
? callee.name.text
: ts.isElementAccessExpression(callee) &&
callee.argumentExpression &&
ts.isStringLiteral(callee.argumentExpression)
? callee.argumentExpression.text
: undefined;
expect(method).not.toBe('addTypescriptStrategy');
if (path.startsWith('strategies/')) {
expect(method).not.toBe('submitOrder');
}
}
ts.forEachChild(node, visit);
}
visit(source);
}
});
it('reviewed analytics and window math live in the shared calculations library', () => {
for (const entry of ['equity', 'performance', 'return-statistics', 'trade-statistics']) {
expect(existsSync(join(root, 'analytics/' + entry + '.ts'))).toBe(false);
}
expect(existsSync(join(root, 'indicators/window-statistics.ts'))).toBe(false);
});
});
describe('shared research boundary', () => {
const repository = fileURLToPath(new URL('../../', import.meta.url));
const research = join(repository, 'libs/research/src');
it('shared domain files have no application implementation or service imports', () => {
for (const name of new Bun.Glob('**/*.ts').scanSync({ cwd: research })) {
const source = readFileSync(join(research, name), 'utf8');
const sourceFile = ts.createSourceFile(name, source, ts.ScriptTarget.Latest, true);
for (const statement of sourceFile.statements) {
if (
(ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement)) &&
statement.moduleSpecifier &&
ts.isStringLiteral(statement.moduleSpecifier)
) {
const dependency = statement.moduleSpecifier.text;
expect(dependency).not.toMatch(
/apps\/|orchestrator|@stock-bot\/(?:di|postgres|mongodb|questdb|engine|queue)(?:\/|$)/
);
}
}
}
});
it('the shared response contract bundles for browsers without server dependencies', async () => {
const result = await Bun.build({
entrypoints: [join(research, 'dataset-contracts.ts')],
target: 'browser',
write: false,
});
expect(result.success).toBe(true);
expect(await result.outputs[0]!.text()).not.toMatch(/node:crypto|node:fs|engine\.node/);
});
});
describe('canonical admission boundary', () => {
it('new run operations cannot construct legacy snapshots or invoke legacy execution', () => {
const path = fileURLToPath(
new URL('../../apps/stock/web-api/src/services/backtests/runs.ts', import.meta.url)
);
const dependencies = runtimeImports(path);
expect(
dependencies.some(value => /execution-engine|BacktestRunner|strategy-manager/.test(value))
).toBe(false);
const source = readFileSync(path, 'utf8');
expect(source).not.toContain('backtestRequestFromDefinition');
expect(source).not.toContain('legacyDefinition');
});
});