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

@ -7,7 +7,7 @@ import {
IsolatedCandidateController,
readCandidateExecution,
} from '../apps/stock/orchestrator/src/backtest/candidate-sandbox';
import { readCanonicalBuildIdentity } from '../apps/stock/orchestrator/src/backtest/canonical-build';
import { readCanonicalBuildIdentity } from '@stock-bot/trading-runtime/canonical-build';
import {
NativeReplaySession,
prepareReplayLoad,

View file

@ -1,47 +0,0 @@
/** Local, deterministic workload; no native engine, database, network or trading credentials. */
import { defaultRiskLimits, type Account } from '../apps/stock/orchestrator/src/execution/model';
import { BacktestExecutionRepository } from '../apps/stock/orchestrator/src/execution/BacktestExecutionRepository';
const account: Account = {
initialCapital: 10000,
cash: 10000,
realizedPnl: 0,
dailyPnl: 0,
day: '2024-01-01',
commission: 0.001,
slippage: 0,
limits: { ...defaultRiskLimits },
maxQuoteAgeMs: 60000,
positions: {},
quotes: {},
strategyPositions: {},
};
for (const history of [0, 1000, 10000]) {
const repository = new BacktestExecutionRepository();
await repository.initialize('benchmark', account);
await repository.transact('benchmark', async tx => {
for (let i = 0; i < history; i++) {
await tx.appendJournal({
kind: 'market',
market: {
type: 'trade',
eventId: String(i),
data: { symbol: 'A.US', price: 100, size: 1, side: 'buy', timestamp: i },
},
recipients: [],
account,
});
}
});
const start = performance.now();
for (let i = 0; i < 200; i++) {
await repository.transact('benchmark', async tx => ({
cash: tx.account.cash,
next: await tx.nextJournal(history),
}));
}
process.stdout.write(
`${history} journal events: ${((performance.now() - start) / 200).toFixed(3)} ms/transaction\n`
);
}

View file

@ -6,7 +6,7 @@ import type {
ReplayOutput,
ReplayProjectionResult,
ReplayResultFormat,
} from '../apps/stock/orchestrator/src/contracts/native-replay';
} from '@stock-bot/stock-config/canonical-replay';
export const replayProfiles = ['none', 'sparse', 'turnover'] as const;
export type ReplayProfile = (typeof replayProfiles)[number];

View file

@ -6,7 +6,7 @@ import { cpus, freemem, platform, release, totalmem } from 'node:os';
import { resolve } from 'node:path';
import { defined } from '@stock-bot/invariants';
import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
import { readCanonicalBuildIdentity } from '../apps/stock/orchestrator/src/backtest/canonical-build';
import { readCanonicalBuildIdentity } from '@stock-bot/trading-runtime/canonical-build';
import type { ResearchConcurrency } from '../apps/stock/orchestrator/src/backtest/ResearchBacktestPool';
import { canonicalReproductionHash } from '../apps/stock/web-api/src/services/reproduction-comparison';
import { nativeReplayFixture } from '../test/fixtures/native-replay';

View file

@ -5,7 +5,7 @@ import { readFileSync } from 'node:fs';
import { loadavg } from 'node:os';
import { join } from 'node:path';
import type { ReplayOutput, ReplayProjectionResult } from '../apps/stock/orchestrator/src/contracts/native-replay';
import type { ReplayOutput, ReplayProjectionResult } from '@stock-bot/stock-config/canonical-replay';
import type { FinancialStrategyDecision } from '@stock-bot/types';
type Mode = 'sma' | 'recorded';
@ -29,7 +29,7 @@ export async function smaChild(root: string, workload: SmaWorkload, mode: Mode)
const importsStart = performance.now();
const { nativeReplayFixture } = await import('../test/fixtures/native-replay');
const { validateDatasetV2 } = await import('../apps/stock/orchestrator/src/data/historical-dataset-v2');
const { builtinStrategySelectionSchema } = await import('../apps/stock/orchestrator/src/contracts/builtin-strategy');
const { builtinStrategySelectionSchema } = await import('@stock-bot/stock-config/strategy');
const { createBuiltinStrategy, validateBuiltinStrategyBindings } = await import('../apps/stock/orchestrator/src/strategies/canonical-builtins');
const { prepareReplayLoad, NativeReplaySession, runReplaySession } = await import('../apps/stock/orchestrator/src/backtest/native-replay');
const { runStrategyReplay } = await import('../apps/stock/orchestrator/src/backtest/strategy-runtime');

View file

@ -19,6 +19,4 @@ for option in "$@"; do
esac
done
# The stock-app package contains convenience commands, not buildable source.
# Select all leaf workspaces so nested stock services are actually built.
exec bun run turbo run build --filter='!@stock-bot/stock-app' "${args[@]}"
exec bun run turbo run build "${args[@]}"

View file

@ -1,53 +0,0 @@
#!/bin/bash
# Build Clean Script for Stock Bot
# Clean previous builds then build everything fresh
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
echo -e "${CYAN}🧹 Clean Build Process Starting...${NC}"
# Store original location
ORIGINAL_DIR=$(pwd)
# Find git root directory
GIT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)
if [ $? -ne 0 ]; then
echo -e "${RED}Error: Not in a git repository. Please run this script from within the stock-bot git repository.${NC}"
exit 1
fi
cd "$GIT_ROOT"
cleanup() {
cd "$ORIGINAL_DIR"
}
# Set up cleanup on exit
trap cleanup EXIT
# Step 1: Clean everything
echo -e "${YELLOW}🗑️ Cleaning previous builds...${NC}"
./scripts/clean.sh --dist --cache --tsbuildinfo
if [ $? -ne 0 ]; then
echo -e "${RED}❌ Clean failed${NC}"
exit 1
fi
# Step 2: Build everything fresh
echo -e "${GREEN}🏗️ Building everything fresh...${NC}"
./scripts/build-all.sh
if [ $? -ne 0 ]; then
echo -e "${RED}❌ Build failed${NC}"
exit 1
fi
echo -e "${GREEN}✅ Clean build completed successfully!${NC}"
echo -e "${CYAN}🚀 Project is ready for deployment.${NC}"

View file

@ -1,44 +0,0 @@
#!/bin/bash
# Build libraries using Turbo instead of direct commands
# This leverages Turbo's caching and dependency management
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
echo -e "${CYAN}Building libraries using Turborepo...${NC}"
# Store original location
ORIGINAL_DIR=$(pwd)
# Find git root directory
GIT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)
if [ $? -ne 0 ]; then
echo -e "${RED}Error: Not in a git repository. Please run this script from within the stock-bot git repository.${NC}"
exit 1
fi
cd "$GIT_ROOT"
cleanup() {
cd "$ORIGINAL_DIR"
}
# Set up cleanup on exit
trap cleanup EXIT
# Build all libraries using turbo
echo -e "${GREEN}Building all libraries at once with Turborepo...${NC}"
npx turbo build --filter="./libs/*"
if [ $? -ne 0 ]; then
echo -e "${RED}Failed to build libraries with Turborepo. Exiting.${NC}"
exit 1
else
echo -e "${GREEN}All libraries built successfully!${NC}"
fi
cd "$GIT_ROOT"

View file

@ -3,6 +3,10 @@
# Trading Bot Docker Management Script (dev / qa / prod)
set -euo pipefail
# Ensure top-level `name:` in each docker-compose*.yml (stock-bot-dev vs stock-bot vs stock-bot-prod)
# is never overridden by COMPOSE_PROJECT_NAME in .env or caller shell environment.
unset COMPOSE_PROJECT_NAME
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'

View file

@ -1,368 +0,0 @@
#!/usr/bin/env bun
/**
* Redis/Dragonfly Connection Monitor - Simplified Version
*
* Shows active connections grouped by client name with basic stats
*
* Usage:
* bun run scripts/get-redis-connections.ts # Show connections once
* bun run scripts/get-redis-connections.ts --monitor # Monitor in real-time
*/
import Redis from 'ioredis';
interface ClientInfo {
id: string;
name?: string;
addr: string;
age: string;
idle: string;
cmd: string;
tot?: string;
fd?: string;
flags?: string;
db?: string;
sub?: string;
psub?: string;
multi?: string;
qbuf?: string;
qbufFree?: string;
obl?: string;
oll?: string;
omem?: string;
events?: string;
[key: string]: string | undefined; // Index signature for dynamic properties
}
interface GroupedConnections {
[clientName: string]: {
count: number;
connections: ClientInfo[];
totalCommands: number;
avgIdleTime: number;
};
}
class RedisConnectionMonitor {
private redis: Redis;
constructor() {
this.redis = new Redis({
host: process.env.DRAGONFLY_HOST || 'localhost',
port: parseInt(process.env.DRAGONFLY_PORT || '6379'),
password: process.env.DRAGONFLY_PASSWORD || undefined,
db: parseInt(process.env.DRAGONFLY_DATABASE || '0'),
maxRetriesPerRequest: 3,
connectTimeout: 10000,
lazyConnect: true,
});
}
/**
* Parse CLIENT LIST output into structured data
*/
private parseClientList(clientListOutput: string): ClientInfo[] {
const lines = clientListOutput.trim().split('\n');
const clients: ClientInfo[] = [];
for (const line of lines) {
if (!line.trim()) continue;
const client: ClientInfo = {
id: '',
addr: '',
age: '',
idle: '',
cmd: '',
};
// Parse key=value pairs
const pairs = line.split(' ');
for (const pair of pairs) {
const [key, value] = pair.split('=');
if (key && value !== undefined) {
client[key] = value;
}
}
clients.push(client);
}
return clients;
}
/**
* Clean up client names by removing timestamp/number suffixes
*/
private cleanClientName(rawName: string): string {
if (!rawName || rawName === 'unnamed') {
return rawName;
}
// Remove timestamp/number suffixes (like BATCH-PROCESSOR-1749573709724)
// Pattern: Remove dash followed by numbers at the end
let cleanName = rawName.replace(/-\d+$/, '');
// Also handle patterns like NAME---1-1- (RedisInsight style)
cleanName = cleanName.replace(/---\d+-\d+-?$/, '');
// Convert to a more readable format
cleanName = cleanName
.replace(/-/g, ' ')
.toLowerCase()
.replace(/\b\w/g, l => l.toUpperCase());
return cleanName;
}
/**
* Group connections by client name/type
*/
private groupConnectionsByName(clients: ClientInfo[]): GroupedConnections {
const grouped: GroupedConnections = {};
for (const client of clients) {
// Determine client name - use 'name' field if set, otherwise infer from other properties
let clientName = client.name || 'unnamed';
// Clean up the client name by removing timestamps/numbers
if (clientName && clientName !== 'unnamed') {
clientName = this.cleanClientName(clientName);
}
// If no name is set, try to infer from the connection characteristics
if (clientName === 'unnamed' || !clientName) {
if (client.flags?.includes('M')) {
clientName = 'Master Connection';
} else if (client.flags?.includes('S')) {
clientName = 'Slave Connection';
} else if (client.flags?.includes('P')) {
clientName = 'PubSub Connection';
} else if (client.cmd === 'monitor') {
clientName = 'Monitor Connection';
} else if (client.addr.includes('127.0.0.1') || client.addr.includes('localhost')) {
clientName = 'Local Client';
} else if (client.addr.includes('172.') || client.addr.includes('192.168.')) {
clientName = 'Docker Network Client';
} else {
clientName = `Client ${client.addr.split(':')[0]}`;
}
}
if (!grouped[clientName]) {
grouped[clientName] = {
count: 0,
connections: [],
totalCommands: 0,
avgIdleTime: 0,
};
}
grouped[clientName].count++;
grouped[clientName].connections.push(client);
// Parse command count if available
const cmdCount = client.tot ? parseInt(client.tot) : 0;
grouped[clientName].totalCommands += cmdCount;
}
// Calculate average idle times
for (const groupName in grouped) {
const group = grouped[groupName];
const totalIdle = group.connections.reduce((sum, client) => {
return sum + parseInt(client.idle || '0');
}, 0);
group.avgIdleTime = group.count > 0 ? Math.round(totalIdle / group.count) : 0;
}
return grouped;
}
/**
* Format connection details for display
*/
private formatConnectionDetails(client: ClientInfo): string {
const details = [
`ID: ${client.id}`,
`Address: ${client.addr}`,
`Age: ${client.age}s`,
`Idle: ${client.idle}s`,
];
if (client.tot) {
details.push(`Total Commands: ${client.tot}`);
}
return details.join(', ');
}
/**
* Get and display all connections grouped by name
*/
async getConnectionsGroupedByName(): Promise<void> {
try {
console.log('🔍 Connecting to Dragonfly...');
// Check if already connected, if not connect
if (this.redis.status !== 'ready') {
await this.redis.connect();
}
console.log('📡 Fetching client connections...');
const clientListOutput = await this.redis.client('LIST') as string;
if (!clientListOutput) {
console.log('❌ No client information available');
return;
}
const clients = this.parseClientList(clientListOutput);
const grouped = this.groupConnectionsByName(clients);
// Get server and memory info first
const info = await this.redis.info('server');
const memoryInfo = await this.redis.info('memory');
// Parse server info
const infoLines = info.split('\n');
let version = '', uptime = '', connectedClients = '';
for (const line of infoLines) {
if (line.includes('dragonfly_version')) version = line.split(':')[1]?.trim() || '';
if (line.includes('uptime_in_seconds')) {
const seconds = parseInt(line.split(':')[1]?.trim() || '0');
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
uptime = `${days}d ${hours}h`;
}
if (line.includes('connected_clients')) connectedClients = line.split(':')[1]?.trim() || '';
}
// Parse memory info
const memoryLines = memoryInfo.split('\n');
let usedMemory = '', maxMemory = '', memoryPercent = '';
for (const line of memoryLines) {
if (line.includes('used_memory_human')) usedMemory = line.split(':')[1]?.trim() || '';
if (line.includes('maxmemory_human')) maxMemory = line.split(':')[1]?.trim() || '';
if (line.includes('used_memory_percentage')) memoryPercent = line.split(':')[1]?.trim() || '';
}
console.log('\n🎯 DRAGONFLY CONNECTION SUMMARY');
console.log('═'.repeat(60));
console.log(`🔗 Connections: ${clients.length} active (${Object.keys(grouped).length} groups) | 🖥️ Version: ${version} | ⏱️ Uptime: ${uptime}`);
console.log(`💾 Memory: ${usedMemory}${maxMemory ? ` / ${maxMemory}` : ''}${memoryPercent ? ` (${memoryPercent}%)` : ''}`);
console.log('');
// Sort groups by count (most connections first)
const sortedGroups = Object.entries(grouped).sort((a, b) => b[1].count - a[1].count);
// Display grouped connections
for (const [groupName, group] of sortedGroups) {
console.log(`📂 ${groupName.toUpperCase()} (${group.count} connections, ${group.totalCommands} commands, ${group.avgIdleTime}s avg idle)`);
for (const client of group.connections) {
console.log(` ├─ ${this.formatConnectionDetails(client)}`);
}
}
} catch (error) {
console.error('❌ Error connecting to Dragonfly:', error);
console.log('\n💡 Troubleshooting:');
console.log(' - Make sure Dragonfly Docker container is running');
console.log(' - Check if port 6379 is accessible');
console.log(' - Verify environment variables if using custom connection settings');
console.log(' - Run: docker ps | grep dragonfly');
} finally {
// Only disconnect if we're not in monitoring mode
if (this.redis.status === 'ready') {
await this.redis.disconnect();
}
}
}
/**
* Monitor connections in real-time
*/
async monitorConnections(intervalSeconds: number = 5): Promise<void> {
console.log(`🔄 Starting real-time monitoring (refresh every ${intervalSeconds}s)`);
console.log('Press Ctrl+C to stop...\n');
const monitor = async () => {
try {
console.clear();
console.log(`🕐 Last updated: ${new Date().toLocaleTimeString()}\n`);
await this.getConnectionsGroupedByName();
} catch (error) {
console.error('❌ Monitoring error:', error);
console.log('Retrying in next interval...');
}
};
// Initial run
await monitor();
// Set up interval
const interval = setInterval(monitor, intervalSeconds * 1000);
// Handle graceful shutdown
process.on('SIGINT', async () => {
clearInterval(interval);
console.log('\n👋 Monitoring stopped');
await this.redis.disconnect();
process.exit(0);
});
}
}
// Main execution
async function main() {
const args = process.argv.slice(2);
const monitor = new RedisConnectionMonitor();
if (args.includes('--monitor') || args.includes('-m')) {
const intervalArg = args.find(arg => arg.startsWith('--interval='));
const interval = intervalArg ? parseInt(intervalArg.split('=')[1]) : 5;
await monitor.monitorConnections(interval);
} else {
await monitor.getConnectionsGroupedByName();
}
}
// Help text
if (process.argv.includes('--help') || process.argv.includes('-h')) {
console.log(`
🐉 Redis/Dragonfly Connection Monitor
Usage:
bun run scripts/get-redis-connections.ts [options]
Options:
--help, -h Show this help message
--monitor, -m Monitor connections in real-time
--interval=N Set monitoring refresh interval in seconds (default: 5)
Examples:
bun run scripts/get-redis-connections.ts # One-time connection list
bun run scripts/get-redis-connections.ts --monitor # Real-time monitoring
bun run scripts/get-redis-connections.ts -m --interval=10 # Monitor every 10 seconds
Environment Variables:
DRAGONFLY_HOST Dragonfly host (default: localhost)
DRAGONFLY_PORT Dragonfly port (default: 6379)
DRAGONFLY_PASSWORD Dragonfly password (if auth enabled)
DRAGONFLY_DATABASE Database number (default: 0)
Features:
✨ Groups connections by clean names (removes timestamp suffixes)
📊 Shows connection statistics and command counts
🔄 Real-time monitoring mode available
🎨 Color-coded output with connection details
`);
process.exit(0);
}
// Run the script
console.log('🚀 Starting Redis connection monitor...');
main().catch((error) => {
console.error('❌ Script error:', error);
process.exit(1);
});

View file

@ -2,9 +2,9 @@
import { readFile } from 'node:fs/promises';
import { Pool } from 'pg';
import { validateDatasetV2 } from '../apps/stock/orchestrator/src/data/historical-dataset-v2';
import { retainResearchDataset } from '../apps/stock/orchestrator/src/data/retained-research-dataset';
import { retainResearchDataset } from '@stock-bot/trading-runtime/retained-dataset';
export { retainResearchDataset } from '../apps/stock/orchestrator/src/data/retained-research-dataset';
export { retainResearchDataset } from '@stock-bot/trading-runtime/retained-dataset';
if (import.meta.main) {
let database: Pool | undefined;

View file

@ -1,134 +0,0 @@
#!/bin/bash
# Playwright Setup Script for Stock Bot
# This script specifically handles Playwright installation and browser setup
set -e
# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m'
log_info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
log_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# Check if we're in the project directory
check_project_directory() {
if [[ ! -f "package.json" ]]; then
log_error "Please run this script from the project root directory"
exit 1
fi
}
# Install Playwright dependencies
install_playwright_deps() {
log_info "Installing Playwright system dependencies..."
bunx playwright install-deps chromium
log_success "Playwright system dependencies installed"
}
# Install Playwright browsers
install_browsers() {
log_info "Installing Playwright browsers..."
# Install all browsers
bunx playwright install chromium
bunx playwright install firefox
bunx playwright install webkit
log_success "All Playwright browsers installed"
}
# Test Playwright installation
test_playwright() {
log_info "Testing Playwright installation..."
# Create a simple test script
cat > /tmp/test-playwright.js << 'EOF'
const { chromium } = require('playwright');
(async () => {
try {
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage();
await page.goto('https://example.com');
const title = await page.title();
console.log('✅ Playwright test successful! Page title:', title);
await browser.close();
} catch (error) {
console.error('❌ Playwright test failed:', error.message);
process.exit(1);
}
})();
EOF
# Run the test
node /tmp/test-playwright.js
# Clean up
rm /tmp/test-playwright.js
log_success "Playwright test completed successfully"
}
# Main function
main() {
log_info "Setting up Playwright for Stock Bot..."
check_project_directory
install_playwright_deps
install_browsers
test_playwright
log_success "Playwright setup completed!"
log_info "You can now run your browser automation scripts"
}
# Show help
show_help() {
echo "Playwright Setup Script for Stock Bot"
echo ""
echo "Usage: $0 [OPTIONS]"
echo ""
echo "Options:"
echo " -h, --help Show this help message"
echo " --test-only Only run the Playwright test"
echo " --deps-only Only install system dependencies"
echo ""
}
# Parse arguments
case "${1:-}" in
-h|--help)
show_help
exit 0
;;
--test-only)
check_project_directory
test_playwright
exit 0
;;
--deps-only)
install_playwright_deps
exit 0
;;
"")
main
;;
*)
log_error "Unknown option: $1"
show_help
exit 1
;;
esac

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);

