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
This commit is contained in:
Boki 2026-11-27 00:11:50 -05:00
parent ce9e2df67c
commit 4cd6038063
432 changed files with 1247 additions and 44469 deletions

View file

@ -76,8 +76,7 @@ describe('orchestrator architecture boundaries', () => {
expect(
path === 'types.ts' ||
path.startsWith('contracts/') ||
path === 'backtest/native-worker-protocol.ts' ||
path === 'backtest/canonical-result.ts'
path === 'backtest/native-worker-protocol.ts'
).toBe(true);
for (const specifier of imports.get(file) ?? []) {
expect(
@ -96,6 +95,7 @@ describe('orchestrator architecture boundaries', () => {
'@stock-bot/calculations/analytics',
'@stock-bot/calculations/returns',
'@stock-bot/research/results',
'@stock-bot/research/strategy-api',
].includes(specifier)
).toBe(true);
}
@ -173,52 +173,8 @@ describe('orchestrator architecture boundaries', () => {
}
});
it('recovery and the ledger port do not depend on concrete adapters, strategies or the service container', () => {
for (const entry of [
'execution/SimulationExecution.ts',
'execution/StrategyRecovery.ts',
'execution/repository.ts',
'execution/strategy-recovery.ts',
'execution/model.ts',
]) {
for (const file of reachable(join(root, entry))) {
expect(relative(root, file)).not.toMatch(/^(services|strategies|core|data)\//);
expect(relative(root, file)).not.toMatch(/(Postgres|Backtest)ExecutionRepository/);
for (const specifier of imports.get(file) ?? []) {
expect(
['@stock-bot/services', '@stock-bot/di', '@stock-bot/engine', 'awilix'].includes(
specifier
)
).toBe(false);
}
}
}
expect(imports.get(join(root, 'execution/repository.ts'))).toEqual([]);
});
it('the strategy manager cannot select or directly import concrete strategies', () => {
const file = join(root, 'strategies/StrategyManager.ts');
expect(
graph
.get(file)
?.some(target => /^strategies\/(builtin|experimental)\//.test(relative(root, target)))
).toBe(false);
expect(readFileSync(file, 'utf8')).not.toMatch(/switch\s*\(\s*config\.name/);
expect(
[...reachable(join(root, 'strategies/StrategyRegistry.ts'))]
.map(file => relative(root, file))
.sort()
).toEqual(['contracts/strategy-names.ts', 'strategies/StrategyRegistry.ts']);
});
it('backtest and strategy lifecycle collaborators are injected, not located or constructed internally', () => {
for (const file of [
'backtest/BacktestEngine.ts',
'backtest/RustBacktestAdapter.ts',
'strategies/StrategyManager.ts',
'core/ModeManager.ts',
'services/MarketDataService.ts',
]) {
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);
@ -238,39 +194,47 @@ describe('orchestrator architecture boundaries', () => {
}
});
it('concrete strategies can only be loaded by the registry or other strategy implementations', () => {
for (const [file, dependencies] of graph) {
const owner = relative(root, file);
for (const dependency of dependencies) {
const target = relative(root, dependency);
if (!/^strategies\/(builtin|experimental)\//.test(target)) {
continue;
}
expect(
owner === 'strategies/builtin-strategies.ts' ||
/^strategies\/(builtin|experimental)\//.test(owner)
).toBe(true);
if (owner.startsWith('strategies/builtin/')) {
expect(target.startsWith('strategies/experimental/')).toBe(false);
}
}
}
});
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\/(examples|rust|position|risk|signals|indicators)\//
/^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', () => {
@ -298,7 +262,6 @@ describe('orchestrator architecture boundaries', () => {
true
);
function visit(node: ts.Node) {
// Check named imports anywhere, including aliases; a new wrapper outside backtest/ is still forbidden.
if (
ts.isImportDeclaration(node) &&
ts.isStringLiteral(node.moduleSpecifier) &&
@ -349,75 +312,11 @@ describe('orchestrator architecture boundaries', () => {
}
});
it('production research and paper entrypoints cannot reach prototype financial execution', () => {
const forbidden = [
'backtest/BacktestEngine.ts',
'backtest/BacktestMarket.ts',
'core/ModeManager.ts',
'execution/SimulationExecution.ts',
'execution/model.ts',
'services/ExecutionService.ts',
'paper/PaperTradingManager.ts',
'api/rest/orders.ts',
'api/rest/positions.ts',
'api/websocket/index.ts',
];
for (const entry of [
'index.ts',
'container.ts',
'simple-container.ts',
'backtest/native-worker.ts',
]) {
const production = [...reachable(join(root, entry))].map(file => relative(root, file));
for (const prototype of forbidden) {
expect(production).not.toContain(prototype);
}
}
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('backtest playback cannot depend on trading, data, reporting or service adapters', () => {
const dependencies = [...reachable(join(root, 'backtest/BacktestPlayback.ts'))]
.map(file => relative(root, file))
.sort();
expect(dependencies).toEqual(['backtest/BacktestPlayback.ts', 'backtest/execution-engine.ts']);
});
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);
expect(imports.get(join(root, 'analytics/PerformanceAnalyzer.ts'))).toEqual([
'@stock-bot/calculations/analytics',
]);
});
it('backtest reports are independent of run control, native engines, data loading and financial mutation', () => {
for (const entry of ['backtest/BacktestReport.ts', 'backtest/report-format.ts']) {
for (const file of reachable(join(root, entry))) {
expect(relative(root, file)).not.toMatch(/^(services|strategies|core|data|execution)\//);
expect(relative(root, file)).not.toMatch(
/backtest\/(BacktestEngine|BacktestMarket|BacktestRunner|BacktestPlayback)/
);
for (const specifier of imports.get(file) ?? []) {
expect(
specifier.startsWith('.') ||
[
'zod',
'@stock-bot/invariants',
'@stock-bot/logger',
'@stock-bot/calculations/analytics',
].includes(specifier)
).toBe(true);
}
}
}
});
});
@ -429,15 +328,25 @@ describe('shared research boundary', () => {
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)) {
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)(?:\/|$)/);
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 });
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/);
});
@ -445,9 +354,13 @@ describe('shared research boundary', () => {
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 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);
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');

View file

@ -18,12 +18,8 @@ const sourceFiles = [...new Bun.Glob('src/**/*.ts').scanSync({ cwd: utilsRoot })
describe('shared library boundaries', () => {
it('utils exposes general helpers without a financial framework', () => {
expect(Object.keys(utils).sort()).toEqual([
'createProxyUrl',
'dateUtils',
'fetch',
'getRandomUserAgent',
'sleep',
'utcDates',
]);
expect(utils.fetch).toBe(fetch);
expect(utils.getRandomUserAgent).toBe(getRandomUserAgent);
@ -32,10 +28,8 @@ describe('shared library boundaries', () => {
'.': './src/index.ts',
'./fetch': './src/fetch.ts',
'./user-agent': './src/user-agent.ts',
'./common': './src/common.ts',
'./dates': './src/dateUtils.ts',
});
for (const retired of ['assertions', 'calculations', 'src/fetch', 'dateUtils']) {
for (const retired of ['assertions', 'calculations', 'common', 'dates', 'src/fetch', 'dateUtils']) {
expect(() => Bun.resolveSync(`@stock-bot/utils/${retired}`, root)).toThrow();
}
});
@ -97,11 +91,11 @@ describe('shared library boundaries', () => {
'.',
'./analytics',
'./indicators',
'./legacy',
'./market-data',
'./returns',
]);
for (const path of [
'legacy',
'research',
'src/legacy/basic-calculations',
'legacy/technical-indicators',

View file

@ -12,7 +12,7 @@ import { parseFinancialDecimal } from '@stock-bot/types';
import {
financialTransactionRequestSchema,
parseFinancialTransactionResult,
} from '../../apps/stock/orchestrator/src/contracts/canonical-execution';
} from '@stock-bot/stock-config/canonical-execution';
import nativeReplayLoad from '../../test/fixtures/native-replay-load.json';
describe('generated native bindings', () => {

View file

@ -1,12 +0,0 @@
import { expect, test } from 'bun:test';
import { createExampleRuntime } from '../../apps/stock/orchestrator/examples/example-runtime';
test('offline examples use the shared DI graph without starting a real-time feed', async () => {
const runtime = await createExampleRuntime();
expect(runtime.container.custom?.StorageService).toBe(runtime.storageService);
expect(runtime.container.custom?.StrategyManager).toBe(runtime.strategyManager);
expect(runtime.container.mongodb).toBeNull();
expect(runtime.container.queueManager).toBeNull();
expect(runtime.modeManager.getConfig()).toBeNull();
expect(() => runtime.modeManager.getTradingEngine()).toThrow('Trading engine not initialized');
});

View file

@ -14,7 +14,7 @@ import {
import type {
StrategyContext,
StrategyProgram,
} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
} from '@stock-bot/research/strategy-api';
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
import { packageBuiltinStrategies } from '../package-builtin-strategies';
import { runtimeImports } from '../runtime-imports';

View file

@ -9,7 +9,7 @@ import {
StrategyReplayError,
type StrategyProgram,
} from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
import { nativeAdmissionOrders } from '../../apps/stock/orchestrator/src/contracts/native-replay';
import { nativeAdmissionOrders } from '@stock-bot/stock-config/canonical-replay';
import { nativeReplayFixture } from '../../test/fixtures/native-replay';
const hold = () => ({ mode: 'target' as const, targets: [] });

View file

@ -32,7 +32,7 @@ function config(path: string) {
}
describe('workspace verification', () => {
it('the real root build selects every buildable workspace and excludes the command aggregate', () => {
it('the real root build selects every buildable workspace', () => {
const result = Bun.spawnSync([process.execPath, 'run', 'build', '--dry=json'], {
cwd: root,
env: { ...process.env, TURBO_TELEMETRY_DISABLED: '1' },
@ -42,11 +42,10 @@ describe('workspace verification', () => {
const planned = new Set(plan.tasks.map((task: { taskId: string }) => task.taskId));
for (const file of packageFiles) {
const pkg = JSON.parse(readFileSync(join(root, file), 'utf8'));
if (pkg.scripts?.build && pkg.name !== '@stock-bot/stock-app') {
if (pkg.scripts?.build) {
expect(planned.has(`${pkg.name}#build`)).toBe(true);
}
}
expect(planned.has('@stock-bot/stock-app#build')).toBe(false);
});
it('research development selects only the API, worker and web application', () => {
@ -82,7 +81,7 @@ describe('workspace verification', () => {
const success = invoke('0');
expect(success.exitCode).toBe(0);
const output = new TextDecoder().decode(success.stdout);
expect(output).toContain('compose\n-f\ndocker-compose.yml\nup\n-d\ndragonfly\npostgres\nquestdb\nmongodb');
expect(output).toContain('compose\n-f\ndocker-compose.dev.yml\nup\n-d\ndragonfly\npostgres\nquestdb\nmongodb');
expect(output).not.toContain('down');
const failed = invoke('23');
expect(failed.exitCode).toBe(23);