359 lines
13 KiB
TypeScript
359 lines
13 KiB
TypeScript
import { createHash } from 'node:crypto';
|
|
import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
|
|
import { parseFinancialDecimal, type StrategyVersionPackage } from '@stock-bot/types';
|
|
import {
|
|
builtinCatalogDescriptors,
|
|
builtinStrategySelectionSchema,
|
|
parseStrategyVersionPackage,
|
|
type BuiltinStrategySelection,
|
|
} from '../../apps/stock/config/src/contracts/strategy';
|
|
import type {
|
|
StrategyContext,
|
|
StrategyProgram,
|
|
} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
|
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
|
import { packageBuiltinStrategies } from '../package-builtin-strategies';
|
|
import { runtimeImports } from '../runtime-imports';
|
|
|
|
const root = fileURLToPath(new URL('../../', import.meta.url));
|
|
const sha256 = (content: string | Uint8Array) => createHash('sha256').update(content).digest('hex');
|
|
const d = parseFinancialDecimal;
|
|
let directory: string;
|
|
let packages: StrategyVersionPackage[];
|
|
type Factory = (selection: unknown) => StrategyProgram;
|
|
const packagedFactories = new Map<string, Factory>();
|
|
|
|
function selection(strategyId: string): BuiltinStrategySelection {
|
|
return builtinStrategySelectionSchema.parse({
|
|
ownerId: 'packaging-owner',
|
|
strategyId,
|
|
strategyVersion:
|
|
strategyId === 'sma_crossover'
|
|
? 'sma-crossover-long-only/v1'
|
|
: 'mean-reversion-regime-long-only/v1',
|
|
seed: 42,
|
|
instrumentId: 'X.US',
|
|
seriesId: 'X.US:1m',
|
|
ownerBudget: '40',
|
|
parameters:
|
|
strategyId === 'sma_crossover'
|
|
? { fastPeriod: 2, slowPeriod: 3 }
|
|
: {
|
|
lookbackPeriod: 2,
|
|
trendPeriod: 3,
|
|
momentumPeriod: 1,
|
|
volatilityPeriod: 2,
|
|
entryZScore: 1,
|
|
exitZScore: 0.2,
|
|
minTrendReturn: -0.9,
|
|
minMomentumReturn: -0.9,
|
|
maxVolatility: 10,
|
|
minNotionalVolume: '0',
|
|
regimeFilter: 'volatility',
|
|
},
|
|
});
|
|
}
|
|
|
|
/** Decision inputs only. This is not a second fill/account simulator. */
|
|
function context(
|
|
program: StrategyProgram,
|
|
state: unknown,
|
|
close: number,
|
|
sequence: number
|
|
): StrategyContext {
|
|
const now = sequence + 1;
|
|
const riskSession = {
|
|
calendarId: 'fixture',
|
|
calendarRevision: '1',
|
|
sessionId: 'session',
|
|
startsAt: 0,
|
|
};
|
|
return {
|
|
ownerId: program.ownerId,
|
|
strategyId: program.strategyId,
|
|
strategyVersion: program.strategyVersion,
|
|
decisionSequence: sequence,
|
|
now,
|
|
state,
|
|
previousAdmission: null,
|
|
random: () => {
|
|
throw new Error('These reviewed built-ins do not draw random inputs');
|
|
},
|
|
positions: [],
|
|
observations: [
|
|
{
|
|
instrument_id: 'X.US',
|
|
series_id: 'X.US:1m',
|
|
interval_start: sequence,
|
|
interval_end: now,
|
|
event_time: now,
|
|
available_at: now,
|
|
source_sequence: sequence,
|
|
open: d(String(close)),
|
|
high: d(String(close)),
|
|
low: d(String(close)),
|
|
close: d(String(close)),
|
|
volume: d('100'),
|
|
},
|
|
],
|
|
barrier: {
|
|
barrier_id: `barrier-${sequence}`,
|
|
at: now,
|
|
revision: sequence,
|
|
owner_ids: [program.ownerId],
|
|
observation_count: 1,
|
|
inputs: [
|
|
{ series_id: 'X.US:1m', availability: { Fresh: { event_time: now, available_at: now } } },
|
|
],
|
|
},
|
|
portfolio: {
|
|
admissionRevision: sequence,
|
|
equity: d('10000'),
|
|
availableCash: d('10000'),
|
|
orders: [],
|
|
reservations: [],
|
|
portfolio: {
|
|
version: 1,
|
|
sessionId: 'fixture',
|
|
accountId: 'fixture',
|
|
revision: sequence,
|
|
baseCurrency: 'USD',
|
|
reserveOwnerId: 'reserve',
|
|
cash: d('10000'),
|
|
positions: [],
|
|
fees: [],
|
|
riskSession,
|
|
},
|
|
risk: {
|
|
dailyBaseline: d('10000'),
|
|
peakEquity: d('10000'),
|
|
dailyHalted: false,
|
|
drawdownHalted: false,
|
|
riskSession,
|
|
lastEventTime: now,
|
|
},
|
|
},
|
|
};
|
|
}
|
|
|
|
beforeAll(async () => {
|
|
packages = await packageBuiltinStrategies({ rootDir: root });
|
|
directory = await mkdtemp(join(tmpdir(), 'stock-bot-strategy-package-test-'));
|
|
for (const pkg of packages) {
|
|
const file = join(directory, `${pkg.program.strategyId}.mjs`);
|
|
await writeFile(file, pkg.artifact.content, 'utf8');
|
|
// Only the known built-ins compiled above are imported. Publication/API
|
|
// handling never imports a submitted candidate artifact.
|
|
const exports = await import(pathToFileURL(file).href);
|
|
expect(typeof exports[pkg.artifact.entryExport]).toBe('function');
|
|
packagedFactories.set(pkg.program.strategyId, exports[pkg.artifact.entryExport] as Factory);
|
|
}
|
|
});
|
|
|
|
afterAll(async () => {
|
|
if (directory) {await rm(directory, { recursive: true, force: true });}
|
|
});
|
|
|
|
describe('offline reviewed strategy packaging', () => {
|
|
test('repeat packaging retains byte-identical self-contained bundles and lock bytes', async () => {
|
|
const repeat = await packageBuiltinStrategies({ rootDir: root });
|
|
expect(packages).toHaveLength(2);
|
|
expect(repeat).toEqual(packages);
|
|
const lockBytes = await readFile(join(root, 'bun.lock'));
|
|
for (const pkg of packages) {
|
|
expect(pkg.artifact.sha256).toBe(sha256(pkg.artifact.content));
|
|
expect(pkg.dependencyLock.sha256).toBe(sha256(lockBytes));
|
|
expect(Buffer.from(pkg.dependencyLock.content, 'utf8').equals(lockBytes)).toBe(true);
|
|
expect(pkg.dependencyLock.content).toContain('"lockfileVersion"');
|
|
expect(parseStrategyVersionPackage(pkg)).toEqual(pkg);
|
|
}
|
|
});
|
|
|
|
test('source revision, dirty state, compiler and public descriptor identity are truthful', () => {
|
|
const git = (args: string[]) => {
|
|
const result = Bun.spawnSync(['git', '-C', root, ...args], {
|
|
stdout: 'pipe',
|
|
stderr: 'pipe',
|
|
});
|
|
expect(result.exitCode).toBe(0);
|
|
return result.stdout.toString('utf8');
|
|
};
|
|
const revision = git(['rev-parse', '--verify', 'HEAD']).trim();
|
|
const dirty = git(['status', '--porcelain=v1', '--untracked-files=normal']).length > 0;
|
|
for (const pkg of packages) {
|
|
const descriptor = builtinCatalogDescriptors.find(
|
|
item => item.program.strategyId === pkg.program.strategyId
|
|
)!;
|
|
expect(pkg.source).toEqual({ revision, dirty });
|
|
expect(pkg.build).toEqual({ tool: 'bun', version: Bun.version, target: 'browser' });
|
|
expect(pkg.program).toEqual(descriptor.program);
|
|
expect<unknown>(pkg.parameterSchema).toEqual(descriptor.parameterSchema);
|
|
expect(pkg.artifact.entryExport).toBe(descriptor.entryExport);
|
|
}
|
|
});
|
|
|
|
test('isolated bundles require no workspace, installed packages, native engine or service runtime', async () => {
|
|
expect((await readdir(directory)).sort()).toEqual(['mean_reversion.mjs', 'sma_crossover.mjs']);
|
|
for (const pkg of packages) {
|
|
expect(runtimeImports('strategy.mjs', pkg.artifact.content)).toEqual([]);
|
|
for (const forbidden of [
|
|
'engine.node',
|
|
'BacktestEngine',
|
|
'PostgresClient',
|
|
'ConfigManager',
|
|
'process.env',
|
|
'native-worker',
|
|
]) {
|
|
expect(pkg.artifact.content).not.toContain(forbidden);
|
|
}
|
|
const program = packagedFactories.get(pkg.program.strategyId)!(
|
|
selection(pkg.program.strategyId)
|
|
);
|
|
expect(program.strategyId).toBe(pkg.program.strategyId);
|
|
expect(program.strategyVersion).toBe(pkg.program.strategyVersion);
|
|
expect(program.mode).toBe('target');
|
|
}
|
|
});
|
|
|
|
test('residual imports and require references reject instead of retaining incomplete bundles', async () => {
|
|
for (const content of [
|
|
'import x from "external"; export { x };',
|
|
'export { x } from "external";',
|
|
'export const load = path => import(path);',
|
|
'export const load = path => require(path);',
|
|
'const load = require; export { load };',
|
|
'export const load = path => globalThis["require"](path);',
|
|
]) {
|
|
const output = Object.assign(new Blob([content]), { kind: 'entry-point' });
|
|
const build = spyOn(Bun, 'build').mockResolvedValue({
|
|
success: true,
|
|
logs: [],
|
|
outputs: [output],
|
|
} as unknown as Awaited<ReturnType<typeof Bun.build>>);
|
|
try {
|
|
await expect(packageBuiltinStrategies({ rootDir: root })).rejects.toThrow(
|
|
'external import or require'
|
|
);
|
|
} finally {
|
|
build.mockRestore();
|
|
}
|
|
}
|
|
});
|
|
|
|
test('packaging inspects generated text without importing or executing it', async () => {
|
|
const content =
|
|
'throw new Error("Must not execute during packaging"); const factory = () => {}; export { factory as createSmaStrategy, factory as createMeanReversionStrategy };';
|
|
const output = Object.assign(new Blob([content]), { kind: 'entry-point' });
|
|
const build = spyOn(Bun, 'build').mockResolvedValue({
|
|
success: true,
|
|
logs: [],
|
|
outputs: [output],
|
|
} as unknown as Awaited<ReturnType<typeof Bun.build>>);
|
|
try {
|
|
const inert = await packageBuiltinStrategies({ rootDir: root });
|
|
expect(inert.map(pkg => pkg.artifact.content)).toEqual([content, content]);
|
|
} finally {
|
|
build.mockRestore();
|
|
}
|
|
});
|
|
|
|
test('a bundle missing its declared factory cannot be published as a valid built-in package', async () => {
|
|
const output = Object.assign(new Blob(['const other = () => {}; export { other };']), {
|
|
kind: 'entry-point',
|
|
});
|
|
const build = spyOn(Bun, 'build').mockResolvedValue({
|
|
success: true,
|
|
logs: [],
|
|
outputs: [output],
|
|
} as unknown as Awaited<ReturnType<typeof Bun.build>>);
|
|
try {
|
|
await expect(packageBuiltinStrategies({ rootDir: root })).rejects.toThrow(
|
|
'does not export its declared factory'
|
|
);
|
|
} finally {
|
|
build.mockRestore();
|
|
}
|
|
});
|
|
|
|
for (const strategyId of ['sma_crossover', 'mean_reversion']) {
|
|
test(`${strategyId}: source and packaged decisions/checkpoints agree through entry, exit and restore`, () => {
|
|
const selected = selection(strategyId);
|
|
const source = createBuiltinStrategy(selected);
|
|
const factory = packagedFactories.get(strategyId)!;
|
|
let packaged = factory(selected);
|
|
let sourceState = source.initialState;
|
|
let packagedState = packaged.initialState;
|
|
const quantities: string[] = [];
|
|
expect(packagedState).toEqual(sourceState);
|
|
for (const [sequence, close] of [3, 2, 1, 4, 5, 1, 1].entries()) {
|
|
const expected = source.decide(context(source, sourceState, close, sequence));
|
|
const actual = packaged.decide(context(packaged, packagedState, close, sequence));
|
|
expect(actual).toEqual(expected);
|
|
sourceState = expected.nextState;
|
|
packagedState = JSON.parse(JSON.stringify(actual.nextState));
|
|
if (actual.intent.mode === 'target')
|
|
{quantities.push(...actual.intent.targets.map(target => target.quantity));}
|
|
if (sequence === 3) {
|
|
packaged = factory(selected);
|
|
}
|
|
}
|
|
expect(quantities).toContain('0.00000000');
|
|
expect(quantities).toContain(strategyId === 'sma_crossover' ? '10.00000000' : '40.00000000');
|
|
const corrupted = {
|
|
...(packagedState as Record<string, unknown>),
|
|
selectionKey: 'other-selection',
|
|
};
|
|
expect(() => packaged.decide(context(packaged, corrupted, 3, 7))).toThrow();
|
|
expect(() => source.decide(context(source, corrupted, 3, 7))).toThrow();
|
|
});
|
|
}
|
|
|
|
test('packaged factories retain strict parameter validation and canonical aliases', () => {
|
|
const factory = packagedFactories.get('sma_crossover')!;
|
|
const selected = selection('sma_crossover');
|
|
expect(factory({ ...selected, strategyId: 'moving-average' }).strategyId).toBe('sma_crossover');
|
|
expect(() => factory({ ...selected, parameters: { fastPeriod: 3, slowPeriod: 2 } })).toThrow();
|
|
expect(() =>
|
|
factory({ ...selected, parameters: { fastPeriod: 2, slowPeriod: 3, arbitrary: true } })
|
|
).toThrow();
|
|
expect(() => factory({ ...selected, strategyVersion: 'unknown' })).toThrow();
|
|
const mean = packagedFactories.get('mean_reversion')!;
|
|
const mr = selection('mean_reversion');
|
|
expect(() =>
|
|
mean({ ...mr, parameters: { ...mr.parameters, entryZScore: 1, exitZScore: 2 } })
|
|
).toThrow();
|
|
});
|
|
|
|
test('CLI writes the retained package envelope and rejects unsupported options', async () => {
|
|
const file = join(directory, 'published.json');
|
|
const script = join(root, 'scripts/package-builtin-strategies.ts');
|
|
const child = Bun.spawn([process.execPath, script, '--out', file], {
|
|
cwd: root,
|
|
stdout: 'pipe',
|
|
stderr: 'pipe',
|
|
});
|
|
const [stdout, stderr, exitCode] = await Promise.all([
|
|
new Response(child.stdout).text(),
|
|
new Response(child.stderr).text(),
|
|
child.exited,
|
|
]);
|
|
expect({ exitCode, stderr }).toEqual({ exitCode: 0, stderr: '' });
|
|
expect(stdout).toContain('Packaged 2 reviewed built-ins');
|
|
expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({ version: 1, packages });
|
|
const invalid = Bun.spawn([process.execPath, script, '--execute'], {
|
|
cwd: root,
|
|
stdout: 'pipe',
|
|
stderr: 'pipe',
|
|
});
|
|
const [failure, status] = await Promise.all([
|
|
new Response(invalid.stderr).text(),
|
|
invalid.exited,
|
|
]);
|
|
expect(status).toBe(1);
|
|
expect(failure).toContain('Usage:');
|
|
});
|
|
});
|