View file

@ -1,169 +0,0 @@
#!/bin/bash
# Build verification script for Stock Bot Trading Platform
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
GRAY='\033[0;37m'
NC='\033[0m' # No Color
# Default options
VERBOSE=false
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
--verbose|-v)
VERBOSE=true
shift
;;
--help|-h)
echo "Usage: $0 [--verbose]"
echo " --verbose, -v Show verbose output"
echo " --help, -h Show this help message"
exit 0
;;
*)
echo "Unknown option: $1"
echo "Use --help for usage information"
exit 1
;;
esac
done
echo -e "${GREEN}=== Verifying Build Health ===${NC}"
errors=()
warnings=()
# Check for common build issues
echo -e "${YELLOW}Checking for common build issues...${NC}"
# Check for mismatched .d.ts files in source directories
echo -e "${BLUE}Checking for .d.ts files in source directories...${NC}"
source_dts_files=$(find ./libs/*/src -name "*.d.ts" -type f 2>/dev/null)
if [ -n "$source_dts_files" ]; then
warnings+=("Found .d.ts files in source directories:")
while IFS= read -r file; do
warnings+=(" - $file")
done <<< "$source_dts_files"
fi
# Check for missing dist directories after build
echo -e "${BLUE}Checking for missing dist directories...${NC}"
libraries=("types" "config" "logger" "utils" "cache" "http")
for lib in "${libraries[@]}"; do
dist_path="libs/$lib/dist"
if [ ! -d "$dist_path" ]; then
errors+=("Missing dist directory for $lib")
else
index_file="$dist_path/index.js"
if [ ! -f "$index_file" ]; then
errors+=("Missing index.js in dist for $lib")
fi
fi
done
# Check for TypeScript compilation errors
echo -e "${BLUE}Checking for TypeScript compilation errors...${NC}"
tsc_errors=$(find . -name "*.tsbuildinfo" -exec grep -l "error" {} \; 2>/dev/null)
if [ -n "$tsc_errors" ]; then
errors+=("TypeScript compilation errors found in build info files")
if [ "$VERBOSE" = true ]; then
while IFS= read -r file; do
errors+=(" - $file")
done <<< "$tsc_errors"
fi
fi
# Check for large build files (potential issues)
echo -e "${BLUE}Checking for unusually large build files...${NC}"
large_files=$(find ./libs/*/dist -name "*.js" -size +1M 2>/dev/null)
if [ -n "$large_files" ]; then
warnings+=("Found unusually large build files (>1MB):")
while IFS= read -r file; do
size=$(stat -c%s "$file" 2>/dev/null || stat -f%z "$file" 2>/dev/null)
size_mb=$(echo "scale=2; $size / 1024 / 1024" | bc 2>/dev/null || echo "unknown")
warnings+=(" - $file (${size_mb}MB)")
done <<< "$large_files"
fi
# Check for circular dependencies (basic check)
echo -e "${BLUE}Checking for potential circular dependencies...${NC}"
package_json_files=$(find ./libs -name "package.json" -type f)
while IFS= read -r pkg_file; do
lib_name=$(basename "$(dirname "$pkg_file")")
if [ -f "$pkg_file" ]; then
# Check if library depends on itself (basic check)
self_dep=$(grep -o "@stock-bot/$lib_name" "$pkg_file" 2>/dev/null)
if [ -n "$self_dep" ]; then
warnings+=("Potential circular dependency in $lib_name")
fi
fi
done <<< "$package_json_files"
# Check for missing package.json files
echo -e "${BLUE}Checking for missing package.json files...${NC}"
lib_dirs=$(find ./libs -maxdepth 1 -type d -name "*" ! -name "libs")
while IFS= read -r lib_dir; do
if [ -d "$lib_dir" ] && [ ! -f "$lib_dir/package.json" ]; then
lib_name=$(basename "$lib_dir")
errors+=("Missing package.json in $lib_name")
fi
done <<< "$lib_dirs"
# Check for environment variable dependencies
echo -e "${BLUE}Checking for hardcoded paths...${NC}"
hardcoded_paths_win=$(grep -r "g:\\repos\\stock-bot" ./libs 2>/dev/null || true)
hardcoded_paths_unix=$(grep -r "/home/.*/stock-bot" ./libs 2>/dev/null || true)
if [ -n "$hardcoded_paths_win" ]; then
warnings+=("Found hardcoded Windows paths:")
while IFS= read -r line; do
warnings+=(" - $line")
done <<< "$hardcoded_paths_win"
fi
if [ -n "$hardcoded_paths_unix" ]; then
warnings+=("Found hardcoded Unix paths:")
while IFS= read -r line; do
warnings+=(" - $line")
done <<< "$hardcoded_paths_unix"
fi
# Summary
echo ""
echo -e "${CYAN}=== Build Verification Summary ===${NC}"
if [ ${#errors[@]} -eq 0 ] && [ ${#warnings[@]} -eq 0 ]; then
echo -e "${GREEN}✅ Build verification passed - no issues found!${NC}"
exit 0
fi
if [ ${#errors[@]} -gt 0 ]; then
echo -e "${RED}❌ Errors found (${#errors[@]}):${NC}"
for error in "${errors[@]}"; do
echo -e "${RED} $error${NC}"
done
fi
if [ ${#warnings[@]} -gt 0 ]; then
echo -e "${YELLOW}⚠️ Warnings found (${#warnings[@]}):${NC}"
for warning in "${warnings[@]}"; do
echo -e "${YELLOW} $warning${NC}"
done
fi
if [ ${#errors[@]} -gt 0 ]; then
echo ""
echo -e "${RED}Build verification failed due to errors.${NC}"
exit 1
else
echo ""
echo -e "${YELLOW}Build verification completed with warnings.${NC}"
exit 0
fi