import { EventEmitter } from 'node:events'; import { afterEach, describe, expect, test } from 'bun:test'; import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'; import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies'; import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy'; import { SmaCrossoverStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy'; import { StrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/StrategyRegistry'; import { config, makeExecution, quote } from '../fixtures/execution'; import { CounterStrategy, makeStrategyManager, recoveryConfig, } from '../fixtures/strategy-recovery'; const cleanup: (() => Promise)[] = []; afterEach(async () => { for (const close of cleanup.splice(0).reverse()) { await close(); } }); async function fixture() { const { execution, engine } = makeExecution(); await execution.initialize(config, engine); cleanup.push(() => execution.shutdown()); const modeManager = { getTradingEngine: () => engine } as ModeManager; return { execution, dependencies: { modeManager, execution }, }; } describe('strategy registration and expansion', () => { test('custom lazy factories integrate with ordinary initialization, recovery and restart', async () => { const f = await fixture(); let created = 0; const registry = new StrategyRegistry().register( ['fixture', 'custom-alias'], (config, dependencies) => { created++; expect(dependencies.execution).toBe(f.execution); return new CounterStrategy(dependencies.execution, config); } ); expect(created).toBe(0); const marketData = new EventEmitter(); const manager = makeStrategyManager({ ...f.dependencies, registry, marketData }); cleanup.push(() => manager.shutdown()); await manager.initializeStrategies([{ ...recoveryConfig, name: ' Custom-Alias ' }]); expect(marketData.listenerCount('marketDataBatch')).toBe(1); marketData.emit('marketDataBatch', [quote('first')]); await manager.drain(); expect((manager.getStrategy('counter') as CounterStrategy).count).toBe(1); await manager.shutdown(); expect(marketData.listenerCount('marketDataBatch')).toBe(0); const restarted = makeStrategyManager({ ...f.dependencies, registry, marketData }); cleanup.push(() => restarted.shutdown()); await restarted.restoreStrategies(); restarted.setupEventListeners(); expect(marketData.listenerCount('marketDataBatch')).toBe(1); expect(created).toBe(2); expect((restarted.getStrategy('counter') as CounterStrategy).count).toBe(1); marketData.emit('marketDataBatch', [quote('second')]); await restarted.drain(); expect((restarted.getStrategy('counter') as CounterStrategy).count).toBe(2); }); test('aliases are normalized and registration conflicts fail atomically', async () => { const f = await fixture(); const registry = new StrategyRegistry().register( ['fixture'], config => new CounterStrategy(f.execution, config) ); const factory = () => new CounterStrategy(f.execution); expect(() => registry.register(['new', 'FIXTURE'], factory)).toThrow('already registered'); await expect( registry.create({ ...recoveryConfig, name: 'new' }, f.dependencies) ).rejects.toThrow('Unknown strategy'); for (const aliases of [[], [''], [' '], ['duplicate', 'DUPLICATE']]) { expect(() => registry.register(aliases, factory)).toThrow('nonempty and distinct'); } expect( (await registry.create({ ...recoveryConfig, name: ' FIXTURE ' }, f.dependencies)).getConfig() .id ).toBe('counter'); }); test('built-in aliases keep their implementations and unknown names fail closed', async () => { const f = await fixture(); const registry = createBuiltinStrategyRegistry(); for (const name of ['meanreversion', 'mean-reversion']) { const strategy = await registry.create({ ...recoveryConfig, name }, f.dependencies); expect(strategy).toBeInstanceOf(MeanReversionStrategy); expect(strategy.getCheckpointVersion()).toBe('mean-reversion/v2'); } for (const name of ['smacrossover', 'sma-crossover', 'moving-average']) { const strategy = await registry.create({ ...recoveryConfig, name }, f.dependencies); expect(strategy).toBeInstanceOf(SmaCrossoverStrategy); expect(strategy.getCheckpointVersion()).toBe('sma-crossover-fixed/v2'); } for (const name of ['mlenhanced', 'ml-enhanced']) { expect( (await registry.create({ ...recoveryConfig, name }, f.dependencies)).getCheckpointVersion() ).toBeUndefined(); } await expect( registry.create({ ...recoveryConfig, name: 'missing' }, f.dependencies) ).rejects.toThrow('Unknown strategy: missing'); }); test('factory failures propagate before an invalid strategy can be activated', async () => { const f = await fixture(); const registry = new StrategyRegistry().register(['fixture'], async () => { throw new Error('factory failed'); }); const manager = makeStrategyManager({ ...f.dependencies, registry }); cleanup.push(() => manager.shutdown()); await expect(manager.initializeStrategies([recoveryConfig])).rejects.toThrow('factory failed'); expect(manager.getActiveStrategies()).toEqual([]); expect(await f.execution.registeredStrategies()).toEqual([]); }); });