From 4a2e5ad362f7746a45a694dbcd9c51efac390526 Mon Sep 17 00:00:00 2001 From: Boki Date: Fri, 23 Oct 2026 19:35:56 -0400 Subject: [PATCH] feat(research): retain immutable strategy versions and review history --- apps/stock/config/package.json | 4 + apps/stock/config/src/contracts/backtest.ts | 19 + .../config/src/contracts/builtin-strategy.ts | 107 ++++ .../config/src/contracts/strategy-names.ts | 21 + apps/stock/config/src/contracts/strategy.ts | 324 ++++++++++ .../src/contracts/builtin-strategy.ts | 114 +--- .../orchestrator/src/contracts/strategies.ts | 3 +- .../src/contracts/strategy-names.ts | 26 +- apps/stock/web-api/package.json | 3 +- .../src/migrations/migration-runner.ts | 3 +- .../web-api/src/routes/backtests-v2.routes.ts | 6 +- .../stock/web-api/src/routes/create-routes.ts | 2 + .../web-api/src/routes/strategies.routes.ts | 119 ++++ .../src/services/strategy-catalog.service.ts | 557 ++++++++++++++++++ bun.lock | 1 + .../postgres/init/16-strategy-catalog.sql | 52 ++ docs/development/ROADMAP.md | 16 +- .../architecture/research-product.md | 5 +- docs/development/backlog/manifest.json | 202 ++++++- docs/development/backlog/tasks/R01.md | 27 +- docs/development/backlog/tasks/R02.md | 2 +- docs/development/backlog/tasks/R10.md | 4 + libs/core/di/src/http/security.ts | 9 + libs/core/di/src/index.ts | 1 + libs/core/types/src/index.ts | 6 + libs/core/types/src/strategy-version.ts | 41 ++ scripts/package-builtin-strategies.ts | 187 ++++++ scripts/seed-builtin-strategies.ts | 43 ++ scripts/test/architecture.test.ts | 28 +- scripts/test/strategy-packaging.test.ts | 359 +++++++++++ test/integration/strategy-catalog-api.test.ts | 207 +++++++ .../strategy-version-contract.test.ts | 236 ++++++++ test/postgres/migration-runner.test.ts | 1 + test/postgres/strategy-catalog-seed.test.ts | 116 ++++ test/postgres/strategy-catalog.test.ts | 532 +++++++++++++++++ tsconfig.check.json | 1 + 36 files changed, 3236 insertions(+), 148 deletions(-) create mode 100644 apps/stock/config/src/contracts/builtin-strategy.ts create mode 100644 apps/stock/config/src/contracts/strategy-names.ts create mode 100644 apps/stock/config/src/contracts/strategy.ts create mode 100644 apps/stock/web-api/src/routes/strategies.routes.ts create mode 100644 apps/stock/web-api/src/services/strategy-catalog.service.ts create mode 100644 database/postgres/init/16-strategy-catalog.sql create mode 100644 libs/core/types/src/strategy-version.ts create mode 100644 scripts/package-builtin-strategies.ts create mode 100644 scripts/seed-builtin-strategies.ts create mode 100644 scripts/test/strategy-packaging.test.ts create mode 100644 test/integration/strategy-catalog-api.test.ts create mode 100644 test/integration/strategy-version-contract.test.ts create mode 100644 test/postgres/strategy-catalog-seed.test.ts create mode 100644 test/postgres/strategy-catalog.test.ts diff --git a/apps/stock/config/package.json b/apps/stock/config/package.json index f34d6707..decbf931 100644 --- a/apps/stock/config/package.json +++ b/apps/stock/config/package.json @@ -12,6 +12,10 @@ "./backtest": { "types": "./dist/contracts/backtest.d.ts", "default": "./dist/contracts/backtest.js" + }, + "./strategy": { + "types": "./dist/contracts/strategy.d.ts", + "default": "./dist/contracts/strategy.js" } }, "scripts": { diff --git a/apps/stock/config/src/contracts/backtest.ts b/apps/stock/config/src/contracts/backtest.ts index 5b9aba09..3c765c8b 100644 --- a/apps/stock/config/src/contracts/backtest.ts +++ b/apps/stock/config/src/contracts/backtest.ts @@ -195,6 +195,7 @@ export function normalizeBacktestStrategyConfig( /** One acceptance/defaulting rule for API snapshots, direct execution and queued replay. */ export function parseBacktestRequest(input: unknown): BacktestConfig { + rejectCatalogVersionReferences(input); const config = BacktestConfigSchema.parse(input); validateHistoricalDataRequest(config); config.commission ??= BACKTEST_DEFAULTS.commission; @@ -202,6 +203,23 @@ export function parseBacktestRequest(input: unknown): BacktestConfig { return config; } +/** Retained versions must not be silently interpreted as current legacy name-based code. */ +export function rejectCatalogVersionReferences(input: unknown): void { + if (!input || typeof input !== 'object' || Array.isArray(input)) { + return; + } + const value = input as Record; + if (Object.hasOwn(value, 'strategyVersionId') || Object.hasOwn(value, 'strategyVersionIds')) { + throw new HistoricalDataRequestError( + 'Retained strategy versions are not supported by the current backtest runner' + ); + } + rejectCatalogVersionReferences(value.config); + if (Array.isArray(value.strategies)) { + value.strategies.forEach(rejectCatalogVersionReferences); + } +} + export function isBacktestRequestError(error: unknown): error is Error { return error instanceof z.ZodError || error instanceof HistoricalDataRequestError; } @@ -221,6 +239,7 @@ export function backtestRequestFromDefinition( definition: BacktestDefinitionInput, identity: { runId?: string; backtestId?: string; speedMultiplier?: number | null } = {} ): BacktestConfig { + rejectCatalogVersionReferences(definition); const parameters = definition.config ?? {}; const historical = { symbols: definition.symbols, diff --git a/apps/stock/config/src/contracts/builtin-strategy.ts b/apps/stock/config/src/contracts/builtin-strategy.ts new file mode 100644 index 00000000..36ddd9f9 --- /dev/null +++ b/apps/stock/config/src/contracts/builtin-strategy.ts @@ -0,0 +1,107 @@ +/** Trusted built-in selection only. No callbacks, code paths or checkpoint transport. */ +import { z } from 'zod'; +import { parseFinancialDecimal, type FinancialDecimal } from '@stock-bot/types'; +import { builtinStrategy, maxStrategyPeriod } from './strategy-names'; + +const identity = z + .string() + .min(1) + .refine(value => + [...value].every(character => { + const code = character.charCodeAt(0); + return ( + code >= 32 && code !== 127 && !(character.length === 1 && code >= 0xd800 && code <= 0xdfff) + ); + }) + ); +const period = z.number().int().min(1).max(maxStrategyPeriod); +const positiveBudget: z.ZodType = z + .string() + .transform(value => parseFinancialDecimal(value)) + .refine( + value => !value.startsWith('-') && value !== '0.00000000', + 'Owner budget must be positive' + ); +const nonnegativeNotional: z.ZodType = z + .string() + .transform(value => parseFinancialDecimal(value)) + .refine(value => !value.startsWith('-'), 'Notional volume must be nonnegative'); + +const smaShape = { + ownerId: identity, + strategyId: z + .string() + .refine(value => builtinStrategy(value) === 'sma_crossover', 'Unsupported canonical strategy') + .transform(() => 'sma_crossover' as const), + strategyVersion: z.literal('sma-crossover-long-only/v1'), + seed: z.number().int().min(0).max(0xffffffff), + instrumentId: identity, + seriesId: identity, + ownerBudget: positiveBudget, + parameters: z + .object({ + fastPeriod: period.default(5), + slowPeriod: period.min(2).default(15), + }) + .strict() + .refine( + value => value.fastPeriod < value.slowPeriod, + 'SMA fastPeriod must be below slowPeriod' + ), +}; +export const smaStrategySelectionSchema: z.ZodObject = z + .object(smaShape) + .strict(); + +const meanParameterShape = { + lookbackPeriod: period.min(2), + trendPeriod: period.min(3), + momentumPeriod: period, + volatilityPeriod: period.min(2), + entryZScore: z.number().finite().positive(), + exitZScore: z.number().finite().nonnegative(), + minTrendReturn: z.number().finite().gt(-1), + minMomentumReturn: z.number().finite().gt(-1), + maxVolatility: z.number().finite().nonnegative(), + minNotionalVolume: nonnegativeNotional, + regimeFilter: z.enum(['volatility', 'none']), +}; +type MeanParametersSchema = z.ZodEffects< + z.ZodEffects> +>; +const meanParameters: MeanParametersSchema = z + .object(meanParameterShape) + .strict() + .refine( + value => value.trendPeriod > value.lookbackPeriod, + 'Trend period must exceed the mean-reversion lookback' + ) + .refine( + value => value.exitZScore < value.entryZScore, + 'Exit threshold must be below the entry threshold' + ); + +const meanShape = { + ownerId: identity, + strategyId: z + .string() + .refine(value => builtinStrategy(value) === 'mean_reversion', 'Unsupported canonical strategy') + .transform(() => 'mean_reversion' as const), + strategyVersion: z.literal('mean-reversion-regime-long-only/v1'), + seed: z.number().int().min(0).max(0xffffffff), + instrumentId: identity, + seriesId: identity, + ownerBudget: positiveBudget, + parameters: meanParameters, +}; +export const meanReversionStrategySelectionSchema: z.ZodObject = z + .object(meanShape) + .strict(); + +export const builtinStrategySelectionSchema: z.ZodUnion< + [typeof smaStrategySelectionSchema, typeof meanReversionStrategySelectionSchema] +> = z.union([smaStrategySelectionSchema, meanReversionStrategySelectionSchema]); +export type SmaStrategySelection = z.infer; +export type MeanReversionStrategySelection = z.infer; +export type MeanReversionSignalParameters = MeanReversionStrategySelection['parameters']; +export type BuiltinStrategySelection = z.infer; diff --git a/apps/stock/config/src/contracts/strategy-names.ts b/apps/stock/config/src/contracts/strategy-names.ts new file mode 100644 index 00000000..a231e677 --- /dev/null +++ b/apps/stock/config/src/contracts/strategy-names.ts @@ -0,0 +1,21 @@ +export const maxStrategyPeriod = 10000; +export function normalizeStrategyName(name: string): string { + return name + .trim() + .toLowerCase() + .replace(/[\s_-]/g, ''); +} +export const strategyAliases = { + sma_crossover: ['sma', 'smacrossover', 'simplemovingaveragecrossover', 'movingaverage'], + mean_reversion: ['meanreversion'], + momentum: ['momentum'], + pairs_trading: ['pairs', 'pairstrading'], + ml_enhanced: ['mlenhanced'], +} as const; +export type BuiltinStrategy = keyof typeof strategyAliases; +export function builtinStrategy(name: string): BuiltinStrategy | undefined { + const normalized = normalizeStrategyName(name); + return (Object.keys(strategyAliases) as BuiltinStrategy[]).find(kind => + (strategyAliases[kind] as readonly string[]).includes(normalized) + ); +} diff --git a/apps/stock/config/src/contracts/strategy.ts b/apps/stock/config/src/contracts/strategy.ts new file mode 100644 index 00000000..0267cac4 --- /dev/null +++ b/apps/stock/config/src/contracts/strategy.ts @@ -0,0 +1,324 @@ +/** Pure catalog contracts. Importing this module never constructs or executes a strategy. */ +import { z } from 'zod'; +import type { + StrategyParameterProperty, + StrategyParameterSchema, + StrategyParameterValue, + StrategyVersionPackage, +} from '@stock-bot/types'; +import { + meanReversionStrategySelectionSchema, + smaStrategySelectionSchema, +} from './builtin-strategy'; +import { maxStrategyPeriod } from './strategy-names'; + +export * from './builtin-strategy'; +export * from './strategy-names'; + +/** PostgreSQL JSONB and retained UTF-8 bytes must represent the exact same strings. */ +export function assertStrategyJsonText(input: unknown): void { + if (typeof input === 'string') { + for (let i = 0; i < input.length; i++) { + const code = input.charCodeAt(i); + if (code === 0 || (code >= 0xdc00 && code <= 0xdfff)) { + throw new Error('Strategy text must be valid UTF-8 without NUL characters'); + } + if (code >= 0xd800 && code <= 0xdbff) { + const next = input.charCodeAt(++i); + if (!(next >= 0xdc00 && next <= 0xdfff)) { + throw new Error('Strategy text must be valid UTF-8 without NUL characters'); + } + } + } + } else if (Array.isArray(input)) { + input.forEach(assertStrategyJsonText); + } else if (input && typeof input === 'object') { + for (const [key, value] of Object.entries(input)) { + if (['__proto__', 'constructor', 'prototype'].includes(key)) { + throw new Error('Unsupported strategy metadata key'); + } + assertStrategyJsonText(key); + assertStrategyJsonText(value); + } + } +} + +const scalar = z.union([z.string(), z.number().finite(), z.boolean()]); +const propertySchema = z + .object({ + type: z.enum(['integer', 'number', 'string', 'boolean']), + minimum: z.number().finite().optional(), + maximum: z.number().finite().optional(), + exclusiveMinimum: z.number().finite().optional(), + exclusiveMaximum: z.number().finite().optional(), + enum: z.array(scalar).nonempty().optional(), + default: scalar.optional(), + description: z.string().optional(), + }) + .strict(); +const parameterSchema = z + .object({ + version: z.literal(1), + type: z.literal('object'), + additionalProperties: z.literal(false), + properties: z.record(propertySchema), + required: z.array(z.string()), + }) + .strict(); +const hash = z.string().regex(/^[a-f0-9]{64}$/); +const text = z.string().min(1); +const packageSchema = z + .object({ + version: z.literal(1), + program: z + .object({ + strategyId: text, + strategyVersion: text, + apiVersion: text, + checkpointVersion: text, + }) + .strict(), + artifact: z + .object({ + format: z.literal('esm-bundle/v1'), + entryExport: z.string().regex(/^[A-Za-z_$][\w$]*$/), + content: text, + sha256: hash, + }) + .strict(), + dependencyLock: z + .object({ format: z.literal('bun-lock/v1'), content: text, sha256: hash }) + .strict(), + parameterSchema, + source: z + .object({ revision: z.string().regex(/^[a-f0-9]{40,64}$/), dirty: z.boolean() }) + .strict(), + build: z + .object({ tool: z.literal('bun'), version: text, target: z.literal('browser') }) + .strict(), + }) + .strict(); + +const period = (minimum: number): StrategyParameterProperty => ({ + type: 'integer', + minimum, + maximum: maxStrategyPeriod, +}); +export interface BuiltinCatalogDescriptor { + name: string; + description: string; + program: StrategyVersionPackage['program']; + entryExport: string; + parameterSchema: StrategyParameterSchema; +} +export const builtinCatalogDescriptors: BuiltinCatalogDescriptor[] = [ + { + name: 'SMA crossover (canonical)', + description: 'Long-only reviewed crossover program; Rust enforces financial constraints.', + program: { + strategyId: 'sma_crossover', + strategyVersion: 'sma-crossover-long-only/v1', + apiVersion: 'canonical-ts/v1', + checkpointVersion: 'sma-state/v1', + }, + entryExport: 'createSmaStrategy', + parameterSchema: { + version: 1, + type: 'object', + additionalProperties: false, + properties: { + fastPeriod: { ...period(1), default: 5 }, + slowPeriod: { ...period(2), default: 15 }, + }, + required: [], + }, + }, + { + name: 'Mean reversion with volatility regime (canonical)', + description: 'Long-only fixed signal composition; no claim of validated profitability.', + program: { + strategyId: 'mean_reversion', + strategyVersion: 'mean-reversion-regime-long-only/v1', + apiVersion: 'canonical-ts/v1', + checkpointVersion: 'mean-reversion-state/v1', + }, + entryExport: 'createMeanReversionStrategy', + parameterSchema: { + version: 1, + type: 'object', + additionalProperties: false, + properties: { + lookbackPeriod: period(2), + trendPeriod: period(3), + momentumPeriod: period(1), + volatilityPeriod: period(2), + entryZScore: { type: 'number', exclusiveMinimum: 0 }, + exitZScore: { type: 'number', minimum: 0 }, + minTrendReturn: { type: 'number', exclusiveMinimum: -1 }, + minMomentumReturn: { type: 'number', exclusiveMinimum: -1 }, + maxVolatility: { type: 'number', minimum: 0 }, + minNotionalVolume: { type: 'string' }, + regimeFilter: { type: 'string', enum: ['volatility', 'none'] }, + }, + required: [ + 'lookbackPeriod', + 'trendPeriod', + 'momentumPeriod', + 'volatilityPeriod', + 'entryZScore', + 'exitZScore', + 'minTrendReturn', + 'minMomentumReturn', + 'maxVolatility', + 'minNotionalVolume', + 'regimeFilter', + ], + }, + }, +]; + +/** Stable JSON object-key order; array order and all executable content remain significant. */ +export function canonicalStrategyJson(value: unknown): string { + if (Array.isArray(value)) { + return `[${value.map(canonicalStrategyJson).join(',')}]`; + } + if (value && typeof value === 'object') { + return `{${Object.keys(value) + .sort() + .map( + key => + `${JSON.stringify(key)}:${canonicalStrategyJson((value as Record)[key])}` + ) + .join(',')}}`; + } + const result = JSON.stringify(value); + if (result === undefined) { + throw new Error('Strategy metadata must be JSON'); + } + return result; +} +function checkValue( + name: string, + rule: StrategyParameterProperty, + value: unknown +): asserts value is StrategyParameterValue { + const numeric = rule.type === 'integer' || rule.type === 'number'; + if ( + (numeric + ? typeof value !== 'number' || + !Number.isFinite(value) || + (rule.type === 'integer' && !Number.isInteger(value)) + : typeof value !== rule.type) || + (typeof value === 'number' && + ((rule.minimum !== undefined && value < rule.minimum) || + (rule.maximum !== undefined && value > rule.maximum) || + (rule.exclusiveMinimum !== undefined && value <= rule.exclusiveMinimum) || + (rule.exclusiveMaximum !== undefined && value >= rule.exclusiveMaximum))) || + (rule.enum && !rule.enum.includes(value as StrategyParameterValue)) + ) { + throw new Error(`Invalid parameter: ${name}`); + } +} +function checkSchema(schema: StrategyParameterSchema) { + const properties = schema.properties; + if ( + new Set(schema.required).size !== schema.required.length || + schema.required.some(key => !Object.hasOwn(properties, key)) + ) { + throw new Error('Invalid required parameter names'); + } + for (const [name, rule] of Object.entries(properties)) { + if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name) || ['constructor', 'prototype'].includes(name)) { + throw new Error('Invalid parameter name'); + } + const numeric = rule.type === 'integer' || rule.type === 'number'; + const bounds = [rule.minimum, rule.maximum, rule.exclusiveMinimum, rule.exclusiveMaximum]; + if (!numeric && bounds.some(v => v !== undefined)) { + throw new Error('Only numeric parameters accept bounds'); + } + const low = Math.max(rule.minimum ?? -Infinity, rule.exclusiveMinimum ?? -Infinity); + const high = Math.min(rule.maximum ?? Infinity, rule.exclusiveMaximum ?? Infinity); + if ( + low > high || + (low === high && (rule.exclusiveMinimum === low || rule.exclusiveMaximum === high)) + ) { + throw new Error('Invalid parameter bounds'); + } + if (rule.enum) { + if (new Set(rule.enum).size !== rule.enum.length) { + throw new Error('Duplicate parameter enum value'); + } + for (const value of rule.enum) { + checkValue(name, rule, value); + } + } + if (rule.default !== undefined) { + checkValue(name, rule, rule.default); + } + } +} + +/** Structural validation only. Storage must separately verify artifact/lock SHA256 bytes. */ +export function parseStrategyVersionPackage(input: unknown): StrategyVersionPackage { + assertStrategyJsonText(input); + const parsed = packageSchema.parse(input); + checkSchema(parsed.parameterSchema); + const builtin = builtinCatalogDescriptors.find( + d => + d.program.strategyId === parsed.program.strategyId && + d.program.strategyVersion === parsed.program.strategyVersion + ); + if ( + builtin && + (canonicalStrategyJson(parsed.program) !== canonicalStrategyJson(builtin.program) || + parsed.artifact.entryExport !== builtin.entryExport || + canonicalStrategyJson(parsed.parameterSchema) !== + canonicalStrategyJson(builtin.parameterSchema)) + ) { + throw new Error('A known built-in contract cannot be overridden by published metadata'); + } + return parsed; +} + +/** No schema-supplied code, regex, references or custom validators are executed. */ +export function validateStrategyParameters( + pkg: StrategyVersionPackage, + input: unknown +): Record { + checkSchema(pkg.parameterSchema); + if (!input || typeof input !== 'object' || Array.isArray(input)) { + throw new Error('Parameters must be an object'); + } + const raw = input as Record; + const properties = pkg.parameterSchema.properties; + for (const key of Object.keys(raw)) { + if (!Object.hasOwn(properties, key)) { + throw new Error(`Unknown parameter: ${key}`); + } + } + const result: Record = {}; + for (const [name, rule] of Object.entries(properties)) { + const value = Object.hasOwn(raw, name) ? raw[name] : rule.default; + if (value === undefined) { + if (pkg.parameterSchema.required.includes(name)) { + throw new Error(`Missing parameter: ${name}`); + } + continue; + } + checkValue(name, rule, value); + result[name] = value; + } + if ( + pkg.program.strategyId === 'sma_crossover' && + pkg.program.strategyVersion === 'sma-crossover-long-only/v1' + ) { + return smaStrategySelectionSchema.shape.parameters.parse(result); + } + if ( + pkg.program.strategyId === 'mean_reversion' && + pkg.program.strategyVersion === 'mean-reversion-regime-long-only/v1' + ) { + return meanReversionStrategySelectionSchema.shape.parameters.parse(result); + } + return result; +} diff --git a/apps/stock/orchestrator/src/contracts/builtin-strategy.ts b/apps/stock/orchestrator/src/contracts/builtin-strategy.ts index 27ea0c2f..a751a754 100644 --- a/apps/stock/orchestrator/src/contracts/builtin-strategy.ts +++ b/apps/stock/orchestrator/src/contracts/builtin-strategy.ts @@ -1,108 +1,10 @@ -/** Trusted built-in selection only. No callbacks, code paths or checkpoint transport. */ -import { z } from 'zod'; -import { parseFinancialDecimal } from '@stock-bot/types'; -import { maxStrategyPeriod } from './strategies'; -import { builtinStrategy } from './strategy-names'; - -const identity = z - .string() - .min(1) - .refine(value => - [...value].every(character => { - const code = character.charCodeAt(0); - return ( - code >= 32 && code !== 127 && !(character.length === 1 && code >= 0xd800 && code <= 0xdfff) - ); - }) - ); -const period = z.number().int().min(1).max(maxStrategyPeriod); - -export const smaStrategySelectionSchema = z - .object({ - ownerId: identity, - strategyId: z - .string() - .refine(value => builtinStrategy(value) === 'sma_crossover', 'Unsupported canonical strategy') - .transform(() => 'sma_crossover' as const), - strategyVersion: z.literal('sma-crossover-long-only/v1'), - seed: z.number().int().min(0).max(0xffffffff), - instrumentId: identity, - seriesId: identity, - ownerBudget: z - .string() - .transform(value => parseFinancialDecimal(value)) - .refine( - value => !value.startsWith('-') && value !== '0.00000000', - 'Owner budget must be positive' - ), - parameters: z - .object({ - fastPeriod: period.default(5), - slowPeriod: period.min(2).default(15), - }) - .strict() - .refine( - value => value.fastPeriod < value.slowPeriod, - 'SMA fastPeriod must be below slowPeriod' - ), - }) - .strict(); - -export const meanReversionStrategySelectionSchema = z - .object({ - ownerId: identity, - strategyId: z - .string() - .refine( - value => builtinStrategy(value) === 'mean_reversion', - 'Unsupported canonical strategy' - ) - .transform(() => 'mean_reversion' as const), - strategyVersion: z.literal('mean-reversion-regime-long-only/v1'), - seed: z.number().int().min(0).max(0xffffffff), - instrumentId: identity, - seriesId: identity, - ownerBudget: z - .string() - .transform(value => parseFinancialDecimal(value)) - .refine( - value => !value.startsWith('-') && value !== '0.00000000', - 'Owner budget must be positive' - ), - parameters: z - .object({ - lookbackPeriod: period.min(2), - trendPeriod: period.min(3), - momentumPeriod: period, - volatilityPeriod: period.min(2), - entryZScore: z.number().finite().positive(), - exitZScore: z.number().finite().nonnegative(), - minTrendReturn: z.number().finite().gt(-1), - minMomentumReturn: z.number().finite().gt(-1), - maxVolatility: z.number().finite().nonnegative(), - minNotionalVolume: z - .string() - .transform(value => parseFinancialDecimal(value)) - .refine(value => !value.startsWith('-'), 'Notional volume must be nonnegative'), - regimeFilter: z.enum(['volatility', 'none']), - }) - .strict() - .refine( - value => value.trendPeriod > value.lookbackPeriod, - 'Trend period must exceed the mean-reversion lookback' - ) - .refine( - value => value.exitZScore < value.entryZScore, - 'Exit threshold must be below the entry threshold' - ), - }) - .strict(); - -export const builtinStrategySelectionSchema = z.union([ +/** Compatibility export: canonical validation is shared with the research API. */ +export { smaStrategySelectionSchema, meanReversionStrategySelectionSchema, -]); -export type SmaStrategySelection = z.infer; -export type MeanReversionStrategySelection = z.infer; -export type MeanReversionSignalParameters = MeanReversionStrategySelection['parameters']; -export type BuiltinStrategySelection = z.infer; + builtinStrategySelectionSchema, + type SmaStrategySelection, + type MeanReversionStrategySelection, + type MeanReversionSignalParameters, + type BuiltinStrategySelection, +} from '@stock-bot/stock-config/strategy'; diff --git a/apps/stock/orchestrator/src/contracts/strategies.ts b/apps/stock/orchestrator/src/contracts/strategies.ts index 5619fdd7..81f0fe74 100644 --- a/apps/stock/orchestrator/src/contracts/strategies.ts +++ b/apps/stock/orchestrator/src/contracts/strategies.ts @@ -1,8 +1,9 @@ import { z } from 'zod'; +import { maxStrategyPeriod } from '@stock-bot/stock-config/strategy'; import { instrumentIdSchema } from './historical'; import type { BuiltinStrategy } from './strategy-names'; -export const maxStrategyPeriod = 10000; +export { maxStrategyPeriod }; const period = z.number().finite().int().min(1).max(maxStrategyPeriod); const positive = z.number().finite().positive(); const quantity = positive.min(1e-8).max(1e9); diff --git a/apps/stock/orchestrator/src/contracts/strategy-names.ts b/apps/stock/orchestrator/src/contracts/strategy-names.ts index f53cf15c..7225437c 100644 --- a/apps/stock/orchestrator/src/contracts/strategy-names.ts +++ b/apps/stock/orchestrator/src/contracts/strategy-names.ts @@ -1,20 +1,6 @@ -export function normalizeStrategyName(name: string): string { - return name - .trim() - .toLowerCase() - .replace(/[\s_-]/g, ''); -} -export const strategyAliases = { - sma_crossover: ['sma', 'smacrossover', 'simplemovingaveragecrossover', 'movingaverage'], - mean_reversion: ['meanreversion'], - momentum: ['momentum'], - pairs_trading: ['pairs', 'pairstrading'], - ml_enhanced: ['mlenhanced'], -} as const; -export type BuiltinStrategy = keyof typeof strategyAliases; -export function builtinStrategy(name: string): BuiltinStrategy | undefined { - const normalized = normalizeStrategyName(name); - return (Object.keys(strategyAliases) as BuiltinStrategy[]).find(kind => - (strategyAliases[kind] as readonly string[]).includes(normalized) - ); -} +export { + normalizeStrategyName, + strategyAliases, + builtinStrategy, + type BuiltinStrategy, +} from '@stock-bot/stock-config/strategy'; diff --git a/apps/stock/web-api/package.json b/apps/stock/web-api/package.json index b1dd7865..9cde905a 100644 --- a/apps/stock/web-api/package.json +++ b/apps/stock/web-api/package.json @@ -24,7 +24,8 @@ "@stock-bot/di": "*", "hono": "^4.0.0", "@stock-bot/invariants": "workspace:*", - "@stock-bot/types": "workspace:*" + "@stock-bot/types": "workspace:*", + "zod": "^3.22.4" }, "devDependencies": { "typescript": "^5.0.0" diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index 9bdfbe57..29a11ec5 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -55,7 +55,8 @@ export async function runMigrations(container: IServiceContainer): Promise f === '12-historical-datasets.sql' || f === '13-strategy-recovery.sql' || f === '14-backtest-submission.sql' || - f === '15-canonical-paper-intents.sql') + f === '15-canonical-paper-intents.sql' || + f === '16-strategy-catalog.sql') ) // Explicit additive migration allowlist; never replay destructive init migrations .sort(); diff --git a/apps/stock/web-api/src/routes/backtests-v2.routes.ts b/apps/stock/web-api/src/routes/backtests-v2.routes.ts index 502d913b..b0d1bbdc 100644 --- a/apps/stock/web-api/src/routes/backtests-v2.routes.ts +++ b/apps/stock/web-api/src/routes/backtests-v2.routes.ts @@ -2,7 +2,10 @@ import { Hono } from 'hono'; import { getVerifiedHttpPrincipal } from '@stock-bot/di'; import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; -import { isBacktestRequestError } from '@stock-bot/stock-config/backtest'; +import { + isBacktestRequestError, + rejectCatalogVersionReferences, +} from '@stock-bot/stock-config/backtest'; import { BacktestServiceV2, RunSubmissionConflictError } from '../services/backtest-v2.service'; const logger = getLogger('backtests-v2-routes'); @@ -108,6 +111,7 @@ export function createBacktestV2Routes(container: IServiceContainer) { ); } const body = await c.req.json(); + rejectCatalogVersionReferences(body); const run = await backtestService.createRun( { backtestId: c.req.param('backtestId'), speedMultiplier: body.speedMultiplier }, key !== undefined && principal ? { principal, key } : undefined diff --git a/apps/stock/web-api/src/routes/create-routes.ts b/apps/stock/web-api/src/routes/create-routes.ts index 9eecb581..fce2b72c 100644 --- a/apps/stock/web-api/src/routes/create-routes.ts +++ b/apps/stock/web-api/src/routes/create-routes.ts @@ -14,6 +14,7 @@ import { createExchangeRoutes } from './exchange.routes'; import { createHealthRoutes } from './health.routes'; import { createMonitoringRoutes } from './monitoring.routes'; import { createPipelineRoutes } from './pipeline.routes'; +import { createStrategyRoutes } from './strategies.routes'; export function createRoutes( container: IServiceContainer, @@ -49,6 +50,7 @@ export function createRoutes( app.route('/', backtestRoutes); // Mounted at root since routes already have /api prefix app.route('/', backtestV2Routes); // V2 routes also mounted at root app.route('/', createDatasetRoutes(container)); + app.route('/', createStrategyRoutes(container)); return app; } diff --git a/apps/stock/web-api/src/routes/strategies.routes.ts b/apps/stock/web-api/src/routes/strategies.routes.ts new file mode 100644 index 00000000..869cfb6d --- /dev/null +++ b/apps/stock/web-api/src/routes/strategies.routes.ts @@ -0,0 +1,119 @@ +import { Hono, type MiddlewareHandler } from 'hono'; +import { z } from 'zod'; +import { getCredentialHttpPrincipal } from '@stock-bot/di'; +import type { IServiceContainer } from '@stock-bot/services'; +import { StrategyCatalogError, StrategyCatalogService } from '../services/strategy-catalog.service'; + +const publication = z + .object({ package: z.unknown(), parentVersionId: z.string().uuid().nullable().optional() }) + .strict(); +const parameters = z.object({ parameters: z.unknown() }).strict(); +const submissionKey = z.string().regex(/^[\x21-\x7e]{1,200}$/); + +export function createStrategyRoutes(container: IServiceContainer) { + const app = new Hono(); + const service = new StrategyCatalogService(container); + const credentials: MiddlewareHandler = async (c, next) => { + c.header('Cache-Control', 'no-store'); + if (!['GET', 'HEAD'].includes(c.req.method) && !getCredentialHttpPrincipal(c.req.raw)) { + return c.json({ error: 'Verified credential principal required' }, 401); + } + await next(); + return undefined; + }; + for (const path of [ + '/api/v2/strategies', + '/api/v2/strategies/*', + '/api/v2/strategy-versions/*', + ]) { + app.use(path, credentials); + } + app.onError((error, c) => { + if (error instanceof StrategyCatalogError) { + return c.json({ error: error.message }, error.status); + } + if (error instanceof z.ZodError || error instanceof SyntaxError) { + return c.json({ error: 'Invalid strategy catalog request' }, 400); + } + container.logger.error('Strategy catalog operation failed', { error }); + return c.json({ error: 'Strategy catalog unavailable' }, 500); + }); + // The mounted security layer establishes read access. Writes additionally require + // actual credentials, including on development listeners with auth bypass enabled. + const actor = (request: Request) => { + const value = getCredentialHttpPrincipal(request); + if (!value) { + throw new StrategyCatalogError(401, 'Verified credential principal required'); + } + return value; + }; + app.get('/api/v2/strategies', async c => c.json({ strategies: await service.listStrategies() })); + app.post('/api/v2/strategies', async c => + c.json({ strategy: await service.createStrategy(await c.req.json(), actor(c.req.raw)) }, 201) + ); + app.get('/api/v2/strategies/:id', async c => + c.json({ strategy: await service.getStrategy(c.req.param('id')) }) + ); + app.patch('/api/v2/strategies/:id', async c => + c.json({ + strategy: await service.updateStrategy( + c.req.param('id'), + await c.req.json(), + actor(c.req.raw) + ), + }) + ); + app.get('/api/v2/strategies/:id/versions', async c => + c.json({ versions: await service.listVersions(c.req.param('id')) }) + ); + app.post('/api/v2/strategies/:id/versions', async c => { + const body = publication.parse(await c.req.json()); + return c.json( + { + version: await service.publishVersion( + c.req.param('id'), + body.package, + body.parentVersionId ?? null, + actor(c.req.raw), + submissionKey.parse(c.req.header('Idempotency-Key')) + ), + }, + 201 + ); + }); + app.get('/api/v2/strategy-versions/:id', async c => + c.json({ + version: await service.getVersion(c.req.param('id')), + reviews: await service.getVersionReviews(c.req.param('id')), + }) + ); + app.get('/api/v2/strategy-versions/:id/artifact', async c => + c.json({ package: await service.getVersionArtifact(c.req.param('id')) }) + ); + app.post('/api/v2/strategy-versions/:id/clone', async c => + c.json( + await service.cloneVersion( + c.req.param('id'), + await c.req.json(), + actor(c.req.raw), + submissionKey.parse(c.req.header('Idempotency-Key')) + ), + 201 + ) + ); + app.post('/api/v2/strategy-versions/:id/reviews', async c => { + const principal = actor(c.req.raw); + if (principal !== 'operator') { + throw new StrategyCatalogError(403, 'Human operator approval required'); + } + return c.json( + { version: await service.reviewVersion(c.req.param('id'), await c.req.json(), principal) }, + 201 + ); + }); + app.post('/api/v2/strategy-versions/:id/validate', async c => { + const body = parameters.parse(await c.req.json()); + return c.json(await service.validateVersionParameters(c.req.param('id'), body.parameters)); + }); + return app; +} diff --git a/apps/stock/web-api/src/services/strategy-catalog.service.ts b/apps/stock/web-api/src/services/strategy-catalog.service.ts new file mode 100644 index 00000000..4fb1766d --- /dev/null +++ b/apps/stock/web-api/src/services/strategy-catalog.service.ts @@ -0,0 +1,557 @@ +import { createHash, randomUUID } from 'node:crypto'; +import type { PoolClient, QueryResultRow } from 'pg'; +import { z } from 'zod'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; +import { + assertStrategyJsonText, + builtinCatalogDescriptors, + canonicalStrategyJson, + parseStrategyVersionPackage, + validateStrategyParameters, +} from '@stock-bot/stock-config/strategy'; +import type { StrategyVersionPackage } from '@stock-bot/types'; + +export type StrategyActor = 'operator' | 'service'; +export class StrategyCatalogError extends Error { + constructor( + public readonly status: 400 | 401 | 403 | 404 | 409, + message: string + ) { + super(message); + } +} +const id = z.string().uuid(); +const actorSchema = z.enum(['operator', 'service']); +const keySchema = z.string().regex(/^[\x21-\x7e]{1,200}$/); +const createSchema = z + .object({ name: z.string().trim().min(1), description: z.string().default('') }) + .strict(); +const updateSchema = z + .object({ + name: z.string().trim().min(1).optional(), + description: z.string().optional(), + archived: z.boolean().optional(), + }) + .strict(); +const reviewSchema = z + .object({ decision: z.enum(['approve', 'revoke']), reason: z.string().trim().min(1) }) + .strict(); +const hash = (value: string) => createHash('sha256').update(value, 'utf8').digest('hex'); +function stable(value: unknown): string { + try { + assertStrategyJsonText(value); + return canonicalStrategyJson(value); + } catch { + throw new StrategyCatalogError(400, 'Publication metadata must be JSON'); + } +} +function checkText(value: unknown): void { + try { + assertStrategyJsonText(value); + } catch { + throw new StrategyCatalogError(400, 'Strategy metadata must contain valid JSON text'); + } +} +function checkedPackage(value: unknown): StrategyVersionPackage { + let pkg; + try { + pkg = parseStrategyVersionPackage(value); + } catch (error) { + throw new StrategyCatalogError( + 400, + error instanceof Error ? error.message : 'Invalid strategy package' + ); + } + if ( + hash(pkg.artifact.content) !== pkg.artifact.sha256 || + hash(pkg.dependencyLock.content) !== pkg.dependencyLock.sha256 + ) { + throw new StrategyCatalogError(400, 'Strategy artifact or dependency lock hash mismatch'); + } + return pkg; +} +const metadata = `v.id,v.strategy_id,v.ordinal,v.parent_version_id,v.created_by,v.origin,v.created_at, + (v.envelope #- '{artifact,content}' #- '{dependencyLock,content}') AS package, + COALESCE((SELECT CASE r.decision WHEN 'approve' THEN 'approved' ELSE 'revoked' END + FROM strategy_review_events r WHERE r.version_id=v.id ORDER BY r.ordinal DESC LIMIT 1),'pending') AS review_status`; +type PackageMetadata = Omit & { + artifact: Omit; + dependencyLock: Omit; +}; +export interface StrategyRecord { + id: string; + name: string; + description: string; + ownerPrincipal: StrategyActor; + updatedBy: StrategyActor; + archived: boolean; + createdAt: string; + updatedAt: string; +} +export interface StrategyVersionSummary { + id: string; + strategyId: string; + ordinal: number; + parentVersionId: string | null; + createdBy: StrategyActor; + origin: 'candidate' | 'builtin'; + createdAt: string; + package: PackageMetadata; + reviewStatus: 'pending' | 'approved' | 'revoked'; + runnable: false; + reason: string; +} +const strategy = (row: QueryResultRow): StrategyRecord => ({ + id: row.id, + name: row.name, + description: row.description, + ownerPrincipal: row.owner_principal, + updatedBy: row.updated_by, + archived: row.archived_at !== null, + createdAt: new Date(row.created_at).toISOString(), + updatedAt: new Date(row.updated_at).toISOString(), +}); +const version = (row: QueryResultRow): StrategyVersionSummary => ({ + id: row.id, + strategyId: row.strategy_id, + ordinal: Number(row.ordinal), + parentVersionId: row.parent_version_id, + createdBy: row.created_by, + origin: row.origin, + createdAt: new Date(row.created_at).toISOString(), + package: row.package, + reviewStatus: row.review_status, + runnable: false, + reason: + row.origin === 'builtin' + ? 'Catalog versions require canonical workbench integration (R05) before execution.' + : 'Candidate execution requires isolation (A02); publication and approval do not execute code.', +}); +class ReceiptRace extends Error {} + +export class StrategyCatalogService { + private readonly database; + constructor(container: IServiceContainer) { + this.database = requireServices(container, 'postgres').postgres; + } + + async createStrategy( + input: { name: string; description?: string }, + actor: StrategyActor + ): Promise { + const data = createSchema.parse(input); + checkText(data); + const row = ( + await this.database.query( + 'INSERT INTO strategies(id,name,description,owner_principal,updated_by) VALUES($1,$2,$3,$4,$4) RETURNING *', + [randomUUID(), data.name, data.description, actorSchema.parse(actor)] + ) + ).rows[0]; + if (!row) { + throw new Error('Strategy insertion returned no row'); + } + return strategy(row); + } + async updateStrategy( + strategyId: string, + input: { name?: string; description?: string; archived?: boolean }, + actor: StrategyActor + ): Promise { + actorSchema.parse(actor); + const data = updateSchema.parse(input); + checkText(data); + return this.database.transaction(async client => { + const old = await this.lock(client, strategyId, false); + const row = ( + await client.query( + `UPDATE strategies SET name=$2,description=$3,archived_at=$4,updated_by=$5,updated_at=NOW() WHERE id=$1 RETURNING *`, + [ + old.id, + data.name ?? old.name, + data.description ?? old.description, + data.archived === undefined + ? old.archived_at + : data.archived + ? (old.archived_at ?? new Date()) + : null, + actor, + ] + ) + ).rows[0]; + if (!row) { + throw new Error('Strategy update returned no row'); + } + return strategy(row); + }); + } + async listStrategies(): Promise { + return ( + await this.database.query('SELECT * FROM strategies ORDER BY created_at DESC,id') + ).rows.map(strategy); + } + async getStrategy(strategyId: string): Promise { + const row = ( + await this.database.query('SELECT * FROM strategies WHERE id=$1', [id.parse(strategyId)]) + ).rows[0]; + if (!row) { + throw new StrategyCatalogError(404, 'Strategy not found'); + } + return strategy(row); + } + async listVersions(strategyId: string): Promise { + await this.getStrategy(strategyId); + return ( + await this.database.query( + `SELECT ${metadata} FROM strategy_versions v WHERE v.strategy_id=$1 ORDER BY v.ordinal DESC`, + [strategyId] + ) + ).rows.map(version); + } + async getVersion(versionId: string): Promise { + const row = ( + await this.database.query(`SELECT ${metadata} FROM strategy_versions v WHERE v.id=$1`, [ + id.parse(versionId), + ]) + ).rows[0]; + if (!row) { + throw new StrategyCatalogError(404, 'Strategy version not found'); + } + return version(row); + } + async getVersionArtifact(versionId: string): Promise { + const row = ( + await this.database.query('SELECT envelope FROM strategy_versions WHERE id=$1', [ + id.parse(versionId), + ]) + ).rows[0]; + if (!row) { + throw new StrategyCatalogError(404, 'Strategy version not found'); + } + return checkedPackage(row.envelope); + } + async getVersionReviews(versionId: string) { + await this.getVersion(versionId); + return ( + await this.database.query( + 'SELECT id,ordinal,decision,actor,reason,created_at FROM strategy_review_events WHERE version_id=$1 ORDER BY ordinal', + [versionId] + ) + ).rows.map(row => ({ + id: row.id, + ordinal: Number(row.ordinal), + decision: row.decision as 'approve' | 'revoke', + actor: 'operator' as const, + reason: row.reason as string, + createdAt: new Date(row.created_at).toISOString(), + })); + } + async validateVersionParameters(versionId: string, input: unknown) { + const pkg = await this.getVersionArtifact(versionId); + let parameters; + try { + parameters = validateStrategyParameters(pkg, input); + } catch (error) { + throw new StrategyCatalogError( + 400, + error instanceof Error ? error.message : 'Invalid strategy parameters' + ); + } + return { + parameters, + runnable: false as const, + reason: (await this.getVersion(versionId)).reason, + }; + } + private async lock( + client: PoolClient, + strategyId: string, + active = true + ): Promise { + const row = ( + await client.query('SELECT * FROM strategies WHERE id=$1 FOR UPDATE', [id.parse(strategyId)]) + ).rows[0]; + if (!row) { + throw new StrategyCatalogError(404, 'Strategy not found'); + } + if (active && row.archived_at !== null) { + throw new StrategyCatalogError(409, 'Strategy is archived'); + } + return row; + } + private async receipt( + database: { query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }> }, + actor: StrategyActor, + key: string, + fingerprint: string + ): Promise { + const row = ( + await database.query( + 'SELECT id,submission_fingerprint FROM strategy_versions WHERE created_by=$1 AND submission_key=$2', + [actor, key] + ) + ).rows[0]; + if (!row) { + return null; + } + if (row.submission_fingerprint !== fingerprint) { + throw new StrategyCatalogError( + 409, + 'Idempotency key was already used with different publication content' + ); + } + return row.id; + } + private async publication( + actor: StrategyActor, + key: string, + fingerprint: string, + work: (client: PoolClient) => Promise + ): Promise { + actorSchema.parse(actor); + keySchema.parse(key); + let versionId: string; + try { + versionId = await this.database.transaction(async client => { + const old = await this.receipt(client, actor, key, fingerprint); + return old ?? (await work(client)); + }); + } catch (error) { + if (!(error instanceof ReceiptRace)) { + throw error; + } + // Rollback also removes a losing clone/seed's newly-created strategy. + const winner = await this.receipt(this.database, actor, key, fingerprint); + if (!winner) { + throw new StrategyCatalogError( + 409, + 'Concurrent publication disappeared; retry the same key' + ); + } + versionId = winner; + } + return this.getVersion(versionId); + } + private async insertVersion( + client: PoolClient, + strategyId: string, + pkg: StrategyVersionPackage, + parentVersionId: string | null, + actor: StrategyActor, + origin: 'candidate' | 'builtin', + key: string, + fingerprint: string + ): Promise { + if (parentVersionId !== null) { + const parent = await client.query('SELECT id FROM strategy_versions WHERE id=$1', [ + id.parse(parentVersionId), + ]); + if (!parent.rows[0]) { + throw new StrategyCatalogError(404, 'Parent strategy version not found'); + } + } + const row = ( + await client.query( + `INSERT INTO strategy_versions(id,strategy_id,ordinal,parent_version_id,envelope,created_by,origin,submission_key,submission_fingerprint) + SELECT $1,$2,COALESCE(MAX(ordinal),0)+1,$3,$4::jsonb,$5,$6,$7,$8 FROM strategy_versions WHERE strategy_id=$2 + ON CONFLICT(created_by,submission_key) DO NOTHING RETURNING id`, + [ + randomUUID(), + strategyId, + parentVersionId, + JSON.stringify(pkg), + actor, + origin, + key, + fingerprint, + ] + ) + ).rows[0]; + if (!row) { + throw new ReceiptRace(); + } + return row.id; + } + async publishVersion( + strategyId: string, + input: unknown, + parentVersionId: string | null, + actor: StrategyActor, + key: string + ): Promise { + id.parse(strategyId); + if (parentVersionId !== null) { + id.parse(parentVersionId); + } + const fingerprint = hash( + stable({ kind: 'publish', strategyId, parentVersionId, origin: 'candidate', package: input }) + ); + return this.publication(actor, key, fingerprint, async client => { + const parent = await this.lock(client, strategyId, false); + const old = await this.receipt(client, actor, key, fingerprint); + if (old) { + return old; + } + if (parent.archived_at !== null) { + throw new StrategyCatalogError(409, 'Strategy is archived'); + } + const pkg = checkedPackage(input); + let lineageId = parentVersionId; + if (lineageId === null) { + lineageId = + ( + await client.query( + 'SELECT id FROM strategy_versions WHERE strategy_id=$1 ORDER BY ordinal DESC LIMIT 1', + [strategyId] + ) + ).rows[0]?.id ?? null; + } else { + const lineage = ( + await client.query('SELECT strategy_id FROM strategy_versions WHERE id=$1', [lineageId]) + ).rows[0]; + if (!lineage) { + throw new StrategyCatalogError(404, 'Parent strategy version not found'); + } + if (lineage.strategy_id !== strategyId) { + throw new StrategyCatalogError( + 400, + 'Publication parent must belong to the same strategy; use clone for cross-strategy lineage' + ); + } + } + return this.insertVersion( + client, + strategyId, + pkg, + lineageId, + actor, + 'candidate', + key, + fingerprint + ); + }); + } + async cloneVersion( + sourceId: string, + input: { name: string; description?: string }, + actor: StrategyActor, + key: string + ) { + id.parse(sourceId); + const data = createSchema.parse(input); + const fingerprint = hash(stable({ kind: 'clone', sourceId, ...data, origin: 'candidate' })); + const cloned = await this.publication(actor, key, fingerprint, async client => { + const source = ( + await client.query('SELECT strategy_id,envelope FROM strategy_versions WHERE id=$1', [ + sourceId, + ]) + ).rows[0]; + if (!source) { + throw new StrategyCatalogError(404, 'Source strategy version not found'); + } + await this.lock(client, source.strategy_id, false); + const old = await this.receipt(client, actor, key, fingerprint); + if (old) { + return old; + } + const pkg = checkedPackage(source.envelope); + const strategyId = randomUUID(); + await client.query( + 'INSERT INTO strategies(id,name,description,owner_principal,updated_by) VALUES($1,$2,$3,$4,$4)', + [strategyId, data.name, data.description, actor] + ); + await this.lock(client, strategyId); + return this.insertVersion( + client, + strategyId, + pkg, + sourceId, + actor, + 'candidate', + key, + fingerprint + ); + }); + return { strategy: await this.getStrategy(cloned.strategyId), version: cloned }; + } + async reviewVersion( + versionId: string, + input: { decision: 'approve' | 'revoke'; reason: string }, + actor: StrategyActor + ) { + if (actor !== 'operator') { + throw new StrategyCatalogError(403, 'Human operator approval required'); + } + id.parse(versionId); + const data = reviewSchema.parse(input); + checkText(data); + await this.database.transaction(async client => { + const row = ( + await client.query('SELECT strategy_id FROM strategy_versions WHERE id=$1', [versionId]) + ).rows[0]; + if (!row) { + throw new StrategyCatalogError(404, 'Strategy version not found'); + } + await this.lock(client, row.strategy_id, data.decision === 'approve'); + await client.query( + `INSERT INTO strategy_review_events(id,version_id,ordinal,decision,actor,reason) + SELECT $1,$2,COALESCE(MAX(ordinal),0)+1,$3,'operator',$4 FROM strategy_review_events WHERE version_id=$2`, + [randomUUID(), versionId, data.decision, data.reason] + ); + }); + return this.getVersion(versionId); + } + /** Trusted local import only. This is deliberately absent from HTTP routes. */ + async seedBuiltin(name: string, input: unknown, key: string): Promise { + const pkg = checkedPackage(input); + const descriptor = builtinCatalogDescriptors.find( + item => stable(item.program) === stable(pkg.program) + ); + if ( + !descriptor || + descriptor.entryExport !== pkg.artifact.entryExport || + stable(descriptor.parameterSchema) !== stable(pkg.parameterSchema) + ) { + throw new StrategyCatalogError(400, 'Builtin package does not match a registered descriptor'); + } + const data = createSchema.parse({ name, description: descriptor.description }); + const fingerprint = hash(stable({ kind: 'seed', origin: 'builtin', ...data, package: pkg })); + return this.publication('operator', key, fingerprint, async client => { + await client.query( + `INSERT INTO strategies(id,name,description,owner_principal,updated_by,builtin_key) + VALUES($1,$2,$3,'operator','operator',$4) ON CONFLICT(builtin_key) DO NOTHING`, + [randomUUID(), data.name, data.description, descriptor.program.strategyId] + ); + const family = ( + await client.query('SELECT * FROM strategies WHERE builtin_key=$1 FOR UPDATE', [ + descriptor.program.strategyId, + ]) + ).rows[0]; + if (!family) { + throw new Error('Builtin strategy family disappeared'); + } + const old = await this.receipt(client, 'operator', key, fingerprint); + if (old) { + return old; + } + if (family.archived_at !== null) { + throw new StrategyCatalogError(409, 'Strategy is archived'); + } + const previous = ( + await client.query( + 'SELECT id FROM strategy_versions WHERE strategy_id=$1 ORDER BY ordinal DESC LIMIT 1', + [family.id] + ) + ).rows[0]; + return this.insertVersion( + client, + family.id, + pkg, + previous?.id ?? null, + 'operator', + 'builtin', + key, + fingerprint + ); + }); + } +} diff --git a/bun.lock b/bun.lock index 78ef51ac..07deaf5f 100644 --- a/bun.lock +++ b/bun.lock @@ -180,6 +180,7 @@ "@stock-bot/stock-config": "*", "@stock-bot/types": "workspace:*", "hono": "^4.0.0", + "zod": "^3.22.4", }, "devDependencies": { "typescript": "^5.0.0", diff --git a/database/postgres/init/16-strategy-catalog.sql b/database/postgres/init/16-strategy-catalog.sql new file mode 100644 index 00000000..e7b0b502 --- /dev/null +++ b/database/postgres/init/16-strategy-catalog.sql @@ -0,0 +1,52 @@ +-- Retain authored packages independently of execution eligibility and human review. +CREATE TABLE IF NOT EXISTS strategies ( + id UUID PRIMARY KEY, + name TEXT NOT NULL CHECK (length(btrim(name)) > 0), + description TEXT NOT NULL DEFAULT '', + owner_principal TEXT NOT NULL CHECK (owner_principal IN ('operator', 'service')), + updated_by TEXT NOT NULL CHECK (updated_by IN ('operator', 'service')), + builtin_key TEXT UNIQUE, + archived_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE TABLE IF NOT EXISTS strategy_versions ( + id UUID PRIMARY KEY, + strategy_id UUID NOT NULL REFERENCES strategies(id) ON DELETE RESTRICT, + ordinal INTEGER NOT NULL CHECK (ordinal > 0), + parent_version_id UUID REFERENCES strategy_versions(id) ON DELETE RESTRICT, + envelope JSONB NOT NULL CHECK (jsonb_typeof(envelope) = 'object'), + created_by TEXT NOT NULL CHECK (created_by IN ('operator', 'service')), + origin TEXT NOT NULL CHECK (origin IN ('candidate', 'builtin')), + submission_key TEXT NOT NULL CHECK (length(submission_key) > 0), + submission_fingerprint TEXT NOT NULL CHECK (submission_fingerprint ~ '^[a-f0-9]{64}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (strategy_id, ordinal), + UNIQUE (created_by, submission_key) +); + +CREATE TABLE IF NOT EXISTS strategy_review_events ( + id UUID PRIMARY KEY, + version_id UUID NOT NULL REFERENCES strategy_versions(id) ON DELETE RESTRICT, + ordinal INTEGER NOT NULL CHECK (ordinal > 0), + decision TEXT NOT NULL CHECK (decision IN ('approve', 'revoke')), + actor TEXT NOT NULL CHECK (actor = 'operator'), + reason TEXT NOT NULL CHECK (length(btrim(reason)) > 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (version_id, ordinal) +); + +CREATE OR REPLACE FUNCTION reject_strategy_history_mutation() RETURNS trigger +LANGUAGE plpgsql AS $$ BEGIN + RAISE EXCEPTION 'Strategy history is immutable; publish a new version or append a review'; +END $$; +DROP TRIGGER IF EXISTS strategy_versions_immutable ON strategy_versions; +CREATE TRIGGER strategy_versions_immutable BEFORE UPDATE OR DELETE ON strategy_versions + FOR EACH ROW EXECUTE FUNCTION reject_strategy_history_mutation(); +DROP TRIGGER IF EXISTS strategy_reviews_immutable ON strategy_review_events; +CREATE TRIGGER strategy_reviews_immutable BEFORE UPDATE OR DELETE ON strategy_review_events + FOR EACH ROW EXECUTE FUNCTION reject_strategy_history_mutation(); +DROP TRIGGER IF EXISTS strategies_archive_only ON strategies; +CREATE TRIGGER strategies_archive_only BEFORE DELETE ON strategies + FOR EACH ROW EXECUTE FUNCTION reject_strategy_history_mutation(); diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md index 2a82262a..b3aaa389 100644 --- a/docs/development/ROADMAP.md +++ b/docs/development/ROADMAP.md @@ -332,7 +332,7 @@ Release measurements used six synthetic workloads with **10,000 total bars**, on | Sparse, 1 asset / 1 owner | 788 ms | 1,137 ms | 1,125 ms | −1.0% | | Sparse, 10 assets / 2 owners | 425 ms | 589 ms | 582 ms | −1.3% | | Turnover, 1 asset / 1 owner | 1,425 ms | 1,994 ms | 2,009 ms | +0.7% | -| Turnover, 10 assets / 2 owners | 1,820 ms | 2,432 ms | 2,426 ms | −0.3% | +| Turnover, 10 assets / 2 owners | 1,820 ms | 2, 432 ms | 2,426 ms | −0.3% | Each median has four fresh-session samples across two processes. A separate counterbalanced comparison of projection/report output passed all **48 sessions**, exact repeated report/analytics hashes and an independent integer-cent oracle. Removing reporting fields and normalizing the format discriminator to `projection` yields the identical complete projection. Report finalization medians were 0.24–6.77 ms higher; analytics took 0.50–1.28 ms. These fixtures have only one partial account period: they measure export/occupancy and minimal analytics, not long histories of session statistics, durable research throughput or empty NAPI cost. There is no demonstrated material replay regression on these workloads, and no stable-host SLA is claimed. @@ -481,3 +481,17 @@ The workbench will select exact retained v1 datasets or explicit source requests Independent G1/G2 review accepted the final changes. Repository checks passed 498 integration and 150 Rust tests (four manual ignored), plus build/source/contracts, 82 tooling, 43 utility, 44 calculation and lint gates. The final row-lock fix passed the full disposable PostgreSQL/Redis suite: **111 tests / 792 assertions**. Final release-addon focused coverage: **94 tests / 596 assertions**. Final browser coverage: **6 workflows / 66 assertions**, including real native frozen-hash reuse/reopen/trades, exact intraday save/reopen, mismatch rejection before dispatch and source unpinned-to-pinned display. Strict changed-test types and scoped lint/format/diff checks passed. Exact commands, source hashes and logs are in `manifest.json` → `nineteenth_wave_validation` and `/tmp/stock-bot-wave19.do4GnG/`. The catalog does not certify full content integrity or calendar coverage. Current web economics remain legacy/qualified; v2 entries remain unsupported until R05. No financial Rust change, schema migration, new service, performance measurement, default cutover or trading activation. The final release addon matches this checkout's release library. Both exact disposable fixtures were stopped; development resources, logs and worktrees remain. No R11 commit, push or PR. **Next after acceptance/commit: R01 immutable strategy versions**, now ready under approved ADR-006. + + +## Twentieth-wave execution — 2026-10-23 + +R11 is accepted and committed as `b106c1c`. R01 adds immutable strategy versions, retained bundles/locks, exact parameter validation and audited review. Root owns shared contracts/composition/seeding and integration; backend and offline packaging owners use disjoint worktrees under `/tmp/stock-bot-wave20.XIW6lx/`, with independent review. + +R01 deliberately exposes no version-based execution. R02 catalog/forms can proceed before R05, but actual version submission requires R05 retained-artifact verification/execution. Candidate uploads remain non-runnable until A02. Existing legacy execution stays qualified and rejects unsupported catalog version references. No performance work, new service, engine cutover or trading activation. + + +**Validated handoff:** R01 is `review` / `validated_uncommitted`. Thirty source/config/migration/test files retain immutable bundled-JS versions and dependency locks, source/build identity, scalar parameter schemas with exact canonical validators, stable built-in families, lineage and operator review events. Metadata projection omits content; artifact retrieval verifies exact hashes. Publish/clone idempotency and archive/concurrent-edit behavior use existing SQL transactions. Credential proof excludes development bypass only for new catalog mutations. No candidate code compiles or executes in the API. Offline packaging/seeding commands are documented in [R01](backlog/tasks/R01.md#validated-handoff--2026-10-23). + +Independent G1/G2/security review accepted the final implementation. Validation: build/source/contracts, 93 tooling, 43 utility, 44 calculation, 509 integration and 150 Rust tests (four manual ignored), plus lint. Full disposable PostgreSQL/Redis suite: **122 tests / 903 assertions**. Release-addon focused strategy/API suite: **65 tests / 377 assertions**, plus the final contract edge case. Browser regressions: **6 workflows / 66 assertions**. Strict new-test/script types and scoped lint/format/diff checks passed. Initial allowlist/lint/declaration errors were corrected; the browser contract boundary now builds from current type source after a combined-suite generated-file read failure. Exact commands and evidence are recorded in `manifest.json` → `twentieth_wave_validation` and `/tmp/stock-bot-wave20.XIW6lx/`. + +All catalog versions remain non-runnable until retained-artifact execution is integrated; approval does not enable execution. Original TypeScript source/full-run provenance are not claimed by the bundled-JS catalog. Current legacy workflows remain qualified and reject unsupported catalog version IDs. No financial Rust changes, default cutover, real catalog seeding, trading activation, profiling or benchmarks. The release addon matches the checkout library; both exact test fixtures were stopped. No R01 commit, push or PR. **Next after acceptance/commit: R10 evidence retention; R02 catalog screens are also eligible with disjoint ownership.** diff --git a/docs/development/architecture/research-product.md b/docs/development/architecture/research-product.md index ff7bf6d0..6ba2aac0 100644 --- a/docs/development/architecture/research-product.md +++ b/docs/development/architecture/research-product.md @@ -75,7 +75,7 @@ Keep `/api/v2` and current operator sessions. New APIs follow the task-specific Do not delay M1/M2 for the entire Rust migration. Conversely, delivering those screens does not make old financial results trustworthy. M1 release requires C06 runtime isolation; exploratory labels never excuse interference with paper state. -Dataset selection R11 lists retained manifests without loading bar payloads. A selected existing hash is pinned at submission. A new source request freezes query parameters then prepares asynchronously through the existing runner; only after a fenced atomic dataset binding is it reproducible input. No strategy execution occurs before that binding. Retries reuse the pinned dataset, not a fresh provider query. The UI must distinguish these phases. +Dataset selection R11 lists retained manifests without loading bar payloads. A selected existing hash is recorded in the immutable submission and is bound by the runner after retained-content validation. A new source request freezes query parameters then prepares asynchronously through the existing runner; only after a fenced atomic dataset binding is it reproducible input. No strategy execution occurs before that binding. Retries reuse the pinned dataset, not a fresh provider query. The UI must distinguish these phases. ## Example: bounded AI-assisted multi-strategy research @@ -107,3 +107,6 @@ R11 exposes retained v1 metadata and exact hash selection in both backtest forms - AI narratives cite run/version/metric paths. Traceable evidence is not automatic validation of an arbitrary natural-language conclusion. Validation reports (R08) are immutable experiment-owned outputs, not research findings. Their display must work before R03. R09 enables save/link-finding only when R03 evidence APIs are present; the finding references the exact report and contributing runs, without moving financial truth into a second store. + + +R01 now retains immutable bundled JavaScript and exact dependency locks with source/build metadata. Three tables support editable strategy metadata, immutable versions and append-only reviews. The offline seed command registers only locally packaged built-ins; HTTP uploads/clones remain candidates. Catalog parameter validation never evaluates code, and all versions remain explicitly non-runnable. R02 may deliver catalog/forms before R05, but version-based execution requires R05; arbitrary candidates additionally require A02. Review approval is evidence, not activation. Original TS source and complete run reproducibility remain outside this catalog-only claim. diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 46809de1..619171c9 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,16 +1,16 @@ { "schema_version": 1, - "plan_revision": "2026-10-23.42", + "plan_revision": "2026-10-23.44", "repository_base": "b7aeca4", - "plan_status": "nineteenth_wave_review", + "plan_status": "twentieth_wave_review", "execution_authorized": true, "execution_scope": { - "authorized_by": "User: commit and continue after validated S05 handoff explicitly linked ADR-006 as next research product direction (2026-10-23). S05 accepted and committed 6a67ae868327eebc46872ab58e492933f582b7fd. ADR-006 direction approved by continuation; R11 chosen as next scoped vertical slice. Performance remains deferred.", + "authorized_by": "User: comit all and continue after validated R11 handoff named R01 next (2026-10-23). R11 accepted and committed b106c1ca85e853c7fbcd65fc54c83b9f1024f2ed.", "tasks": [ - "R11" + "R01" ], "permissions": [ - "R11 isolated implementation, correctness/browser tests, independent review and planning updates; prior S05 commit authorized/completed" + "R01 isolated implementation, correctness tests, independent review and planning updates; prior R11 commit authorized and completed" ], "excluded": [ "performance_profiling_or_optimization", @@ -1390,7 +1390,7 @@ "epic": "E6", "priority": "P1", "severity": "High", - "status": "ready", + "status": "review", "dependencies": [ "O01" ], @@ -1409,13 +1409,32 @@ "sql-migrations", "strategy-catalog-api" ], - "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", - "assignment": null, + "parallel_policy": "Root owns pure shared contracts, credential helper, mounts/migration allowlist, trusted seeding and integration. Backend owns additive SQL, catalog service/routes/tests; packaging owns offline build/tests in disjoint worktrees; independent read-only review.", + "assignment": "/root", "branch": null, "pull_request": null, "completed_commit": null, "blocker": null, - "release_gates": [] + "release_gates": [], + "integration_base": "b106c1ca85e853c7fbcd65fc54c83b9f1024f2ed", + "integration_state": "validated_uncommitted", + "worktree": "/home/boki/repos/stock-bot", + "implementation_slices": [ + { + "owner": "/root/s04_controls_audit", + "scope": "Three-table additive migration, catalog API/service, PostgreSQL/HTTP tests", + "worktree": "/tmp/stock-bot-wave20.XIW6lx/backend" + }, + { + "owner": "/root/s04_feed_audit", + "scope": "Offline built-in packaging and artifact conformance tests", + "worktree": "/tmp/stock-bot-wave20.XIW6lx/packaging" + }, + { + "owner": "/root", + "scope": "Pure schemas/contracts, credential proof, legacy version rejection, composition, seed CLI, integration/planning" + } + ] }, { "id": "R02", @@ -1745,7 +1764,7 @@ "epic": "E6", "priority": "P1", "severity": "High", - "status": "review", + "status": "done", "dependencies": [ "D01", "O01" @@ -1771,13 +1790,13 @@ "assignment": "/root", "branch": null, "pull_request": null, - "completed_commit": null, + "completed_commit": "b106c1ca85e853c7fbcd65fc54c83b9f1024f2ed", "blocker": null, "release_gates": [ "W04" ], "integration_base": "6a67ae868327eebc46872ab58e492933f582b7fd", - "integration_state": "validated_uncommitted", + "integration_state": "accepted_committed", "worktree": "/home/boki/repos/stock-bot", "implementation_slices": [ { @@ -2509,6 +2528,32 @@ "Other backlog tasks" ] } + }, + { + "wave": "nineteenth_wave", + "scope": { + "authorized_by": "User: commit and continue after validated S05 handoff explicitly linked ADR-006 as next research product direction (2026-10-23). S05 accepted and committed 6a67ae868327eebc46872ab58e492933f582b7fd. ADR-006 direction approved by continuation; R11 chosen as next scoped vertical slice. Performance remains deferred.", + "tasks": [ + "R11" + ], + "permissions": [ + "R11 isolated implementation, correctness/browser tests, independent review and planning updates; prior S05 commit authorized/completed" + ], + "excluded": [ + "performance_profiling_or_optimization", + "performance_benchmarks", + "new_wave_commits_without_further_approval", + "push", + "pull_requests", + "live_or_paper_operations", + "default_engine_cutover", + "other_backlog_tasks" + ], + "pending_policy_decisions": [ + "ADR-007", + "ADR-008" + ] + } } ], "second_wave": [ @@ -6561,5 +6606,138 @@ "b90c3964498805a5d69bc68540c53b85cef5b9729010d0681a2292d1aff679f8" ], "next": "R01 immutable strategy versions is ADR/code-ready; performance remains deferred." + }, + "twentieth_wave": [ + "R01" + ], + "twentieth_wave_base": "b106c1ca85e853c7fbcd65fc54c83b9f1024f2ed", + "twentieth_wave_notes": [ + "Catalog versions are retained/validated/reviewable but all explicitly non-runnable until R05 (trusted built-ins) or A02 (arbitrary candidates). No canonical-to-legacy alias fallback.", + "R02 catalog/forms may land before R05; actual version-based execution requires R05. R01 does not change active legacy execution beyond rejecting unsupported catalog version references.", + "Trusted source packaging and seeding run offline, never in API. Retained bundles are authoritative executable bytes, not a claim of retaining original TypeScript source or whole-run reproducibility.", + "Catalog write/review identity requires credentials; existing loopback development bypass behavior remains unchanged elsewhere.", + "Performance remains deferred." + ], + "twentieth_wave_validation": { + "state": "validated_uncommitted", + "task": "R01", + "base": "b106c1ca85e853c7fbcd65fc54c83b9f1024f2ed", + "evidence_directory": "/tmp/stock-bot-wave20.XIW6lx", + "source_archive": "/tmp/stock-bot-wave20.XIW6lx/r01-integrated-source.tar", + "source_archive_sha256": "e66dc7778506b7031e133096dae60d85f51a41f302847a5623636c3c9c87143f", + "source_hashes": { + "apps/stock/config/package.json": "2d333adc9382747be0165f89bcf9a505ca0f96348881275d160d58f26052a8fc", + "apps/stock/config/src/contracts/backtest.ts": "7d5319ae1e7ff036516b7c9d765768280c5283e342ce670167e4cd5f83c9b508", + "apps/stock/config/src/contracts/builtin-strategy.ts": "4550b956486ed592602ae54b1d9da3ceaa70d30eae7e4782ea580cf4f4c840ae", + "apps/stock/config/src/contracts/strategy-names.ts": "e0a2d4df53e0e25a6a628bbfc3a99e637a3fc0168b5ae284364e670d1f0140c0", + "apps/stock/config/src/contracts/strategy.ts": "0bbf9d1031de735027217d1abf928a33cc231619cb7380f481b88d5e36e35f4f", + "apps/stock/orchestrator/src/contracts/builtin-strategy.ts": "90111ec562227a8a6683eca82d136f39e70c78515594ad051dd089e6009bb3ef", + "apps/stock/orchestrator/src/contracts/strategies.ts": "4e3b65e6f085029b15b0ba40c04ff98c90fbf9ad51399a27feca4221e3480e40", + "apps/stock/orchestrator/src/contracts/strategy-names.ts": "a8cae1080a1adc96af8e75d54c7dfd11bac783482144544d212a81a250455102", + "apps/stock/web-api/package.json": "a7b6195ae6d85c6f6e8f71c95966b679ddaa96bedcab9755ee59669abb0c5a05", + "apps/stock/web-api/src/migrations/migration-runner.ts": "d4082b767d2cfa46cdd2c94e8b532409703a026e8ee289bd7d93374537152ede", + "apps/stock/web-api/src/routes/backtests-v2.routes.ts": "9c15ed3edc98c1ca2a96501b1a0bc8253365f3d2cd3013f6c363fdc960ac13d4", + "apps/stock/web-api/src/routes/create-routes.ts": "86021b72409fd6d9de1118afac966ba84c157de6f2a77f988db141cc1bc6eded", + "apps/stock/web-api/src/routes/strategies.routes.ts": "17e1ec0d908157e29deaa63d0852c82b4cb28268e92fcc7693e431d0c0a5f115", + "apps/stock/web-api/src/services/strategy-catalog.service.ts": "524aa623e2487418da3bf09c8465f7a69e1262812c9e0a3c19f4ed19159174dd", + "bun.lock": "5a45fe3ab33deb5cf8a6a7268072d05d5532e6251d31985430c3d1d900fa36ea", + "database/postgres/init/16-strategy-catalog.sql": "b4aefd6defc8d5b3ea54eb42106d894eab431ef50d10616ad58cf8a2d11c7b07", + "libs/core/di/src/http/security.ts": "50aaa48f93a1388ecff9d7ece8a11b96cab2a2f4d238ae85097849101a2aacaf", + "libs/core/di/src/index.ts": "0c54996e95f27d877d82e5d60df926371b07c26a32bca6839a56f363f31c06fc", + "libs/core/types/src/index.ts": "b0d5aff5444fc58812f05e21597de215e3e40b670c971ae1303a1fe1b1b9e6de", + "libs/core/types/src/strategy-version.ts": "defe9b9a72229fa95490201965c03602bb6b83f6f5e7c624260cc0857362b22f", + "scripts/package-builtin-strategies.ts": "6dd950e808cd43303e9cf8647712e799a9540cd87b24ca9868b31ff138298996", + "scripts/seed-builtin-strategies.ts": "f8a53726994aa07c549586857483b266b5ec18ab6306ab1ca4d4f3e2dad15153", + "scripts/test/architecture.test.ts": "4c95143f1c237155051b872004b3454851863019fbf8177d9db7094d79b6e0f3", + "scripts/test/strategy-packaging.test.ts": "20fd06d300691bb1f6914d100270b4e10a475dd9270ab6a42c19b2da8c70ab9c", + "test/integration/strategy-catalog-api.test.ts": "7d41f852a9ed6dba60bd28b0d4e0790af1f6c751b8ae9119848aeb2463f95f04", + "test/integration/strategy-version-contract.test.ts": "f0ea588b0dbd8c0793d5e5768fef676161da90fbee0d77b5c683d6fb0afaaf90", + "test/postgres/migration-runner.test.ts": "d2473c534e5eaeac5d7813b719dd4a58d1c9234d7db57c78b195b5fc428b66ed", + "test/postgres/strategy-catalog-seed.test.ts": "f0326abdb81865a9981fe2fd1a183c4fbf3e8f673a52ef6a1514567c05eed78a", + "test/postgres/strategy-catalog.test.ts": "094d0920f5c2abafa96d0d4d0da7b8d30bdef5b8067d645f2a1cd74aa4377c53", + "tsconfig.check.json": "dc301eb7a89afd838afdcb09c1fc32cfee898d3fb26913fb3ff2be01c09bd19a" + }, + "independent_review": { + "owner": "/root/s03_review", + "outcome": "G1/G2 and catalog security accepted; no remaining must-fix findings. Retained bundles, SQL custody, actor receipts, lineage and review/execution separation verified by source review. Reviewer did not run tests.", + "backend_archive_sha256": "5603c18b6f7b34b1a5a0210ce8ff731cbf538f60c177ac8ad2010646da453ff2", + "packaging_archive_sha256": "bdea404390eda37131983ae10bd13f30507a2cb8bbb0dee780d1936fe2d4f42d", + "root_final_adjustments": "Formatting braces in packaging/root tests; architecture allowlist expanded only for pure strategy contract plus explicit source-based browser bundle check; strict root mock types and reserved metadata-key regression." + }, + "checks": [ + { + "command": "CARGO_BUILD_JOBS=2 bun run check", + "log": "/tmp/stock-bot-wave20.XIW6lx/check.log", + "outcome": "Build/source/contracts, 43 utility, 44 calculation, 509 integration and 150 Rust tests (4 manual ignored) passed. Initial tooling allowlist and root curly lint failed and were corrected; failed gates rerun below." + }, + { + "command": "bun run test:tooling", + "log": "/tmp/stock-bot-wave20.XIW6lx/tooling-final-source.log", + "outcome": "93 tests / 12140 assertions passed. Pure strategy subpath explicitly allowed and independently checked. New browser-bundle test resolves current type source rather than generated dist; prior full-suite attempt hit Bun generated-file read errors, isolated test had passed." + }, + { + "command": "bun run lint:check", + "log": "/tmp/stock-bot-wave20.XIW6lx/lint-final.log", + "outcome": "Passed all application/library/tool source lint." + }, + { + "command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32823/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32824/15 bun run test:postgres", + "log": "/tmp/stock-bot-wave20.XIW6lx/postgres.log", + "outcome": "122 tests / 903 assertions passed. Includes additive migration repeat/concurrency, immutable versions/reviews, publication races, archive/clone/seed lineage, UTF-8/hash validation, real builtin seed-to-mounted HTTP workflow, existing durable recovery." + }, + { + "command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:release", + "log": "/tmp/stock-bot-wave20.XIW6lx/native-release.log", + "outcome": "Release addon restored; SHA256 equals checkout release library." + }, + { + "command": "bun test test/integration/strategy-version-contract.test.ts test/integration/canonical-builtins.test.ts test/integration/canonical-sma.test.ts test/integration/canonical-mean-reversion.test.ts test/integration/canonical-strategy-worker.test.ts test/integration/strategy-catalog-api.test.ts", + "log": "/tmp/stock-bot-wave20.XIW6lx/release-focused.log", + "outcome": "65 tests / 377 assertions passed with release addon. Final additional reserved-key assertion passed in contract rerun below." + }, + { + "command": "bun test test/integration/strategy-version-contract.test.ts", + "log": "/tmp/stock-bot-wave20.XIW6lx/final-contract-tests.log", + "outcome": "5 tests / 40 assertions passed, including reserved-key rejection before metadata can be stripped." + }, + { + "command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32823/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32824/15 bun run test:e2e", + "log": "/tmp/stock-bot-wave20.XIW6lx/e2e.log", + "outcome": "6 browser workflows / 66 assertions passed against final routes/security and release addon; legacy web functionality preserved." + }, + { + "command": "bunx tsc --project /tmp/stock-bot-wave20.XIW6lx/tests-tsconfig.json --noEmit", + "log": "/tmp/stock-bot-wave20.XIW6lx/strict-tests-final.log", + "outcome": "Passed strict types for new APIs/contracts/packaging/seed scripts and integration/PostgreSQL tests." + }, + { + "command": "bunx eslint --no-ignore --max-warnings 0; bunx prettier --check ; git diff --check", + "logs": [ + "/tmp/stock-bot-wave20.XIW6lx/scoped-lint-final.log", + "/tmp/stock-bot-wave20.XIW6lx/scoped-format-final.log" + ], + "outcome": "Passed. Existing architecture test style remains covered by tooling tests, not an unrelated formatting rewrite." + } + ], + "native_release_sha256": "ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103", + "scope": "30 source/config/migration/test files. One additive migration; existing Zod dependency explicitly declared for web-api. No Rust financial code, browser catalog implementation or engine activation.", + "limitations": [ + "All catalog versions are non-runnable; R05 must verify/load retained built-in artifacts, A02 gates arbitrary candidate execution.", + "Retained bundled JavaScript is authoritative content. Original TypeScript source and whole-run provenance are not claimed to be retained by R01.", + "Operator/service credentials identify the existing single-owner roles, not individual human identities. Development auth bypass is excluded from catalog mutations.", + "Only explicit local seed command compiles repository built-ins. No production/development catalog was seeded during this wave.", + "R10 still must protect existing template/run/result/dataset evidence from deletion; strategy version/review retention and checksums already exist." + ], + "environment_notes": [ + "Offline bun install required escalation after tempdir write restriction; added only the API direct Zod declaration and matching lock entry, no new dependency version.", + "Initial declaration-generation private-brand error was fixed with explicit Zod shape/effect aliases, preserving input/output types and runtime validation.", + "Initial architecture browser bundle read of generated types failed only in combined tooling suite; source resolution made the assertion deterministic and checks current source.", + "Only exact disposable fixture containers stopped; worktrees/logs retained. No performance work, benchmark measurements, live/paper operations, push, PR or R01 commit." + ], + "stopped_fixture_ids": [ + "ca8a880ef81bbace95ca5fae84328a086f7f68580b0bdc754c507732989df943", + "51c5b994f16c6c2bc7f095d6d9946457cb62a0ac2df5f1a3a8f2be0516f4be78" + ], + "next": "After acceptance/commit, R10 retained research evidence is the next foundation; R02 catalog UI can proceed in parallel only with disjoint files. Performance remains deferred." } } diff --git a/docs/development/backlog/tasks/R01.md b/docs/development/backlog/tasks/R01.md index bd61a3cf..290e9c3a 100644 --- a/docs/development/backlog/tasks/R01.md +++ b/docs/development/backlog/tasks/R01.md @@ -30,7 +30,7 @@ No general workflow framework, browser IDE, multi-tenant identity platform or se - apps/stock/orchestrator/src/strategies/StrategyRegistry.ts - libs/core/types/src/strategy-version.ts (new) -Write locks: sql-migrations, strategy-catalog-api. One agent owns this change. Lock names do not override actual overlapping files. +Write locks: sql-migrations, strategy-catalog-api. Root coordinates shared contracts; backend and packaging agents reserve disjoint actual files. Lock names do not override actual overlapping files. ## Dependencies and blockers @@ -42,7 +42,7 @@ Parallel eligibility: only with disjoint actual files and reserved write locks; ## Acceptance criteria -- Invalid versioned parameters reject before enqueue; only registered/reviewed supported artifacts run. +- Version parameters reject through the catalog validation API using the retained schema and exact registered built-in validators. R01 exposes no enqueue path: every catalog version is explicitly non-runnable until R05 (trusted built-ins) or A02 (arbitrary candidates). Existing legacy requests carrying catalog version IDs reject rather than silently execute current name-based code. - An idempotency key plus content fingerprint makes identical publish retries return the same version; changed content with the same key returns409. An intentional new revision gets a new ID and lineage even if content matches. - Published source/schema/checkpoint/dependency content is immutable and retained. Review/approval is separately audited metadata, not a mutation of executable content. - Registration never executes candidate code in the API; arbitrary untrusted execution stays unavailable until A02. @@ -68,3 +68,26 @@ Keep migrations additive and previous results readable. Do not add a switch that ## Handoff Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done. + +## Execution contract — 2026-10-23 + +- Three additive tables only: editable/archiveable strategies, immutable strategy_versions with retained package JSONB and numbered lineage, append-only operator review events. No R03 placeholders, artifact store or delete cascade. SQL rejects version/review UPDATE/DELETE. +- Package v1 retains self-contained bundled JavaScript, exact Bun lock bytes, SHA256 hashes, source revision/dirty state, compiler identity, parameter schema and API/checkpoint identity. The bundle is authoritative executable content; source metadata does not imply original TS retention or full experiment reproducibility. +- Canonical SMA/MR schemas and aliases move to the existing pure stock-config subpath with compatibility reexports. JSON form schema is a small scalar subset; exact Zod cross-field validation remains authoritative. No uploaded validator or code executes in API. +- Offline packaging builds the two reviewed repository programs with workspace source resolution and no external runtime imports. A separate explicit local seed command registers these built-ins; HTTP publication always creates candidate origin. New/cloned versions start unreviewed. Operator approval/revocation appends audited events, never modifies executable content or enables execution. +- Publish and clone use actor/key receipts plus canonical content fingerprints. Read receipt before mutable parent state, lock parent for ordinal/archive decisions, recheck receipt, insert atomically; changed payload with same key conflicts. New key yields intentional new identity even for identical bytes. Clone retains parent lineage and clears registration/review. +- Catalog mutations require credential-backed operator/service identity; reviews require operator. The development bypass is not authorship proof. Existing routes preserve their prior authentication behavior. +- Metadata list/detail omits artifact/lock content; explicit artifact retrieval retains exact bytes. Version validation returns normalized parameters and `runnable:false`. No UI (R02), retained-artifact execution (R05), untrusted execution (A02), strategy financial changes or performance work. + +## Validated handoff — 2026-10-23 + +Catalog APIs, additive migration 16, pure version/parameter contracts, offline built-in packaging and explicit local seeding are integrated and independently reviewed. Metadata is editable/archiveable; versions/reviews are immutable. Publish/clone receipts, stable built-in families, parent lineage, role checks and exact artifact checksums have real PostgreSQL coverage. New/cloned/rebuilt versions start unreviewed, and all versions remain non-runnable. + +Local commands (not run against development data in this wave): + +- `bun run scripts/package-builtin-strategies.ts --out /tmp/builtin-strategies.json` packages both trusted repository programs without database access. +- After normal migration startup has applied 16, set `STRATEGY_CATALOG_DATABASE_URL` explicitly and run `bun run scripts/seed-builtin-strategies.ts --seed`. It compiles the local built-ins itself, reuses their catalog families, retains package/lock bytes and leaves new versions pending review. It accepts no arbitrary artifact input and performs no schema migration or strategy execution. + +HTTP metadata: `/api/v2/strategies`, `/strategies/:id/versions`, `/strategy-versions/:id`; full bytes use `/:id/artifact`; clone/review/parameter validation use `/:id/clone`, `/:id/reviews`, `/:id/validate`. Publication/clone require `Idempotency-Key`. Catalog mutations require actual operator/service credentials, even when other development routes permit loopback bypass; only operator may review. API-supplied names/flags cannot self-register trusted code. + +Validation: 93 tooling, 509 integration, 150 Rust (four manual ignored), 122 PostgreSQL/Redis and six browser workflows passed, plus source/contracts/build/lint/strict changed-test types. Final release native regressions passed 65 tests. Exact sequencing, hashes, commands and raw logs are canonical in `manifest.json` → `twentieth_wave_validation`. R10 and R02 follow; no current engine switch, candidate execution, trading activation or performance work. diff --git a/docs/development/backlog/tasks/R02.md b/docs/development/backlog/tasks/R02.md index 63a8921d..da427b9a 100644 --- a/docs/development/backlog/tasks/R02.md +++ b/docs/development/backlog/tasks/R02.md @@ -46,7 +46,7 @@ Parallel eligibility: only with disjoint actual files and reserved write locks; - User can create/clone metadata, choose immutable version and schema-valid parameters, then open the existing run flow. - Unavailable native/custom strategy choices are not offered as runnable. - Version detail links deployment/backtest history when available; absent histories show empty states. -- During legacy migration only registered artifacts matching the current supported build are runnable; version selection is persisted, but legacy runs remain unproject-gated until R05. +- Catalog browsing, metadata, version comparison and parameter forms can ship after R01. Persist version selection, but disable version-based submission until R05 verifies and executes retained artifacts. Never map canonical catalog versions to legacy name-based strategies. Existing independent legacy runs remain visibly qualified. ## Mandatory tests diff --git a/docs/development/backlog/tasks/R10.md b/docs/development/backlog/tasks/R10.md index 56e51b68..0fa2730c 100644 --- a/docs/development/backlog/tasks/R10.md +++ b/docs/development/backlog/tasks/R10.md @@ -63,3 +63,7 @@ Keep migrations additive and previous results readable. Do not add a switch that ## Handoff Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done. + +## Predecessor capability — R01 + +R01 already protects strategy versions/review events from update/delete and verifies retained artifact/lock checksums on retrieval. Reuse those paths. R10's remaining work is existing template/run/result/dataset retention and compatibility; do not create a second artifact store or repeat the catalog implementation. R01 currently has no run-to-version link; add references only with the task that introduces them. diff --git a/libs/core/di/src/http/security.ts b/libs/core/di/src/http/security.ts index 24529b5e..c08e99de 100644 --- a/libs/core/di/src/http/security.ts +++ b/libs/core/di/src/http/security.ts @@ -3,11 +3,16 @@ import type { Hono, MiddlewareHandler } from 'hono'; type Role = 'read' | 'admin' | 'service'; const verifiedPrincipals = new WeakMap(); +const credentialRequests = new WeakSet(); /** Server-owned identity established only after successful HTTP authorization. */ export function getVerifiedHttpPrincipal(request: Request): 'operator' | 'service' | undefined { return verifiedPrincipals.get(request); } +/** Catalog authorship/review needs a credential, not the loopback development bypass. */ +export function getCredentialHttpPrincipal(request: Request): 'operator' | 'service' | undefined { + return credentialRequests.has(request) ? verifiedPrincipals.get(request) : undefined; +} export interface HttpSecurityOptions { readToken?: string; adminToken?: string; @@ -149,6 +154,7 @@ export function createHttpSecurity(options: HttpSecurityOptions = httpSecurityOp } function authorize(request: Request, admin = false): Response | undefined { verifiedPrincipals.delete(request); + credentialRequests.delete(request); const identity = authenticate(request); if (!identity) { return Response.json( @@ -170,6 +176,9 @@ export function createHttpSecurity(options: HttpSecurityOptions = httpSecurityOp } if (identity.role !== 'read') { verifiedPrincipals.set(request, identity.role === 'service' ? 'service' : 'operator'); + if (!disabled) { + credentialRequests.add(request); + } } return undefined; } diff --git a/libs/core/di/src/index.ts b/libs/core/di/src/index.ts index bbb3b79a..a0183b94 100644 --- a/libs/core/di/src/index.ts +++ b/libs/core/di/src/index.ts @@ -7,6 +7,7 @@ export { httpSecurityOptions, authenticatedServiceFetch, getVerifiedHttpPrincipal, + getCredentialHttpPrincipal, } from './http/security'; export type { HttpSecurity, HttpSecurityOptions } from './http/security'; export { calculatePoolSize, getServicePoolSize, getHandlerPoolSize } from './pool-size-calculator'; diff --git a/libs/core/types/src/index.ts b/libs/core/types/src/index.ts index 4068fc14..9d4f7ea0 100644 --- a/libs/core/types/src/index.ts +++ b/libs/core/types/src/index.ts @@ -129,6 +129,12 @@ export { validateHistoricalDataRequest, } from './historical-data'; export type { HistoricalDatasetCatalogEntry, BacktestRunDatasetSelection } from './dataset-catalog'; +export type { + StrategyParameterValue, + StrategyParameterProperty, + StrategyParameterSchema, + StrategyVersionPackage, +} from './strategy-version'; export type { InstrumentIdentity, HistoricalDataPolicy, diff --git a/libs/core/types/src/strategy-version.ts b/libs/core/types/src/strategy-version.ts new file mode 100644 index 00000000..5b0bde1d --- /dev/null +++ b/libs/core/types/src/strategy-version.ts @@ -0,0 +1,41 @@ +export type StrategyParameterValue = string | number | boolean; +export interface StrategyParameterProperty { + type: 'integer' | 'number' | 'string' | 'boolean'; + minimum?: number; + maximum?: number; + exclusiveMinimum?: number; + exclusiveMaximum?: number; + enum?: StrategyParameterValue[]; + default?: StrategyParameterValue; + description?: string; +} + +/** Deliberately small JSON schema subset for parameter forms, not executable code. */ +export interface StrategyParameterSchema { + version: 1; + type: 'object'; + additionalProperties: false; + properties: Record; + required: string[]; +} + +/** Retained executable bytes; registration never imports or compiles this content. */ +export interface StrategyVersionPackage { + version: 1; + program: { + strategyId: string; + strategyVersion: string; + apiVersion: string; + checkpointVersion: string; + }; + artifact: { + format: 'esm-bundle/v1'; + entryExport: string; + content: string; + sha256: string; + }; + dependencyLock: { format: 'bun-lock/v1'; content: string; sha256: string }; + parameterSchema: StrategyParameterSchema; + source: { revision: string; dirty: boolean }; + build: { tool: 'bun'; version: string; target: 'browser' }; +} diff --git a/scripts/package-builtin-strategies.ts b/scripts/package-builtin-strategies.ts new file mode 100644 index 00000000..90e17f69 --- /dev/null +++ b/scripts/package-builtin-strategies.ts @@ -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 = { + '@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 { + 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 '); + } + 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; + } +} diff --git a/scripts/seed-builtin-strategies.ts b/scripts/seed-builtin-strategies.ts new file mode 100644 index 00000000..9fed25c1 --- /dev/null +++ b/scripts/seed-builtin-strategies.ts @@ -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) { + 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= 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(); + } +} diff --git a/scripts/test/architecture.test.ts b/scripts/test/architecture.test.ts index 4579af7b..bd6d78ca 100644 --- a/scripts/test/architecture.test.ts +++ b/scripts/test/architecture.test.ts @@ -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', diff --git a/scripts/test/strategy-packaging.test.ts b/scripts/test/strategy-packaging.test.ts new file mode 100644 index 00000000..aaad9b3e --- /dev/null +++ b/scripts/test/strategy-packaging.test.ts @@ -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(); + +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(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>); + 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>); + 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>); + 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), + 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:'); + }); +}); diff --git a/test/integration/strategy-catalog-api.test.ts b/test/integration/strategy-catalog-api.test.ts new file mode 100644 index 00000000..c3f5a9c8 --- /dev/null +++ b/test/integration/strategy-catalog-api.test.ts @@ -0,0 +1,207 @@ +import { randomUUID } from 'node:crypto'; +import { describe, expect, mock, test } from 'bun:test'; +import { Hono } from 'hono'; +import { createHttpSecurity } from '@stock-bot/di'; +import type { IServiceContainer } from '@stock-bot/services'; +import { createStrategyRoutes } from '../../apps/stock/web-api/src/routes/strategies.routes'; + +const tokens = { + operator: 'catalog-admin-fixture-not-a-real-secret-1234', + service: 'catalog-service-fixture-not-a-real-secret-1234', + read: 'catalog-read-fixture-not-a-real-secret-1234', +}; +function fixture(security: 'enabled' | 'disabled' | 'absent' = 'enabled') { + const database = { + query: mock(async () => { + throw new Error('Rejected request reached storage'); + }), + transaction: mock(async () => { + throw new Error('Rejected request reached transaction'); + }), + }; + const logger = { error: mock(() => {}) }; + const app = new Hono(); + if (security !== 'absent') { + createHttpSecurity({ + adminToken: tokens.operator, + serviceToken: tokens.service, + readToken: tokens.read, + environment: 'test', + hostname: '127.0.0.1', + disabled: security === 'disabled', + }).mount(app); + } + app.route( + '/', + createStrategyRoutes({ postgres: database, logger } as unknown as IServiceContainer) + ); + app.post('/api/v2/unrelated', c => c.json({ ok: true })); + return { + database, + app, + request( + path: string, + body: unknown, + role?: keyof typeof tokens, + extra: Record = {}, + method = 'POST' + ) { + return app.request(`/api/v2/${path}`, { + method, + headers: { + ...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}), + 'Content-Type': 'application/json', + ...extra, + }, + body: JSON.stringify(body), + }); + }, + }; +} +const strategyId = randomUUID(); +const versionId = randomUUID(); +const writes = [ + { path: 'strategies', body: { name: 'Candidate' } }, + { path: `strategies/${strategyId}`, body: { archived: true }, method: 'PATCH' }, + { path: `strategies/${strategyId}/versions`, body: { package: {} } }, + { path: `strategy-versions/${versionId}/clone`, body: { name: 'Clone' } }, + { + path: `strategy-versions/${versionId}/reviews`, + body: { decision: 'approve', reason: 'Review' }, + }, + { path: `strategy-versions/${versionId}/validate`, body: { parameters: {} } }, +]; + +describe('strategy catalog HTTP credential boundary', () => { + test('NUL and unpaired Unicode surrogates reject before storage instead of failing JSONB persistence', async () => { + const f = fixture(); + for (const text of ['bad\u0000text', 'bad\ud800text', 'bad\udc00text']) { + const cases = [ + { path: 'strategies', body: { name: text } }, + { path: `strategies/${strategyId}`, body: { description: text }, method: 'PATCH' }, + { + path: `strategies/${strategyId}/versions`, + body: { package: { artifact: { content: text } } }, + }, + { path: `strategy-versions/${versionId}/clone`, body: { name: text } }, + { + path: `strategy-versions/${versionId}/reviews`, + body: { decision: 'approve', reason: text }, + }, + ]; + for (const item of cases) { + expect( + ( + await f.request( + item.path, + item.body, + 'operator', + { 'Idempotency-Key': 'unicode' }, + item.method + ) + ).status + ).toBe(400); + } + } + expect(f.database.query.mock.calls).toHaveLength(0); + expect(f.database.transaction.mock.calls).toHaveLength(0); + }); + test('catalog middleware does not alter unrelated routes on a shared listener', async () => { + const f = fixture('disabled'); + const result = await f.request('unrelated', {}); + expect(result.status).toBe(200); + expect(result.headers.get('Cache-Control')).toBeNull(); + }); + test('every mutation requires verified credentials even with loopback auth bypass or no middleware', async () => { + for (const mode of ['enabled', 'disabled', 'absent'] as const) { + const f = fixture(mode); + for (const item of writes) { + const result = await f.request( + item.path, + item.body, + undefined, + { 'X-Actor': 'operator', 'X-Principal': 'operator', 'Idempotency-Key': 'forged' }, + item.method + ); + expect(result.status).toBe(401); + } + expect(f.database.query.mock.calls).toHaveLength(0); + expect(f.database.transaction.mock.calls).toHaveLength(0); + } + }); + test('read credentials cannot mutate and service credentials cannot append human review', async () => { + const f = fixture(); + for (const item of writes) { + expect((await f.request(item.path, item.body, 'read', {}, item.method)).status).toBe(403); + } + const review = await f.request( + `strategy-versions/${versionId}/reviews?actor=operator`, + { decision: 'approve', reason: 'forged', actor: 'operator' }, + 'service', + { 'X-Principal': 'operator' } + ); + expect(review.status).toBe(403); + expect(f.database.query.mock.calls).toHaveLength(0); + expect(f.database.transaction.mock.calls).toHaveLength(0); + }); + test('strict transport bodies reject privilege fields and missing or malformed receipt keys before storage', async () => { + const f = fixture(); + const cases = [ + { path: 'strategies', body: { name: 'Candidate', ownerPrincipal: 'operator' } }, + { + path: `strategies/${strategyId}`, + body: { name: 'Rename', origin: 'builtin' }, + method: 'PATCH', + }, + { + path: `strategies/${strategyId}/versions`, + body: { package: {}, origin: 'builtin' }, + key: 'key', + }, + { path: `strategies/${strategyId}/versions`, body: { package: {} } }, + { path: `strategies/${strategyId}/versions`, body: { package: {} }, key: 'has spaces' }, + { + path: `strategy-versions/${versionId}/clone`, + body: { name: 'Copy', reviewed: true }, + key: 'key', + }, + { + path: `strategy-versions/${versionId}/reviews`, + body: { decision: 'approve', reason: 'Review', actor: 'operator' }, + }, + { path: `strategy-versions/${versionId}/validate`, body: { parameters: {}, execute: true } }, + ]; + for (const item of cases) { + expect( + ( + await f.request( + item.path, + item.body, + 'operator', + item.key ? { 'Idempotency-Key': item.key } : {}, + item.method + ) + ).status + ).toBe(400); + } + expect(f.database.query.mock.calls).toHaveLength(0); + expect(f.database.transaction.mock.calls).toHaveLength(0); + }); + test('malformed JSON is a client error and no seed or execution endpoint exists', async () => { + const f = fixture(); + const response = await f.app.request('/api/v2/strategies', { + method: 'POST', + headers: { Authorization: `Bearer ${tokens.operator}` }, + body: '{', + }); + expect(response.status).toBe(400); + for (const path of [ + 'strategies/seed', + `strategy-versions/${versionId}/execute`, + `strategy-versions/${versionId}/deploy`, + ]) { + expect((await f.request(path, {}, 'operator')).status).toBe(404); + } + expect(f.database.query.mock.calls).toHaveLength(0); + }); +}); diff --git a/test/integration/strategy-version-contract.test.ts b/test/integration/strategy-version-contract.test.ts new file mode 100644 index 00000000..0a43435e --- /dev/null +++ b/test/integration/strategy-version-contract.test.ts @@ -0,0 +1,236 @@ +import { describe, expect, test } from 'bun:test'; +import { Hono } from 'hono'; +import { getLogger } from '@stock-bot/logger'; +import { PostgreSQLClient } from '@stock-bot/postgres'; +import { + backtestRequestFromDefinition, + parseBacktestRequest, +} from '@stock-bot/stock-config/backtest'; +import type { StrategyVersionPackage } from '@stock-bot/types'; +import { + builtinCatalogDescriptors, + builtinStrategy, + canonicalStrategyJson, + parseStrategyVersionPackage, + validateStrategyParameters, +} from '../../apps/stock/config/src/contracts/strategy'; +import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes'; +import { + createHttpSecurity, + getCredentialHttpPrincipal, + getVerifiedHttpPrincipal, +} from '../../libs/core/di/src/http/security'; + +function packageFor(index = 0): StrategyVersionPackage { + const descriptor = builtinCatalogDescriptors[index]!; + return { + version: 1, + program: structuredClone(descriptor.program), + artifact: { + format: 'esm-bundle/v1', + entryExport: descriptor.entryExport, + content: 'throw new Error("must never execute")', + sha256: 'a'.repeat(64), + }, + dependencyLock: { format: 'bun-lock/v1', content: 'lock-bytes', sha256: 'b'.repeat(64) }, + parameterSchema: structuredClone(descriptor.parameterSchema), + source: { revision: 'c'.repeat(40), dirty: true }, + build: { tool: 'bun', version: 'fixture', target: 'browser' }, + }; +} +const mean = { + lookbackPeriod: 3, + trendPeriod: 5, + momentumPeriod: 1, + volatilityPeriod: 2, + entryZScore: 1, + exitZScore: 0.5, + minTrendReturn: -0.1, + minMomentumReturn: 0, + maxVolatility: 0.01, + minNotionalVolume: '0', + regimeFilter: 'volatility', +}; + +describe('retained strategy contracts', () => { + test('schema_validation retains exact builtin defaults, strict keys and cross-field rules', () => { + const sma = parseStrategyVersionPackage(packageFor()); + expect(validateStrategyParameters(sma, {})).toEqual({ fastPeriod: 5, slowPeriod: 15 }); + for (const params of [ + { fastPeriod: 15, slowPeriod: 5 }, + { fastPeriod: 0 }, + { slowPeriod: 10001 }, + { typo: 1 }, + ]) { + expect(() => validateStrategyParameters(sma, params)).toThrow(); + } + const mr = parseStrategyVersionPackage(packageFor(1)); + expect(validateStrategyParameters(mr, mean).minNotionalVolume).toBe('0.00000000'); + for (const params of [ + { ...mean, trendPeriod: 3 }, + { ...mean, exitZScore: 2 }, + { ...mean, minNotionalVolume: '-1' }, + { ...mean, regimeFilter: 'learned' }, + ]) { + expect(() => validateStrategyParameters(mr, params)).toThrow(); + } + expect(() => + parseStrategyVersionPackage({ + ...sma, + parameterSchema: { ...sma.parameterSchema, required: ['fastPeriod'] }, + }) + ).toThrow('cannot be overridden'); + expect(() => + parseStrategyVersionPackage({ + ...sma, + program: { ...sma.program, checkpointVersion: 'other' }, + }) + ).toThrow('cannot be overridden'); + expect(() => parseStrategyVersionPackage({ ...sma, reviewStatus: 'approved' })).toThrow(); + const reserved = JSON.parse('{"__proto__":{"type":"number"}}'); + expect(() => + parseStrategyVersionPackage({ + ...sma, + parameterSchema: { ...sma.parameterSchema, properties: reserved }, + }) + ).toThrow('Unsupported strategy metadata key'); + }); + test('candidate scalar schema validates without executing code or arbitrary validators', () => { + const pkg = { + ...packageFor(), + program: { + strategyId: 'candidate', + strategyVersion: 'v1', + apiVersion: 'candidate/v1', + checkpointVersion: 'v1', + }, + parameterSchema: { + version: 1 as const, + type: 'object' as const, + additionalProperties: false as const, + properties: { + window: { type: 'integer' as const, minimum: 2, default: 3 }, + enabled: { type: 'boolean' as const }, + mode: { type: 'string' as const, enum: ['a', 'b'] }, + }, + required: ['enabled', 'mode'], + }, + }; + const parsed = parseStrategyVersionPackage(pkg); + expect(validateStrategyParameters(parsed, { enabled: true, mode: 'a' })).toEqual({ + window: 3, + enabled: true, + mode: 'a', + }); + for (const input of [ + { enabled: 1, mode: 'a' }, + { enabled: true, mode: 'c' }, + { enabled: true }, + { enabled: true, mode: 'a', window: 1.5 }, + { enabled: true, mode: 'a', extra: 0 }, + ]) { + expect(() => validateStrategyParameters(parsed, input)).toThrow(); + } + for (const schema of [ + { ...pkg.parameterSchema, required: ['missing'] }, + { ...pkg.parameterSchema, properties: { x: { type: 'number', minimum: 5, maximum: 1 } } }, + { ...pkg.parameterSchema, properties: { x: { type: 'string', pattern: '(.*)*' } } }, + { ...pkg.parameterSchema, properties: { x: { type: 'number', default: 'oops' } } }, + ]) { + expect(() => parseStrategyVersionPackage({ ...pkg, parameterSchema: schema })).toThrow(); + } + }); + test('metadata fingerprints are stable across object key order; arrays and bytes remain significant', () => { + expect(canonicalStrategyJson({ b: 2, a: { d: 4, c: 3 } })).toBe( + canonicalStrategyJson({ a: { c: 3, d: 4 }, b: 2 }) + ); + expect(canonicalStrategyJson({ a: ['a', 'b'] })).not.toBe( + canonicalStrategyJson({ a: ['b', 'a'] }) + ); + expect(builtinStrategy('Moving Average')).toBe('sma_crossover'); + expect(builtinStrategy('mean-reversion')).toBe('mean_reversion'); + }); +}); + +test('catalog credentials exclude loopback bypass while preserving prior route identities', async () => { + const options = { + adminToken: 'operator-test-credential-not-real-123456', + serviceToken: 'service-test-credential-not-real-123456', + }; + const app = new Hono(); + createHttpSecurity(options).mount(app); + // Explicit route callbacks keep the Hono context type local to this router. + app.post('/api/identity', c => + c.json({ + credential: getCredentialHttpPrincipal(c.req.raw), + legacy: getVerifiedHttpPrincipal(c.req.raw), + }) + ); + for (const [token, principal] of [ + [options.adminToken, 'operator'], + [options.serviceToken, 'service'], + ]) { + const response = await app.request('/api/identity', { + method: 'POST', + headers: { Authorization: `Bearer ${token}`, 'X-Principal': 'operator' }, + }); + expect(await response.json()).toEqual({ credential: principal, legacy: principal }); + } + const bypass = new Hono(); + createHttpSecurity({ disabled: true }).mount(bypass); + bypass.post('/api/identity', c => + c.json({ + credential: getCredentialHttpPrincipal(c.req.raw), + legacy: getVerifiedHttpPrincipal(c.req.raw), + }) + ); + expect(await (await bypass.request('/api/identity', { method: 'POST' })).json()).toEqual({ + legacy: 'operator', + }); + expect( + getCredentialHttpPrincipal( + new Request('http://localhost', { headers: { 'X-Principal': 'operator' } }) + ) + ).toBeUndefined(); +}); + +const definition = { + name: 'legacy', + strategy: 'moving-average', + symbols: ['A.US'], + startDate: '2024-01-01T00:00:00Z', + endDate: '2024-02-01T00:00:00Z', + initialCapital: 1000, +}; +test('legacy requests reject catalog references before parsers or routes discard them', async () => { + for (const extra of [ + { strategyVersionId: 'retained' }, + { config: { strategyVersionId: 'retained' } }, + { strategies: [{ name: 'sma', config: { strategyVersionId: 'retained' } }] }, + ]) { + expect(() => backtestRequestFromDefinition({ ...definition, ...extra })).toThrow( + 'not supported' + ); + expect(() => + parseBacktestRequest({ ...definition, mode: 'backtest', dataFrequency: '1d', ...extra }) + ).toThrow('not supported'); + } + const app = createBacktestV2Routes({ + postgres: new PostgreSQLClient({ + host: 'unused', + port: 5432, + database: 'unused', + username: 'unused', + password: 'unused', + }), + logger: getLogger('catalog-contract'), + }); + const response = await app.request( + '/api/v2/backtests/00000000-0000-4000-8000-000000000001/runs', + { method: 'POST', body: JSON.stringify({ strategyVersionId: 'retained' }) } + ); + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ + error: 'Retained strategy versions are not supported by the current backtest runner', + }); +}); diff --git a/test/postgres/migration-runner.test.ts b/test/postgres/migration-runner.test.ts index 6837a6b9..48fff2b8 100644 --- a/test/postgres/migration-runner.test.ts +++ b/test/postgres/migration-runner.test.ts @@ -18,6 +18,7 @@ const migrations = [ '13-strategy-recovery.sql', '14-backtest-submission.sql', '15-canonical-paper-intents.sql', + '16-strategy-catalog.sql', ]; const cleanup: (() => Promise)[] = []; afterEach(async () => { diff --git a/test/postgres/strategy-catalog-seed.test.ts b/test/postgres/strategy-catalog-seed.test.ts new file mode 100644 index 00000000..c13229b7 --- /dev/null +++ b/test/postgres/strategy-catalog-seed.test.ts @@ -0,0 +1,116 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { expect, test } from 'bun:test'; +import { Pool } from 'pg'; +import { createHttpSecurity } from '@stock-bot/di'; +import { getLogger } from '@stock-bot/logger'; +import { PostgreSQLClient } from '@stock-bot/postgres'; +import { createRoutes } from '../../apps/stock/web-api/src/routes/create-routes'; +import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service'; +import { seedBuiltinCatalog } from '../../scripts/seed-builtin-strategies'; + +const url = process.env.PIPELINE_TEST_DATABASE_URL; +test('trusted local seed retains real bundles and exposes only reviewed catalog operations over HTTP', async () => { + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Disposable stock_bot_safety database required'); + } + const schema = `stock_bot_safety_seed_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: url }); + let pool: Pool | undefined; + try { + await admin.query(`CREATE SCHEMA ${schema}`); + pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` }); + await pool.query( + readFileSync( + new URL('../../database/postgres/init/16-strategy-catalog.sql', import.meta.url), + 'utf8' + ) + ); + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + getLogger('seed-fixture') + ); + Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); + Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); + const container = { postgres, logger: getLogger('catalog-seed') }; + const service = new StrategyCatalogService(container); + const versions = await seedBuiltinCatalog(service); + expect(versions).toHaveLength(2); + expect( + versions.every(v => v.origin === 'builtin' && v.reviewStatus === 'pending' && !v.runnable) + ).toBe(true); + expect((await seedBuiltinCatalog(service)).map(v => v.id)).toEqual(versions.map(v => v.id)); + expect((await pool.query('SELECT count(*) FROM strategies')).rows[0].count).toBe('2'); + expect((await pool.query('SELECT count(*) FROM strategy_versions')).rows[0].count).toBe('2'); + const security = { + adminToken: 'operator-catalog-fixture-not-real-123456', + serviceToken: 'service-catalog-fixture-not-real-123456', + environment: 'test', + }; + const app = createRoutes(container, createHttpSecurity(security)); + const request = (path: string, body?: unknown, operator = false, key?: string) => + app.request(path, { + method: body === undefined ? 'GET' : 'POST', + headers: { + Authorization: `Bearer ${operator ? security.adminToken : security.serviceToken}`, + 'Content-Type': 'application/json', + ...(key ? { 'Idempotency-Key': key } : {}), + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + const selected = versions.find(v => v.package.program.strategyId === 'sma_crossover')!; + const path = `/api/v2/strategy-versions/${selected.id}`; + const detail = await (await request(path)).json(); + expect(detail.version.package.artifact.content).toBeUndefined(); + expect(detail.version.package.dependencyLock.content).toBeUndefined(); + expect(detail.version.runnable).toBe(false); + const artifact = await (await request(`${path}/artifact`)).json(); + expect(createHash('sha256').update(artifact.package.artifact.content).digest('hex')).toBe( + artifact.package.artifact.sha256 + ); + const invalid = await request(`${path}/validate`, { + parameters: { fastPeriod: 20, slowPeriod: 10 }, + }); + expect(invalid.status).toBe(400); + const valid = await request(`${path}/validate`, { parameters: {} }); + expect(valid.status).toBe(200); + expect((await valid.json()).parameters).toEqual({ fastPeriod: 5, slowPeriod: 15 }); + expect( + (await request(`${path}/reviews`, { decision: 'approve', reason: 'service cannot approve' })) + .status + ).toBe(403); + const approved = await request( + `${path}/reviews`, + { decision: 'approve', reason: 'fixture operator reviewed bundle' }, + true + ); + expect(approved.status).toBe(201); + const reviewed = await approved.json(); + expect(reviewed.version.reviewStatus).toBe('approved'); + expect(reviewed.version.runnable).toBe(false); + // Even exact built-in bytes uploaded through HTTP do not self-register as trusted code. + const upload = await request( + `/api/v2/strategies/${selected.strategyId}/versions`, + { package: artifact.package }, + false, + 'candidate-copy' + ); + expect(upload.status).toBe(201); + const candidate = await upload.json(); + expect(candidate.version.origin).toBe('candidate'); + expect(candidate.version.parentVersionId).toBe(selected.id); + expect(candidate.version.reviewStatus).toBe('pending'); + expect(candidate.version.runnable).toBe(false); + const replay = await request( + `/api/v2/strategies/${selected.strategyId}/versions`, + { package: artifact.package }, + false, + 'candidate-copy' + ); + expect((await replay.json()).version.id).toBe(candidate.version.id); + } finally { + await pool?.end(); + await admin.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`); + await admin.end(); + } +}, 30000); diff --git a/test/postgres/strategy-catalog.test.ts b/test/postgres/strategy-catalog.test.ts new file mode 100644 index 00000000..880c1d16 --- /dev/null +++ b/test/postgres/strategy-catalog.test.ts @@ -0,0 +1,532 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Hono } from 'hono'; +import { Pool } from 'pg'; +import { createHttpSecurity } from '@stock-bot/di'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient } from '@stock-bot/postgres'; +import { + builtinCatalogDescriptors, + parseStrategyVersionPackage, +} from '@stock-bot/stock-config/strategy'; +import type { StrategyVersionPackage } from '@stock-bot/types'; +import { createStrategyRoutes } from '../../apps/stock/web-api/src/routes/strategies.routes'; +import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('strategy-catalog-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const cleanup: (() => Promise)[] = []; +const migration = readFileSync( + new URL('../../database/postgres/init/16-strategy-catalog.sql', import.meta.url), + 'utf8' +); +const tokens = { + operator: 'catalog-admin-fixture-not-a-real-secret-1234', + service: 'catalog-service-fixture-not-a-real-secret-1234', + read: 'catalog-read-fixture-not-a-real-secret-1234', +}; +const hash = (text: string) => createHash('sha256').update(text).digest('hex'); +function candidate( + content = 'throw new Error("ARTIFACT_MUST_NEVER_EXECUTE");' +): StrategyVersionPackage { + const lock = '{"lockfileVersion":1,"workspaces":{}}'; + return { + version: 1, + program: { + strategyId: 'candidate-fixture', + strategyVersion: 'v1', + apiVersion: 'canonical-ts/v1', + checkpointVersion: 'v1', + }, + artifact: { + format: 'esm-bundle/v1', + entryExport: 'createStrategy', + content, + sha256: hash(content), + }, + dependencyLock: { format: 'bun-lock/v1', content: lock, sha256: hash(lock) }, + parameterSchema: { + version: 1, + type: 'object', + additionalProperties: false, + properties: { + lookback: { type: 'integer', minimum: 1, default: 3 }, + mode: { type: 'string', enum: ['long', 'flat'] }, + }, + required: ['mode'], + }, + source: { revision: 'a'.repeat(40), dirty: false }, + build: { tool: 'bun', version: 'fixture', target: 'browser' }, + }; +} +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); +async function fixture() { + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated stock_bot_safety database required'); + } + const schema = 'stock_bot_safety_catalog_' + randomUUID().replaceAll('-', ''); + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ + connectionString: url, + application_name: schema, + options: `-c search_path=${schema} -c statement_timeout=10000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + await pool.query(migration); + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); + Object.defineProperty(postgres, 'query', { configurable: true, value: pool.query.bind(pool) }); + const api = new StrategyCatalogService({ postgres, logger }); + const app = new Hono(); + createHttpSecurity({ + adminToken: tokens.operator, + serviceToken: tokens.service, + readToken: tokens.read, + environment: 'test', + }).mount(app); + app.route('/', createStrategyRoutes({ postgres, logger })); + return { + pool, + postgres, + api, + app, + request( + path: string, + role: keyof typeof tokens, + body?: unknown, + key?: string, + method = body === undefined ? 'GET' : 'POST' + ) { + return app.request(`/api/v2/${path}`, { + method, + headers: { + Authorization: `Bearer ${tokens[role]}`, + 'Content-Type': 'application/json', + ...(key ? { 'Idempotency-Key': key } : {}), + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + }, + }; +} + +describe.skipIf(!url)('immutable strategy catalog on real PostgreSQL', () => { + test('valid UTF-8 metadata and artifact content retain exact bytes and hashes', async () => { + const f = await fixture(); + const name = 'Research 🚀 東京'; + const s = await f.api.createStrategy({ name }, 'service'); + const pkg = candidate('export const label = "📈 café";'); + const v = await f.api.publishVersion(s.id, pkg, null, 'service', 'unicode'); + expect((await f.api.getStrategy(s.id)).name).toBe(name); + expect(await f.api.getVersionArtifact(v.id)).toEqual(pkg); + expect( + (await f.api.reviewVersion(v.id, { decision: 'approve', reason: 'Reviewed 📈' }, 'operator')) + .reviewStatus + ).toBe('approved'); + expect((await f.api.getVersionReviews(v.id))[0]!.reason).toBe('Reviewed 📈'); + }); + test('retains exact artifact bytes without execution, projects lightweight metadata and validates parameters only', async () => { + const f = await fixture(); + const s = await f.api.createStrategy({ name: 'Candidate' }, 'service'); + const pkg = candidate(); + const v = await f.api.publishVersion(s.id, pkg, null, 'service', 'publish-1'); + expect(s).toMatchObject({ ownerPrincipal: 'service', updatedBy: 'service' }); + expect( + await f.api.updateStrategy(s.id, { description: 'Operator note' }, 'operator') + ).toMatchObject({ ownerPrincipal: 'service', updatedBy: 'operator' }); + expect(v).toMatchObject({ + ordinal: 1, + createdBy: 'service', + origin: 'candidate', + reviewStatus: 'pending', + runnable: false, + }); + expect(v.reason).toContain('A02'); + expect(v.package.artifact).not.toHaveProperty('content'); + expect(v.package.dependencyLock).not.toHaveProperty('content'); + expect(await f.api.getVersionArtifact(v.id)).toEqual(pkg); + expect(await f.api.validateVersionParameters(v.id, { mode: 'long' })).toMatchObject({ + parameters: { mode: 'long', lookback: 3 }, + runnable: false, + }); + for (const invalid of [ + {}, + { mode: 'short' }, + { mode: 'long', lookback: 0 }, + { mode: 'long', extra: true }, + { mode: 'long', lookback: 1.5 }, + ]) { + await expect(f.api.validateVersionParameters(v.id, invalid)).rejects.toMatchObject({ + status: 400, + }); + } + const metadataQueries: string[] = []; + const realQuery = f.pool.query.bind(f.pool); + Object.defineProperty(f.postgres, 'query', { + configurable: true, + value: async (text: string, values: unknown[]) => { + metadataQueries.push(text); + const result = await realQuery(text, values); + for (const row of result.rows) { + expect(row).not.toHaveProperty('envelope'); + if (row.package) { + expect(row.package.artifact).not.toHaveProperty('content'); + } + } + return result; + }, + }); + await f.api.listVersions(s.id); + await f.api.getVersion(v.id); + expect( + metadataQueries + .filter(text => text.includes('FROM strategy_versions')) + .every(text => text.includes("#- '{artifact,content}'")) + ).toBe(true); + }); + + test('hash and schema failures are atomic, and missing references do not leave versions', async () => { + const f = await fixture(); + const s = await f.api.createStrategy({ name: 'Invalid submissions' }, 'operator'); + const badHash = candidate(); + badHash.artifact.content += '\nchanged'; + const badLock = candidate(); + badLock.dependencyLock.content += 'changed'; + const badSchema = candidate(); + badSchema.parameterSchema.required.push('missing'); + for (const [index, pkg] of [badHash, badLock, badSchema].entries()) { + await expect( + f.api.publishVersion(s.id, pkg, null, 'operator', `bad-${index}`) + ).rejects.toMatchObject({ status: 400 }); + } + await expect( + f.api.publishVersion(s.id, candidate(), randomUUID(), 'operator', 'missing-parent') + ).rejects.toMatchObject({ status: 404 }); + expect(await f.api.listVersions(s.id)).toHaveLength(0); + }); + + test('receipt replay is key-order independent, survives archive, and rejects changed intent', async () => { + const f = await fixture(); + const s = await f.api.createStrategy({ name: 'Receipts' }, 'operator'); + const pkg = candidate(); + const v = await f.api.publishVersion(s.id, pkg, null, 'operator', 'same'); + const reordered = { + ...pkg, + program: { + checkpointVersion: pkg.program.checkpointVersion, + apiVersion: pkg.program.apiVersion, + strategyVersion: pkg.program.strategyVersion, + strategyId: pkg.program.strategyId, + }, + }; + expect((await f.api.publishVersion(s.id, reordered, null, 'operator', 'same')).id).toBe(v.id); + const next = await f.api.publishVersion(s.id, pkg, null, 'operator', 'intentional-new'); + expect(next).toMatchObject({ ordinal: 2, parentVersionId: v.id }); + const fork = await f.api.publishVersion(s.id, pkg, v.id, 'operator', 'older-parent'); + expect(fork).toMatchObject({ ordinal: 3, parentVersionId: v.id }); + const foreign = await f.api.createStrategy({ name: 'Foreign parent' }, 'operator'); + await expect( + f.api.publishVersion(foreign.id, pkg, v.id, 'operator', 'cross-parent-invalid') + ).rejects.toMatchObject({ status: 400 }); + await f.api.updateStrategy(s.id, { archived: true }, 'operator'); + expect((await f.api.publishVersion(s.id, pkg, null, 'operator', 'same')).id).toBe(v.id); + await expect( + f.api.publishVersion(s.id, candidate('different'), null, 'operator', 'same') + ).rejects.toMatchObject({ status: 409 }); + await expect( + f.api.publishVersion(s.id, pkg, null, 'operator', 'new-after-archive') + ).rejects.toMatchObject({ status: 409 }); + expect(await f.api.listVersions(s.id)).toHaveLength(3); + }); + + test('parallel publication serializes ordinals and global actor receipts across strategies', async () => { + const f = await fixture(); + const s = await f.api.createStrategy({ name: 'Parallel' }, 'operator'); + const pkg = candidate(); + const repeated = await Promise.all( + Array.from({ length: 5 }, () => f.api.publishVersion(s.id, pkg, null, 'operator', 'repeat')) + ); + expect(new Set(repeated.map(v => v.id)).size).toBe(1); + const unique = await Promise.all( + Array.from({ length: 4 }, (_, index) => + f.api.publishVersion(s.id, pkg, null, 'operator', `unique-${index}`) + ) + ); + expect(unique.map(v => v.ordinal).sort()).toEqual([2, 3, 4, 5]); + const other = await f.api.createStrategy({ name: 'Other' }, 'operator'); + const conflict = await Promise.allSettled( + [s, other].map(target => + f.api.publishVersion(target.id, pkg, null, 'operator', 'cross-parent') + ) + ); + expect(conflict.filter(item => item.status === 'fulfilled')).toHaveLength(1); + expect(conflict.find(item => item.status === 'rejected')).toMatchObject({ + reason: { status: 409 }, + }); + // Different credential cohorts have independent receipt namespaces. + expect((await f.api.publishVersion(other.id, pkg, null, 'service', 'repeat')).createdBy).toBe( + 'service' + ); + }); + + test('archive row lock prevents a blocked publication from entering an archived strategy', async () => { + const f = await fixture(); + const s = await f.api.createStrategy({ name: 'Archive race' }, 'operator'); + const blocker = await f.pool.connect(); + await blocker.query('BEGIN'); + await blocker.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE', [s.id]); + const attempt = f.api.publishVersion(s.id, candidate(), null, 'operator', 'archive-race').then( + () => null, + error => error + ); + await blocker.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [s.id]); + await blocker.query('COMMIT'); + blocker.release(); + expect(await attempt).toMatchObject({ status: 409 }); + expect(await f.api.listVersions(s.id)).toEqual([]); + }); + + test('reviews are explicit human-only append-only evidence, with immutable version and lineage storage', async () => { + const f = await fixture(); + const s = await f.api.createStrategy({ name: 'Audit' }, 'operator'); + const v = await f.api.publishVersion(s.id, candidate(), null, 'operator', 'audit-version'); + await expect( + f.api.reviewVersion(v.id, { decision: 'approve', reason: 'pretend human' }, 'service') + ).rejects.toMatchObject({ status: 403 }); + expect(await f.api.getVersionReviews(v.id)).toHaveLength(0); + expect( + await f.api.reviewVersion( + v.id, + { decision: 'approve', reason: 'Reviewed retained artifact' }, + 'operator' + ) + ).toMatchObject({ reviewStatus: 'approved', runnable: false }); + expect( + await f.api.reviewVersion( + v.id, + { decision: 'revoke', reason: 'Needs further validation' }, + 'operator' + ) + ).toMatchObject({ reviewStatus: 'revoked', runnable: false }); + expect( + (await f.api.getVersionReviews(v.id)).map(event => [ + event.ordinal, + event.decision, + event.actor, + ]) + ).toEqual([ + [1, 'approve', 'operator'], + [2, 'revoke', 'operator'], + ]); + for (const query of [ + 'UPDATE strategy_versions SET ordinal=99', + 'DELETE FROM strategy_versions', + "UPDATE strategy_review_events SET reason='rewrite'", + 'DELETE FROM strategy_review_events', + 'DELETE FROM strategies', + ]) { + await expect(f.pool.query(query)).rejects.toThrow('immutable'); + } + await poolMigrationAgain(f.pool); + expect(await f.api.getVersionReviews(v.id)).toHaveLength(2); + expect(await f.api.getVersionArtifact(v.id)).toEqual(candidate()); + }); + + test('clones retain parent lineage, do not inherit approval, and retry without orphan strategies', async () => { + const f = await fixture(); + const s = await f.api.createStrategy({ name: 'Original' }, 'operator'); + const v = await f.api.publishVersion(s.id, candidate(), null, 'operator', 'source'); + await f.api.reviewVersion(v.id, { decision: 'approve', reason: 'Source reviewed' }, 'operator'); + const clones = await Promise.all( + Array.from({ length: 4 }, () => + f.api.cloneVersion(v.id, { name: 'Copy' }, 'service', 'clone') + ) + ); + expect(new Set(clones.map(item => item.strategy.id)).size).toBe(1); + expect(clones[0]!.version).toMatchObject({ + parentVersionId: v.id, + ordinal: 1, + origin: 'candidate', + reviewStatus: 'pending', + runnable: false, + }); + expect(clones[0]!.strategy.ownerPrincipal).toBe('service'); + expect(await f.api.getVersionReviews(clones[0]!.version.id)).toHaveLength(0); + expect(await f.api.listStrategies()).toHaveLength(2); + await expect( + f.api.cloneVersion(v.id, { name: 'Different copy' }, 'service', 'clone') + ).rejects.toMatchObject({ status: 409 }); + const revision = await f.api.publishVersion( + s.id, + candidate('revision'), + v.id, + 'operator', + 'revision' + ); + expect(revision.parentVersionId).toBe(v.id); + expect(revision.reviewStatus).toBe('pending'); + }); + + test('trusted builtin seeding is idempotent and never grants review or execution', async () => { + const f = await fixture(); + const descriptor = builtinCatalogDescriptors[0]!; + const base = candidate(); + const pkg = parseStrategyVersionPackage({ + ...base, + program: descriptor.program, + parameterSchema: descriptor.parameterSchema, + artifact: { ...base.artifact, entryExport: descriptor.entryExport }, + }); + const seeded = await Promise.all( + Array.from({ length: 3 }, () => f.api.seedBuiltin(descriptor.name, pkg, 'builtin-seed')) + ); + expect(new Set(seeded.map(v => v.id)).size).toBe(1); + expect(seeded[0]).toMatchObject({ + origin: 'builtin', + createdBy: 'operator', + reviewStatus: 'pending', + runnable: false, + }); + expect(seeded[0]!.reason).toContain('R05'); + expect(await f.api.listStrategies()).toHaveLength(1); + await expect(f.api.seedBuiltin('Fake builtin', candidate(), 'fake')).rejects.toMatchObject({ + status: 400, + }); + expect((await f.api.validateVersionParameters(seeded[0]!.id, {})).parameters).toMatchObject({ + fastPeriod: 5, + slowPeriod: 15, + }); + await expect( + f.api.validateVersionParameters(seeded[0]!.id, { fastPeriod: 15, slowPeriod: 5 }) + ).rejects.toMatchObject({ status: 400 }); + const first = seeded[0]!; + await f.api.reviewVersion( + first.id, + { decision: 'approve', reason: 'Reviewed first build' }, + 'operator' + ); + await f.api.updateStrategy( + first.strategyId, + { name: 'Personal SMA', description: 'Retained note' }, + 'service' + ); + const changed = structuredClone(pkg); + changed.source.revision = 'b'.repeat(40); + const updates = await Promise.all( + Array.from({ length: 3 }, () => + f.api.seedBuiltin(descriptor.name, changed, 'builtin-revision') + ) + ); + expect(new Set(updates.map(v => v.id)).size).toBe(1); + expect(updates[0]).toMatchObject({ + strategyId: first.strategyId, + ordinal: 2, + parentVersionId: first.id, + reviewStatus: 'pending', + runnable: false, + }); + expect(await f.api.getStrategy(first.strategyId)).toMatchObject({ + name: 'Personal SMA', + description: 'Retained note', + updatedBy: 'service', + }); + expect(await f.api.listStrategies()).toHaveLength(1); + await f.api.updateStrategy(first.strategyId, { archived: true }, 'operator'); + expect((await f.api.seedBuiltin(descriptor.name, pkg, 'builtin-seed')).id).toBe(first.id); + await expect( + f.api.seedBuiltin(descriptor.name, changed, 'new-after-archive') + ).rejects.toMatchObject({ status: 409 }); + }); + + test('HTTP service candidates cannot impersonate builtin authors or reviewers; readers retain artifact access', async () => { + const f = await fixture(); + const created = await f.request('strategies', 'service', { name: 'HTTP candidate' }); + expect(created.status).toBe(201); + const s = (await created.json()).strategy; + const published = await f.request( + `strategies/${s.id}/versions`, + 'service', + { package: candidate() }, + 'http-publish' + ); + expect(published.status).toBe(201); + const v = (await published.json()).version; + expect(v).toMatchObject({ + origin: 'candidate', + createdBy: 'service', + reviewStatus: 'pending', + runnable: false, + }); + expect( + ( + await f.request( + `strategies/${s.id}/versions`, + 'service', + { package: candidate(), origin: 'builtin' }, + 'forgery' + ) + ).status + ).toBe(400); + expect( + ( + await f.request(`strategy-versions/${v.id}/reviews`, 'service', { + decision: 'approve', + reason: 'forged', + actor: 'operator', + }) + ).status + ).toBe(403); + expect( + ( + await f.request(`strategy-versions/${v.id}/reviews`, 'operator', { + decision: 'approve', + reason: 'checked', + }) + ).status + ).toBe(201); + const detail = await f.request(`strategy-versions/${v.id}`, 'read'); + expect(await detail.json()).toMatchObject({ + version: { reviewStatus: 'approved', runnable: false }, + reviews: [{ ordinal: 1, actor: 'operator' }], + }); + const artifact = await f.request(`strategy-versions/${v.id}/artifact`, 'read'); + expect(await artifact.json()).toEqual({ package: candidate() }); + expect( + ( + await f.request(`strategy-versions/${v.id}/validate`, 'service', { + parameters: { mode: 'flat' }, + }) + ).status + ).toBe(200); + expect( + ( + await f.request(`strategy-versions/${v.id}/validate`, 'service', { + parameters: { mode: 'invalid' }, + }) + ).status + ).toBe(400); + expect( + (await f.request(`strategy-versions/${v.id}/artifact`, 'read')).headers.get('Cache-Control') + ).toBe('no-store'); + expect((await f.request('strategies/seed', 'operator', {})).status).toBe(404); + expect((await f.request(`strategy-versions/${randomUUID()}`, 'read')).status).toBe(404); + }); +}); + +async function poolMigrationAgain(pool: Pool) { + await pool.query(migration); +} diff --git a/tsconfig.check.json b/tsconfig.check.json index 5d916a81..d525a864 100644 --- a/tsconfig.check.json +++ b/tsconfig.check.json @@ -11,6 +11,7 @@ "@/*": ["apps/stock/web-app/src/*"], "@stock-bot/stock-config": ["apps/stock/config/src/index.ts"], "@stock-bot/stock-config/backtest": ["apps/stock/config/src/contracts/backtest.ts"], + "@stock-bot/stock-config/strategy": ["apps/stock/config/src/contracts/strategy.ts"], "@stock-bot/engine": ["apps/stock/engine/index.d.ts"], "@stock-bot/*": [ "libs/core/*/src/index.ts",