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

@ -1,6 +1,6 @@
import { parseFinancialDecimal } from '@stock-bot/types';
import type { CanonicalMatchingConfig } from '../../apps/stock/orchestrator/src/contracts/canonical-execution';
import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
import type { CanonicalMatchingConfig } from '@stock-bot/stock-config/canonical-execution';
import type { StrategyProgram } from '@stock-bot/research/strategy-api';
import type { CanonicalPaperInput } from '../../apps/stock/orchestrator/src/execution/canonical-paper';
export function canonicalConfig(owners = ['A']): CanonicalMatchingConfig {

View file

@ -3,7 +3,7 @@ import {
type BuiltinStrategySelection,
type MeanReversionSignalParameters,
type MeanReversionStrategySelection,
} from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
} from '@stock-bot/stock-config/strategy';
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
import { nativeReplayFixture } from './native-replay';

View file

@ -2,7 +2,7 @@ import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
import { smaStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
import { smaStrategySelectionSchema } from '@stock-bot/stock-config/strategy';
import { createSmaStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-sma';
import { canonicalRunnerFixture } from './canonical-runner';

View file

@ -1,4 +1,4 @@
import { smaStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
import { smaStrategySelectionSchema } from '@stock-bot/stock-config/strategy';
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
import { nativeReplayFixture } from './native-replay';

View file

@ -1,55 +1,4 @@
import { TradingEngine } from '@stock-bot/engine';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import type { ExecutionRepository } from '../../apps/stock/orchestrator/src/execution/repository';
import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService';
import type { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
import {
BacktestConfigSchema,
type MarketData,
type OrderRequest,
} from '../../apps/stock/orchestrator/src/types';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
export const logger = getLogger('execution-test');
export const start = Date.parse('2024-01-01T00:00:00Z');
export const config = BacktestConfigSchema.parse({
mode: 'backtest',
strategy: 'sma-crossover',
symbols: ['A.US', 'B.US'],
startDate: new Date(start).toISOString(),
endDate: '2025-01-01T00:00:00Z',
initialCapital: 10000,
dataFrequency: '1d',
commission: 0.001,
slippage: 0,
});
export function quote(
id: string,
price = 100,
size = 100,
timestamp = start,
symbol = 'A'
): MarketData {
return {
type: 'quote',
eventId: id,
data: { symbol, bid: price, ask: price, bidSize: size, askSize: size, timestamp },
};
}
export function order(
clientOrderId: string,
side: 'buy' | 'sell' = 'buy',
quantity = 10
): OrderRequest {
return { symbol: 'A', side, quantity, orderType: 'market', timeInForce: 'DAY', clientOrderId };
}
export function makeExecution(repository?: ExecutionRepository, clock = () => start) {
const engine = new TradingEngine('backtest', {
startTime: start,
endTime: Date.parse(config.endDate),
speedMultiplier: 0,
initialCapital: 10000,
});
const execution = new ExecutionService({ logger }, {} as StorageService, { repository, clock });
return { execution, engine };
}

View file

@ -1,5 +1,5 @@
import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay';
import { replayTraceSchema } from '../../apps/stock/orchestrator/src/contracts/native-replay';
import { replayTraceSchema } from '@stock-bot/stock-config/canonical-replay';
function send(message: unknown): Promise<void> {
return new Promise((resolve, reject) =>

View file

@ -1,4 +1,4 @@
import type { ReplayConfig } from '../../apps/stock/orchestrator/src/contracts/native-replay';
import type { ReplayConfig } from '@stock-bot/stock-config/canonical-replay';
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
/** Retained synthetic sessions, raw executable bars, explicit availability. */

View file

@ -2,7 +2,7 @@ import { parseFinancialDecimal } from '@stock-bot/types';
import type {
PaperConfigurationInput,
PaperFrameInput,
} from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
} from '@stock-bot/stock-config/paper-runtime';
import { canonicalConfig } from './canonical-paper';
export function paperFeedConfiguration(instruments = ['X']): PaperConfigurationInput {

View file

@ -3,11 +3,11 @@ import { readFileSync } from 'node:fs';
import { Pool } from 'pg';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { parseFinancialDecimal } from '@stock-bot/types';
import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
import type { StrategyProgram } from '@stock-bot/research/strategy-api';
import type {
PaperConfigurationInput,
PaperFrameInput,
} from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
} from '@stock-bot/stock-config/paper-runtime';
import type {
CanonicalExecutionRepository,
CanonicalTransaction,

View file

@ -1,56 +0,0 @@
/** Disposable process used only against an isolated stock_bot_safety schema. */
import { Pool } from 'pg';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository';
import { logger, makeExecution, start } from './execution';
import { attachCounter, CounterStrategy, FaultRepository } from './strategy-recovery';
const url = process.env.PIPELINE_TEST_DATABASE_URL,
schema = process.env.STRATEGY_FIXTURE_SCHEMA,
phase = process.env.STRATEGY_FIXTURE_PHASE;
if (
!url ||
!new URL(url).pathname.startsWith('/stock_bot_safety') ||
!schema ||
!/^stock_bot_safety_[a-f0-9]+$/.test(schema) ||
!['decision', 'checkpoint', 'dispatch'].includes(phase ?? '')
) {
throw new Error('Unsafe strategy crash fixture');
}
const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema });
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
const repository = new FaultRepository(new PostgresExecutionRepository(postgres));
const { execution, engine } = makeExecution(repository, () => start + 100);
await execution.initialize(
{
mode: 'paper',
accountId: 'fixture',
startingCapital: 10000,
commission: 0.001,
slippage: 0,
maxQuoteAgeMs: 1000,
},
engine
);
const blocked = async () => {
process.send?.({ phase });
await new Promise<void>(() => {});
};
const strategy = new CounterStrategy(execution);
if (phase === 'decision') {
strategy.onDecision = blocked;
} else {
repository.fault = {
method: 'putIntent',
stage: 'commit',
matches: value =>
(value as { status: string }).status === (phase === 'checkpoint' ? 'pending' : 'dispatched'),
hook: blocked,
};
}
await attachCounter(execution, strategy);
throw new Error('Crash fixture did not reach its requested boundary');

View file

@ -1,158 +0,0 @@
import { EventEmitter } from 'node:events';
import { z } from 'zod';
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
import type {
ExecutionRepository,
ExecutionTransaction,
} from '../../apps/stock/orchestrator/src/execution/repository';
import type {
ExecutionService,
StrategyFill,
} from '../../apps/stock/orchestrator/src/services/ExecutionService';
import {
BaseStrategy,
type Signal,
} from '../../apps/stock/orchestrator/src/strategies/BaseStrategy';
import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
import type {
StrategyDependencies,
StrategyRegistry,
} from '../../apps/stock/orchestrator/src/strategies/StrategyRegistry';
import type { MarketData, StrategyConfig } from '../../apps/stock/orchestrator/src/types';
import { logger } from './execution';
export const recoveryConfig: StrategyConfig = {
id: 'counter',
name: 'fixture',
symbols: ['A'],
parameters: {},
allocation: 1,
enabled: true,
};
export function makeStrategyManager({
execution,
modeManager,
registry = createBuiltinStrategyRegistry(),
marketData = new EventEmitter(),
}: StrategyDependencies & { registry?: StrategyRegistry; marketData?: EventEmitter }) {
return new StrategyManager({
logger,
execution,
marketData,
createStrategy: config => registry.create(config, { execution, modeManager }),
});
}
export class CounterStrategy extends BaseStrategy {
count = 0;
equities: number[] = [];
failDecision = false;
failFill = false;
onDecision?: () => Promise<void>;
version = 'counter/v1';
constructor(execution: ExecutionService, config = recoveryConfig) {
super(config, {} as ModeManager, execution);
}
override getCheckpointVersion() {
return this.version;
}
protected override captureIndicators() {
return { count: this.count, equities: this.equities };
}
protected override restoreIndicators(input: unknown) {
const state = z
.object({ count: z.number().int().nonnegative(), equities: z.array(z.number().finite()) })
.parse(input);
this.count = state.count;
this.equities = state.equities;
}
protected updateIndicators() {
this.count++;
}
protected async generateSignal(data: MarketData): Promise<Signal | null> {
this.equities.push((await this.executionService.getAccount()).equity);
await this.onDecision?.();
if (this.failDecision) {
throw new Error('injected decision failure');
}
return { type: 'buy', symbol: data.data.symbol, strength: 1, metadata: { quantity: 1 } };
}
override async onFill(fill: StrategyFill) {
await super.onFill(fill);
if (this.failFill) {
throw new Error('injected fill callback failure');
}
}
}
export async function attachCounter(
execution: ExecutionService,
strategy = new CounterStrategy(execution)
) {
const manager = new StrategyManager({
logger,
execution,
marketData: new EventEmitter(),
createStrategy: () => {
throw new Error('Counter fixtures attach their strategies directly');
},
});
try {
await manager.attachStrategy(strategy);
} catch (error) {
await manager.shutdown();
throw error;
}
return { manager, strategy };
}
export class FaultRepository implements ExecutionRepository {
fault?: {
method: keyof ExecutionTransaction;
matches: (argument: unknown) => boolean;
stage: 'before' | 'after' | 'commit';
hook?: () => Promise<void>;
};
constructor(private readonly delegate: ExecutionRepository) {}
initialize(...args: Parameters<ExecutionRepository['initialize']>) {
return this.delegate.initialize(...args);
}
async transact<T>(account: string, work: (tx: ExecutionTransaction) => Promise<T>): Promise<T> {
let matched: typeof this.fault;
const result = await this.delegate.transact(account, tx =>
work(
new Proxy(tx, {
get: (target, key: keyof ExecutionTransaction) => {
const value = target[key];
if (typeof value !== 'function') {
return value;
}
return async (...args: unknown[]) => {
const fault = this.fault;
const hit = fault && key === fault.method && fault.matches(args[0]);
if (hit) {
this.fault = undefined;
matched = fault;
}
if (hit && fault.stage === 'before') {
throw new Error('injected transaction failure');
}
const answer = await Reflect.apply(value, target, args);
if (hit && fault.stage === 'after') {
throw new Error('injected transaction failure');
}
return answer;
};
},
})
)
);
if (matched?.stage === 'commit') {
if (matched.hook) {
await matched.hook();
}
throw new Error('injected lost commit acknowledgement');
}
return result;
}
}