feat(research): retain immutable strategy versions and review history
This commit is contained in:
parent
b106c1ca85
commit
4a2e5ad362
36 changed files with 3236 additions and 148 deletions
187
scripts/package-builtin-strategies.ts
Normal file
187
scripts/package-builtin-strategies.ts
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
/** Offline compilation of the two reviewed canonical built-ins. No database,
|
||||
* native engine, candidate module imports or runtime activation. */
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import ts from 'typescript';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
import {
|
||||
builtinCatalogDescriptors,
|
||||
parseStrategyVersionPackage,
|
||||
} from '../apps/stock/config/src/contracts/strategy';
|
||||
|
||||
const repositoryRoot = fileURLToPath(new URL('../', import.meta.url));
|
||||
const entries = {
|
||||
sma_crossover: 'apps/stock/orchestrator/src/strategies/canonical-sma.ts',
|
||||
mean_reversion: 'apps/stock/orchestrator/src/strategies/canonical-mean-reversion.ts',
|
||||
} as const;
|
||||
|
||||
// Workspace packages normally expose generated dist files. Packaging must read
|
||||
// current source, including the pure config subpaths, without relying on those
|
||||
// files having been rebuilt in the right order.
|
||||
const workspaceSources: Record<string, string> = {
|
||||
'@stock-bot/types': 'libs/core/types/src/index.ts',
|
||||
'@stock-bot/invariants': 'libs/core/invariants/src/index.ts',
|
||||
'@stock-bot/calculations': 'libs/calculations/src/index.ts',
|
||||
'@stock-bot/calculations/indicators': 'libs/calculations/src/indicators/index.ts',
|
||||
'@stock-bot/calculations/returns': 'libs/calculations/src/returns.ts',
|
||||
'@stock-bot/stock-config/strategy': 'apps/stock/config/src/contracts/strategy.ts',
|
||||
'@stock-bot/stock-config/backtest': 'apps/stock/config/src/contracts/backtest.ts',
|
||||
};
|
||||
|
||||
const sha256 = (content: string) => createHash('sha256').update(content, 'utf8').digest('hex');
|
||||
|
||||
function git(root: string, args: string[]): string {
|
||||
const result = Bun.spawnSync(['git', '-C', root, ...args], {
|
||||
stdout: 'pipe',
|
||||
stderr: 'pipe',
|
||||
});
|
||||
if (result.exitCode !== 0) {
|
||||
throw new Error(`Cannot read packaging source identity: git ${args[0]} failed`);
|
||||
}
|
||||
return result.stdout.toString('utf8');
|
||||
}
|
||||
|
||||
function assertSelfContained(content: string, entryExport: string): void {
|
||||
const source = ts.createSourceFile(
|
||||
'strategy.mjs',
|
||||
content,
|
||||
ts.ScriptTarget.Latest,
|
||||
true,
|
||||
ts.ScriptKind.JS
|
||||
);
|
||||
let exportsFactory = false;
|
||||
function visit(node: ts.Node): void {
|
||||
if (
|
||||
ts.isExportDeclaration(node) &&
|
||||
node.exportClause &&
|
||||
ts.isNamedExports(node.exportClause) &&
|
||||
node.exportClause.elements.some(element => element.name.text === entryExport)
|
||||
) {
|
||||
exportsFactory = true;
|
||||
}
|
||||
const imported =
|
||||
ts.isImportDeclaration(node) ||
|
||||
(ts.isExportDeclaration(node) && node.moduleSpecifier !== undefined) ||
|
||||
(ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference));
|
||||
const loaded =
|
||||
(ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) ||
|
||||
(ts.isIdentifier(node) && /^(?:__)?require$/.test(node.text)) ||
|
||||
(ts.isElementAccessExpression(node) &&
|
||||
ts.isStringLiteral(node.argumentExpression) &&
|
||||
node.argumentExpression.text === 'require');
|
||||
if (imported || loaded) {
|
||||
throw new Error('Strategy bundle contains an external import or require');
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
}
|
||||
visit(source);
|
||||
if (!exportsFactory) {
|
||||
throw new Error(`Strategy bundle does not export its declared factory: ${entryExport}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function packageBuiltinStrategies({
|
||||
rootDir = repositoryRoot,
|
||||
}: { rootDir?: string } = {}): Promise<StrategyVersionPackage[]> {
|
||||
const root = resolve(rootDir);
|
||||
const revision = git(root, ['rev-parse', '--verify', 'HEAD']).trim();
|
||||
if (!/^[a-f0-9]{40,64}$/.test(revision)) {
|
||||
throw new Error('Cannot read full Git source revision');
|
||||
}
|
||||
const dirtyBefore =
|
||||
git(root, ['status', '--porcelain=v1', '--untracked-files=normal']).length > 0;
|
||||
// Keep original lock bytes: parsing/stringifying Bun's JSONC lock would change
|
||||
// the retained artifact even if dependency resolution remained equivalent.
|
||||
const lockBytes = await readFile(resolve(root, 'bun.lock'));
|
||||
const lockContent = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(lockBytes);
|
||||
if (!Buffer.from(lockContent, 'utf8').equals(lockBytes)) {
|
||||
throw new Error('Dependency lock must contain exact UTF-8 bytes');
|
||||
}
|
||||
const dependencyLock = {
|
||||
format: 'bun-lock/v1' as const,
|
||||
content: lockContent,
|
||||
sha256: sha256(lockContent),
|
||||
};
|
||||
const packages: StrategyVersionPackage[] = [];
|
||||
for (const descriptor of builtinCatalogDescriptors) {
|
||||
const entry = entries[descriptor.program.strategyId as keyof typeof entries];
|
||||
if (!entry) {
|
||||
throw new Error(`No reviewed bundle entry for ${descriptor.program.strategyId}`);
|
||||
}
|
||||
const build = await Bun.build({
|
||||
entrypoints: [resolve(root, entry)],
|
||||
root,
|
||||
target: 'browser',
|
||||
format: 'esm',
|
||||
packages: 'bundle',
|
||||
splitting: false,
|
||||
sourcemap: 'none',
|
||||
minify: false,
|
||||
env: 'disable',
|
||||
plugins: [
|
||||
{
|
||||
name: 'reviewed-strategy-workspace-sources',
|
||||
setup(builder) {
|
||||
builder.onResolve({ filter: /^@stock-bot\// }, ({ path }) => {
|
||||
const source = workspaceSources[path];
|
||||
if (!source) {
|
||||
throw new Error(`Unsupported strategy workspace dependency: ${path}`);
|
||||
}
|
||||
return { path: resolve(root, source) };
|
||||
});
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
if (!build.success || build.outputs.length !== 1 || build.outputs[0]?.kind !== 'entry-point') {
|
||||
throw new Error(
|
||||
`Expected one self-contained strategy bundle for ${descriptor.program.strategyId}`
|
||||
);
|
||||
}
|
||||
const content = await build.outputs[0].text();
|
||||
assertSelfContained(content, descriptor.entryExport);
|
||||
packages.push(
|
||||
parseStrategyVersionPackage({
|
||||
version: 1,
|
||||
program: structuredClone(descriptor.program),
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: descriptor.entryExport,
|
||||
content,
|
||||
sha256: sha256(content),
|
||||
},
|
||||
dependencyLock: { ...dependencyLock },
|
||||
parameterSchema: structuredClone(descriptor.parameterSchema),
|
||||
source: { revision, dirty: dirtyBefore },
|
||||
build: { tool: 'bun', version: Bun.version, target: 'browser' },
|
||||
})
|
||||
);
|
||||
}
|
||||
if (git(root, ['rev-parse', '--verify', 'HEAD']).trim() !== revision) {
|
||||
throw new Error('Source revision changed during strategy packaging; retry');
|
||||
}
|
||||
const dirtyAfter = git(root, ['status', '--porcelain=v1', '--untracked-files=normal']).length > 0;
|
||||
for (const entry of packages) {
|
||||
entry.source.dirty = dirtyBefore || dirtyAfter;
|
||||
}
|
||||
return packages.map(parseStrategyVersionPackage);
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
const args = process.argv.slice(2);
|
||||
if (args.length !== 2 || args[0] !== '--out' || !args[1]) {
|
||||
throw new Error('Usage: bun run scripts/package-builtin-strategies.ts --out <path>');
|
||||
}
|
||||
const packages = await packageBuiltinStrategies();
|
||||
const output = resolve(args[1]);
|
||||
await mkdir(dirname(output), { recursive: true });
|
||||
await writeFile(output, `${JSON.stringify({ version: 1, packages }, null, 2)}\n`, 'utf8');
|
||||
process.stdout.write(`Packaged ${packages.length} reviewed built-ins to ${output}\n`);
|
||||
} catch (error) {
|
||||
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
43
scripts/seed-builtin-strategies.ts
Normal file
43
scripts/seed-builtin-strategies.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
/** Explicit local import. The HTTP process never builds/imports candidate code. */
|
||||
import { createHash } from 'node:crypto';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { builtinCatalogDescriptors, canonicalStrategyJson } from '../apps/stock/config/src/contracts/strategy';
|
||||
import { StrategyCatalogService } from '../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
import { packageBuiltinStrategies } from './package-builtin-strategies';
|
||||
|
||||
/** Packages only the known local repository entries; callers cannot supply an arbitrary bundle. */
|
||||
export async function seedBuiltinCatalog(service: Pick<StrategyCatalogService,'seedBuiltin'>) {
|
||||
const packages=await packageBuiltinStrategies();
|
||||
const versions=[];
|
||||
for (const pkg of packages) {
|
||||
const descriptor=builtinCatalogDescriptors.find(item=>item.program.strategyId===pkg.program.strategyId);
|
||||
if (!descriptor) {throw new Error('Missing built-in descriptor');}
|
||||
const key=`builtin:${createHash('sha256').update(canonicalStrategyJson(pkg)).digest('hex')}`;
|
||||
versions.push(await service.seedBuiltin(descriptor.name,pkg,key));
|
||||
}
|
||||
return versions;
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
let postgres:PostgreSQLClient|undefined;
|
||||
try {
|
||||
if (process.argv.slice(2).join(' ')!=='--seed') {throw new Error('Usage: STRATEGY_CATALOG_DATABASE_URL=<database> bun run scripts/seed-builtin-strategies.ts --seed');}
|
||||
const value=process.env.STRATEGY_CATALOG_DATABASE_URL;
|
||||
if(!value) {throw new Error('Set STRATEGY_CATALOG_DATABASE_URL explicitly; this command writes the strategy catalog');}
|
||||
const url=new URL(value);
|
||||
const sslMode=url.searchParams.get('sslmode')??'disable';
|
||||
if(!['postgres:','postgresql:'].includes(url.protocol)||!url.hostname||url.pathname==='/'||!['disable','require','verify-full'].includes(sslMode)||[...url.searchParams.keys()].some(key=>key!=='sslmode')) {throw new Error('Unsupported catalog database URL');}
|
||||
const logger=getLogger('seed-builtin-strategies');
|
||||
postgres=new PostgreSQLClient({host:url.hostname,port:Number(url.port||5432),database:decodeURIComponent(url.pathname.slice(1)),username:decodeURIComponent(url.username),password:decodeURIComponent(url.password),ssl:{enabled:sslMode!=='disable',rejectUnauthorized:sslMode==='verify-full'}},logger);
|
||||
await postgres.connect();
|
||||
// Startup migration 16 must already exist. Seeding never changes application schemas.
|
||||
const versions=await seedBuiltinCatalog(new StrategyCatalogService({postgres,logger}));
|
||||
process.stdout.write(`${JSON.stringify(versions.map(({strategyId,id,ordinal,reviewStatus,runnable})=>({strategyId,versionId:id,ordinal,reviewStatus,runnable})),null,2)}\n`);
|
||||
} catch(error) {
|
||||
process.stderr.write(`${error instanceof Error?error.message:String(error)}\n`);
|
||||
process.exitCode=1;
|
||||
} finally {
|
||||
await postgres?.disconnect();
|
||||
}
|
||||
}
|
||||
|
|
@ -65,7 +65,7 @@ describe('orchestrator architecture boundaries', () => {
|
|||
path === 'backtest/native-worker-protocol.ts'
|
||||
).toBe(true);
|
||||
for (const specifier of imports.get(file) ?? []) {
|
||||
expect(specifier.startsWith('.') || ['zod', '@stock-bot/types', '@stock-bot/stock-config/backtest'].includes(specifier)).toBe(
|
||||
expect(specifier.startsWith('.') || ['zod', '@stock-bot/types', '@stock-bot/stock-config/backtest', '@stock-bot/stock-config/strategy'].includes(specifier)).toBe(
|
||||
true
|
||||
);
|
||||
}
|
||||
|
|
@ -85,6 +85,32 @@ describe('orchestrator architecture boundaries', () => {
|
|||
expect(code).not.toContain('engine.node');
|
||||
});
|
||||
|
||||
it('shared strategy catalog contracts cannot import strategy execution or application services', async () => {
|
||||
const directory = resolve(root, '../../config/src/contracts');
|
||||
for (const name of ['strategy.ts', 'builtin-strategy.ts', 'strategy-names.ts']) {
|
||||
for (const specifier of runtimeImports(join(directory, name))) {
|
||||
expect(['zod', '@stock-bot/types', './builtin-strategy', './strategy-names'].includes(specifier)).toBe(true);
|
||||
}
|
||||
}
|
||||
const bundle = await Bun.build({
|
||||
entrypoints: [join(directory, 'strategy.ts')], target: 'browser',
|
||||
plugins: [{
|
||||
name: 'current-contract-types',
|
||||
setup(builder) {
|
||||
builder.onResolve({ filter: /^@stock-bot\/types$/ }, () => ({
|
||||
path: fileURLToPath(new URL('../../libs/core/types/src/index.ts', import.meta.url)),
|
||||
}));
|
||||
},
|
||||
}],
|
||||
});
|
||||
expect(bundle.success).toBe(true);
|
||||
const code = await bundle.outputs[0]?.text();
|
||||
expect(code).toBeDefined();
|
||||
for (const forbidden of ['config-instance', 'PostgresClient', 'engine.node', 'createBuiltinStrategy']) {
|
||||
expect(code).not.toContain(forbidden);
|
||||
}
|
||||
});
|
||||
|
||||
it('recovery and the ledger port do not depend on concrete adapters, strategies or the service container', () => {
|
||||
for (const entry of [
|
||||
'execution/SimulationExecution.ts',
|
||||
|
|
|
|||
359
scripts/test/strategy-packaging.test.ts
Normal file
359
scripts/test/strategy-packaging.test.ts
Normal file
|
|
@ -0,0 +1,359 @@
|
|||
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:');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue