feat(research): retain immutable strategy versions and review history
This commit is contained in:
parent
b106c1ca85
commit
4a2e5ad362
36 changed files with 3236 additions and 148 deletions
|
|
@ -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": {
|
||||
|
|
|
|||
|
|
@ -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<string, unknown>;
|
||||
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,
|
||||
|
|
|
|||
107
apps/stock/config/src/contracts/builtin-strategy.ts
Normal file
107
apps/stock/config/src/contracts/builtin-strategy.ts
Normal file
|
|
@ -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<FinancialDecimal, z.ZodTypeDef, string> = z
|
||||
.string()
|
||||
.transform(value => parseFinancialDecimal(value))
|
||||
.refine(
|
||||
value => !value.startsWith('-') && value !== '0.00000000',
|
||||
'Owner budget must be positive'
|
||||
);
|
||||
const nonnegativeNotional: z.ZodType<FinancialDecimal, z.ZodTypeDef, string> = 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<typeof smaShape, 'strict'> = 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<z.ZodObject<typeof meanParameterShape, 'strict'>>
|
||||
>;
|
||||
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<typeof meanShape, 'strict'> = z
|
||||
.object(meanShape)
|
||||
.strict();
|
||||
|
||||
export const builtinStrategySelectionSchema: z.ZodUnion<
|
||||
[typeof smaStrategySelectionSchema, typeof meanReversionStrategySelectionSchema]
|
||||
> = z.union([smaStrategySelectionSchema, meanReversionStrategySelectionSchema]);
|
||||
export type SmaStrategySelection = z.infer<typeof smaStrategySelectionSchema>;
|
||||
export type MeanReversionStrategySelection = z.infer<typeof meanReversionStrategySelectionSchema>;
|
||||
export type MeanReversionSignalParameters = MeanReversionStrategySelection['parameters'];
|
||||
export type BuiltinStrategySelection = z.infer<typeof builtinStrategySelectionSchema>;
|
||||
21
apps/stock/config/src/contracts/strategy-names.ts
Normal file
21
apps/stock/config/src/contracts/strategy-names.ts
Normal file
|
|
@ -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)
|
||||
);
|
||||
}
|
||||
324
apps/stock/config/src/contracts/strategy.ts
Normal file
324
apps/stock/config/src/contracts/strategy.ts
Normal file
|
|
@ -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<string, unknown>)[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<string, StrategyParameterValue> {
|
||||
checkSchema(pkg.parameterSchema);
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) {
|
||||
throw new Error('Parameters must be an object');
|
||||
}
|
||||
const raw = input as Record<string, unknown>;
|
||||
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<string, StrategyParameterValue> = {};
|
||||
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;
|
||||
}
|
||||
|
|
@ -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<typeof smaStrategySelectionSchema>;
|
||||
export type MeanReversionStrategySelection = z.infer<typeof meanReversionStrategySelectionSchema>;
|
||||
export type MeanReversionSignalParameters = MeanReversionStrategySelection['parameters'];
|
||||
export type BuiltinStrategySelection = z.infer<typeof builtinStrategySelectionSchema>;
|
||||
builtinStrategySelectionSchema,
|
||||
type SmaStrategySelection,
|
||||
type MeanReversionStrategySelection,
|
||||
type MeanReversionSignalParameters,
|
||||
type BuiltinStrategySelection,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -55,7 +55,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
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();
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
119
apps/stock/web-api/src/routes/strategies.routes.ts
Normal file
119
apps/stock/web-api/src/routes/strategies.routes.ts
Normal file
|
|
@ -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;
|
||||
}
|
||||
557
apps/stock/web-api/src/services/strategy-catalog.service.ts
Normal file
557
apps/stock/web-api/src/services/strategy-catalog.service.ts
Normal file
|
|
@ -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<StrategyVersionPackage, 'artifact' | 'dependencyLock'> & {
|
||||
artifact: Omit<StrategyVersionPackage['artifact'], 'content'>;
|
||||
dependencyLock: Omit<StrategyVersionPackage['dependencyLock'], 'content'>;
|
||||
};
|
||||
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<StrategyRecord> {
|
||||
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<StrategyRecord> {
|
||||
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<StrategyRecord[]> {
|
||||
return (
|
||||
await this.database.query('SELECT * FROM strategies ORDER BY created_at DESC,id')
|
||||
).rows.map(strategy);
|
||||
}
|
||||
async getStrategy(strategyId: string): Promise<StrategyRecord> {
|
||||
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<StrategyVersionSummary[]> {
|
||||
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<StrategyVersionSummary> {
|
||||
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<StrategyVersionPackage> {
|
||||
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<QueryResultRow> {
|
||||
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<string | null> {
|
||||
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<string>
|
||||
): Promise<StrategyVersionSummary> {
|
||||
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<string> {
|
||||
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<StrategyVersionSummary> {
|
||||
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<StrategyVersionSummary> {
|
||||
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
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue