feat(research): add strategy catalog and versioned backtest setup
This commit is contained in:
parent
8cca0ee588
commit
d929db707a
44 changed files with 4198 additions and 209 deletions
|
|
@ -209,7 +209,12 @@ export function rejectCatalogVersionReferences(input: unknown): void {
|
|||
return;
|
||||
}
|
||||
const value = input as Record<string, unknown>;
|
||||
if (Object.hasOwn(value, 'strategyVersionId') || Object.hasOwn(value, 'strategyVersionIds')) {
|
||||
if (
|
||||
value.strategy === 'catalog' ||
|
||||
Object.hasOwn(value, 'strategyParameters') ||
|
||||
Object.hasOwn(value, 'strategyVersionId') ||
|
||||
Object.hasOwn(value, 'strategyVersionIds')
|
||||
) {
|
||||
throw new HistoricalDataRequestError(
|
||||
'Retained strategy versions are not supported by the current backtest runner'
|
||||
);
|
||||
|
|
@ -235,11 +240,10 @@ export interface BacktestDefinitionInput {
|
|||
}
|
||||
|
||||
/** Translate the existing API definition shape without changing its stored parameter bag. */
|
||||
export function backtestRequestFromDefinition(
|
||||
export function backtestSettingsFromDefinition(
|
||||
definition: BacktestDefinitionInput,
|
||||
identity: { runId?: string; backtestId?: string; speedMultiplier?: number | null } = {}
|
||||
): BacktestConfig {
|
||||
rejectCatalogVersionReferences(definition);
|
||||
): BacktestExecutionSettings {
|
||||
const parameters = definition.config ?? {};
|
||||
const historical = {
|
||||
symbols: definition.symbols,
|
||||
|
|
@ -260,21 +264,19 @@ export function backtestRequestFromDefinition(
|
|||
if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) {
|
||||
throw new HistoricalDataRequestError('Speed multiplier must be positive or null');
|
||||
}
|
||||
return parseBacktestRequest({
|
||||
return BacktestExecutionSettingsSchema.parse({
|
||||
...historical,
|
||||
runId: identity.runId,
|
||||
backtestId: identity.backtestId,
|
||||
name: definition.name,
|
||||
mode: 'backtest',
|
||||
strategy: definition.strategy,
|
||||
startDate: new Date(historical.startDate).toISOString(),
|
||||
endDate: new Date(historical.endDate).toISOString(),
|
||||
initialCapital: definition.initialCapital,
|
||||
config: parameters,
|
||||
riskLimits: parameters.riskLimits,
|
||||
// Definition APIs historically treat null fees as unset; the parser owns defaults.
|
||||
commission: parameters.commission ?? undefined,
|
||||
slippage: parameters.slippage ?? undefined,
|
||||
commission: parameters.commission ?? BACKTEST_DEFAULTS.commission,
|
||||
slippage: parameters.slippage ?? BACKTEST_DEFAULTS.slippage,
|
||||
speed:
|
||||
multiplier === null
|
||||
? 'max'
|
||||
|
|
@ -287,3 +289,43 @@ export function backtestRequestFromDefinition(
|
|||
: 'realtime',
|
||||
});
|
||||
}
|
||||
|
||||
/** Legacy execution admission remains separate from catalog draft validation. */
|
||||
export function backtestRequestFromDefinition(
|
||||
definition: BacktestDefinitionInput,
|
||||
identity: { runId?: string; backtestId?: string; speedMultiplier?: number | null } = {}
|
||||
): BacktestConfig {
|
||||
rejectCatalogVersionReferences(definition);
|
||||
return parseBacktestRequest({
|
||||
...backtestSettingsFromDefinition(definition, identity),
|
||||
strategy: definition.strategy,
|
||||
config: definition.config ?? {},
|
||||
});
|
||||
}
|
||||
|
||||
/** Catalog strategy parameters never share the run-wide settings bag. */
|
||||
export const CatalogBacktestConfigSchema = BacktestExecutionSettingsSchema.pick({
|
||||
dataFrequency: true,
|
||||
dataPolicy: true,
|
||||
datasetHash: true,
|
||||
dataSource: true,
|
||||
commission: true,
|
||||
slippage: true,
|
||||
riskLimits: true,
|
||||
fillModel: true,
|
||||
})
|
||||
.partial()
|
||||
.strict();
|
||||
export const CatalogBacktestDefinitionSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1),
|
||||
strategy: z.literal('catalog'),
|
||||
strategyVersionId: z.string().uuid(),
|
||||
strategyParameters: z.record(z.unknown()),
|
||||
symbols: BacktestExecutionSettingsSchema.shape.symbols,
|
||||
startDate: z.union([z.string(), z.date()]),
|
||||
endDate: z.union([z.string(), z.date()]),
|
||||
initialCapital: BacktestExecutionSettingsSchema.shape.initialCapital,
|
||||
config: CatalogBacktestConfigSchema.default({}),
|
||||
})
|
||||
.strict();
|
||||
|
|
|
|||
|
|
@ -285,6 +285,7 @@ export function validateStrategyParameters(
|
|||
pkg: StrategyVersionPackage,
|
||||
input: unknown
|
||||
): Record<string, StrategyParameterValue> {
|
||||
assertStrategyJsonText(input);
|
||||
checkSchema(pkg.parameterSchema);
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) {
|
||||
throw new Error('Parameters must be an object');
|
||||
|
|
|
|||
|
|
@ -2,7 +2,10 @@ import { randomUUID } from 'node:crypto';
|
|||
import type { PoolClient } from 'pg';
|
||||
import type { TransactionCallback } from '@stock-bot/postgres';
|
||||
import type { PostgresClient } from '@stock-bot/services';
|
||||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
parseBacktestRequest,
|
||||
rejectCatalogVersionReferences,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
|
||||
import { prepareDataset } from '../data/historical-dataset';
|
||||
import type { BacktestConfig } from '../types';
|
||||
|
|
@ -36,6 +39,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
}
|
||||
|
||||
async start(config: BacktestConfig): Promise<RunClaim> {
|
||||
rejectCatalogVersionReferences(config);
|
||||
const attemptId = randomUUID();
|
||||
return this.postgres.transaction(async client => {
|
||||
if (config.runId) {
|
||||
|
|
|
|||
|
|
@ -57,7 +57,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '14-backtest-submission.sql' ||
|
||||
f === '15-canonical-paper-intents.sql' ||
|
||||
f === '16-strategy-catalog.sql' ||
|
||||
f === '17-research-retention.sql')
|
||||
f === '17-research-retention.sql' ||
|
||||
f === '18-backtest-strategy-versions.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -10,8 +10,10 @@ import {
|
|||
import {
|
||||
BacktestRetentionError,
|
||||
BacktestServiceV2,
|
||||
CatalogExecutionUnavailableError,
|
||||
RunSubmissionConflictError,
|
||||
} from '../services/backtest-v2.service';
|
||||
import { StrategyCatalogError } from '../services/strategy-catalog.service';
|
||||
|
||||
const logger = getLogger('backtests-v2-routes');
|
||||
|
||||
|
|
@ -60,10 +62,14 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
return c.json({ error: 'autoStart must be a boolean' }, 400);
|
||||
}
|
||||
// Omitted autoStart preserves legacy clients. New web clients explicitly save only.
|
||||
const backtest = await backtestService.createBacktest(body, { autoStart: body.autoStart });
|
||||
const { autoStart, ...definition } = body;
|
||||
const backtest = await backtestService.createBacktest(definition, { autoStart });
|
||||
return c.json(backtest, 201);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create backtest', error);
|
||||
if (error instanceof StrategyCatalogError) {
|
||||
return c.json({ error: error.message }, error.status);
|
||||
}
|
||||
if (isBacktestRequestError(error)) {
|
||||
return c.json({ error: error.message }, 400);
|
||||
}
|
||||
|
|
@ -81,6 +87,9 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
return c.json(backtest);
|
||||
} catch (error) {
|
||||
logger.error('Failed to update backtest', error);
|
||||
if (error instanceof StrategyCatalogError) {
|
||||
return c.json({ error: error.message }, error.status);
|
||||
}
|
||||
if (error instanceof BacktestRetentionError) {
|
||||
return c.json({ error: error.message, code: error.code }, 409);
|
||||
}
|
||||
|
|
@ -155,6 +164,9 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
return c.json(run, 202);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create run', error);
|
||||
if (error instanceof CatalogExecutionUnavailableError) {
|
||||
return c.json({ error: error.message, code: error.code }, 409);
|
||||
}
|
||||
if (error instanceof BacktestRetentionError) {
|
||||
return c.json({ error: error.message, code: error.code }, 409);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,20 +1,33 @@
|
|||
import { createHash, randomUUID as uuidv4 } from 'node:crypto';
|
||||
import type { QueryResultRow } from 'pg';
|
||||
import type { PoolClient, QueryResultRow } from 'pg';
|
||||
import { authenticatedServiceFetch } from '@stock-bot/di';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import {
|
||||
backtestRequestFromDefinition,
|
||||
backtestSettingsFromDefinition,
|
||||
CatalogBacktestDefinitionSchema,
|
||||
datasetHashSchema,
|
||||
parseBacktestRequest,
|
||||
rejectCatalogVersionReferences,
|
||||
type BacktestDefinitionInput,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestRunDatasetSelection, BacktestRunResult } from '@stock-bot/types';
|
||||
import {
|
||||
assertStrategyJsonText,
|
||||
validateStrategyParameters,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import type {
|
||||
BacktestRunDatasetSelection,
|
||||
BacktestRunResult,
|
||||
StrategyParameterValue,
|
||||
} from '@stock-bot/types';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { getWebSocketHandler } from '../websocket/run-updates';
|
||||
import type { WebSocketHandler } from '../websocket/run-updates';
|
||||
import { mapStoredBacktestResult, type StoredBacktestResult } from './backtest-result';
|
||||
import { assertSelectedDatasetMatchesRequest } from './dataset-catalog.service';
|
||||
import { StrategyCatalogError, StrategyCatalogService } from './strategy-catalog.service';
|
||||
|
||||
const logger = getLogger('backtest-v2-service');
|
||||
|
||||
|
|
@ -31,11 +44,15 @@ export interface BacktestRequest {
|
|||
endDate: string;
|
||||
initialCapital: number;
|
||||
config?: Record<string, unknown>;
|
||||
strategyVersionId?: string | null;
|
||||
strategyParameters?: Record<string, StrategyParameterValue> | null;
|
||||
}
|
||||
|
||||
export interface Backtest {
|
||||
id: string;
|
||||
archivedAt: string | null;
|
||||
strategyVersionId: string | null;
|
||||
strategyParameters: Record<string, StrategyParameterValue> | null;
|
||||
name: string;
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
|
|
@ -82,6 +99,27 @@ export class RunSubmissionConflictError extends Error {
|
|||
this.name = 'RunSubmissionConflictError';
|
||||
}
|
||||
}
|
||||
export class CatalogExecutionUnavailableError extends Error {
|
||||
readonly code = 'catalog_execution_unavailable';
|
||||
constructor() {
|
||||
super(
|
||||
'Catalog strategy execution is unavailable until the canonical runner is integrated (R05); this saved draft cannot run through a legacy strategy'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Strip only DTO metadata from legacy definitions; caller-supplied markers are rejected first. */
|
||||
function legacyDefinition(input: BacktestDefinitionInput): BacktestDefinitionInput {
|
||||
return {
|
||||
name: input.name,
|
||||
strategy: input.strategy,
|
||||
symbols: input.symbols,
|
||||
startDate: input.startDate,
|
||||
endDate: input.endDate,
|
||||
initialCapital: input.initialCapital,
|
||||
config: input.config,
|
||||
};
|
||||
}
|
||||
|
||||
export class BacktestRetentionError extends Error {
|
||||
constructor(
|
||||
|
|
@ -113,28 +151,41 @@ export class BacktestServiceV2 {
|
|||
request: BacktestRequest,
|
||||
options: { autoStart?: boolean } = {}
|
||||
): Promise<Backtest> {
|
||||
await assertSelectedDatasetMatchesRequest(
|
||||
this.container.postgres,
|
||||
backtestRequestFromDefinition(request)
|
||||
);
|
||||
const catalog = request.strategy === 'catalog';
|
||||
if (catalog && options.autoStart !== false) {
|
||||
throw new HistoricalDataRequestError('Catalog drafts require explicit autoStart:false');
|
||||
}
|
||||
if (!catalog) {
|
||||
rejectCatalogVersionReferences(request);
|
||||
}
|
||||
const backtestId = uuidv4();
|
||||
|
||||
const result = await this.container.postgres.query(
|
||||
`INSERT INTO backtests
|
||||
(id, name, strategy, symbols, start_date, end_date, initial_capital, config)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
const result = await this.container.postgres.transaction(async client => {
|
||||
const definition = catalog ? await this.validateCatalogDraft(client, request) : request;
|
||||
if (!catalog) {
|
||||
await assertSelectedDatasetMatchesRequest(
|
||||
client,
|
||||
backtestRequestFromDefinition(definition)
|
||||
);
|
||||
}
|
||||
return client.query(
|
||||
`INSERT INTO backtests
|
||||
(id, name, strategy, symbols, start_date, end_date, initial_capital, config, strategy_version_id, strategy_parameters)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
RETURNING *`,
|
||||
[
|
||||
backtestId,
|
||||
request.name,
|
||||
request.strategy,
|
||||
JSON.stringify(request.symbols),
|
||||
request.startDate,
|
||||
request.endDate,
|
||||
request.initialCapital,
|
||||
JSON.stringify(request.config || {}),
|
||||
]
|
||||
);
|
||||
[
|
||||
backtestId,
|
||||
definition.name,
|
||||
definition.strategy,
|
||||
JSON.stringify(definition.symbols),
|
||||
definition.startDate,
|
||||
definition.endDate,
|
||||
definition.initialCapital,
|
||||
JSON.stringify(definition.config || {}),
|
||||
definition.strategyVersionId ?? null,
|
||||
definition.strategyParameters ? JSON.stringify(definition.strategyParameters) : null,
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
const backtest = this.mapBacktest(at(result.rows, 0));
|
||||
|
||||
|
|
@ -178,39 +229,74 @@ export class BacktestServiceV2 {
|
|||
throw new BacktestRetentionError('backtest_archived');
|
||||
}
|
||||
const existing = this.mapBacktest(locked.rows[0]);
|
||||
const next = { ...existing, ...request };
|
||||
await assertSelectedDatasetMatchesRequest(client, backtestRequestFromDefinition(next));
|
||||
const catalog = existing.strategyVersionId !== null;
|
||||
let next = { ...existing, ...request };
|
||||
if (catalog) {
|
||||
CatalogBacktestDefinitionSchema.partial().parse(request);
|
||||
if (
|
||||
request.strategyVersionId !== undefined &&
|
||||
request.strategyVersionId !== existing.strategyVersionId &&
|
||||
request.strategyParameters === undefined
|
||||
) {
|
||||
throw new HistoricalDataRequestError(
|
||||
'Changing a selected version requires explicit strategyParameters'
|
||||
);
|
||||
}
|
||||
const normalized = await this.validateCatalogDraft(
|
||||
client,
|
||||
{
|
||||
...legacyDefinition(next),
|
||||
strategyVersionId: next.strategyVersionId,
|
||||
strategyParameters: next.strategyParameters,
|
||||
},
|
||||
existing.strategyVersionId
|
||||
);
|
||||
next = { ...next, ...normalized } as typeof next;
|
||||
} else {
|
||||
rejectCatalogVersionReferences(request);
|
||||
await assertSelectedDatasetMatchesRequest(
|
||||
client,
|
||||
backtestRequestFromDefinition(legacyDefinition(next))
|
||||
);
|
||||
}
|
||||
const updates: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
let paramCount = 1;
|
||||
|
||||
if (request.name !== undefined) {
|
||||
updates.push(`name = $${paramCount++}`);
|
||||
values.push(request.name);
|
||||
values.push(catalog ? next.name : request.name);
|
||||
}
|
||||
if (request.strategy !== undefined) {
|
||||
updates.push(`strategy = $${paramCount++}`);
|
||||
values.push(request.strategy);
|
||||
values.push(catalog ? next.strategy : request.strategy);
|
||||
}
|
||||
if (request.symbols !== undefined) {
|
||||
updates.push(`symbols = $${paramCount++}`);
|
||||
values.push(JSON.stringify(request.symbols));
|
||||
values.push(JSON.stringify(catalog ? next.symbols : request.symbols));
|
||||
}
|
||||
if (request.startDate !== undefined) {
|
||||
updates.push(`start_date = $${paramCount++}`);
|
||||
values.push(request.startDate);
|
||||
values.push(catalog ? next.startDate : request.startDate);
|
||||
}
|
||||
if (request.endDate !== undefined) {
|
||||
updates.push(`end_date = $${paramCount++}`);
|
||||
values.push(request.endDate);
|
||||
values.push(catalog ? next.endDate : request.endDate);
|
||||
}
|
||||
if (request.initialCapital !== undefined) {
|
||||
updates.push(`initial_capital = $${paramCount++}`);
|
||||
values.push(request.initialCapital);
|
||||
values.push(catalog ? next.initialCapital : request.initialCapital);
|
||||
}
|
||||
if (request.config !== undefined) {
|
||||
updates.push(`config = $${paramCount++}`);
|
||||
values.push(JSON.stringify(request.config));
|
||||
values.push(JSON.stringify(catalog ? next.config : request.config));
|
||||
}
|
||||
if (catalog) {
|
||||
updates.push(
|
||||
`strategy_version_id = $${paramCount++}`,
|
||||
`strategy_parameters = $${paramCount++}`
|
||||
);
|
||||
values.push(next.strategyVersionId, JSON.stringify(next.strategyParameters));
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
|
|
@ -337,7 +423,10 @@ export class BacktestServiceV2 {
|
|||
throw new BacktestRetentionError('backtest_archived');
|
||||
}
|
||||
const definition = this.mapBacktest(at(parent.rows, 0));
|
||||
const snapshot = backtestRequestFromDefinition(definition, {
|
||||
if (definition.strategyVersionId !== null || definition.strategy === 'catalog') {
|
||||
throw new CatalogExecutionUnavailableError();
|
||||
}
|
||||
const snapshot = backtestRequestFromDefinition(legacyDefinition(definition), {
|
||||
runId,
|
||||
backtestId: definition.id,
|
||||
speedMultiplier: multiplier,
|
||||
|
|
@ -486,10 +575,62 @@ export class BacktestServiceV2 {
|
|||
}
|
||||
|
||||
// Private methods
|
||||
private async validateCatalogDraft(
|
||||
client: PoolClient,
|
||||
input: unknown,
|
||||
previousVersionId?: string | null
|
||||
): Promise<BacktestRequest> {
|
||||
try {
|
||||
assertStrategyJsonText(input);
|
||||
} catch (error) {
|
||||
throw new HistoricalDataRequestError(
|
||||
error instanceof Error ? error.message : 'Invalid catalog draft text'
|
||||
);
|
||||
}
|
||||
const draft = CatalogBacktestDefinitionSchema.parse(input);
|
||||
let parameters: Record<string, StrategyParameterValue>;
|
||||
const pkg = await new StrategyCatalogService(this.container).getVersionArtifact(
|
||||
draft.strategyVersionId,
|
||||
client
|
||||
);
|
||||
try {
|
||||
assertStrategyJsonText(draft);
|
||||
parameters = validateStrategyParameters(pkg, draft.strategyParameters);
|
||||
} catch (error) {
|
||||
throw new HistoricalDataRequestError(
|
||||
error instanceof Error ? error.message : 'Invalid strategy parameters'
|
||||
);
|
||||
}
|
||||
const family = (
|
||||
await client.query(
|
||||
`SELECT s.archived_at FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id WHERE v.id=$1 FOR UPDATE OF s`,
|
||||
[draft.strategyVersionId]
|
||||
)
|
||||
).rows[0];
|
||||
if (!family) {
|
||||
throw new StrategyCatalogError(404, 'Strategy version not found');
|
||||
}
|
||||
if (previousVersionId !== draft.strategyVersionId && family.archived_at) {
|
||||
throw new StrategyCatalogError(
|
||||
409,
|
||||
'Strategy is archived; restore it before selecting a new version'
|
||||
);
|
||||
}
|
||||
const settings = backtestSettingsFromDefinition(draft);
|
||||
await assertSelectedDatasetMatchesRequest(client, settings);
|
||||
return {
|
||||
...draft,
|
||||
startDate: settings.startDate,
|
||||
endDate: settings.endDate,
|
||||
strategyParameters: parameters,
|
||||
};
|
||||
}
|
||||
private mapBacktest(row: QueryResultRow): Backtest {
|
||||
return {
|
||||
id: row.id,
|
||||
archivedAt: row.archived_at ? new Date(row.archived_at).toISOString() : null,
|
||||
strategyVersionId: row.strategy_version_id ?? null,
|
||||
strategyParameters: row.strategy_parameters ?? null,
|
||||
name: row.name,
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { rejectCatalogVersionReferences } from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
BacktestServiceV2,
|
||||
type Backtest,
|
||||
|
|
@ -37,6 +38,7 @@ export class BacktestService {
|
|||
}
|
||||
|
||||
async createBacktest(request: BacktestRequest): Promise<BacktestJob> {
|
||||
rejectCatalogVersionReferences(request);
|
||||
const backtest = await this.service.createBacktest(
|
||||
{
|
||||
...request,
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ import {
|
|||
assertDatasetMatchesRequest,
|
||||
datasetHashSchema,
|
||||
validateDatasetManifestMetadata,
|
||||
type BacktestConfig,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import { HistoricalDataRequestError, type HistoricalDatasetCatalogEntry } from '@stock-bot/types';
|
||||
|
||||
|
|
@ -112,7 +111,7 @@ export class DatasetCatalogService {
|
|||
/** Acceptance uses metadata only. The existing runner still verifies full content. */
|
||||
export async function assertSelectedDatasetMatchesRequest(
|
||||
database: DatasetCatalogQuery,
|
||||
config: BacktestConfig
|
||||
config: Parameters<typeof assertDatasetMatchesRequest>[1]
|
||||
): Promise<void> {
|
||||
if (config.datasetHash === undefined) {
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -9,7 +9,15 @@ import {
|
|||
parseStrategyVersionPackage,
|
||||
validateStrategyParameters,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
import type {
|
||||
ParameterValidationResult,
|
||||
StrategyRecord,
|
||||
StrategyReviewEvent,
|
||||
StrategyVersionPackage,
|
||||
StrategyVersionSummary,
|
||||
} from '@stock-bot/types';
|
||||
|
||||
export type { StrategyRecord, StrategyVersionSummary } from '@stock-bot/types';
|
||||
|
||||
export type StrategyActor = 'operator' | 'service';
|
||||
export class StrategyCatalogError extends Error {
|
||||
|
|
@ -74,33 +82,6 @@ const metadata = `v.id,v.strategy_id,v.ordinal,v.parent_version_id,v.created_by,
|
|||
(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,
|
||||
|
|
@ -218,9 +199,14 @@ export class StrategyCatalogService {
|
|||
}
|
||||
return version(row);
|
||||
}
|
||||
async getVersionArtifact(versionId: string): Promise<StrategyVersionPackage> {
|
||||
async getVersionArtifact(
|
||||
versionId: string,
|
||||
database: {
|
||||
query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }>;
|
||||
} = this.database
|
||||
): Promise<StrategyVersionPackage> {
|
||||
const row = (
|
||||
await this.database.query('SELECT envelope FROM strategy_versions WHERE id=$1', [
|
||||
await database.query('SELECT envelope FROM strategy_versions WHERE id=$1', [
|
||||
id.parse(versionId),
|
||||
])
|
||||
).rows[0];
|
||||
|
|
@ -229,7 +215,7 @@ export class StrategyCatalogService {
|
|||
}
|
||||
return checkedPackage(row.envelope);
|
||||
}
|
||||
async getVersionReviews(versionId: string) {
|
||||
async getVersionReviews(versionId: string): Promise<StrategyReviewEvent[]> {
|
||||
await this.getVersion(versionId);
|
||||
return (
|
||||
await this.database.query(
|
||||
|
|
@ -245,7 +231,10 @@ export class StrategyCatalogService {
|
|||
createdAt: new Date(row.created_at).toISOString(),
|
||||
}));
|
||||
}
|
||||
async validateVersionParameters(versionId: string, input: unknown) {
|
||||
async validateVersionParameters(
|
||||
versionId: string,
|
||||
input: unknown
|
||||
): Promise<ParameterValidationResult> {
|
||||
const pkg = await this.getVersionArtifact(versionId);
|
||||
let parameters;
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { DashboardPage } from '@/features/dashboard';
|
|||
import { ExchangesPage } from '@/features/exchanges';
|
||||
import { MonitoringPage } from '@/features/monitoring';
|
||||
import { PipelinePage } from '@/features/pipeline';
|
||||
import { StrategyDetailPage, StrategyListPage, StrategyVersionPage } from '@/features/strategies';
|
||||
import { SymbolDetailPage, SymbolsPage } from '@/features/symbols';
|
||||
import { AuthGate } from './AuthGate';
|
||||
|
||||
|
|
@ -25,10 +26,12 @@ export function App() {
|
|||
path="portfolio"
|
||||
element={<div className="p-4">Portfolio Page - Coming Soon</div>}
|
||||
/>
|
||||
<Route
|
||||
path="strategies"
|
||||
element={<div className="p-4">Strategies Page - Coming Soon</div>}
|
||||
/>
|
||||
<Route path="strategies">
|
||||
<Route index element={<StrategyListPage />} />
|
||||
<Route path="versions/:versionId" element={<StrategyVersionPage />} />
|
||||
<Route path=":strategyId" element={<StrategyDetailPage />} />
|
||||
<Route path=":strategyId/versions/:versionId" element={<StrategyDetailPage />} />
|
||||
</Route>
|
||||
<Route
|
||||
path="analytics"
|
||||
element={<div className="p-4">Analytics Page - Coming Soon</div>}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
import { ArrowLeftIcon, PlusIcon } from '@heroicons/react/24/outline';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom';
|
||||
import {
|
||||
catalogExecutionReason,
|
||||
supportedLegacyStrategy,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import { useWebSocket } from '@/hooks/useWebSocket';
|
||||
import { ArchiveBacktestDialog } from './components/ArchiveBacktestDialog';
|
||||
import { BacktestConfiguration } from './components/BacktestConfiguration';
|
||||
|
|
@ -50,7 +54,11 @@ export function BacktestDetailPageV2() {
|
|||
refreshRun,
|
||||
} = useBacktestV2();
|
||||
const archived = Boolean(backtest?.archivedAt);
|
||||
const canSubmit = !archived || hasPendingSubmission;
|
||||
const catalog = Boolean(backtest?.strategyVersionId) || backtest?.strategy === 'catalog';
|
||||
const unsupportedLegacy = Boolean(
|
||||
backtest && !catalog && !supportedLegacyStrategy(backtest.strategy)
|
||||
);
|
||||
const canSubmit = (!archived && !catalog && !unsupportedLegacy) || hasPendingSubmission;
|
||||
|
||||
// Notifications invalidate the same persisted-state reader used by polling.
|
||||
useWebSocket({
|
||||
|
|
@ -93,18 +101,29 @@ export function BacktestDetailPageV2() {
|
|||
return;
|
||||
}
|
||||
|
||||
const executionConfig = { ...backtest?.config };
|
||||
if (catalog) {
|
||||
delete executionConfig.speedMultiplier;
|
||||
} else {
|
||||
executionConfig.speedMultiplier = config.speedMultiplier;
|
||||
}
|
||||
await updateBacktest(id, {
|
||||
name: config.name,
|
||||
strategy: config.strategy,
|
||||
...(config.strategyVersionId
|
||||
? {
|
||||
strategyVersionId: config.strategyVersionId,
|
||||
strategyParameters: config.strategyParameters,
|
||||
}
|
||||
: {}),
|
||||
symbols: config.symbols,
|
||||
startDate: config.startDate,
|
||||
endDate: config.endDate,
|
||||
initialCapital: config.initialCapital,
|
||||
config: {
|
||||
...backtest?.config,
|
||||
...executionConfig,
|
||||
commission: config.commission,
|
||||
slippage: config.slippage,
|
||||
speedMultiplier: config.speedMultiplier,
|
||||
dataFrequency: config.dataFrequency,
|
||||
dataSource: config.dataSource,
|
||||
datasetHash: config.datasetHash,
|
||||
|
|
@ -118,7 +137,7 @@ export function BacktestDetailPageV2() {
|
|||
},
|
||||
});
|
||||
},
|
||||
[id, updateBacktest, backtest, archived]
|
||||
[id, updateBacktest, backtest, archived, catalog]
|
||||
);
|
||||
|
||||
// Handle new run creation
|
||||
|
|
@ -154,6 +173,8 @@ export function BacktestDetailPageV2() {
|
|||
initialCapital: backtest.initialCapital,
|
||||
symbols: backtest.symbols,
|
||||
strategy: backtest.strategy,
|
||||
strategyVersionId: backtest.strategyVersionId,
|
||||
strategyParameters: backtest.strategyParameters,
|
||||
speedMultiplier: 1,
|
||||
dataFrequency: (backtest.config?.dataFrequency ??
|
||||
'1d') as BacktestConfig['dataFrequency'],
|
||||
|
|
@ -239,7 +260,7 @@ export function BacktestDetailPageV2() {
|
|||
<h3 className="text-lg font-medium text-text-primary">Run History</h3>
|
||||
<button
|
||||
onClick={() => setShowNewRun(true)}
|
||||
disabled={archived}
|
||||
disabled={archived || catalog || unsupportedLegacy}
|
||||
className="inline-flex items-center px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
|
||||
>
|
||||
<PlusIcon className="w-4 h-4 mr-2" />
|
||||
|
|
@ -422,6 +443,7 @@ export function BacktestDetailPageV2() {
|
|||
isSubmitting={isSubmitting}
|
||||
hasPendingSubmission={hasPendingSubmission}
|
||||
archived={archived}
|
||||
executionUnavailable={catalog || unsupportedLegacy}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -430,6 +452,33 @@ export function BacktestDetailPageV2() {
|
|||
|
||||
{/* Tab Content */}
|
||||
<div className="flex flex-col flex-1 min-h-0 overflow-hidden py-4">
|
||||
{catalog && (
|
||||
<p
|
||||
role="status"
|
||||
className="mb-4 p-3 border border-border rounded-lg text-sm text-text-secondary"
|
||||
>
|
||||
{catalogExecutionReason}
|
||||
{backtest?.strategyVersionId && (
|
||||
<>
|
||||
{' '}
|
||||
Selected immutable version:{' '}
|
||||
<Link
|
||||
className="text-primary-500"
|
||||
to={`/strategies/versions/${backtest.strategyVersionId}`}
|
||||
>
|
||||
{backtest.strategyVersionId}
|
||||
</Link>
|
||||
.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{unsupportedLegacy && (
|
||||
<p role="status" className="mb-4 text-sm text-text-secondary">
|
||||
This legacy strategy is not supported for new submissions by this form. Its existing
|
||||
history remains readable.
|
||||
</p>
|
||||
)}
|
||||
{archived && (
|
||||
<p
|
||||
role="status"
|
||||
|
|
|
|||
|
|
@ -1,17 +1,21 @@
|
|||
import { PlusIcon } from '@heroicons/react/24/solid';
|
||||
import type { ColumnDef } from '@tanstack/react-table';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { DataTable } from '@/components/ui/DataTable/DataTable';
|
||||
import type { Parameters } from '@/features/strategies/services/strategyApi';
|
||||
import { CreateBacktestDialog } from './components/CreateBacktestDialog';
|
||||
import { backtestApiV2, type Backtest } from './services/backtestApiV2';
|
||||
|
||||
export function BacktestListPageV2() {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const location = useLocation();
|
||||
const selectedVersion = searchParams.get('strategyVersionId');
|
||||
const [backtests, setBacktests] = useState<Backtest[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [showCreateDialog, setShowCreateDialog] = useState(false);
|
||||
const [showCreateDialog, setShowCreateDialog] = useState(Boolean(selectedVersion));
|
||||
const [includeArchived, setIncludeArchived] = useState(false);
|
||||
const request = useRef<AbortController | null>(null);
|
||||
|
||||
|
|
@ -43,6 +47,12 @@ export function BacktestListPageV2() {
|
|||
return () => request.current?.abort();
|
||||
}, [loadBacktests]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedVersion) {
|
||||
setShowCreateDialog(true);
|
||||
}
|
||||
}, [selectedVersion]);
|
||||
|
||||
const columns: ColumnDef<Backtest>[] = [
|
||||
{
|
||||
accessorKey: 'name',
|
||||
|
|
@ -62,7 +72,11 @@ export function BacktestListPageV2() {
|
|||
header: 'Strategy',
|
||||
size: 150,
|
||||
cell: ({ row }) => (
|
||||
<span className="capitalize text-text-primary">{row.original.strategy}</span>
|
||||
<span className="text-text-primary">
|
||||
{row.original.strategyVersionId
|
||||
? `Catalog draft · ${row.original.strategyVersionId}`
|
||||
: row.original.strategy}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
|
|
@ -168,8 +182,21 @@ export function BacktestListPageV2() {
|
|||
|
||||
{showCreateDialog && (
|
||||
<CreateBacktestDialog
|
||||
key={selectedVersion ?? 'legacy'}
|
||||
initialSelection={
|
||||
selectedVersion
|
||||
? {
|
||||
strategyVersionId: selectedVersion,
|
||||
strategyParameters: (location.state as { strategyParameters?: Parameters } | null)
|
||||
?.strategyParameters,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onClose={() => {
|
||||
setShowCreateDialog(false);
|
||||
if (selectedVersion) {
|
||||
setSearchParams({}, { replace: true });
|
||||
}
|
||||
void loadBacktests();
|
||||
}}
|
||||
onCreated={(created, run) => {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
LegacyStrategySelect,
|
||||
StrategySelection,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import { HistoricalDataSelection } from './HistoricalDataSelection';
|
||||
|
||||
|
|
@ -31,20 +35,28 @@ export function BacktestConfiguration({
|
|||
}
|
||||
);
|
||||
|
||||
const catalog = formData.strategy === 'catalog' || Boolean(formData.strategyVersionId);
|
||||
const [strategyValid, setStrategyValid] = useState(false);
|
||||
const [selectionEpoch, setSelectionEpoch] = useState(0);
|
||||
const authoritativeConfig = useRef(initialConfig);
|
||||
const [historicalValid, setHistoricalValid] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
const locked = disabled || saving;
|
||||
|
||||
useEffect(() => {
|
||||
if (initialConfig) {
|
||||
if (initialConfig && initialConfig !== authoritativeConfig.current) {
|
||||
authoritativeConfig.current = initialConfig;
|
||||
setFormData(initialConfig);
|
||||
setStrategyValid(false);
|
||||
setSaveError(null);
|
||||
setSelectionEpoch(value => value + 1);
|
||||
}
|
||||
}, [initialConfig]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!historicalValid || locked) {
|
||||
if (!historicalValid || (catalog && !strategyValid) || locked) {
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
|
|
@ -111,30 +123,26 @@ export function BacktestConfiguration({
|
|||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">Strategy</label>
|
||||
<select
|
||||
name="strategy"
|
||||
{catalog ? (
|
||||
<StrategySelection
|
||||
key={selectionEpoch}
|
||||
allowArchivedSelection
|
||||
value={formData}
|
||||
onChange={selection => setFormData(previous => ({ ...previous, ...selection }))}
|
||||
onValidityChange={setStrategyValid}
|
||||
disabled={Boolean(locked)}
|
||||
/>
|
||||
) : (
|
||||
<LegacyStrategySelect
|
||||
value={formData.strategy}
|
||||
onChange={handleChange}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
|
||||
disabled={locked}
|
||||
>
|
||||
<option value="sma-crossover">SMA Crossover</option>
|
||||
<option value="mean-reversion">Mean Reversion</option>
|
||||
<option value="ml-enhanced">ML Enhanced (Advanced)</option>
|
||||
<option value="momentum">Momentum (Coming Soon)</option>
|
||||
<option value="pairs-trading">Pairs Trading (Coming Soon)</option>
|
||||
</select>
|
||||
<p className="text-xs text-text-muted mt-1">
|
||||
{formData.strategy === 'sma-crossover' && 'Trades on 10/20 day moving average crossovers'}
|
||||
{formData.strategy === 'mean-reversion' &&
|
||||
'Trades when price deviates from mean by 2+ std devs'}
|
||||
{formData.strategy === 'ml-enhanced' && 'Uses machine learning for signal generation'}
|
||||
{formData.strategy === 'momentum' && 'Follows strong price trends'}
|
||||
{formData.strategy === 'pairs-trading' && 'Trades correlated asset pairs'}
|
||||
</p>
|
||||
</div>
|
||||
onChange={strategy => setFormData(previous => ({ ...previous, strategy }))}
|
||||
disabled={Boolean(locked)}
|
||||
/>
|
||||
)}
|
||||
<p className="text-xs text-text-muted">
|
||||
This saved template keeps its strategy mode. Create another backtest to switch between
|
||||
catalog and legacy modes.
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
|
|
@ -172,28 +180,30 @@ export function BacktestConfiguration({
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Speed Multiplier
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
name="speedMultiplier"
|
||||
value={formData.speedMultiplier}
|
||||
onChange={handleChange}
|
||||
min="0.1"
|
||||
max="1000"
|
||||
step="0.1"
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
|
||||
disabled={locked}
|
||||
/>
|
||||
<p className="text-xs text-text-muted mt-1">1x = real-time, 10x = 10x faster</p>
|
||||
</div>
|
||||
{!catalog && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Speed Multiplier
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
name="speedMultiplier"
|
||||
value={formData.speedMultiplier}
|
||||
onChange={handleChange}
|
||||
min="0.1"
|
||||
max="1000"
|
||||
step="0.1"
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
|
||||
disabled={locked}
|
||||
/>
|
||||
<p className="text-xs text-text-muted mt-1">1x = real-time, 10x = 10x faster</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className="w-full px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
disabled={locked || !historicalValid}
|
||||
disabled={locked || !historicalValid || (catalog && !strategyValid)}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
|
|
|
|||
|
|
@ -1,15 +1,29 @@
|
|||
import { XMarkIcon } from '@heroicons/react/24/solid';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
LegacyStrategySelect,
|
||||
StrategySelection,
|
||||
type CatalogSelection,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import {
|
||||
confirmDiscard,
|
||||
useUnsavedWarning,
|
||||
} from '@/features/strategies/components/useUnsavedWarning';
|
||||
import { backtestApiV2, type Backtest, type Run } from '../services/backtestApiV2';
|
||||
import type { HistoricalSelection } from '../services/historical-selection';
|
||||
import { HistoricalDataSelection } from './HistoricalDataSelection';
|
||||
|
||||
interface CreateBacktestDialogProps {
|
||||
initialSelection?: CatalogSelection;
|
||||
onClose: () => void;
|
||||
onCreated: (backtest: Backtest, run?: Run) => void;
|
||||
}
|
||||
|
||||
export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialogProps) {
|
||||
export function CreateBacktestDialog({
|
||||
onClose,
|
||||
onCreated,
|
||||
initialSelection,
|
||||
}: CreateBacktestDialogProps) {
|
||||
const [formData, setFormData] = useState<
|
||||
HistoricalSelection & {
|
||||
name: string;
|
||||
|
|
@ -32,6 +46,11 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
|
|||
dataSource: 'auto',
|
||||
});
|
||||
|
||||
const [catalogMode, setCatalogMode] = useState(Boolean(initialSelection?.strategyVersionId));
|
||||
const [selection, setSelection] = useState<CatalogSelection>(initialSelection ?? {});
|
||||
const [strategyValid, setStrategyValid] = useState(false);
|
||||
const [edited, setEdited] = useState(false);
|
||||
useUnsavedWarning(edited);
|
||||
const [historicalValid, setHistoricalValid] = useState(true);
|
||||
const [phase, setPhase] = useState<'idle' | 'saving' | 'submitting'>('idle');
|
||||
const isSubmitting = phase !== 'idle';
|
||||
|
|
@ -53,12 +72,20 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
|
|||
if (pending.current && !saved.current) {
|
||||
return;
|
||||
}
|
||||
if (!saved.current && !confirmDiscard(edited)) {
|
||||
return;
|
||||
}
|
||||
active.current = false;
|
||||
onClose();
|
||||
};
|
||||
|
||||
const handleSubmit = async (runAfterSave: boolean) => {
|
||||
if (pending.current || !active.current || (!saved.current && !historicalValid)) {
|
||||
if (
|
||||
pending.current ||
|
||||
!active.current ||
|
||||
(!saved.current && (!historicalValid || (catalogMode && !strategyValid))) ||
|
||||
(runAfterSave && catalogMode)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -74,7 +101,8 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
|
|||
if (!saved.current) {
|
||||
const created = await backtestApiV2.createBacktest({
|
||||
name: formData.name,
|
||||
strategy: formData.strategy,
|
||||
strategy: catalogMode ? 'catalog' : formData.strategy,
|
||||
...(catalogMode ? selection : {}),
|
||||
symbols: formData.symbols,
|
||||
startDate: formData.startDate,
|
||||
endDate: formData.endDate,
|
||||
|
|
@ -152,6 +180,7 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
|
|||
void handleSubmit(saved.current !== null);
|
||||
}}
|
||||
className="space-y-6"
|
||||
onChange={() => setEdited(true)}
|
||||
>
|
||||
<fieldset disabled={isSubmitting || saved.current !== null} className="space-y-6">
|
||||
<div>
|
||||
|
|
@ -168,20 +197,35 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
|
|||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-2">Strategy</label>
|
||||
<label className="block text-sm text-text-secondary">
|
||||
Strategy mode
|
||||
<select
|
||||
value={formData.strategy}
|
||||
onChange={e => setFormData({ ...formData, strategy: e.target.value })}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
|
||||
aria-label="Strategy mode"
|
||||
value={catalogMode ? 'catalog' : 'legacy'}
|
||||
onChange={event => {
|
||||
if (confirmDiscard(Boolean(selection.strategyVersionId))) {
|
||||
setCatalogMode(event.target.value === 'catalog');
|
||||
}
|
||||
}}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md"
|
||||
>
|
||||
<option value="moving-average">Moving Average</option>
|
||||
<option value="momentum">Momentum</option>
|
||||
<option value="mean-reversion">Mean Reversion</option>
|
||||
<option value="pairs-trading">Pairs Trading</option>
|
||||
<option value="custom">Custom</option>
|
||||
<option value="legacy">Legacy strategy</option>
|
||||
<option value="catalog">Catalog version (save only)</option>
|
||||
</select>
|
||||
</div>
|
||||
</label>
|
||||
{catalogMode ? (
|
||||
<StrategySelection
|
||||
value={selection}
|
||||
onChange={setSelection}
|
||||
onValidityChange={setStrategyValid}
|
||||
disabled={isSubmitting || saved.current !== null}
|
||||
/>
|
||||
) : (
|
||||
<LegacyStrategySelect
|
||||
value={formData.strategy}
|
||||
onChange={strategy => setFormData(previous => ({ ...previous, strategy }))}
|
||||
/>
|
||||
)}
|
||||
|
||||
<HistoricalDataSelection
|
||||
value={formData}
|
||||
|
|
@ -251,7 +295,10 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
|
|||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting || (!saved.current && !historicalValid)}
|
||||
disabled={
|
||||
isSubmitting ||
|
||||
(!saved.current && (!historicalValid || (catalogMode && !strategyValid)))
|
||||
}
|
||||
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
|
||||
>
|
||||
{isSubmitting
|
||||
|
|
@ -263,7 +310,7 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
|
|||
{!saved.current && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={isSubmitting || (!saved.current && !historicalValid)}
|
||||
disabled={isSubmitting || catalogMode || (!saved.current && !historicalValid)}
|
||||
onClick={e => {
|
||||
if (e.currentTarget.form?.reportValidity()) {
|
||||
void handleSubmit(true);
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ interface RunControlsCompactProps {
|
|||
isSubmitting?: boolean;
|
||||
hasPendingSubmission?: boolean;
|
||||
archived?: boolean;
|
||||
executionUnavailable?: boolean;
|
||||
}
|
||||
|
||||
export function RunControlsCompact({
|
||||
|
|
@ -19,6 +20,7 @@ export function RunControlsCompact({
|
|||
isSubmitting = false,
|
||||
hasPendingSubmission = false,
|
||||
archived = false,
|
||||
executionUnavailable = false,
|
||||
}: RunControlsCompactProps) {
|
||||
const active = ['pending', 'running', 'paused'].includes(run.status);
|
||||
const requested = active && (cancelRequested || run.cancelRequested);
|
||||
|
|
@ -44,7 +46,7 @@ export function RunControlsCompact({
|
|||
)}
|
||||
<button
|
||||
onClick={() => onRerun(null)}
|
||||
disabled={isSubmitting || (archived && !hasPendingSubmission)}
|
||||
disabled={isSubmitting || ((archived || executionUnavailable) && !hasPendingSubmission)}
|
||||
className="p-1 rounded hover:bg-surface-tertiary transition-colors disabled:opacity-50"
|
||||
title={hasPendingSubmission ? 'Retry submission' : 'Run current settings'}
|
||||
aria-label={hasPendingSubmission ? 'Retry submission' : 'Run current settings'}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
catalogExecutionReason,
|
||||
supportedLegacyStrategy,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import { backtestApiV2, RunResultsUnavailableError } from '../services/backtestApiV2';
|
||||
import type { Backtest, CreateBacktestRequest, Run, RunResult } from '../services/backtestApiV2';
|
||||
|
||||
|
|
@ -330,6 +334,16 @@ export function useBacktestV2() {
|
|||
if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) {
|
||||
return undefined;
|
||||
}
|
||||
if ((backtest.strategyVersionId || backtest.strategy === 'catalog') && !submission.current) {
|
||||
setSubmissionError(catalogExecutionReason);
|
||||
return undefined;
|
||||
}
|
||||
if (!supportedLegacyStrategy(backtest.strategy) && !submission.current) {
|
||||
setSubmissionError(
|
||||
'This legacy strategy is not supported for new submissions by this form.'
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
if (backtest.archivedAt && !submission.current) {
|
||||
setSubmissionError('Restore this archived backtest before starting a new run.');
|
||||
return undefined;
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import type {
|
|||
BacktestRunDatasetSelection,
|
||||
BacktestRunResult,
|
||||
HistoricalDatasetCatalogEntry,
|
||||
StrategyParameterValue,
|
||||
} from '@stock-bot/types';
|
||||
import { API_BASE_URL, apiFetch as fetch } from '@/lib/api';
|
||||
|
||||
|
|
@ -9,6 +10,8 @@ export interface Backtest {
|
|||
id: string;
|
||||
name: string;
|
||||
strategy: string;
|
||||
strategyVersionId?: string | null;
|
||||
strategyParameters?: Record<string, StrategyParameterValue> | null;
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
|
|
@ -41,6 +44,8 @@ export interface Run {
|
|||
export interface CreateBacktestRequest {
|
||||
name: string;
|
||||
strategy: string;
|
||||
strategyVersionId?: string | null;
|
||||
strategyParameters?: Record<string, StrategyParameterValue> | null;
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import type { StrategyParameterValue } from '@stock-bot/types';
|
||||
import type { HistoricalSelection } from '../services/historical-selection';
|
||||
|
||||
export type BacktestStatus =
|
||||
|
|
@ -13,6 +14,8 @@ export interface BacktestConfig extends HistoricalSelection {
|
|||
name: string;
|
||||
initialCapital: number;
|
||||
strategy: string;
|
||||
strategyVersionId?: string | null;
|
||||
strategyParameters?: Record<string, StrategyParameterValue> | null;
|
||||
speedMultiplier: number;
|
||||
commission: number;
|
||||
slippage: number;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,756 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, Navigate, useNavigate, useParams } from 'react-router-dom';
|
||||
import type {
|
||||
StrategyRecord,
|
||||
StrategyVersionPackage,
|
||||
StrategyVersionSummary,
|
||||
} from '@stock-bot/types';
|
||||
import { actionClass, fieldClass, StrategyParameterForm } from './components/StrategyParameterForm';
|
||||
import { versionPath } from './components/StrategySelection';
|
||||
import { confirmDiscard, useUnsavedWarning } from './components/useUnsavedWarning';
|
||||
import { strategyApi, type Parameters } from './services/strategyApi';
|
||||
|
||||
export function StrategyDetailPage() {
|
||||
const { strategyId = '', versionId } = useParams<{ strategyId: string; versionId?: string }>();
|
||||
return <StrategyDetail key={strategyId} strategyId={strategyId} versionId={versionId} />;
|
||||
}
|
||||
function StrategyDetail({ strategyId, versionId }: { strategyId: string; versionId?: string }) {
|
||||
const navigate = useNavigate();
|
||||
const [strategy, setStrategy] = useState<StrategyRecord | null>(null);
|
||||
const [versions, setVersions] = useState<StrategyVersionSummary[]>([]);
|
||||
const [version, setVersion] = useState<StrategyVersionSummary | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [versionLoading, setVersionLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [versionError, setVersionError] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
const [versionRetry, setVersionRetry] = useState(0);
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
const [parameters, setParameters] = useState<Parameters>({});
|
||||
const [validParameters, setValidParameters] = useState(false);
|
||||
const [parameterEdits, setParameterEdits] = useState(false);
|
||||
const [cloneOpen, setCloneOpen] = useState(false);
|
||||
const [cloneName, setCloneName] = useState('');
|
||||
const [cloneDescription, setCloneDescription] = useState('');
|
||||
const [cloning, setCloning] = useState(false);
|
||||
const [cloneError, setCloneError] = useState<string | null>(null);
|
||||
const cloneIntent = useRef<{
|
||||
versionId: string;
|
||||
versionOrdinal: number;
|
||||
body: { name: string; description: string };
|
||||
key: string;
|
||||
} | null>(null);
|
||||
const [cloneFrozen, setCloneFrozen] = useState(false);
|
||||
const mounted = useRef(true);
|
||||
const selectedVersionId = useRef(versionId);
|
||||
selectedVersionId.current = versionId;
|
||||
const metadataDirty = Boolean(
|
||||
strategy && (name !== strategy.name || description !== strategy.description)
|
||||
);
|
||||
const dirty =
|
||||
metadataDirty || parameterEdits || (cloneOpen && Boolean(cloneName || cloneDescription));
|
||||
useUnsavedWarning(dirty);
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
void Promise.all([
|
||||
strategyApi.get(strategyId, controller.signal),
|
||||
strategyApi.versions(strategyId, controller.signal),
|
||||
])
|
||||
.then(([record, history]) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setStrategy(record.strategy);
|
||||
setName(record.strategy.name);
|
||||
setDescription(record.strategy.description);
|
||||
setVersions(history.versions);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [strategyId, retry]);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setVersion(null);
|
||||
setVersionError(null);
|
||||
setValidParameters(false);
|
||||
setParameterEdits(false);
|
||||
if (!versionId) {
|
||||
setVersionLoading(false);
|
||||
return () => controller.abort();
|
||||
}
|
||||
setVersionLoading(true);
|
||||
void strategyApi
|
||||
.version(versionId, controller.signal)
|
||||
.then(result => {
|
||||
if (controller.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
if (result.version.strategyId !== strategyId) {
|
||||
throw new Error('This version belongs to a different strategy family.');
|
||||
}
|
||||
setVersion(result.version);
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setVersionError(cause.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setVersionLoading(false);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [strategyId, versionId, versionRetry]);
|
||||
const update = async (body: { name?: string; description?: string; archived?: boolean }) => {
|
||||
if (saving) {
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setSaveError(null);
|
||||
try {
|
||||
const result = await strategyApi.update(strategyId, body);
|
||||
if (mounted.current) {
|
||||
setStrategy(result.strategy);
|
||||
setName(result.strategy.name);
|
||||
setDescription(result.strategy.description);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (mounted.current) {
|
||||
setSaveError(cause instanceof Error ? cause.message : 'Could not save strategy');
|
||||
}
|
||||
} finally {
|
||||
if (mounted.current) {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const clone = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!version || cloning || !cloneName.trim()) {
|
||||
return;
|
||||
}
|
||||
const intent = (cloneIntent.current ??= {
|
||||
versionId: version.id,
|
||||
versionOrdinal: version.ordinal,
|
||||
body: { name: cloneName, description: cloneDescription },
|
||||
key: crypto.randomUUID(),
|
||||
});
|
||||
setCloneFrozen(true);
|
||||
setCloning(true);
|
||||
setCloneError(null);
|
||||
try {
|
||||
const result = await strategyApi.clone(intent.versionId, intent.body, intent.key);
|
||||
if (mounted.current && selectedVersionId.current === intent.versionId) {
|
||||
navigate(versionPath(result.version));
|
||||
}
|
||||
} catch (cause) {
|
||||
if (mounted.current && selectedVersionId.current === intent.versionId) {
|
||||
setCloneError(
|
||||
`${cause instanceof Error ? cause.message : 'Clone failed'}. Retry clone to recover the same immutable version.`
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (mounted.current) {
|
||||
setCloning(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className="space-y-5 text-text-primary">
|
||||
<Link
|
||||
className="text-primary-500 text-sm"
|
||||
to="/strategies"
|
||||
onClick={event => {
|
||||
if (!confirmDiscard(dirty)) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
>
|
||||
All strategies
|
||||
</Link>
|
||||
{loading && <p role="status">Loading strategy...</p>}
|
||||
{error && (
|
||||
<div>
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
<button
|
||||
className={actionClass}
|
||||
onClick={() => {
|
||||
if (confirmDiscard(dirty)) {
|
||||
setRetry(value => value + 1);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Retry strategy
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{!loading && !error && strategy && (
|
||||
<>
|
||||
<h1 className="text-lg font-bold">
|
||||
{strategy.name}
|
||||
{strategy.archived ? ' — Archived' : ''}
|
||||
</h1>
|
||||
<form
|
||||
className="space-y-3 border border-border rounded-md p-4"
|
||||
onSubmit={event => {
|
||||
event.preventDefault();
|
||||
void update({ name, description });
|
||||
}}
|
||||
>
|
||||
<label className="block text-sm">
|
||||
Strategy name
|
||||
<input
|
||||
aria-label="Strategy name"
|
||||
className={fieldClass}
|
||||
required
|
||||
disabled={saving}
|
||||
value={name}
|
||||
onChange={event => setName(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
Strategy description
|
||||
<textarea
|
||||
aria-label="Strategy description"
|
||||
className={fieldClass}
|
||||
disabled={saving}
|
||||
value={description}
|
||||
onChange={event => setDescription(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{metadataDirty && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
Unsaved strategy metadata. Save or discard before leaving.
|
||||
</p>
|
||||
)}
|
||||
{saveError && (
|
||||
<p role="alert" className="text-error text-sm">
|
||||
{saveError}
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
className={actionClass}
|
||||
disabled={saving || !metadataDirty || !name.trim()}
|
||||
>
|
||||
Save metadata
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={saving || !metadataDirty}
|
||||
onClick={() => {
|
||||
if (confirmDiscard(metadataDirty)) {
|
||||
setName(strategy.name);
|
||||
setDescription(strategy.description);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Discard metadata changes
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={saving}
|
||||
onClick={() => {
|
||||
if (
|
||||
confirmDiscard(metadataDirty) &&
|
||||
window.confirm(
|
||||
strategy.archived
|
||||
? 'Restore this strategy family?'
|
||||
: 'Archive this strategy family? Saved versions and history remain available.'
|
||||
)
|
||||
) {
|
||||
void update({ archived: !strategy.archived });
|
||||
}
|
||||
}}
|
||||
>
|
||||
{strategy.archived ? 'Restore strategy' : 'Archive strategy'}
|
||||
</button>
|
||||
</form>
|
||||
<section className="space-y-3">
|
||||
<h2 className="font-semibold">Immutable versions</h2>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Publish version packages using the existing catalog API. Metadata edits do not change
|
||||
retained code.
|
||||
</p>
|
||||
<label className="block text-sm">
|
||||
Strategy version
|
||||
<select
|
||||
aria-label="Strategy version"
|
||||
className={fieldClass}
|
||||
value={versionId ?? ''}
|
||||
disabled={cloning || cloneFrozen}
|
||||
onChange={event => {
|
||||
if (confirmDiscard(parameterEdits)) {
|
||||
navigate(
|
||||
event.target.value
|
||||
? `/strategies/${strategyId}/versions/${event.target.value}`
|
||||
: `/strategies/${strategyId}`
|
||||
);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="">Select an immutable version</option>
|
||||
{versions.map(item => (
|
||||
<option key={item.id} value={item.id}>
|
||||
Version {item.ordinal} — {item.id}
|
||||
</option>
|
||||
))}
|
||||
{versionId && !versions.some(item => item.id === versionId) && (
|
||||
<option value={versionId}>{versionId}</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
{!versions.length && (
|
||||
<p role="status">
|
||||
No immutable versions have been published. Publish a package or clone an existing
|
||||
version from another family.
|
||||
</p>
|
||||
)}
|
||||
{versionLoading && <p role="status">Loading strategy version...</p>}
|
||||
{versionError && (
|
||||
<div>
|
||||
<p role="alert" className="text-error">
|
||||
{versionError}
|
||||
</p>
|
||||
<button className={actionClass} onClick={() => setVersionRetry(value => value + 1)}>
|
||||
Retry version
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{version && version.id === versionId && (
|
||||
<>
|
||||
<VersionIdentity version={version} />
|
||||
<VersionComparison key={version.id} version={version} versions={versions} />
|
||||
<StrategyParameterForm
|
||||
key={version.id}
|
||||
versionId={version.id}
|
||||
schema={version.package.parameterSchema}
|
||||
onEdit={() => setParameterEdits(true)}
|
||||
onChange={(next, valid) => {
|
||||
setParameters(next);
|
||||
setValidParameters(valid);
|
||||
if (valid) {
|
||||
setParameterEdits(true);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
className={actionClass}
|
||||
disabled={!validParameters || strategy.archived}
|
||||
onClick={() => {
|
||||
if (confirmDiscard(metadataDirty)) {
|
||||
navigate(`/backtests?strategyVersionId=${version.id}`, {
|
||||
state: { strategyParameters: parameters },
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
Use in backtest
|
||||
</button>
|
||||
{strategy.archived && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
Restore this family before selecting its versions for a new backtest.
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
className={actionClass}
|
||||
disabled={cloneOpen}
|
||||
onClick={() => {
|
||||
setCloneOpen(true);
|
||||
setCloneName(`${strategy.name} (copy)`);
|
||||
setCloneDescription(strategy.description);
|
||||
}}
|
||||
>
|
||||
Clone version
|
||||
</button>
|
||||
{cloneOpen && (
|
||||
<form
|
||||
onSubmit={event => void clone(event)}
|
||||
className="space-y-3 border border-border rounded-md p-4"
|
||||
>
|
||||
<h3 className="font-medium">
|
||||
Clone immutable version{' '}
|
||||
{cloneIntent.current?.versionOrdinal ?? version.ordinal}
|
||||
</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Clone source version ID:{' '}
|
||||
<code>{cloneIntent.current?.versionId ?? version.id}</code>
|
||||
</p>
|
||||
{cloneIntent.current && cloneIntent.current.versionId !== version.id && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
This pending clone and its retries still use version{' '}
|
||||
{cloneIntent.current.versionOrdinal} ({cloneIntent.current.versionId}), even
|
||||
while you view version {version.ordinal} ({version.id}). Retrying recovers
|
||||
the original clone; it does not clone the currently displayed version.
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-text-secondary">
|
||||
The clone retains exact artifact bytes and parent lineage. It is a new
|
||||
candidate awaiting review; cloning does not enable execution.
|
||||
</p>
|
||||
<label className="block text-sm">
|
||||
Clone name
|
||||
<input
|
||||
aria-label="Clone name"
|
||||
className={fieldClass}
|
||||
disabled={cloneFrozen}
|
||||
required
|
||||
value={cloneName}
|
||||
onChange={event => setCloneName(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
Clone description
|
||||
<textarea
|
||||
aria-label="Clone description"
|
||||
className={fieldClass}
|
||||
disabled={cloneFrozen}
|
||||
value={cloneDescription}
|
||||
onChange={event => setCloneDescription(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{cloneError && (
|
||||
<p role="alert" className="text-error text-sm">
|
||||
{cloneError}
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
className={actionClass}
|
||||
disabled={cloning || !cloneName.trim()}
|
||||
>
|
||||
{cloning ? 'Cloning...' : cloneFrozen ? 'Retry clone' : 'Create clone'}
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={cloning}
|
||||
onClick={() => {
|
||||
if (
|
||||
window.confirm(
|
||||
cloneFrozen
|
||||
? 'Abandon this clone receipt? If the response was lost, the clone may already exist. Check the catalog before creating another.'
|
||||
: 'Discard clone metadata?'
|
||||
)
|
||||
) {
|
||||
setCloneOpen(false);
|
||||
setCloneFrozen(false);
|
||||
cloneIntent.current = null;
|
||||
setCloneError(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Close clone
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
<section className="text-sm text-text-secondary space-y-2">
|
||||
<h3 className="font-medium text-text-primary">Version history</h3>
|
||||
<p>
|
||||
No runs using retained versions are available yet. Legacy name-based runs are
|
||||
not evidence for this version.
|
||||
</p>
|
||||
<p>Deployment history is not available in this catalog yet.</p>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function VersionIdentity({ version }: { version: StrategyVersionSummary }) {
|
||||
const pkg = version.package;
|
||||
return (
|
||||
<div className="space-y-2 text-sm border border-border rounded-md p-4">
|
||||
<h3 className="font-medium">Version {version.ordinal}</h3>
|
||||
<p>
|
||||
Immutable version ID: <code>{version.id}</code>
|
||||
</p>
|
||||
<p>
|
||||
Origin: {version.origin} · Review: {version.reviewStatus}
|
||||
</p>
|
||||
<p role="status">
|
||||
{version.origin === 'candidate'
|
||||
? 'Candidate execution is unavailable until isolated execution is supported.'
|
||||
: 'Execution of this retained built-in version is not available from the workbench yet.'}
|
||||
</p>
|
||||
<p>
|
||||
Program: {pkg.program.strategyId} / {pkg.program.strategyVersion}
|
||||
</p>
|
||||
<p>
|
||||
API: {pkg.program.apiVersion} · Checkpoint: {pkg.program.checkpointVersion}
|
||||
</p>
|
||||
<p className="break-all">Artifact SHA256: {pkg.artifact.sha256}</p>
|
||||
<p className="break-all">Dependency lock SHA256: {pkg.dependencyLock.sha256}</p>
|
||||
<p className="break-all">
|
||||
Source revision: {pkg.source.revision} (
|
||||
{pkg.source.dirty ? 'dirty working tree' : 'clean working tree'})
|
||||
</p>
|
||||
<p>
|
||||
Build: {pkg.build.tool} {pkg.build.version} / {pkg.build.target}
|
||||
</p>
|
||||
{version.parentVersionId && <p>Parent version: {version.parentVersionId}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function VersionComparison({
|
||||
version,
|
||||
versions,
|
||||
}: {
|
||||
version: StrategyVersionSummary;
|
||||
versions: StrategyVersionSummary[];
|
||||
}) {
|
||||
const [showArtifact, setShowArtifact] = useState(false);
|
||||
const [compareId, setCompareId] = useState('');
|
||||
const [artifact, setArtifact] = useState<StrategyVersionPackage | null>(null);
|
||||
const [comparison, setComparison] = useState<StrategyVersionPackage | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setComparison(null);
|
||||
setError(null);
|
||||
if (!showArtifact && !compareId) {
|
||||
setLoading(false);
|
||||
return () => controller.abort();
|
||||
}
|
||||
setLoading(true);
|
||||
void Promise.all([
|
||||
strategyApi.artifact(version.id, controller.signal),
|
||||
compareId ? strategyApi.artifact(compareId, controller.signal) : Promise.resolve(null),
|
||||
])
|
||||
.then(([current, other]) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setArtifact(current.package);
|
||||
setComparison(other?.package ?? null);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [version.id, showArtifact, compareId, retry]);
|
||||
const options = versions.filter(item => item.id !== version.id);
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
<button className={actionClass} onClick={() => setShowArtifact(value => !value)}>
|
||||
{showArtifact ? 'Hide bundled JavaScript' : 'View bundled JavaScript'}
|
||||
</button>
|
||||
<label className="block text-sm">
|
||||
Compare with version
|
||||
<select
|
||||
aria-label="Compare with version"
|
||||
className={fieldClass}
|
||||
value={compareId}
|
||||
onChange={event => setCompareId(event.target.value)}
|
||||
>
|
||||
<option value="">No comparison</option>
|
||||
{options.map(item => (
|
||||
<option key={item.id} value={item.id}>
|
||||
Version {item.ordinal} — {item.id}
|
||||
</option>
|
||||
))}
|
||||
{version.parentVersionId &&
|
||||
!options.some(item => item.id === version.parentVersionId) && (
|
||||
<option value={version.parentVersionId}>
|
||||
Parent version — {version.parentVersionId}
|
||||
</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
{(showArtifact || compareId) && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
Retained bundled JavaScript, not original TypeScript. Displayed as text; never executed in
|
||||
the browser.
|
||||
</p>
|
||||
)}
|
||||
{loading && <p role="status">Loading retained artifacts...</p>}
|
||||
{error && (
|
||||
<div>
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
<button className={actionClass} onClick={() => setRetry(value => value + 1)}>
|
||||
Retry artifacts
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{!loading && !error && artifact && (showArtifact || compareId) && (
|
||||
<>
|
||||
{comparison && (
|
||||
<>
|
||||
<h3 className="font-medium">Version comparison</h3>
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="text-left">Retained field</th>
|
||||
<th className="text-left">Comparison</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(['program', 'parameterSchema', 'source', 'build'] as const).map(key => (
|
||||
<tr key={key}>
|
||||
<td>{key}</td>
|
||||
<td>
|
||||
{JSON.stringify(artifact[key]) === JSON.stringify(comparison[key])
|
||||
? 'Unchanged'
|
||||
: 'Changed'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr>
|
||||
<td>Artifact SHA256</td>
|
||||
<td>
|
||||
{artifact.artifact.sha256 === comparison.artifact.sha256
|
||||
? 'Identical artifact bytes'
|
||||
: 'Different artifact bytes'}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Dependency lock SHA256</td>
|
||||
<td>
|
||||
{artifact.dependencyLock.sha256 === comparison.dependencyLock.sha256
|
||||
? 'Unchanged'
|
||||
: 'Changed'}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<h4>Selected version metadata</h4>
|
||||
<pre className="overflow-auto text-xs max-h-64">
|
||||
{JSON.stringify(
|
||||
{
|
||||
program: artifact.program,
|
||||
parameterSchema: artifact.parameterSchema,
|
||||
source: artifact.source,
|
||||
build: artifact.build,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</pre>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Compared version metadata</h4>
|
||||
<pre className="overflow-auto text-xs max-h-64">
|
||||
{JSON.stringify(
|
||||
{
|
||||
program: comparison.program,
|
||||
parameterSchema: comparison.parameterSchema,
|
||||
source: comparison.source,
|
||||
build: comparison.build,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className={comparison ? 'grid gap-4 md:grid-cols-2' : ''}>
|
||||
<div>
|
||||
<h4>Selected bundled JavaScript</h4>
|
||||
<pre
|
||||
aria-label="Selected bundled JavaScript"
|
||||
className="overflow-auto max-h-96 text-xs p-3 border border-border rounded-md"
|
||||
>
|
||||
{artifact.artifact.content}
|
||||
</pre>
|
||||
</div>
|
||||
{comparison && (
|
||||
<div>
|
||||
<h4>Compared bundled JavaScript</h4>
|
||||
<pre
|
||||
aria-label="Compared bundled JavaScript"
|
||||
className="overflow-auto max-h-96 text-xs p-3 border border-border rounded-md"
|
||||
>
|
||||
{comparison.artifact.content}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Saved backtests retain version identity without duplicating the mutable family metadata. */
|
||||
export function StrategyVersionPage() {
|
||||
const { versionId = '' } = useParams<{ versionId: string }>();
|
||||
const [version, setVersion] = useState<StrategyVersionSummary | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setVersion(null);
|
||||
setError(null);
|
||||
void strategyApi
|
||||
.version(versionId, controller.signal)
|
||||
.then(result => {
|
||||
if (!controller.signal.aborted) {
|
||||
setVersion(result.version);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause.message);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [versionId, retry]);
|
||||
if (version) {
|
||||
return <Navigate to={versionPath(version)} replace />;
|
||||
}
|
||||
return (
|
||||
<div className="space-y-3 text-text-primary">
|
||||
{error ? (
|
||||
<>
|
||||
<p role="alert">{error}</p>
|
||||
<button className={actionClass} onClick={() => setRetry(value => value + 1)}>
|
||||
Retry version
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<p role="status">Loading strategy version...</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
201
apps/stock/web-app/src/features/strategies/StrategyListPage.tsx
Normal file
201
apps/stock/web-app/src/features/strategies/StrategyListPage.tsx
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import type { StrategyRecord } from '@stock-bot/types';
|
||||
import { actionClass, fieldClass } from './components/StrategyParameterForm';
|
||||
import { confirmDiscard, useUnsavedWarning } from './components/useUnsavedWarning';
|
||||
import { strategyApi } from './services/strategyApi';
|
||||
|
||||
export function StrategyListPage() {
|
||||
const navigate = useNavigate();
|
||||
const mounted = useRef(true);
|
||||
const pendingCreate = useRef(false);
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
};
|
||||
}, []);
|
||||
const [strategies, setStrategies] = useState<StrategyRecord[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [createError, setCreateError] = useState<string | null>(null);
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
const dirty = showCreate && Boolean(name || description);
|
||||
useUnsavedWarning(dirty);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
void strategyApi
|
||||
.list(controller.signal)
|
||||
.then(result => {
|
||||
if (!controller.signal.aborted) {
|
||||
setStrategies(result.strategies);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [retry]);
|
||||
const create = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (pendingCreate.current || !name.trim()) {
|
||||
return;
|
||||
}
|
||||
pendingCreate.current = true;
|
||||
setCreating(true);
|
||||
setCreateError(null);
|
||||
try {
|
||||
const result = await strategyApi.create({ name, description });
|
||||
if (mounted.current) {
|
||||
navigate(`/strategies/${result.strategy.id}`);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (mounted.current) {
|
||||
setCreateError(
|
||||
`${cause instanceof Error ? cause.message : 'Could not create strategy'}. Refresh the catalog before retrying if the response was lost; the strategy may already have been created.`
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
pendingCreate.current = false;
|
||||
if (mounted.current) {
|
||||
setCreating(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const visible = strategies.filter(item => showArchived || !item.archived);
|
||||
return (
|
||||
<div className="space-y-5 text-text-primary">
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="text-lg font-bold">Strategies</h1>
|
||||
<button className={actionClass} onClick={() => setShowCreate(true)}>
|
||||
New strategy
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Organize immutable strategy packages and prepare backtest drafts. Catalog execution is not
|
||||
available yet.
|
||||
</p>
|
||||
{showCreate && (
|
||||
<form
|
||||
className="space-y-3 border border-border rounded-md p-4"
|
||||
onSubmit={event => void create(event)}
|
||||
>
|
||||
<label className="block text-sm">
|
||||
Strategy name
|
||||
<input
|
||||
className={fieldClass}
|
||||
aria-label="Strategy name"
|
||||
value={name}
|
||||
onChange={event => setName(event.target.value)}
|
||||
required
|
||||
disabled={creating}
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
Strategy description
|
||||
<textarea
|
||||
className={fieldClass}
|
||||
aria-label="Strategy description"
|
||||
value={description}
|
||||
onChange={event => setDescription(event.target.value)}
|
||||
disabled={creating}
|
||||
/>
|
||||
</label>
|
||||
{dirty && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
Unsaved strategy metadata. Save or discard before leaving.
|
||||
</p>
|
||||
)}
|
||||
{createError && (
|
||||
<p role="alert" className="text-sm text-error">
|
||||
{createError}
|
||||
</p>
|
||||
)}
|
||||
<button className={actionClass} disabled={creating || !name.trim()} type="submit">
|
||||
{creating ? 'Creating strategy...' : 'Create strategy'}
|
||||
</button>{' '}
|
||||
<button
|
||||
className={actionClass}
|
||||
disabled={creating}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (confirmDiscard(dirty)) {
|
||||
setShowCreate(false);
|
||||
setName('');
|
||||
setDescription('');
|
||||
setCreateError(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Discard
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
<label className="flex gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={showArchived}
|
||||
onChange={event => setShowArchived(event.target.checked)}
|
||||
/>
|
||||
Show archived strategies
|
||||
</label>
|
||||
{loading && <p role="status">Loading strategies...</p>}
|
||||
{error && (
|
||||
<div>
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
<button className={actionClass} onClick={() => setRetry(value => value + 1)}>
|
||||
Retry strategies
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{!loading && !error && !visible.length && (
|
||||
<p role="status">
|
||||
No strategies found. Create a strategy family, then publish an immutable package through
|
||||
the existing catalog API.
|
||||
</p>
|
||||
)}
|
||||
{!loading && !error && (
|
||||
<ul className="space-y-3">
|
||||
{visible.map(strategy => (
|
||||
<li className="border border-border rounded-md p-4" key={strategy.id}>
|
||||
<Link
|
||||
className="text-primary-500 font-medium"
|
||||
to={`/strategies/${strategy.id}`}
|
||||
onClick={event => {
|
||||
if (!confirmDiscard(dirty)) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{strategy.name}
|
||||
</Link>
|
||||
{strategy.archived && <span className="ml-2 text-xs">Archived</span>}
|
||||
<p className="text-sm text-text-secondary whitespace-pre-wrap">
|
||||
{strategy.description || 'No description yet.'}
|
||||
</p>
|
||||
<p className="text-xs text-text-muted">
|
||||
Owner: {strategy.ownerPrincipal} · {strategy.id}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,251 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { StrategyParameterSchema, StrategyParameterValue } from '@stock-bot/types';
|
||||
import { strategyApi, type Parameters } from '../services/strategyApi';
|
||||
|
||||
export const fieldClass =
|
||||
'w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary disabled:opacity-50';
|
||||
export const actionClass =
|
||||
'px-3 py-2 rounded-md border border-border text-sm text-primary-500 disabled:opacity-50';
|
||||
|
||||
export function parameterFields(
|
||||
schema: StrategyParameterSchema,
|
||||
raw: Record<string, string>,
|
||||
included: Record<string, boolean>
|
||||
) {
|
||||
const parameters: Parameters = Object.create(null);
|
||||
const errors: Record<string, string> = Object.create(null);
|
||||
for (const key of Object.keys(raw)) {
|
||||
if (!Object.prototype.hasOwnProperty.call(schema.properties, key)) {
|
||||
errors[key] = 'Unknown parameter';
|
||||
}
|
||||
}
|
||||
for (const [name, rule] of Object.entries(schema.properties)) {
|
||||
const text = raw[name] ?? '';
|
||||
const stringValue = rule.type === 'string' && !rule.enum;
|
||||
if ((stringValue && !included[name]) || (!stringValue && text === '')) {
|
||||
if (schema.required.includes(name) && rule.default === undefined) {
|
||||
errors[name] = 'Required';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let value: StrategyParameterValue;
|
||||
if (rule.enum) {
|
||||
const choice = rule.enum.find(item => JSON.stringify(item) === text);
|
||||
if (choice === undefined) {
|
||||
errors[name] = 'Choose a listed value';
|
||||
continue;
|
||||
}
|
||||
value = choice;
|
||||
} else if (rule.type === 'boolean') {
|
||||
if (text !== 'true' && text !== 'false') {
|
||||
errors[name] = 'Choose true or false';
|
||||
continue;
|
||||
}
|
||||
value = text === 'true';
|
||||
} else if (rule.type === 'string') {
|
||||
value = text;
|
||||
} else {
|
||||
value = Number(text);
|
||||
if (
|
||||
text.trim() === '' ||
|
||||
!Number.isFinite(value) ||
|
||||
(rule.type === 'integer' && !Number.isInteger(value))
|
||||
) {
|
||||
errors[name] = `Enter a finite ${rule.type}`;
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
(rule.minimum !== undefined && value < rule.minimum) ||
|
||||
(rule.maximum !== undefined && value > rule.maximum) ||
|
||||
(rule.exclusiveMinimum !== undefined && value <= rule.exclusiveMinimum) ||
|
||||
(rule.exclusiveMaximum !== undefined && value >= rule.exclusiveMaximum)
|
||||
) {
|
||||
errors[name] = 'Value is outside the allowed range';
|
||||
continue;
|
||||
}
|
||||
}
|
||||
parameters[name] = value;
|
||||
}
|
||||
return { parameters, errors };
|
||||
}
|
||||
function initialFields(
|
||||
schema: StrategyParameterSchema,
|
||||
values: Parameters
|
||||
): { raw: Record<string, string>; included: Record<string, boolean> } {
|
||||
const raw: Record<string, string> = Object.create(null);
|
||||
const included: Record<string, boolean> = Object.create(null);
|
||||
for (const name of new Set([...Object.keys(schema.properties), ...Object.keys(values)])) {
|
||||
const rule = schema.properties[name];
|
||||
const value = Object.prototype.hasOwnProperty.call(values, name) ? values[name] : rule?.default;
|
||||
raw[name] = value === undefined ? '' : rule?.enum ? JSON.stringify(value) : String(value);
|
||||
included[name] = value !== undefined;
|
||||
}
|
||||
return { raw, included };
|
||||
}
|
||||
|
||||
/** Key this component by immutable version ID. Server validation remains authoritative. */
|
||||
export function StrategyParameterForm({
|
||||
versionId,
|
||||
schema,
|
||||
initialParameters = {},
|
||||
disabled = false,
|
||||
onChange,
|
||||
onEdit,
|
||||
}: {
|
||||
versionId: string;
|
||||
schema: StrategyParameterSchema;
|
||||
initialParameters?: Parameters;
|
||||
disabled?: boolean;
|
||||
onChange: (parameters: Parameters, valid: boolean) => void;
|
||||
onEdit?: () => void;
|
||||
}) {
|
||||
const [{ raw, included }, setFields] = useState(() => initialFields(schema, initialParameters));
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [validating, setValidating] = useState(false);
|
||||
const [validated, setValidated] = useState(false);
|
||||
const generation = useRef(0);
|
||||
const changed = useRef(onChange);
|
||||
changed.current = onChange;
|
||||
const parsed = parameterFields(schema, raw, included);
|
||||
useEffect(() => {
|
||||
changed.current(parameterFields(schema, raw, included).parameters, false);
|
||||
return () => {
|
||||
generation.current++;
|
||||
};
|
||||
// Parent keys this form by immutable version, preserving raw edits during unrelated renders.
|
||||
}, []);
|
||||
const edit = (name: string, text: string, include = true) => {
|
||||
onEdit?.();
|
||||
generation.current++;
|
||||
const next = { ...raw, [name]: text };
|
||||
const nextIncluded = { ...included, [name]: include };
|
||||
setFields({ raw: next, included: nextIncluded });
|
||||
setValidated(false);
|
||||
setValidating(false);
|
||||
setError(null);
|
||||
onChange(parameterFields(schema, next, nextIncluded).parameters, false);
|
||||
};
|
||||
const validate = async () => {
|
||||
if (disabled || Object.keys(parsed.errors).length) {
|
||||
return;
|
||||
}
|
||||
const current = ++generation.current;
|
||||
setValidating(true);
|
||||
setValidated(false);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await strategyApi.validate(versionId, parsed.parameters);
|
||||
if (current !== generation.current) {
|
||||
return;
|
||||
}
|
||||
setFields(initialFields(schema, result.parameters));
|
||||
setValidated(true);
|
||||
onChange(result.parameters, true);
|
||||
} catch (cause) {
|
||||
if (current === generation.current) {
|
||||
setError(cause instanceof Error ? cause.message : 'Parameter validation failed');
|
||||
onChange(parsed.parameters, false);
|
||||
}
|
||||
} finally {
|
||||
if (current === generation.current) {
|
||||
setValidating(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<h3 className="font-medium text-text-primary">Strategy parameters</h3>
|
||||
<p className="text-xs text-text-muted">
|
||||
Blank optional numeric fields are omitted; declared defaults apply. Use Include for string
|
||||
values to distinguish omitted values from empty text. Included strings are kept exactly as
|
||||
entered.
|
||||
</p>
|
||||
{Object.entries(schema.properties).map(([name, rule]) => (
|
||||
<div key={name}>
|
||||
{rule.type === 'string' && !rule.enum && (
|
||||
<label className="flex items-center gap-2 text-xs text-text-secondary">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={`Include ${name}`}
|
||||
checked={included[name] ?? false}
|
||||
disabled={disabled}
|
||||
onChange={event => edit(name, raw[name] ?? '', event.target.checked)}
|
||||
/>
|
||||
Include {name} (empty text is a value)
|
||||
</label>
|
||||
)}
|
||||
<label className="block text-sm text-text-secondary">
|
||||
{name}
|
||||
{schema.required.includes(name) ? ' *' : ''}
|
||||
{rule.enum || rule.type === 'boolean' ? (
|
||||
<select
|
||||
aria-label={name}
|
||||
value={raw[name] ?? ''}
|
||||
disabled={disabled}
|
||||
className={fieldClass}
|
||||
onChange={event => edit(name, event.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
{schema.required.includes(name)
|
||||
? 'Select a value'
|
||||
: 'Omit (use default if defined)'}
|
||||
</option>
|
||||
{(rule.enum ?? [true, false]).map(value => (
|
||||
<option key={JSON.stringify(value)} value={JSON.stringify(value)}>
|
||||
{String(value)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
aria-label={name}
|
||||
type="text"
|
||||
inputMode={rule.type === 'string' ? 'text' : 'decimal'}
|
||||
className={fieldClass}
|
||||
disabled={disabled || (rule.type === 'string' && !included[name])}
|
||||
value={raw[name] ?? ''}
|
||||
onChange={event => edit(name, event.target.value)}
|
||||
aria-invalid={Boolean(parsed.errors[name])}
|
||||
/>
|
||||
)}
|
||||
</label>
|
||||
{rule.description && <p className="text-xs text-text-muted">{rule.description}</p>}
|
||||
{parsed.errors[name] && (
|
||||
<p role="alert" className="text-sm text-error">
|
||||
{name}: {parsed.errors[name]}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{Object.keys(parsed.errors)
|
||||
.filter(name => !Object.prototype.hasOwnProperty.call(schema.properties, name))
|
||||
.map(name => (
|
||||
<p key={name} role="alert" className="text-sm text-error">
|
||||
{name}: Unknown parameter. Select another version or correct the saved parameters
|
||||
through the API.
|
||||
</p>
|
||||
))}
|
||||
{Object.keys(schema.properties).length === 0 && (
|
||||
<p className="text-sm text-text-muted">This version has no parameters.</p>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={disabled || validating || Object.keys(parsed.errors).length > 0}
|
||||
onClick={() => void validate()}
|
||||
>
|
||||
{validating ? 'Validating parameters...' : 'Validate parameters'}
|
||||
</button>
|
||||
{validated && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
Parameters validated for this immutable version. Execution remains unavailable.
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,312 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { StrategyRecord, StrategyVersionSummary } from '@stock-bot/types';
|
||||
import { strategyApi, type Parameters } from '../services/strategyApi';
|
||||
import { actionClass, fieldClass, StrategyParameterForm } from './StrategyParameterForm';
|
||||
|
||||
export interface CatalogSelection {
|
||||
strategyVersionId?: string | null;
|
||||
strategyParameters?: Parameters | null;
|
||||
}
|
||||
export const catalogExecutionReason =
|
||||
'Catalog versions are save-only. Execution of retained versions is not available yet.';
|
||||
export function versionPath(version: Pick<StrategyVersionSummary, 'strategyId' | 'id'>) {
|
||||
return `/strategies/${encodeURIComponent(version.strategyId)}/versions/${encodeURIComponent(version.id)}`;
|
||||
}
|
||||
|
||||
export function StrategySelection({
|
||||
value,
|
||||
onChange,
|
||||
onValidityChange,
|
||||
disabled = false,
|
||||
allowArchivedSelection = false,
|
||||
}: {
|
||||
value: CatalogSelection;
|
||||
onChange: (value: CatalogSelection) => void;
|
||||
onValidityChange: (valid: boolean) => void;
|
||||
disabled?: boolean;
|
||||
allowArchivedSelection?: boolean;
|
||||
}) {
|
||||
const [families, setFamilies] = useState<StrategyRecord[]>([]);
|
||||
const [familyId, setFamilyId] = useState('');
|
||||
const [family, setFamily] = useState<StrategyRecord | null>(null);
|
||||
const [versions, setVersions] = useState<StrategyVersionSummary[]>([]);
|
||||
const [selected, setSelected] = useState<StrategyVersionSummary | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [catalogLoading, setCatalogLoading] = useState(true);
|
||||
const [versionsLoading, setVersionsLoading] = useState(false);
|
||||
const [catalogError, setCatalogError] = useState<string | null>(null);
|
||||
const [selectionError, setSelectionError] = useState<string | null>(null);
|
||||
const [versionsError, setVersionsError] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
const callbacks = useRef({ onChange, onValidityChange });
|
||||
callbacks.current = { onChange, onValidityChange };
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setCatalogError(null);
|
||||
setCatalogLoading(true);
|
||||
void strategyApi
|
||||
.list(controller.signal)
|
||||
.then(result => {
|
||||
if (!controller.signal.aborted) {
|
||||
setFamilies(result.strategies);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
if (!controller.signal.aborted) {
|
||||
setCatalogError(error.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setCatalogLoading(false);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [retry]);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setSelected(null);
|
||||
setFamily(null);
|
||||
setSelectionError(null);
|
||||
callbacks.current.onValidityChange(false);
|
||||
const selectedId = value.strategyVersionId;
|
||||
if (!selectedId) {
|
||||
setLoading(false);
|
||||
return () => controller.abort();
|
||||
}
|
||||
setLoading(true);
|
||||
void (async () => {
|
||||
try {
|
||||
const result = await strategyApi.version(selectedId, controller.signal);
|
||||
const owner = await strategyApi.get(result.version.strategyId, controller.signal);
|
||||
if (!controller.signal.aborted) {
|
||||
setSelected(result.version);
|
||||
setFamily(owner.strategy);
|
||||
setFamilyId(result.version.strategyId);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (!controller.signal.aborted) {
|
||||
setSelectionError(cause instanceof Error ? cause.message : 'Version unavailable');
|
||||
}
|
||||
} finally {
|
||||
if (!controller.signal.aborted) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
})();
|
||||
return () => controller.abort();
|
||||
}, [value.strategyVersionId, retry]);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setVersions([]);
|
||||
setVersionsError(null);
|
||||
setVersionsLoading(Boolean(familyId));
|
||||
if (familyId) {
|
||||
void strategyApi
|
||||
.versions(familyId, controller.signal)
|
||||
.then(result => {
|
||||
if (!controller.signal.aborted) {
|
||||
setVersions(result.versions);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
if (!controller.signal.aborted) {
|
||||
setVersionsError(error.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setVersionsLoading(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
return () => controller.abort();
|
||||
}, [familyId, retry]);
|
||||
const activeFamilies = families.filter(item => !item.archived);
|
||||
const displayedFamilies = family?.archived ? [family, ...activeFamilies] : activeFamilies;
|
||||
const displayedVersions =
|
||||
selected && !versions.some(item => item.id === selected.id)
|
||||
? [selected, ...versions]
|
||||
: versions;
|
||||
return (
|
||||
<div className="space-y-3 border border-border rounded-md p-3">
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
{catalogExecutionReason}
|
||||
</p>
|
||||
<label className="block text-sm text-text-secondary">
|
||||
Strategy family
|
||||
<select
|
||||
aria-label="Strategy family"
|
||||
className={fieldClass}
|
||||
disabled={disabled || Boolean(catalogError)}
|
||||
value={familyId}
|
||||
onChange={event => {
|
||||
setFamilyId(event.target.value);
|
||||
callbacks.current.onValidityChange(false);
|
||||
onChange({ strategyVersionId: null, strategyParameters: {} });
|
||||
}}
|
||||
>
|
||||
<option value="">Select a strategy family</option>
|
||||
{displayedFamilies.map(item => (
|
||||
<option key={item.id} value={item.id} disabled={item.archived}>
|
||||
{item.name}
|
||||
{item.archived ? ' (archived — retained selection)' : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{catalogLoading && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
Loading strategy catalog...
|
||||
</p>
|
||||
)}
|
||||
{!catalogLoading && !catalogError && !activeFamilies.length && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
No strategies available.{' '}
|
||||
<Link to="/strategies" className="text-primary-500">
|
||||
Open strategy catalog
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
<label className="block text-sm text-text-secondary">
|
||||
Immutable strategy version
|
||||
<select
|
||||
aria-label="Immutable strategy version"
|
||||
className={fieldClass}
|
||||
value={value.strategyVersionId ?? ''}
|
||||
disabled={disabled || !familyId || Boolean(family?.archived) || Boolean(versionsError)}
|
||||
onChange={event => {
|
||||
callbacks.current.onValidityChange(false);
|
||||
onChange({ strategyVersionId: event.target.value || null, strategyParameters: {} });
|
||||
}}
|
||||
>
|
||||
<option value="">Select an immutable version</option>
|
||||
{displayedVersions.map(item => (
|
||||
<option key={item.id} value={item.id}>
|
||||
Version {item.ordinal} — {item.id} ({item.origin}, {item.reviewStatus})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{versionsLoading && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
Loading available versions...
|
||||
</p>
|
||||
)}
|
||||
{familyId && !versionsLoading && !versionsError && !versions.length && !loading && (
|
||||
<p className="text-sm text-text-secondary">No versions published for this family.</p>
|
||||
)}
|
||||
{loading && <p role="status">Loading selected strategy version...</p>}
|
||||
{[catalogError, versionsError, selectionError].filter(Boolean).map((error, index) => (
|
||||
<p key={index} role="alert" className="text-sm text-error">
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
{(catalogError || versionsError || selectionError) && (
|
||||
<button type="button" className={actionClass} onClick={() => setRetry(value => value + 1)}>
|
||||
Retry strategy catalog
|
||||
</button>
|
||||
)}
|
||||
{value.strategyVersionId && !selected && !loading && (
|
||||
<p role="alert" className="text-sm text-error">
|
||||
Selected version {value.strategyVersionId} is unavailable. The selection has been
|
||||
retained; saving is disabled.
|
||||
</p>
|
||||
)}
|
||||
{selected && selected.id === value.strategyVersionId && (
|
||||
<>
|
||||
<Link className="text-sm text-primary-500" to={versionPath(selected)}>
|
||||
View immutable version {selected.ordinal}
|
||||
</Link>
|
||||
<p className="text-xs text-text-muted">
|
||||
{selected.origin === 'candidate'
|
||||
? 'Candidate execution is unavailable until isolated execution is supported.'
|
||||
: 'This retained built-in version cannot be executed from the workbench yet.'}
|
||||
</p>
|
||||
{family?.archived && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
This strategy family is archived. Its retained version remains readable; restore the
|
||||
family before selecting it for a new backtest.
|
||||
</p>
|
||||
)}
|
||||
<StrategyParameterForm
|
||||
key={selected.id}
|
||||
versionId={selected.id}
|
||||
schema={selected.package.parameterSchema}
|
||||
initialParameters={value.strategyParameters ?? {}}
|
||||
disabled={disabled || Boolean(family?.archived && !allowArchivedSelection)}
|
||||
onChange={(parameters, valid) => {
|
||||
onChange({ strategyVersionId: selected.id, strategyParameters: parameters });
|
||||
callbacks.current.onValidityChange(
|
||||
valid && (!family?.archived || allowArchivedSelection)
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LegacyStrategySelect({
|
||||
value,
|
||||
onChange,
|
||||
disabled = false,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const options = [
|
||||
['moving-average', 'Moving Average'],
|
||||
...(value === 'sma-crossover' || value === 'sma' || value === 'sma_crossover'
|
||||
? [[value, 'SMA Crossover']]
|
||||
: []),
|
||||
['momentum', 'Momentum'],
|
||||
['mean-reversion', 'Mean Reversion'],
|
||||
...(value === 'mean_reversion' ? [[value, 'Mean Reversion']] : []),
|
||||
];
|
||||
const supported = options.some(([id]) => id === value);
|
||||
return (
|
||||
<div>
|
||||
<label className="block text-sm text-text-secondary">
|
||||
Legacy strategy
|
||||
<select
|
||||
aria-label="Legacy strategy"
|
||||
className={fieldClass}
|
||||
value={value}
|
||||
onChange={event => onChange(event.target.value)}
|
||||
disabled={disabled}
|
||||
>
|
||||
{!supported && (
|
||||
<option value={value} disabled>
|
||||
{value} (not supported by this form)
|
||||
</option>
|
||||
)}
|
||||
{options.map(([id, label]) => (
|
||||
<option value={id} key={id}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p className="text-xs text-text-muted">
|
||||
Legacy name-based workflow. These runs do not execute retained catalog versions or provide
|
||||
canonical strategy-version provenance.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function supportedLegacyStrategy(value: string) {
|
||||
return [
|
||||
'moving-average',
|
||||
'sma-crossover',
|
||||
'sma',
|
||||
'sma_crossover',
|
||||
'momentum',
|
||||
'mean-reversion',
|
||||
'mean_reversion',
|
||||
].includes(value);
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
import { useEffect } from 'react';
|
||||
|
||||
export function useUnsavedWarning(dirty: boolean) {
|
||||
useEffect(() => {
|
||||
if (!dirty) {
|
||||
return;
|
||||
}
|
||||
const warn = (event: BeforeUnloadEvent) => {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
};
|
||||
window.addEventListener('beforeunload', warn);
|
||||
return () => window.removeEventListener('beforeunload', warn);
|
||||
}, [dirty]);
|
||||
}
|
||||
export const confirmDiscard = (dirty: boolean) =>
|
||||
!dirty || window.confirm('Discard unsaved changes?');
|
||||
2
apps/stock/web-app/src/features/strategies/index.ts
Normal file
2
apps/stock/web-app/src/features/strategies/index.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export { StrategyListPage } from './StrategyListPage';
|
||||
export { StrategyDetailPage, StrategyVersionPage } from './StrategyDetailPage';
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
import type {
|
||||
ParameterValidationResult,
|
||||
StrategyParameterValue,
|
||||
StrategyRecord,
|
||||
StrategyReviewEvent,
|
||||
StrategyVersionPackage,
|
||||
StrategyVersionSummary,
|
||||
} from '@stock-bot/types';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
|
||||
export type Parameters = Record<string, StrategyParameterValue>;
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const response = await apiFetch(`${API_BASE_URL}/api/v2/${path}`, init);
|
||||
const body = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
typeof body?.error === 'string' ? body.error : `Strategy request failed (${response.status})`
|
||||
);
|
||||
}
|
||||
return body as T;
|
||||
}
|
||||
const json = (method: string, body: unknown, key?: string): RequestInit => ({
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json', ...(key ? { 'Idempotency-Key': key } : {}) },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const id = encodeURIComponent;
|
||||
export const strategyApi = {
|
||||
list: (signal?: AbortSignal) =>
|
||||
request<{ strategies: StrategyRecord[] }>('strategies', { signal }),
|
||||
get: (strategyId: string, signal?: AbortSignal) =>
|
||||
request<{ strategy: StrategyRecord }>(`strategies/${id(strategyId)}`, { signal }),
|
||||
create: (body: { name: string; description: string }) =>
|
||||
request<{ strategy: StrategyRecord }>('strategies', json('POST', body)),
|
||||
update: (strategyId: string, body: { name?: string; description?: string; archived?: boolean }) =>
|
||||
request<{ strategy: StrategyRecord }>(`strategies/${id(strategyId)}`, json('PATCH', body)),
|
||||
versions: (strategyId: string, signal?: AbortSignal) =>
|
||||
request<{ versions: StrategyVersionSummary[] }>(`strategies/${id(strategyId)}/versions`, {
|
||||
signal,
|
||||
}),
|
||||
version: (versionId: string, signal?: AbortSignal) =>
|
||||
request<{ version: StrategyVersionSummary; reviews: StrategyReviewEvent[] }>(
|
||||
`strategy-versions/${id(versionId)}`,
|
||||
{ signal }
|
||||
),
|
||||
artifact: (versionId: string, signal?: AbortSignal) =>
|
||||
request<{ package: StrategyVersionPackage }>(`strategy-versions/${id(versionId)}/artifact`, {
|
||||
signal,
|
||||
}),
|
||||
validate: (versionId: string, parameters: Parameters) =>
|
||||
request<ParameterValidationResult>(
|
||||
`strategy-versions/${id(versionId)}/validate`,
|
||||
json('POST', { parameters })
|
||||
),
|
||||
clone: (versionId: string, body: { name: string; description: string }, key: string) =>
|
||||
request<{ strategy: StrategyRecord; version: StrategyVersionSummary }>(
|
||||
`strategy-versions/${id(versionId)}/clone`,
|
||||
json('POST', body, key)
|
||||
),
|
||||
};
|
||||
44
database/postgres/init/18-backtest-strategy-versions.sql
Normal file
44
database/postgres/init/18-backtest-strategy-versions.sql
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
-- A catalog selection is a saved draft, never a legacy strategy alias.
|
||||
ALTER TABLE backtests ADD COLUMN IF NOT EXISTS strategy_version_id UUID
|
||||
REFERENCES strategy_versions(id) ON DELETE RESTRICT;
|
||||
ALTER TABLE backtests ADD COLUMN IF NOT EXISTS strategy_parameters JSONB;
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='backtests_catalog_selection' AND conrelid='backtests'::regclass) THEN
|
||||
ALTER TABLE backtests ADD CONSTRAINT backtests_catalog_selection CHECK (
|
||||
(strategy_version_id IS NULL AND strategy_parameters IS NULL)
|
||||
OR (strategy_version_id IS NOT NULL AND strategy_parameters IS NOT NULL
|
||||
AND jsonb_typeof(strategy_parameters)='object' AND strategy='catalog')
|
||||
);
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION protect_backtest_strategy_mode() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$ BEGIN
|
||||
IF (OLD.strategy_version_id IS NULL) IS DISTINCT FROM (NEW.strategy_version_id IS NULL) THEN
|
||||
RAISE EXCEPTION 'Create a separate template to switch between legacy execution and catalog drafts'
|
||||
USING ERRCODE='23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
DROP TRIGGER IF EXISTS backtests_strategy_mode ON backtests;
|
||||
CREATE TRIGGER backtests_strategy_mode BEFORE UPDATE ON backtests
|
||||
FOR EACH ROW EXECUTE FUNCTION protect_backtest_strategy_mode();
|
||||
|
||||
-- Retain the same parent lock and archive rule from17. Existing admitted runs only
|
||||
-- UPDATE their own rows, so their progress/recovery remains independent of drafts.
|
||||
CREATE OR REPLACE FUNCTION require_active_backtest_for_new_run() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE parent RECORD;
|
||||
BEGIN
|
||||
SELECT archived_at,strategy_version_id,strategy INTO parent
|
||||
FROM backtests WHERE id=NEW.backtest_id FOR UPDATE;
|
||||
IF FOUND THEN
|
||||
IF parent.archived_at IS NOT NULL THEN
|
||||
RAISE EXCEPTION 'Backtest is archived; restore it before submitting a new run' USING ERRCODE='23514';
|
||||
END IF;
|
||||
IF parent.strategy_version_id IS NOT NULL OR parent.strategy='catalog' THEN
|
||||
RAISE EXCEPTION 'Catalog strategy execution is unavailable until canonical runner integration (R05)' USING ERRCODE='23514';
|
||||
END IF;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
# Revised development roadmap
|
||||
|
||||
Baseline `b7aeca4` · execution 2026-10-23 · **R01 committed; R10 validated, uncommitted**
|
||||
Baseline `b7aeca4` · execution 2026-10-23 · **R10 committed; R02 catalog/setup validated and awaiting acceptance/commit**
|
||||
|
||||
Authorization update: the owner requested “commit and continue with backlog”. R01 is committed as `4a2e5ad`; R10 is authorized under ADR-006. Performance work remains paused. New R10 implementation commits, pushes, PRs and trading/default-engine operations remain outside this continuation’s scope.
|
||||
Authorization update: the owner requested “commit and continue”. R10 is committed as `8cca0ee`; R02 is authorized under ADR-006. Performance work remains paused. New R02 commits, pushes, PRs and trading/default-engine operations remain outside this continuation’s scope.
|
||||
|
||||
## Strategy and review outcome
|
||||
|
||||
|
|
@ -21,7 +21,7 @@ The existing web workbench improves during engine migration. Legacy results rema
|
|||
| [ADR-003](architecture/decisions/003-time-and-datasets.md) | Availability/event phases; open-only next-interval matching; explicit zero-latency convention; mark-open terminal policy; account risk-session clock | Approved by owner, 2026-10-22 |
|
||||
| [ADR-004](architecture/decisions/004-strategy-boundary.md) | NAPI pull sessions in existing workers; tagged decision barriers; IPC for untrusted code; no embedded JS | Approved by owner, 2026-10-22 |
|
||||
| [ADR-005](architecture/decisions/005-durable-cutover.md) | One Rust transition kernel; resident research state; private staged paper state under existing SQL transactions | Approved by owner continuation, 2026-10-23; paper activation separately gated |
|
||||
| [ADR-006](architecture/decisions/006-research-product.md) | Existing API/queue/database; immutable versions, provenance and evidence retention; no laboratory framework | Plan approval |
|
||||
| [ADR-006](architecture/decisions/006-research-product.md) | Existing API/queue/database; immutable versions, provenance and evidence retention; no laboratory framework | Approved by owner continuation, 2026-10-23 |
|
||||
| [ADR-007](architecture/decisions/007-ai-boundary.md) | Isolated untrusted code, research-only permissions/budgets; human-only paper promotion; live disabled | Explicit trust-model approval |
|
||||
| [ADR-008](architecture/decisions/008-performance.md) | Measure actual paths; cursor replay and bounded trials; caching/DSL only when measured | Plan approval; later optimization go/no-go |
|
||||
|
||||
|
|
@ -508,3 +508,17 @@ R01 accepted and committed as `4a2e5ad`. R10 is independently reviewed and `vali
|
|||
The initial sandbox run could not support native worker IPC or fixture network access; full checks were rerun successfully outside it. Optional broad strict legacy harness checks retain pre-existing errors, recorded in the manifest. Release addon is restored and matches the prior wave hash; Rust code and financial semantics were unchanged. Disposable fixture containers were removed; development services were untouched. No performance work, new R10 commit, push, PR or trading/default activation.
|
||||
|
||||
Legacy economic/provenance limitations remain explicit; retaining evidence does not certify its economics or create missing version history. Next: R02 strategy catalog UI and version-aware setup. R05 still owns retained-artifact execution and canonical durable cutover.
|
||||
|
||||
|
||||
## Twenty-second-wave handoff — 2026-10-23
|
||||
|
||||
R10 is accepted and committed as `8cca0ee`, superseding its uncommitted handoff above. R02 is `review` / `validated_uncommitted`. Thirty-nine implementation/shared-contract/migration/test files were integrated from isolated backend/frontend owners and root browser/fixture integration, with independent review. Worktrees/logs remain under `/tmp/stock-bot-wave22.fPRkAC/`.
|
||||
|
||||
- **Catalog and versions:** Browse/create/edit/archive strategy families; select immutable versions; clone with frozen retry identity; compare retained bundled JavaScript/schema/identities as escaped text. Parameter forms preserve omission, explicit empty strings, false, zero, typed enums and decimal strings, and require exact server validation. Version-linked execution/deployment history remains explicitly unavailable.
|
||||
- **Saved backtest setups:** Migration 18 retains exact version IDs and normalized parameters separately from execution settings. Create, save, reopen and edit catalog setups in the existing workbench. Archive/restore resets visible parameter state and validation together. Legacy pacing stays out of strict catalog settings. Existing supported legacy strategies retain their qualified independent workflow.
|
||||
- **Admission boundary:** Every catalog version remains non-runnable, including approved built-ins. API, direct repository and SQL gates reject before run/outbox creation; accepted legacy receipts still replay first. No legacy alias fallback, catalog/legacy mode conversion, browser code execution or fabricated provenance.
|
||||
- **Validation:** Full checks passed: 93 tooling, 43 utility, 44 calculation, **541 integration** and **150 Rust** tests (4 manual ignored), plus build/source/contracts/lint/secrets. Full disposable PostgreSQL/Redis: **137 tests / 1052 assertions**. Final unfiltered Chromium suite: **8 workflows / 117 assertions**, including catalog selection/save/reopen/edit/archive/clone and existing native/frozen-dataset workflows. Strict new/modern changed tests and scoped lint/format/diff checks pass. Exact commands, source hashes and limitations are in `manifest.json` → `twenty_second_wave_validation`.
|
||||
|
||||
The browser gate exposed intermittent Chromium control-pipe loss across serial launches, not a financial assertion failure. Isolated workflows passed. The fixture now shares one suite-owned Chromium process while giving each workflow a fresh context/server/schema/queue; the complete suite passed without retries. Production workers are unchanged. The release addon matches the prior wave and checkout library; no Rust financial semantics changed. Both exact disposable containers were stopped; development services were untouched.
|
||||
|
||||
No new R02 commit, push, PR, performance work or trading/default activation. **Next after acceptance/commit: R05**, connecting verified retained executable identity and canonical reports to durable runs. Start with a trusted-built-in single-asset vertical slice; do not certify a retained hash while executing an unrelated current built-in. Candidate execution remains gated by A02 and multi-asset default by the explicit mark-policy decision. R03 research metadata is also ready for disjoint work, but does not unlock catalog execution.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Canonical development backlog
|
||||
|
||||
**First seventeen waves committed; S05 is validated and awaiting acceptance/commit.** S04 is accepted as `75abae2`. P08 remains deferred at the owner's request. S05 adds a small composable mean-reversion/regime strategy on the canonical runtime; S04 still requires an external producer for operational feed readiness. Consult manifest execution_scope and [current wave](../ROADMAP.md#eighteenth-wave-execution--2026-10-23). ADR-002/003/004/005 are approved; other policies/default cutovers remain gated.
|
||||
**First twenty-one waves committed; R02 is validated and awaiting acceptance/commit.** R10 is accepted as `8cca0ee`. R02 adds catalog/version browsing and validated saved backtest setups; catalog execution remains gated by R05. Performance work remains paused. See [current handoff](../ROADMAP.md#twenty-second-wave-handoff--2026-10-23) and manifest execution scope.
|
||||
|
||||
## One source of truth
|
||||
|
||||
|
|
@ -73,15 +73,15 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| [R01 Persist immutable strategy versions and parameter schemas](tasks/R01.md) | P1 / done | O01, ADR-006 | — | Full-stack research product / M |
|
||||
| [R02 Deliver strategy catalog and version-aware backtest setup](tasks/R02.md) | P1 / ready | R01, W03, ADR-006 | W04 | Full-stack research product / M |
|
||||
| [R03 Add projects, hypotheses and evidence-linked findings APIs](tasks/R03.md) | P1 / blocked | R01, R10, ADR-006 | — | Full-stack research product / M |
|
||||
| [R02 Deliver strategy catalog and version-aware backtest setup](tasks/R02.md) | P1 / review | R01, W03, ADR-006 | W04 | Full-stack research product / M |
|
||||
| [R03 Add projects, hypotheses and evidence-linked findings APIs](tasks/R03.md) | P1 / ready | R01, R10, ADR-006 | — | Full-stack research product / M |
|
||||
| [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / blocked | R03, W02, ADR-006 | W04 | Full-stack research product / M |
|
||||
| [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / blocked | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M |
|
||||
| [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / ready | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M |
|
||||
| [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / blocked | R05, ADR-006 | — | Full-stack research product / M |
|
||||
| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / blocked | R06, ADR-006 | W04 | Full-stack research product / M |
|
||||
| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / blocked | R06, ADR-006 | — | Quantitative research integrity / M |
|
||||
| [R09 Expose validation, cost and regime evidence in the workbench](tasks/R09.md) | P1 / blocked | R07, R08, ADR-006 | S05 when Regime comparison is enabled; R03 when Saving or linking a research finding is enabled | Full-stack research product / M |
|
||||
| [R10 Protect retained research evidence and artifact integrity](tasks/R10.md) | P1 / review | R01, ADR-006 | — | Full-stack research product / M |
|
||||
| [R10 Protect retained research evidence and artifact integrity](tasks/R10.md) | P1 / done | R01, ADR-006 | — | Full-stack research product / M |
|
||||
| [R11 Select and reuse frozen datasets in the workbench](tasks/R11.md) | P1 / done | D01, O01, ADR-003, ADR-006 | W04 | Full-stack market data/research / M |
|
||||
| [R12 Reproduce an original run separately from rerunning current settings](tasks/R12.md) | P1 / blocked | R05, W04, ADR-006 | — | Full-stack reproducible research / S |
|
||||
|
||||
|
|
@ -118,4 +118,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
|
||||
Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation.
|
||||
|
||||
The first twenty waves are committed, including R01 (`4a2e5ad`). **R10 retention is validated and uncommitted; performance work remains deferred by the owner.** ADR-006 is approved; R02 is ready after R01. The multi-asset mark-policy gate still blocks default activation. No default/paper activation, push or PR is included in this continuation.
|
||||
The first twenty-one waves are committed, including R10 (`8cca0ee`). **R02 catalog and versioned setup is validated and awaiting acceptance/commit; performance work remains deferred by the owner.** ADR-006 is approved; R03/R05 prerequisites are integrated but those tasks are outside this wave. R05 is next: verified retained-artifact execution through the existing canonical runtime and durable runner. The multi-asset mark-policy gate still blocks default activation. No default/paper activation, push or PR is included in this continuation.
|
||||
|
|
|
|||
|
|
@ -1,16 +1,16 @@
|
|||
{
|
||||
"schema_version": 1,
|
||||
"plan_revision": "2026-10-23.46",
|
||||
"plan_revision": "2026-10-23.48",
|
||||
"repository_base": "b7aeca4",
|
||||
"plan_status": "twenty_first_wave_review",
|
||||
"plan_status": "twenty_second_wave_review",
|
||||
"execution_authorized": true,
|
||||
"execution_scope": {
|
||||
"authorized_by": "User: commit and continue with backlog (2026-10-23). R01 accepted and committed 4a2e5ad362f7746a45a694dbcd9c51efac390526.",
|
||||
"authorized_by": "User: commit and continue after validated R10 handoff named R02 next. R10 committed 8cca0ee588b55cf904f46199ccb65942de70ee99.",
|
||||
"tasks": [
|
||||
"R10"
|
||||
"R02"
|
||||
],
|
||||
"permissions": [
|
||||
"R10 isolated implementation, correctness tests, independent review and planning updates; prior R01 commit authorized and completed"
|
||||
"R02 isolated implementation, correctness tests, independent review and planning updates; prior R10 commit authorized and completed"
|
||||
],
|
||||
"excluded": [
|
||||
"performance_profiling_or_optimization",
|
||||
|
|
@ -1442,7 +1442,7 @@
|
|||
"epic": "E6",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "ready",
|
||||
"status": "review",
|
||||
"dependencies": [
|
||||
"R01",
|
||||
"W03"
|
||||
|
|
@ -1461,14 +1461,33 @@
|
|||
"web-backtest-detail",
|
||||
"web-strategies"
|
||||
],
|
||||
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
|
||||
"assignment": null,
|
||||
"parallel_policy": "Pinned shared DTOs and draft admission contract. Isolated backend and frontend owners; root owns existing fixture/browser integration/planning, independent read-only reviewer.",
|
||||
"assignment": "/root",
|
||||
"branch": null,
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [
|
||||
"W04"
|
||||
],
|
||||
"integration_state": "validated_uncommitted",
|
||||
"integration_base": "8cca0ee588b55cf904f46199ccb65942de70ee99",
|
||||
"worktree": "/home/boki/repos/stock-bot",
|
||||
"implementation_slices": [
|
||||
{
|
||||
"owner": "/root/s04_controls_audit",
|
||||
"worktree": "/tmp/stock-bot-wave22.fPRkAC/backend",
|
||||
"scope": "Shared DTOs, saved catalog selection/validation, migration18 and execution gates, new API/PostgreSQL tests"
|
||||
},
|
||||
{
|
||||
"owner": "/root/s04_feed_audit",
|
||||
"worktree": "/tmp/stock-bot-wave22.fPRkAC/frontend",
|
||||
"scope": "Catalog/version/clone/comparison/forms and existing backtest draft UI with focused interaction tests"
|
||||
},
|
||||
{
|
||||
"owner": "/root",
|
||||
"scope": "Existing fixture compatibility, real browser catalog-to-draft workflow, integration/planning"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
|
|
@ -1477,7 +1496,7 @@
|
|||
"epic": "E6",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "blocked",
|
||||
"status": "ready",
|
||||
"dependencies": [
|
||||
"R01",
|
||||
"R10"
|
||||
|
|
@ -1546,7 +1565,7 @@
|
|||
"epic": "E6",
|
||||
"priority": "P0",
|
||||
"severity": "Critical",
|
||||
"status": "blocked",
|
||||
"status": "ready",
|
||||
"dependencies": [
|
||||
"F08",
|
||||
"S02",
|
||||
|
|
@ -1578,7 +1597,9 @@
|
|||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": []
|
||||
"release_gates": [
|
||||
"Explicit owner disposition of the simultaneous multi-asset mark/risk policy before canonical default activation"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "R06",
|
||||
|
|
@ -1732,7 +1753,7 @@
|
|||
"epic": "E6",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "review",
|
||||
"status": "done",
|
||||
"dependencies": [
|
||||
"R01"
|
||||
],
|
||||
|
|
@ -1754,11 +1775,11 @@
|
|||
"assignment": "/root",
|
||||
"branch": null,
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"completed_commit": "8cca0ee588b55cf904f46199ccb65942de70ee99",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_base": "4a2e5ad362f7746a45a694dbcd9c51efac390526",
|
||||
"integration_state": "validated_uncommitted",
|
||||
"integration_state": "validated_committed",
|
||||
"worktree": "/home/boki/repos/stock-bot",
|
||||
"implementation_slices": [
|
||||
{
|
||||
|
|
@ -6855,5 +6876,136 @@
|
|||
"f90476a79b0df259a204bbc2f2015b2b6a8e582a8771729f48775cb18b4bac65"
|
||||
],
|
||||
"next": "After acceptance/commit, R02 delivers the strategy catalog UI and version-aware backtest setup without claiming retained-artifact execution before R05. Performance remains deferred."
|
||||
},
|
||||
"twenty_second_wave": [
|
||||
"R02"
|
||||
],
|
||||
"twenty_second_wave_base": "8cca0ee588b55cf904f46199ccb65942de70ee99",
|
||||
"twenty_second_wave_notes": [
|
||||
"R10 accepted and committed; R02 catalog and save-only versioned templates authorized.",
|
||||
"No catalog version execution, run snapshots or default cutover until R05. All versions remain non-runnable independently of review approval.",
|
||||
"Exact version+normalized parameters persisted separately from execution config; legacy/catalog mode conversion forbidden, current independent legacy workflows remain supported.",
|
||||
"No performance work, benchmarks, new-wave commits/pushes/PRs or paper/live operations."
|
||||
],
|
||||
"twenty_second_wave_validation": {
|
||||
"status": "validated_uncommitted",
|
||||
"log_directory": "/tmp/stock-bot-wave22.fPRkAC",
|
||||
"source_hashes": {
|
||||
"apps/stock/config/src/contracts/backtest.ts": "6c01dc72f8bde73b0ec4357a0a2293560b749f7246e145c2f3f62e92f383e810",
|
||||
"apps/stock/config/src/contracts/strategy.ts": "490cf68d955e622a28733452508d540060cc4df341036ecb32269b9c533887b2",
|
||||
"apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts": "f15195b3c3108f33e5d78d1a0bdf52c5d923a867b43e02989dadeb9ed428b82f",
|
||||
"apps/stock/web-api/src/migrations/migration-runner.ts": "c573bf2a7e9eae38f422c0352c9f0f7975a9380841805addf519174bb66dfadc",
|
||||
"apps/stock/web-api/src/routes/backtests-v2.routes.ts": "ec5610a79d96e92a0f033f336024eff051fe19f2b0d4cdccb4f57a5da6d9f603",
|
||||
"apps/stock/web-api/src/services/backtest-v2.service.ts": "d81494606741335096f872e872a6b2d64bfb65eac361840ec8556e437717e474",
|
||||
"apps/stock/web-api/src/services/backtest.service.ts": "c2e8dbedca288be928f3aa68e5b31c8c49776efd2cac8c646ae328d77d8aa5ce",
|
||||
"apps/stock/web-api/src/services/dataset-catalog.service.ts": "0c12046adaa0ed3886d25f314a5da416e244be0bd21fefe0de8cc23e9a093a41",
|
||||
"apps/stock/web-api/src/services/strategy-catalog.service.ts": "000b23fa1cbd78c9693c5beaa0cb69b17064c7f8eda5ba5b59fb33f37f5cdfd1",
|
||||
"apps/stock/web-app/src/app/App.tsx": "abf33f3a675ccbc6c88d5b08b1e5d31efb61e3b25c62cbf6482b327909ede69d",
|
||||
"apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx": "83db281e6160dc3ed0ae7f34a62ffba27b8021267b48148d91c73a52acaad92a",
|
||||
"apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx": "44093e2efb5b5ca2e84a82381ec3495b1df9adf4d2698b66720297ad655beada",
|
||||
"apps/stock/web-app/src/features/backtest/components/BacktestConfiguration.tsx": "11abd70aec6ac20ffbb3389746d084aca798a5ff284430457a6b6690008ac3af",
|
||||
"apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx": "8afd246afe647e08412d14d556a566586cc4cd4e1a0e496c0970d70cead74d32",
|
||||
"apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx": "1dc8619e659670d477d4a411840f0819c65be64b1f4dae86a6128c06fc5ed38c",
|
||||
"apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts": "da35dac1cebaf3e36a5d6a6ccb9d59760187298fc6a4f9e9ac6c94bd184454bd",
|
||||
"apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts": "d331cefe99209f09e12b79fc313a408087b9f55bcc1d6f97de1a53eb56412e85",
|
||||
"apps/stock/web-app/src/features/backtest/types/backtest.types.ts": "d7965fc66fd43f65811e50cc4df5ad3fac9655c1bc2cfaa838316a7bb8fe9f4f",
|
||||
"apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx": "3d6f4fad802bf2e63d1d730110f5fd76f7cf4da9bd3d4092b5c394e83893fbee",
|
||||
"apps/stock/web-app/src/features/strategies/StrategyListPage.tsx": "5fedd203ee945f59adb22b01e93eb5b61f5bdebeb5dfa5a3d02c06e01ad20bd4",
|
||||
"apps/stock/web-app/src/features/strategies/components/StrategyParameterForm.tsx": "d532d8af8dcfc3c6d62424138db4fae2b356704f6143c53b6ce8ecf16d3473f4",
|
||||
"apps/stock/web-app/src/features/strategies/components/StrategySelection.tsx": "42026ae8c87ef90c617a61917dfd874d5b83f0373b22d74128285007f8553be5",
|
||||
"apps/stock/web-app/src/features/strategies/components/useUnsavedWarning.ts": "9029a84d183803a4125b7c5808070ad69ad928c0dd4773cf30e376d3e81a326f",
|
||||
"apps/stock/web-app/src/features/strategies/index.ts": "0d3a6b0010b25f739c2ff2753bbdd8f5cc118e73e1f6b7e95f559cb8336cfacf",
|
||||
"apps/stock/web-app/src/features/strategies/services/strategyApi.ts": "be7dcd0226ec8c4cd3307643b385540ab060bbeddd1156a547c9845f74d33023",
|
||||
"database/postgres/init/18-backtest-strategy-versions.sql": "ad60e1d33be3131ddc5df34e3adcdb50c0efa7e12c2adbbbee8d132c92b5d240",
|
||||
"libs/core/types/src/index.ts": "2b9e3f1cc9f93ad5342a7064a3d8045688f33a8417c0a6e68eeaace01056d5d9",
|
||||
"libs/core/types/src/strategy-catalog.ts": "8c1ccca63c4c32ebd34f9f2fa2813014a874c4d0378c96512e854e0f4160900e",
|
||||
"test/e2e/fixture.ts": "0d9360e1eb3bddfb86ba4619d9e20e8c427faba98a67c654377ab286809075bf",
|
||||
"test/e2e/workbench.test.ts": "472ecf91b5b2f6c591f4cac9ae441243b32f3a2bc0c1fec5226734253b140dfa",
|
||||
"test/integration/backtest-workflow.test.ts": "7abdfb22370554619946728e9e7e33c4c90839aec7dba7b401e8e8a4981c7cac",
|
||||
"test/integration/catalog-backtest-contract.test.ts": "df6a15add6305586a483fe52f6bf2253ea3913a4c26d5b8b4f981c1909928d64",
|
||||
"test/integration/strategy-workbench.test.tsx": "d28f30f773724caa8c628c7b361976bd97df84ec9a7495ffe572be76fbb3a151",
|
||||
"test/postgres/catalog-backtest-drafts.test.ts": "2e15de1732d0820b3bab5fafa128a7e0cec3b34edfd3ddae9b9dcfe99e71549d",
|
||||
"test/postgres/dataset-catalog.test.ts": "13e0f3f0256b9bdcc542709e14b83cc85ce9225b49684880b6725c59c94acc91",
|
||||
"test/postgres/durable-backtest.test.ts": "b5436a2aa3cbbf7fccaf0cc715df113d8abbb746575726d548c9f3455e9df5fd",
|
||||
"test/postgres/migration-runner.test.ts": "a9a866a8a1054e3bda525d1e9c64826f72ff9f42e8513599ecc82947010adee8",
|
||||
"test/postgres/research-retention.test.ts": "86560c30b62c0af4664c5d9775594cce294e1b32083bece4566686dd57f1e78b",
|
||||
"test/postgres/research-runtime-isolation.test.ts": "ca5a84728ee36426a2d1955ff997ac3119d51c61ec605c9157ef7885dd6addc7"
|
||||
},
|
||||
"independent_review": {
|
||||
"owner": "/root/s03_review",
|
||||
"outcome": "Final G1/G2/G3 signoff from /root/s03_review: no remaining must-fix findings; all 39 final hashes match, no unlisted source changes. Reviewed artifact/parameter custody, admission gates, clone identity, settings reset and suite-owned Chromium/context cleanup. Reviewer inspected green full-check, database and unfiltered browser logs; ran no tests/builds. Integration owner executed all recorded gates.",
|
||||
"backend_archive_sha256": "8d4f58e353649399ffaf5bbf95720151e6972dae9e5d9a4c9b7427bc31ffc78f",
|
||||
"frontend_base_archive_sha256": "63dedea37e23368d3c4cd942961773597680bf70a053f4b22f8f74137ec97fba",
|
||||
"frontend_clone_delta_sha256": "4acccf336fcc50ef6dc9b23fdda8ada972b42ffb7e2114a005bc8d08cc3b5b35",
|
||||
"frontend_settings_delta_sha256": "b129d4067f13359f0147d079facea5566b2bd9da0a5d55eae855ed08960e4889",
|
||||
"source_manifest_sha256": "05d8a9fa9ef6d6b99444bf63b4ff5c62a1e2a3baefc44d27fc7d31968467bd84"
|
||||
},
|
||||
"checks": [
|
||||
{
|
||||
"command": "CARGO_BUILD_JOBS=2 bun run check",
|
||||
"log": "/tmp/stock-bot-wave22.fPRkAC/check-final.log",
|
||||
"outcome": "All repository checks passed: build/source/contracts, 93 tooling/12168 assertions, 43 utility/86, 44 calculation/2285, 541 integration/4685, 150 Rust (4 manual ignored), lint and secret audit. No application source changed afterward; final browser-only lifecycle changes passed strict test types, scoped lint/format and the full browser gate."
|
||||
},
|
||||
{
|
||||
"command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32827/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32828/15 bun run test:postgres",
|
||||
"log": "/tmp/stock-bot-wave22.fPRkAC/postgres-final.log",
|
||||
"outcome": "137 tests / 1052 assertions passed across all 15 PostgreSQL/Redis files. Catalog draft validation/edit/archive locking and API/repository/SQL admission rejection; additive migration compatibility; existing retention, idempotency, lease/recovery, paper custody and runtime isolation."
|
||||
},
|
||||
{
|
||||
"command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:napi",
|
||||
"log": "/tmp/stock-bot-wave22.fPRkAC/native-release-final.log",
|
||||
"outcome": "Release addon restored; matches checkout release library and prior wave release hash. No Rust source or financial policy changes."
|
||||
},
|
||||
{
|
||||
"command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32827/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32828/15 bun run test:e2e",
|
||||
"log": "/tmp/stock-bot-wave22.fPRkAC/e2e-isolated-contexts.log",
|
||||
"outcome": "All 8 workflows / 117 assertions passed unfiltered, without retries, against fresh same-origin UI build and release addon. Catalog create/edit, exact validation, save/reopen, settings save/reset, immutable publication, safe bundle display, clone lineage, and no run/outbox; existing native/frozen-dataset/submission/retention workflows remain green."
|
||||
},
|
||||
{
|
||||
"command": "bunx tsc --project /tmp/stock-bot-wave22.fPRkAC/tests-tsconfig.json --noEmit",
|
||||
"log": "/tmp/stock-bot-wave22.fPRkAC/strict-tests-final.log",
|
||||
"outcome": "Passed strict new catalog contract/component/PostgreSQL tests and changed modern migration/dataset/retention/browser fixtures. This is not a broad strict claim for older legacy harnesses."
|
||||
},
|
||||
{
|
||||
"command": "bunx eslint test/postgres/catalog-backtest-drafts.test.ts test/postgres/dataset-catalog.test.ts test/postgres/migration-runner.test.ts test/postgres/research-retention.test.ts test/integration/catalog-backtest-contract.test.ts test/integration/strategy-workbench.test.tsx test/e2e/fixture.ts test/e2e/workbench.test.ts",
|
||||
"log": "/tmp/stock-bot-wave22.fPRkAC/scoped-lint-final.log",
|
||||
"outcome": "Passed; final browser lifecycle edits also passed focused ESLint."
|
||||
},
|
||||
{
|
||||
"command": "bunx prettier --check <changed TS/TSX>; git diff --check",
|
||||
"logs": [
|
||||
"/tmp/stock-bot-wave22.fPRkAC/scoped-format.log",
|
||||
"/tmp/stock-bot-wave22.fPRkAC/format-last.log"
|
||||
],
|
||||
"outcome": "Passed; final two browser files rechecked after lifecycle fix. Manifest/reference/hash validation recorded separately."
|
||||
},
|
||||
{
|
||||
"command": "Validate manifest IDs/task paths/dependency DAG, exact changed-source/hash inventory, HEAD and release-addon identity; git diff --check",
|
||||
"outcome": "Passed: 55 unique IDs, valid references, acyclic task graph, 39 matching reviewed implementation/test hashes, 5 planning artifacts, HEAD 8cca0ee, release addon matches checkout library. No unlisted source changes."
|
||||
}
|
||||
],
|
||||
"native_release_sha256": "ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103",
|
||||
"scope": "39 application/shared-contract/migration/test files; one additive migration, existing catalog APIs and React backtest workflow. No new service, compiler/editor, financial simulator or engine semantics.",
|
||||
"limitations": [
|
||||
"Every catalog version remains non-runnable, including approved built-ins. R05 must verify executable artifact identity and connect durable canonical execution; candidates also require A02 isolation. No catalog request_snapshot, run or outbox is created in R02.",
|
||||
"Independent legacy name-based runs retain existing economics/provenance qualifications; saving a catalog setup does not certify performance or make it a legacy alias.",
|
||||
"Source comparison shows retained bundled JavaScript and schema/identity metadata, not reconstructed original TypeScript. Publication remains repository/offline tooling or existing artifact APIs; no upload/editor UI.",
|
||||
"Version-linked run/deployment histories are explicitly unavailable until integration; no inference from name-based legacy runs.",
|
||||
"Unsaved warnings cover local discard actions and document unload; no application-wide route-blocking framework. Clone retries preserve a frozen key/body during the mounted detail view, not across reloads.",
|
||||
"R05 multi-asset default activation still requires explicit owner disposition of simultaneous-mark risk. No trading or default activation in this wave."
|
||||
],
|
||||
"environment_notes": [
|
||||
"Initial PostgreSQL regression run exposed four legacy test helpers spreading the expanded response DTO into legacy input. Helpers now explicitly project definition input; parser null-marker rejection remains intact. Full suite rerun passed.",
|
||||
"Initial browser helper selected the first select after the new mode select was added; it now selects the labelled Legacy strategy. Exact version loading is awaited before assertions.",
|
||||
"Repeated serial Chromium launch/close cycles lost the control pipe, including during existing native smoke and ordinary catalog validation. Isolated workflows passed; diagnostic logs support likely runtime pipe lifecycle interference, not proven native-worker causation. The suite now owns one Chromium process and each fixture closes its own fresh context before its server/queue/database cleanup. The final complete suite passes with no retries or swallowed disconnects; production worker code is unchanged.",
|
||||
"Native worker/browser and disposable database checks needed sandbox escalation. Development services were untouched. Worktrees and logs retained.",
|
||||
"Strict checks cover new/modern tests; pre-existing broad legacy-harness strict errors from prior waves were not suppressed or expanded into this task.",
|
||||
"Exact disposable fixture containers stopped after verification. No profiling, performance benchmarks, new-wave commit, push, PR or trading/default activation."
|
||||
],
|
||||
"stopped_fixture_ids": [
|
||||
"25dcbeefeecdf21189f42b6d2694acf51f84878e3c4bedcb21494f2bf4c5fcee",
|
||||
"ea7d33b519a35b14ca493e460734a70d98937507a29406765edff53688f12b9a"
|
||||
],
|
||||
"next": "After acceptance/commit, R05: integrate verified retained executable identity, frozen provenance and existing canonical reports with the durable runner. Begin with a trusted-built-in single-asset slice, without claiming all R05 complete or enabling candidates/multi-asset default. R03 is independently ready. Performance remains deferred."
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -62,7 +62,7 @@ Keep migrations additive and previous results readable. Do not add a switch that
|
|||
|
||||
## Web/API contract and user states
|
||||
|
||||
- API: R01 catalog/version endpoints plus version ID in saved backtest template/request snapshot.
|
||||
- API: R01 catalog/version endpoints plus exact version ID and normalized parameters in saved backtest templates. R05 owns versioned run admission and immutable request snapshots; R02 creates no catalog run/outbox.
|
||||
- Backend/data dependencies: R01 schema; current engine capability metadata. Unsupported version/runtime combinations fail before submit.
|
||||
- Loading/error/empty behavior: Skeleton list/detail; no-strategies create CTA; schema error next to parameter; retry fetch; unsaved edit warning.
|
||||
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
|
||||
|
|
@ -70,3 +70,24 @@ 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.
|
||||
|
||||
## Wave22 execution contract
|
||||
|
||||
R10 committed `8cca0ee`; owner authorized R02. Reuse existing catalog APIs, React routes and backtest templates. Publish author code through existing repository/artifact APIs; no browser IDE or new compilation/runtime service. Read-only artifact comparison shows retained bundled JavaScript, schema and identities, not reconstructed original TypeScript.
|
||||
|
||||
Migration18 adds `strategy_version_id` (restrictive FK) and separate scalar `strategy_parameters`. The saved template uses `strategy: 'catalog'`; the version never becomes a legacy alias. Creation requires explicit `autoStart:false`. Save validates retained checksums, exact version parameters, data/execution settings and selected-dataset compatibility. Preserve omitted selection on partial updates; an explicit new version requires explicit parameters. Both legacy/catalog mode conversions are rejected; create another template instead. New selections reject archived families under their row lock; existing references remain readable and editable unless the template itself is archived.
|
||||
|
||||
V2 submission rejects before run/outbox insertion; V1 rejects catalog input before saving. Direct repository marker checks and the existing SQL run-admission trigger close alternate paths. Legacy receipt replay remains first. Keep the pure legacy parser's pre-strip rejection intact, including null version fields. Map trusted legacy DTOs explicitly instead of weakening that guard.
|
||||
|
||||
All versions remain non-runnable, including approved built-ins. The UI supports exact version selection, schema fields, server validation and saved setups with fresh submission disabled. Existing supported legacy strategies remain a separate qualified workflow. No inferred version/deployment histories from names; show absent integration honestly. Schema forms preserve optional omissions, false, zero, typed enums and decimal strings. Retained bundle text is never executed. Metadata/clone drafts preserve input and use explicit discard warnings; clone retries retain their original key/body.
|
||||
|
||||
|
||||
## Validated handoff — 2026-10-23
|
||||
|
||||
Implemented the pinned Wave22 contract in 39 source/shared-contract/migration/test files. Catalog family metadata, immutable version selection, clone retries, exact schema validation, escaped bundle comparison and existing save/reopen/settings flows are integrated. API, repository and SQL gates keep all catalog versions non-runnable; legacy receipt ordering and supported legacy runs remain unchanged. Migration 18 retains version/parameters without creating catalog runs or request snapshots.
|
||||
|
||||
Review fixes include explicit empty-string versus omitted parameters, normalized value display, frozen clone source identity during navigation, catalog settings omitting legacy pacing, and authoritative archive/restore resets that invalidate stale parameter validation. Browser coverage proves exact saved values, immutable selection after new publication, clone lineage, safe bundle display, and zero runs/outbox. Each browser fixture has its own context/server/schema/queue within one suite-owned Chromium process after repeated driver teardown exposed pipe loss under Bun 1.2.17; no retry hides failures.
|
||||
|
||||
Validation: full repository checks passed (541 integration, 150 Rust, 93 tooling, 43 utility, 44 calculation plus build/types/contracts/lint/secrets); full PostgreSQL/Redis 137 tests/1052 assertions; all 8 browser workflows/117 assertions; strict new/modern test types and scoped lint/format/diff checks. Source hashes, commands, logs, independent review and stopped fixture IDs are in `manifest.json` → `twenty_second_wave_validation`. Release addon matches the prior wave; Rust financial source is unchanged.
|
||||
|
||||
Read-only source is retained bundled JavaScript, not original TypeScript. Code publication stays in repository/offline tooling or existing artifact APIs; no embedded editor/upload UI. Version-linked backtest/deployment histories remain unavailable. Unsaved warnings cover local discard actions/document unload, not a new global routing framework. Clone retry identity lasts within the mounted detail view. Current legacy economics remain explicitly qualified. R05 owns verified retained-artifact execution and full provenance; A02 gates candidates, and the multi-asset default policy remains unresolved. No R02 commit/push/PR, default cutover, trading activation or performance work.
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ Scheduling source of truth: [manifest entry R05](../manifest.json). No task is a
|
|||
|
||||
- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107).
|
||||
- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190).
|
||||
- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114).
|
||||
- **FIN-05 — Updated after S01/S02/F08:** Canonical TypeScript decisions on Rust sessions and canonical reports already exist. The durable runner still calls the legacy `runBacktest` path; the canonical worker constructs the current built-in implementation by identity. R05 must connect retained executable identity and canonical results to durable admission, not introduce another strategy engine. [native-worker.ts:26](../../../../apps/stock/orchestrator/src/backtest/native-worker.ts#L26), [strategy-runtime.ts:224](../../../../apps/stock/orchestrator/src/backtest/strategy-runtime.ts#L224), [canonical-result.ts:37](../../../../apps/stock/orchestrator/src/backtest/canonical-result.ts#L37), [BacktestRunner.ts:191](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L191).
|
||||
|
||||
## Intended behavior and implementation scope
|
||||
|
||||
|
|
@ -16,6 +16,8 @@ Freeze strategy/model artifact IDs, parameters, seed, code/lockfile/build hashes
|
|||
|
||||
Consume F08's additive canonical analytics/report contract here. Version the persisted/public projection so canonical fractions, genuine zero exposure and null reasons bypass legacy percentage conversion/placeholder suppression. Preserve owner books and distinguish fills from round trips. Additional position valuations needed by the UI must come from Rust or be explicitly unavailable; do not invent marks, average-price basis or unrealized P&L in TypeScript merely to satisfy the old DTO. Keep historical readers unchanged and prove reopen/render compatibility during this cutover.
|
||||
|
||||
R02 now saves catalog versions and validated parameters with execution blocked at API, repository and SQL boundaries. Replace those gates only for verified supported execution. Before parallel implementation, pin the executable artifact/build binding: a retained bundle hash must never certify execution of a different current `createBuiltinStrategy` implementation. Verify the exact executable identity before the first decision; mismatches fail closed without a legacy-name fallback. Start with a trusted built-in single-asset vertical slice, retaining candidate isolation and multi-asset policy gates. That milestone alone does not complete all R05 requirements or authorize default activation.
|
||||
|
||||
Measurable benefit: Creates reproducible, project-gated runs usable by humans and AI.
|
||||
|
||||
## Exclusions
|
||||
|
|
@ -43,12 +45,14 @@ Parallel eligibility: only with disjoint actual files and reserved write locks;
|
|||
|
||||
- Changing template, strategy source or provider history after dataset freezing cannot alter an admitted run. A source query alone is not labelled a frozen dataset.
|
||||
- No strategy decision executes before artifact verification and atomic dataset binding; failed preparation remains diagnosed and retry-safe.
|
||||
- A retained-version/current-build mismatch rejects before execution; successful provenance identifies the executable that actually ran. Changing the current built-in implementation cannot silently change a retained version's behavior.
|
||||
- New results declare financialEngine=rust and strategyExecution separately; correctness-gate evidence requires approved engine/data gates, not a UI flag.
|
||||
- Before making canonical multi-asset research the default, obtain explicit owner disposition of sequential equal-time mark risk: either accept the disclosed versioned approximation or approve a coordinated atomic-mark policy/implementation with independent fixtures. F04/F05 currently evaluate each ordered mark; F06 demonstrates offsetting simultaneous moves can latch intermediate loss/drawdown halts. A passing deterministic replay suite alone does not resolve this material modeling issue. Single-asset component work and additive native integration need not wait for this decision.
|
||||
|
||||
## Mandatory tests
|
||||
|
||||
- mutate_template_after_submit, freeze_before_first_decision, frozen_seed_replay, provider_change_after_dataset_bind.
|
||||
- retained_artifact_executable_binding, current_builtin_mismatch_rejected_before_decision, catalog_version_never_falls_back_to_legacy_name.
|
||||
- Full durable runner restart/lease/cancel suite and result contract compatibility.
|
||||
- Canonical reporting fractions/zero/null reasons, owner attribution and fill-versus-round-trip semantics survive persistence/reopen/UI rendering; existing legacy rows retain their prior interpretation.
|
||||
- Multi-asset default activation rejects while the mark-policy disposition is absent; accepted policy/version/limitations are frozen in provenance, with offsetting-mark regression evidence.
|
||||
|
|
|
|||
|
|
@ -135,6 +135,13 @@ export type {
|
|||
StrategyParameterSchema,
|
||||
StrategyVersionPackage,
|
||||
} from './strategy-version';
|
||||
export type {
|
||||
StrategyPackageMetadata,
|
||||
StrategyRecord,
|
||||
StrategyVersionSummary,
|
||||
StrategyReviewEvent,
|
||||
ParameterValidationResult,
|
||||
} from './strategy-catalog';
|
||||
export type {
|
||||
InstrumentIdentity,
|
||||
HistoricalDataPolicy,
|
||||
|
|
|
|||
45
libs/core/types/src/strategy-catalog.ts
Normal file
45
libs/core/types/src/strategy-catalog.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import type { StrategyParameterValue, StrategyVersionPackage } from './strategy-version';
|
||||
|
||||
export type StrategyPackageMetadata = Omit<
|
||||
StrategyVersionPackage,
|
||||
'artifact' | 'dependencyLock'
|
||||
> & {
|
||||
artifact: Omit<StrategyVersionPackage['artifact'], 'content'>;
|
||||
dependencyLock: Omit<StrategyVersionPackage['dependencyLock'], 'content'>;
|
||||
};
|
||||
export interface StrategyRecord {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
ownerPrincipal: 'operator' | 'service';
|
||||
updatedBy: 'operator' | 'service';
|
||||
archived: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
export interface StrategyVersionSummary {
|
||||
id: string;
|
||||
strategyId: string;
|
||||
ordinal: number;
|
||||
parentVersionId: string | null;
|
||||
createdBy: 'operator' | 'service';
|
||||
origin: 'candidate' | 'builtin';
|
||||
createdAt: string;
|
||||
package: StrategyPackageMetadata;
|
||||
reviewStatus: 'pending' | 'approved' | 'revoked';
|
||||
runnable: false;
|
||||
reason: string;
|
||||
}
|
||||
export interface StrategyReviewEvent {
|
||||
id: string;
|
||||
ordinal: number;
|
||||
decision: 'approve' | 'revoke';
|
||||
actor: 'operator';
|
||||
reason: string;
|
||||
createdAt: string;
|
||||
}
|
||||
export interface ParameterValidationResult {
|
||||
parameters: Record<string, StrategyParameterValue>;
|
||||
runnable: false;
|
||||
reason: string;
|
||||
}
|
||||
|
|
@ -3,7 +3,7 @@ import { EventEmitter } from 'node:events';
|
|||
import { readFileSync } from 'node:fs';
|
||||
import type { ServerWebSocket } from 'bun';
|
||||
import { Pool } from 'pg';
|
||||
import { chromium, type Page } from 'playwright';
|
||||
import type { Browser, Page } from 'playwright';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import { HandlerRegistry } from '@stock-bot/handler-registry';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
|
|
@ -27,10 +27,12 @@ import {
|
|||
handleWebSocketConnection,
|
||||
} from '../../apps/stock/web-api/src/routes/websocket.routes';
|
||||
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
|
||||
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
import {
|
||||
getWebSocketHandler,
|
||||
type RunSocketData,
|
||||
} from '../../apps/stock/web-api/src/websocket/run-updates';
|
||||
import { seedBuiltinCatalog } from '../../scripts/seed-builtin-strategies';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('browser-fixture');
|
||||
|
|
@ -214,7 +216,7 @@ class FixtureEngine extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
export async function fixture(native = false) {
|
||||
export async function fixture(browser: Browser, native = false) {
|
||||
const database = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const redisUrl = process.env.BACKTEST_TEST_REDIS_URL;
|
||||
if (
|
||||
|
|
@ -285,7 +287,9 @@ export async function fixture(native = false) {
|
|||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
@ -399,6 +403,8 @@ export async function fixture(native = false) {
|
|||
(!pathname.startsWith('/api/v2/backtests') &&
|
||||
!pathname.startsWith('/api/v2/runs') &&
|
||||
!pathname.startsWith('/api/v2/datasets') &&
|
||||
!pathname.startsWith('/api/v2/strategies') &&
|
||||
!pathname.startsWith('/api/v2/strategy-versions') &&
|
||||
pathname !== '/api/auth/session') ||
|
||||
/\/(pause|resume|speed)$/.test(pathname)
|
||||
) {
|
||||
|
|
@ -458,9 +464,8 @@ export async function fixture(native = false) {
|
|||
}
|
||||
});
|
||||
const origin = `http://127.0.0.1:${server.port}`;
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
cleanup.push(() => browser.close());
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 1080 } });
|
||||
cleanup.push(() => context.close());
|
||||
await context.route('**/*', route => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.origin !== origin && !['data:', 'blob:'].includes(url.protocol)) {
|
||||
|
|
@ -520,10 +525,19 @@ export async function fixture(native = false) {
|
|||
await target.getByRole('button', { name: 'Sign in', exact: true }).click();
|
||||
await visible(target, 'Create and manage backtest configurations');
|
||||
};
|
||||
const request = async (path: string, method = 'GET', body?: unknown) => {
|
||||
const request = async (
|
||||
path: string,
|
||||
method = 'GET',
|
||||
body?: unknown,
|
||||
headers: Record<string, string> = {}
|
||||
) => {
|
||||
const response = await fetch(origin + path, {
|
||||
method,
|
||||
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
...headers,
|
||||
},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
if (!response.ok) {
|
||||
|
|
@ -546,6 +560,7 @@ export async function fixture(native = false) {
|
|||
login,
|
||||
close,
|
||||
unexpectedNetwork,
|
||||
seedCatalog: () => seedBuiltinCatalog(new StrategyCatalogService(container)),
|
||||
};
|
||||
} catch (error) {
|
||||
try {
|
||||
|
|
@ -560,7 +575,7 @@ export async function fixture(native = false) {
|
|||
export async function createInBrowser(page: Page, name: string, run = false) {
|
||||
await page.getByRole('button', { name: 'New Backtest', exact: true }).click();
|
||||
await page.getByPlaceholder('My Strategy Backtest').fill(name);
|
||||
await page.locator('select').first().selectOption('moving-average');
|
||||
await page.getByLabel('Legacy strategy', { exact: true }).selectOption('moving-average');
|
||||
await page.locator('input[type="date"]').nth(0).fill('2024-01-01');
|
||||
await page.locator('input[type="date"]').nth(1).fill('2024-03-15');
|
||||
await page.getByRole('button', { name: run ? 'Save and run' : 'Save', exact: true }).click();
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { expect, test } from 'bun:test';
|
||||
import type { Request } from 'playwright';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { afterAll, beforeAll, expect, test } from 'bun:test';
|
||||
import { chromium, type Browser, type Request } from 'playwright';
|
||||
import {
|
||||
fixture as createFixture,
|
||||
createInBrowser,
|
||||
fixture,
|
||||
gate,
|
||||
retainDataset,
|
||||
submitInBrowser,
|
||||
|
|
@ -11,6 +11,18 @@ import {
|
|||
visible,
|
||||
} from './fixture';
|
||||
|
||||
// Repeated launch/close cycles lost Chromium's control pipe under Bun 1.2.17.
|
||||
// Keep one suite-owned process; each fixture still owns
|
||||
// a fresh context, server, database schema and queue. No retries hide failures.
|
||||
let browser: Browser;
|
||||
beforeAll(async () => {
|
||||
browser = await chromium.launch({ headless: true });
|
||||
});
|
||||
afterAll(async () => {
|
||||
await browser?.close();
|
||||
});
|
||||
const fixture = (native = false) => createFixture(browser, native);
|
||||
|
||||
// Serial by design: the production WebSocket projection has a process-local handler.
|
||||
test('browser_saved_run_lifecycle', async () => {
|
||||
const f = await fixture();
|
||||
|
|
@ -479,3 +491,213 @@ test('browser_archive_retains_history_and_restore_admits_new_work', async () =>
|
|||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
|
||||
const f = await fixture();
|
||||
f.page.on('dialog', dialog => void dialog.accept());
|
||||
try {
|
||||
await f.login();
|
||||
await f.page.goto(`${f.origin}/strategies`);
|
||||
await visible(f.page, /No strategies found/);
|
||||
await f.page.getByRole('button', { name: 'New strategy', exact: true }).click();
|
||||
await f.page.getByLabel('Strategy name', { exact: true }).fill('Browser research family');
|
||||
await f.page
|
||||
.getByLabel('Strategy description', { exact: true })
|
||||
.fill('A hypothesis awaiting evidence.');
|
||||
await f.page.getByRole('button', { name: 'Create strategy', exact: true }).click();
|
||||
await f.page.waitForURL(/\/strategies\/[^/]+$/);
|
||||
await visible(f.page, /No immutable versions have been published/);
|
||||
await f.page
|
||||
.getByLabel('Strategy description', { exact: true })
|
||||
.fill('Revised hypothesis, still unvalidated.');
|
||||
await f.page.getByRole('button', { name: 'Save metadata', exact: true }).click();
|
||||
await until(
|
||||
async () =>
|
||||
(await f.request('/api/v2/strategies')).strategies[0]?.description ===
|
||||
'Revised hypothesis, still unvalidated.',
|
||||
'saved strategy metadata'
|
||||
);
|
||||
|
||||
const seeded = await f.seedCatalog();
|
||||
const selected = seeded.find(item => item.package.program.strategyId === 'sma_crossover')!;
|
||||
const versionUrl = `${f.origin}/strategies/${selected.strategyId}/versions/${selected.id}`;
|
||||
await f.page.goto(versionUrl);
|
||||
await f.page.getByLabel('fastPeriod', { exact: true }).fill('20');
|
||||
await f.page.getByLabel('slowPeriod', { exact: true }).fill('10');
|
||||
const invalid = f.page.waitForResponse(response =>
|
||||
response.url().endsWith(`/strategy-versions/${selected.id}/validate`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
expect((await invalid).status()).toBe(400);
|
||||
expect(
|
||||
await f.page.getByRole('button', { name: 'Use in backtest', exact: true }).isDisabled()
|
||||
).toBe(true);
|
||||
await f.page.getByLabel('fastPeriod', { exact: true }).fill('2');
|
||||
await f.page.getByLabel('slowPeriod', { exact: true }).fill('5');
|
||||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
await visible(
|
||||
f.page,
|
||||
'Parameters validated for this immutable version. Execution remains unavailable.'
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Use in backtest', exact: true }).click();
|
||||
await f.page.waitForURL(
|
||||
url =>
|
||||
url.pathname === '/backtests' && url.searchParams.get('strategyVersionId') === selected.id
|
||||
);
|
||||
await f.page.getByPlaceholder('My Strategy Backtest').fill('Pinned version browser draft');
|
||||
await until(
|
||||
async () =>
|
||||
(await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()) ===
|
||||
selected.id,
|
||||
'loaded exact immutable version selection'
|
||||
);
|
||||
expect(
|
||||
await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()
|
||||
).toBe(selected.id);
|
||||
await f.page.locator('input[type="date"]').nth(0).fill('2024-01-01');
|
||||
await f.page.locator('input[type="date"]').nth(1).fill('2024-03-15');
|
||||
expect(await f.page.getByLabel('fastPeriod', { exact: true }).inputValue()).toBe('2');
|
||||
expect(await f.page.getByLabel('slowPeriod', { exact: true }).inputValue()).toBe('5');
|
||||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
await visible(
|
||||
f.page,
|
||||
'Parameters validated for this immutable version. Execution remains unavailable.'
|
||||
);
|
||||
expect(
|
||||
await f.page.getByRole('button', { name: 'Save and run', exact: true }).isDisabled()
|
||||
).toBe(true);
|
||||
await f.page.getByRole('button', { name: 'Save', exact: true }).click();
|
||||
await f.page.waitForURL(/\/backtests\/[^/?]+$/);
|
||||
const draftUrl = f.page.url();
|
||||
const draftId = draftUrl.split('/').at(-1)!;
|
||||
const saved = await f.request(`/api/v2/backtests/${draftId}`);
|
||||
expect(saved.strategy).toBe('catalog');
|
||||
expect(saved.strategyVersionId).toBe(selected.id);
|
||||
expect(saved.strategyParameters).toEqual({ fastPeriod: 2, slowPeriod: 5 });
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
|
||||
await expect(f.request(`/api/v2/backtests/${draftId}/runs`, 'POST', {})).rejects.toThrow('409');
|
||||
|
||||
// A later immutable publication must never move the saved selection to the newest version.
|
||||
const { package: retained } = await f.request(
|
||||
`/api/v2/strategy-versions/${selected.id}/artifact`
|
||||
);
|
||||
const changed = structuredClone(retained);
|
||||
changed.artifact.content +=
|
||||
'\n/* </pre><script>globalThis.__catalogBrowserExecuted=true</script> */\nglobalThis.__catalogBrowserExecuted=true;';
|
||||
changed.artifact.sha256 = createHash('sha256').update(changed.artifact.content).digest('hex');
|
||||
const revision = await f.request(
|
||||
`/api/v2/strategies/${selected.strategyId}/versions`,
|
||||
'POST',
|
||||
{ package: changed },
|
||||
{ 'Idempotency-Key': randomUUID() }
|
||||
);
|
||||
await f.page.reload();
|
||||
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
||||
await until(
|
||||
async () =>
|
||||
(await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()) ===
|
||||
selected.id,
|
||||
'loaded exact immutable version selection'
|
||||
);
|
||||
expect(
|
||||
await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()
|
||||
).toBe(selected.id);
|
||||
expect(await f.page.getByLabel('fastPeriod', { exact: true }).inputValue()).toBe('2');
|
||||
const validateVisibleParameters = async () => {
|
||||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
await visible(
|
||||
f.page,
|
||||
'Parameters validated for this immutable version. Execution remains unavailable.'
|
||||
);
|
||||
};
|
||||
const saveVisibleSettings = async () => {
|
||||
const update = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'PUT' && response.url().endsWith(`/backtests/${draftId}`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Save', exact: true }).click();
|
||||
const response = await update;
|
||||
expect(response.status()).toBe(200);
|
||||
const updated = await response.json();
|
||||
expect(updated.strategyVersionId).toBe(selected.id);
|
||||
expect(updated.config).not.toHaveProperty('speedMultiplier');
|
||||
return updated;
|
||||
};
|
||||
await f.page.getByLabel('fastPeriod', { exact: true }).fill('3');
|
||||
await f.page.getByLabel('slowPeriod', { exact: true }).fill('7');
|
||||
await validateVisibleParameters();
|
||||
expect((await saveVisibleSettings()).strategyParameters).toEqual({
|
||||
fastPeriod: 3,
|
||||
slowPeriod: 7,
|
||||
});
|
||||
// Archive/restore replaces authoritative settings; stale validated child state must reset too.
|
||||
await f.page.getByLabel('fastPeriod', { exact: true }).fill('4');
|
||||
await f.page.getByLabel('slowPeriod', { exact: true }).fill('9');
|
||||
await validateVisibleParameters();
|
||||
await f.page.getByRole('button', { name: 'Archive backtest', exact: true }).click();
|
||||
await f.page.getByRole('button', { name: 'Confirm archive', exact: true }).click();
|
||||
await visible(f.page, 'Restore backtest');
|
||||
await f.page.getByRole('button', { name: 'Restore backtest', exact: true }).click();
|
||||
await f.page.getByRole('button', { name: 'Confirm restore', exact: true }).click();
|
||||
await visible(f.page, 'Archive backtest');
|
||||
await until(
|
||||
async () => (await f.page.getByLabel('fastPeriod', { exact: true }).inputValue()) === '3',
|
||||
'restored saved parameter state'
|
||||
);
|
||||
expect(await f.page.getByLabel('slowPeriod', { exact: true }).inputValue()).toBe('7');
|
||||
expect(await f.page.getByRole('button', { name: 'Save', exact: true }).isDisabled()).toBe(true);
|
||||
await f.page.getByLabel('fastPeriod', { exact: true }).fill('4');
|
||||
await f.page.getByLabel('slowPeriod', { exact: true }).fill('9');
|
||||
await validateVisibleParameters();
|
||||
expect((await saveVisibleSettings()).strategyParameters).toEqual({
|
||||
fastPeriod: 4,
|
||||
slowPeriod: 9,
|
||||
});
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
expect(await f.page.getByRole('button', { name: 'New Run', exact: true }).isDisabled()).toBe(
|
||||
true
|
||||
);
|
||||
expect(f.page.url()).toBe(draftUrl);
|
||||
await f.page.goto(
|
||||
`${f.origin}/strategies/${selected.strategyId}/versions/${revision.version.id}`
|
||||
);
|
||||
await f.page.getByLabel('Compare with version', { exact: true }).selectOption(selected.id);
|
||||
await visible(f.page, 'Different artifact bytes');
|
||||
expect(
|
||||
await f.page.getByLabel('Selected bundled JavaScript', { exact: true }).textContent()
|
||||
).toContain('__catalogBrowserExecuted');
|
||||
expect(await f.page.evaluate(() => Object.hasOwn(globalThis, '__catalogBrowserExecuted'))).toBe(
|
||||
false
|
||||
);
|
||||
|
||||
await f.page.goto(versionUrl);
|
||||
await f.page.getByRole('button', { name: 'Clone version', exact: true }).click();
|
||||
await f.page.getByLabel('Clone name', { exact: true }).fill('Browser candidate clone');
|
||||
const cloned = f.page.waitForResponse(response =>
|
||||
response.url().endsWith(`/strategy-versions/${selected.id}/clone`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Create clone', exact: true }).click();
|
||||
const cloneResponse = await cloned;
|
||||
expect(cloneResponse.status()).toBe(201);
|
||||
const clone = await cloneResponse.json();
|
||||
expect(clone.version.parentVersionId).toBe(selected.id);
|
||||
expect(clone.version.origin).toBe('candidate');
|
||||
expect(clone.version.reviewStatus).toBe('pending');
|
||||
expect(clone.version.runnable).toBe(false);
|
||||
await f.page.waitForURL(url => url.pathname.endsWith(`/versions/${clone.version.id}`));
|
||||
await f.page.getByLabel('Compare with version', { exact: true }).selectOption(selected.id);
|
||||
await visible(f.page, 'Identical artifact bytes');
|
||||
await f.page.reload();
|
||||
await f.page.getByLabel('Strategy version', { exact: true }).waitFor();
|
||||
expect(await f.page.getByLabel('Strategy version', { exact: true }).inputValue()).toBe(
|
||||
clone.version.id
|
||||
);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -75,7 +75,7 @@ async function fixture(
|
|||
});
|
||||
db.public
|
||||
.none(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
|
||||
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb, archived_at timestamptz,
|
||||
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb, archived_at timestamptz, strategy_version_id uuid, strategy_parameters jsonb,
|
||||
start_date timestamptz, end_date timestamptz, initial_capital numeric, config jsonb,
|
||||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW());
|
||||
CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id), run_number integer,
|
||||
|
|
|
|||
138
test/integration/catalog-backtest-contract.test.ts
Normal file
138
test/integration/catalog-backtest-contract.test.ts
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import {
|
||||
backtestRequestFromDefinition,
|
||||
backtestSettingsFromDefinition,
|
||||
CatalogBacktestDefinitionSchema,
|
||||
parseBacktestRequest,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
builtinCatalogDescriptors,
|
||||
parseStrategyVersionPackage,
|
||||
validateStrategyParameters,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service';
|
||||
|
||||
const definition = {
|
||||
name: 'Catalog setup',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: randomUUID(),
|
||||
strategyParameters: {},
|
||||
symbols: ['AAPL.US'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-02-01T00:00:00.000Z',
|
||||
initialCapital: 1000,
|
||||
config: { dataFrequency: '1d', commission: 0.002 },
|
||||
};
|
||||
describe('catalog draft and execution contracts', () => {
|
||||
test('shared settings validation is independent of execution and never merges strategy parameters', () => {
|
||||
const parsed = CatalogBacktestDefinitionSchema.parse({
|
||||
...definition,
|
||||
strategyParameters: { commission: 99 },
|
||||
});
|
||||
const settings = backtestSettingsFromDefinition(parsed);
|
||||
expect(settings).toMatchObject({
|
||||
commission: 0.002,
|
||||
slippage: 0.0001,
|
||||
symbols: ['AAPL.US'],
|
||||
dataFrequency: '1d',
|
||||
});
|
||||
expect(settings).not.toHaveProperty('strategy');
|
||||
expect(settings).not.toHaveProperty('strategyParameters');
|
||||
expect(() => backtestRequestFromDefinition(parsed)).toThrow('Retained strategy versions');
|
||||
for (const config of [
|
||||
{ ...definition.config, lookback: 5 },
|
||||
{ ...definition.config, strategyVersionId: randomUUID() },
|
||||
]) {
|
||||
expect(() => CatalogBacktestDefinitionSchema.parse({ ...definition, config })).toThrow();
|
||||
}
|
||||
expect(() => backtestSettingsFromDefinition({ ...definition, initialCapital: 0 })).toThrow();
|
||||
expect(() =>
|
||||
backtestSettingsFromDefinition({ ...definition, endDate: definition.startDate })
|
||||
).toThrow();
|
||||
});
|
||||
test('legacy parsers and direct repository refuse markers even when null or nested', async () => {
|
||||
const legacy = {
|
||||
mode: 'backtest',
|
||||
name: 'Legacy',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: definition.symbols,
|
||||
startDate: definition.startDate,
|
||||
endDate: definition.endDate,
|
||||
dataFrequency: '1d',
|
||||
initialCapital: 1000,
|
||||
};
|
||||
const database = {
|
||||
transaction: mock(async () => {
|
||||
throw new Error('Unexpected write');
|
||||
}),
|
||||
};
|
||||
const repository = new PostgresBacktestRunRepository(database);
|
||||
for (const marker of [
|
||||
{ strategy: 'catalog' },
|
||||
{ strategyVersionId: null },
|
||||
{ strategyVersionIds: [] },
|
||||
{ strategyParameters: {} },
|
||||
{ config: { strategyVersionId: null } },
|
||||
{ strategies: [{ name: 'sma-crossover', config: { strategyVersionId: 'retained' } }] },
|
||||
]) {
|
||||
const input = { ...legacy, ...marker };
|
||||
expect(() => parseBacktestRequest(input)).toThrow('Retained strategy versions');
|
||||
await expect(
|
||||
repository.start(input as ReturnType<typeof parseBacktestRequest>)
|
||||
).rejects.toThrow('Retained strategy versions');
|
||||
}
|
||||
expect(database.transaction.mock.calls).toHaveLength(0);
|
||||
const facade = new BacktestService({
|
||||
postgres: database,
|
||||
logger: { info() {} },
|
||||
} as unknown as IServiceContainer);
|
||||
await expect(facade.createBacktest(definition)).rejects.toThrow('Retained strategy versions');
|
||||
expect(database.transaction.mock.calls).toHaveLength(0);
|
||||
});
|
||||
test('builtin parameter validation preserves decimal strings and refuses invalid Unicode', () => {
|
||||
const descriptor = builtinCatalogDescriptors.find(
|
||||
item => item.program.strategyId === 'mean_reversion'
|
||||
)!;
|
||||
const pkg = parseStrategyVersionPackage({
|
||||
version: 1,
|
||||
program: descriptor.program,
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: descriptor.entryExport,
|
||||
content: 'retained-not-executed',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: { format: 'bun-lock/v1', content: '{}', sha256: 'b'.repeat(64) },
|
||||
parameterSchema: descriptor.parameterSchema,
|
||||
source: { revision: 'a'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: 'fixture', target: 'browser' },
|
||||
});
|
||||
const parameters = {
|
||||
lookbackPeriod: 2,
|
||||
trendPeriod: 3,
|
||||
momentumPeriod: 1,
|
||||
volatilityPeriod: 2,
|
||||
entryZScore: 1,
|
||||
exitZScore: 0,
|
||||
minTrendReturn: -0.9,
|
||||
minMomentumReturn: -0.9,
|
||||
maxVolatility: 0,
|
||||
minNotionalVolume: '0.01',
|
||||
regimeFilter: 'none',
|
||||
};
|
||||
expect(() => validateStrategyParameters(pkg, {})).toThrow('Missing parameter');
|
||||
expect(validateStrategyParameters(pkg, parameters).minNotionalVolume).toBe('0.01000000');
|
||||
expect(() =>
|
||||
validateStrategyParameters(pkg, { ...parameters, minNotionalVolume: 100 })
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
validateStrategyParameters(pkg, { ...parameters, minNotionalVolume: '\ud800' })
|
||||
).toThrow('UTF-8');
|
||||
expect(() =>
|
||||
validateStrategyParameters(pkg, { ...parameters, minNotionalVolume: '1\u0000' })
|
||||
).toThrow('UTF-8');
|
||||
});
|
||||
});
|
||||
986
test/integration/strategy-workbench.test.tsx
Normal file
986
test/integration/strategy-workbench.test.tsx
Normal file
|
|
@ -0,0 +1,986 @@
|
|||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { GlobalWindow } from 'happy-dom';
|
||||
import { act, createElement, useState, type ReactElement } from 'react';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import type {
|
||||
StrategyParameterSchema,
|
||||
StrategyRecord,
|
||||
StrategyVersionPackage,
|
||||
StrategyVersionSummary,
|
||||
} from '@stock-bot/types';
|
||||
import type { CatalogSelection } from '../../apps/stock/web-app/src/features/strategies/components/StrategySelection';
|
||||
import type { Parameters } from '../../apps/stock/web-app/src/features/strategies/services/strategyApi';
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const keys = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
||||
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
||||
let createRoot: typeof import('react-dom/client').createRoot;
|
||||
let router: typeof import('react-router-dom');
|
||||
let StrategyListPage: typeof import('../../apps/stock/web-app/src/features/strategies').StrategyListPage;
|
||||
let StrategyDetailPage: typeof import('../../apps/stock/web-app/src/features/strategies').StrategyDetailPage;
|
||||
let StrategyParameterForm: typeof import('../../apps/stock/web-app/src/features/strategies/components/StrategyParameterForm').StrategyParameterForm;
|
||||
let StrategySelection: typeof import('../../apps/stock/web-app/src/features/strategies/components/StrategySelection').StrategySelection;
|
||||
let LegacyStrategySelect: typeof import('../../apps/stock/web-app/src/features/strategies/components/StrategySelection').LegacyStrategySelect;
|
||||
let CreateBacktestDialog: typeof import('../../apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog').CreateBacktestDialog;
|
||||
let BacktestDetailPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2').BacktestDetailPageV2;
|
||||
let useBacktestV2: typeof import('../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2').useBacktestV2;
|
||||
let RunControlsCompact: typeof import('../../apps/stock/web-app/src/features/backtest/components/RunControlsCompact').RunControlsCompact;
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement;
|
||||
let navigate: ReturnType<typeof router.useNavigate>;
|
||||
let location = '';
|
||||
let latest: ReturnType<typeof useBacktestV2>;
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<T>((yes, no) => {
|
||||
resolve = yes;
|
||||
reject = no;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
type Pending = ReturnType<typeof deferred<Response>> & {
|
||||
path: string;
|
||||
method: string;
|
||||
body: unknown;
|
||||
headers: Headers;
|
||||
settled: boolean;
|
||||
};
|
||||
const requests: Pending[] = [];
|
||||
function request(path: string, method = 'GET') {
|
||||
const found = requests.find(
|
||||
item => item.path === path && item.method === method && !item.settled
|
||||
);
|
||||
if (!found) {
|
||||
throw new Error(
|
||||
`No pending ${method} ${path}; requests: ${requests.map(item => `${item.method} ${item.path} ${item.settled}`).join(', ')}`
|
||||
);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function reply(item: Pending, body: unknown, status = 200) {
|
||||
item.settled = true;
|
||||
item.resolve(Response.json(body, { status }));
|
||||
}
|
||||
function fail(item: Pending) {
|
||||
item.settled = true;
|
||||
item.reject(new Error('Response lost'));
|
||||
}
|
||||
async function flush(action: () => void = () => {}) {
|
||||
await act(async () => {
|
||||
action();
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
function button(label: string) {
|
||||
const found = [...host.querySelectorAll('button')].find(
|
||||
item => item.textContent?.trim() === label || item.getAttribute('aria-label') === label
|
||||
);
|
||||
if (!found) {
|
||||
throw new Error(`Missing button ${label}: ${host.textContent}`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function click(label: string) {
|
||||
button(label).click();
|
||||
}
|
||||
function field(label: string) {
|
||||
const found = host.querySelector(`[aria-label="${label}"]`) as
|
||||
| HTMLInputElement
|
||||
| HTMLSelectElement
|
||||
| HTMLTextAreaElement
|
||||
| null;
|
||||
if (!found) {
|
||||
throw new Error(`Missing field ${label}`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function edit(label: string, value: string) {
|
||||
const input = field(label);
|
||||
const prototype =
|
||||
input.tagName === 'SELECT'
|
||||
? browser.HTMLSelectElement.prototype
|
||||
: input.tagName === 'TEXTAREA'
|
||||
? browser.HTMLTextAreaElement.prototype
|
||||
: browser.HTMLInputElement.prototype;
|
||||
Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value);
|
||||
input.dispatchEvent(
|
||||
new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', {
|
||||
bubbles: true,
|
||||
}) as unknown as Event
|
||||
);
|
||||
}
|
||||
function Probe() {
|
||||
location = router.useLocation().pathname + router.useLocation().search;
|
||||
navigate = router.useNavigate();
|
||||
return null;
|
||||
}
|
||||
async function mount(element: ReactElement, path = '/') {
|
||||
root = createRoot(host);
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(router.MemoryRouter, { initialEntries: [path] }, element, createElement(Probe))
|
||||
)
|
||||
);
|
||||
}
|
||||
const family = (id = 'family', extra: Partial<StrategyRecord> = {}): StrategyRecord => ({
|
||||
id,
|
||||
name: `Strategy ${id}`,
|
||||
description: 'Reviewed fixture',
|
||||
ownerPrincipal: 'operator',
|
||||
updatedBy: 'operator',
|
||||
archived: false,
|
||||
createdAt: '2026-01-01',
|
||||
updatedAt: '2026-01-01',
|
||||
...extra,
|
||||
});
|
||||
const schema: StrategyParameterSchema = {
|
||||
version: 1,
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: [],
|
||||
properties: {
|
||||
fastPeriod: { type: 'integer', minimum: 1, default: 5 },
|
||||
slowPeriod: { type: 'integer', minimum: 2, default: 15 },
|
||||
},
|
||||
};
|
||||
const pkg = (
|
||||
content = 'globalThis.CATALOG_MUST_NOT_EXECUTE = true; <img src=x onerror=alert(1)>'
|
||||
): StrategyVersionPackage => ({
|
||||
version: 1,
|
||||
program: {
|
||||
strategyId: 'fixture',
|
||||
strategyVersion: 'v1',
|
||||
apiVersion: 'canonical-ts/v1',
|
||||
checkpointVersion: 'fixture/v1',
|
||||
},
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: 'createFixture',
|
||||
content,
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: { format: 'bun-lock/v1', content: 'lock', sha256: 'b'.repeat(64) },
|
||||
parameterSchema: schema,
|
||||
source: { revision: 'c'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: '1.2.17', target: 'browser' },
|
||||
});
|
||||
const version = (
|
||||
id = 'version-one',
|
||||
extra: Partial<StrategyVersionSummary> = {}
|
||||
): StrategyVersionSummary => {
|
||||
const full = pkg();
|
||||
const { content: _artifact, ...artifact } = full.artifact;
|
||||
const { content: _lock, ...dependencyLock } = full.dependencyLock;
|
||||
return {
|
||||
id,
|
||||
strategyId: 'family',
|
||||
ordinal: 1,
|
||||
parentVersionId: null,
|
||||
createdBy: 'operator',
|
||||
origin: 'builtin',
|
||||
createdAt: '2026-01-01',
|
||||
package: { ...full, artifact, dependencyLock },
|
||||
reviewStatus: 'approved',
|
||||
runnable: false,
|
||||
reason: 'Execution unavailable',
|
||||
...extra,
|
||||
};
|
||||
};
|
||||
const definition = {
|
||||
id: 'definition',
|
||||
name: 'Catalog fixture',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: { fastPeriod: 5, slowPeriod: 15 },
|
||||
symbols: ['AAPL.US'],
|
||||
startDate: '2024-01-01',
|
||||
endDate: '2024-03-01',
|
||||
initialCapital: 100000,
|
||||
config: {},
|
||||
archivedAt: null,
|
||||
createdAt: '2026-01-01',
|
||||
updatedAt: '2026-01-01',
|
||||
};
|
||||
async function detail(path = '/strategies/family/versions/version-one', versions = [version()]) {
|
||||
await mount(
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/strategies/:strategyId/versions/:versionId',
|
||||
element: createElement(StrategyDetailPage),
|
||||
})
|
||||
),
|
||||
path
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/strategies/family'), { strategy: family() });
|
||||
reply(request('/api/v2/strategies/family/versions'), { versions });
|
||||
reply(request('/api/v2/strategy-versions/version-one'), { version: versions[0], reviews: [] });
|
||||
});
|
||||
}
|
||||
async function selected(archived = false) {
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/strategies'), { strategies: [family('family', { archived })] });
|
||||
reply(request('/api/v2/strategy-versions/version-one'), { version: version(), reviews: [] });
|
||||
});
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategies/family'), { strategy: family('family', { archived }) })
|
||||
);
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategies/family/versions'), { versions: [version()] })
|
||||
);
|
||||
}
|
||||
beforeAll(async () => {
|
||||
for (const [key, value] of Object.entries({
|
||||
window: browser,
|
||||
document: browser.document,
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
})) {
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
({ createRoot } = await import('react-dom/client'));
|
||||
router = await import('react-router-dom');
|
||||
({ StrategyListPage, StrategyDetailPage } = await import(
|
||||
'../../apps/stock/web-app/src/features/strategies'
|
||||
));
|
||||
({ StrategyParameterForm } = await import(
|
||||
'../../apps/stock/web-app/src/features/strategies/components/StrategyParameterForm'
|
||||
));
|
||||
({ StrategySelection, LegacyStrategySelect } = await import(
|
||||
'../../apps/stock/web-app/src/features/strategies/components/StrategySelection'
|
||||
));
|
||||
({ CreateBacktestDialog } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog'
|
||||
));
|
||||
({ BacktestDetailPageV2 } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2'
|
||||
));
|
||||
({ useBacktestV2 } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2'
|
||||
));
|
||||
({ RunControlsCompact } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/components/RunControlsCompact'
|
||||
));
|
||||
});
|
||||
beforeEach(() => {
|
||||
requests.length = 0;
|
||||
location = '';
|
||||
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
||||
browser.document.body.append(host as never);
|
||||
Object.defineProperty(browser, 'confirm', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: () => true,
|
||||
});
|
||||
browser.fetch = ((url: RequestInfo | URL, init?: RequestInit) => {
|
||||
const item: Pending = {
|
||||
...deferred<Response>(),
|
||||
path: new URL(String(url)).pathname,
|
||||
method: init?.method ?? 'GET',
|
||||
headers: new Headers(init?.headers),
|
||||
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
||||
settled: false,
|
||||
};
|
||||
requests.push(item);
|
||||
return item.promise; // Ignore abort deliberately: stale-response fences must still hold.
|
||||
}) as unknown as typeof browser.fetch;
|
||||
});
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await flush(() => root!.unmount());
|
||||
}
|
||||
root = undefined;
|
||||
host.remove();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await browser.happyDOM.close();
|
||||
for (const key of keys) {
|
||||
const descriptor = originals.get(key);
|
||||
if (descriptor) {
|
||||
Object.defineProperty(globalThis, key, descriptor);
|
||||
} else {
|
||||
delete (globalThis as Record<string, unknown>)[key];
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
describe('strategy workbench', () => {
|
||||
test('catalog_navigation: loading, failure, retry, empty and metadata create route', async () => {
|
||||
await mount(createElement(StrategyListPage), '/strategies');
|
||||
expect(host.textContent).toContain('Loading strategies...');
|
||||
await flush(() => reply(request('/api/v2/strategies'), { error: 'Catalog offline' }, 503));
|
||||
expect(host.textContent).toContain('Catalog offline');
|
||||
await flush(() => click('Retry strategies'));
|
||||
await flush(() => reply(request('/api/v2/strategies'), { strategies: [] }));
|
||||
expect(host.textContent).toContain('No strategies found');
|
||||
await flush(() => click('New strategy'));
|
||||
await flush(() => {
|
||||
edit('Strategy name', 'My hypothesis');
|
||||
edit('Strategy description', 'Research only');
|
||||
});
|
||||
expect(host.textContent).toContain('Unsaved strategy metadata');
|
||||
await flush(() => click('Create strategy'));
|
||||
expect(request('/api/v2/strategies', 'POST').body).toEqual({
|
||||
name: 'My hypothesis',
|
||||
description: 'Research only',
|
||||
});
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategies', 'POST'), { strategy: family('new-family') }, 201)
|
||||
);
|
||||
expect(location).toBe('/strategies/new-family');
|
||||
});
|
||||
|
||||
test('metadata errors retain unsaved edits; local exit can be declined; archive is explicit', async () => {
|
||||
await detail();
|
||||
await flush(() => edit('Strategy name', 'Edited'));
|
||||
Object.defineProperty(browser, 'confirm', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: () => false,
|
||||
});
|
||||
await flush(() => click('Discard metadata changes'));
|
||||
expect(field('Strategy name').value).toBe('Edited');
|
||||
await flush(() => click('Save metadata'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategies/family', 'PATCH'), { error: 'Write failed' }, 503)
|
||||
);
|
||||
expect(field('Strategy name').value).toBe('Edited');
|
||||
expect(host.textContent).toContain('Write failed');
|
||||
Object.defineProperty(browser, 'confirm', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: () => true,
|
||||
});
|
||||
await flush(() => click('Discard metadata changes'));
|
||||
await flush(() => click('Archive strategy'));
|
||||
expect(request('/api/v2/strategies/family', 'PATCH').body).toEqual({ archived: true });
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategies/family', 'PATCH'), {
|
||||
strategy: family('family', { archived: true }),
|
||||
})
|
||||
);
|
||||
expect(button('Use in backtest').disabled).toBe(true);
|
||||
expect(button('Restore strategy')).toBeDefined();
|
||||
});
|
||||
|
||||
test('parameter_form_validation: false, zero, typed enums, optional omission and decimal strings survive', async () => {
|
||||
const mixed: StrategyParameterSchema = {
|
||||
version: 1,
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['enabled', 'budget'],
|
||||
properties: {
|
||||
enabled: { type: 'boolean', default: false },
|
||||
count: { type: 'integer', minimum: 0, default: 0 },
|
||||
budget: { type: 'string', default: '000.10' },
|
||||
choice: { type: 'number', enum: [0, 1], default: 0 },
|
||||
optional: { type: 'string' },
|
||||
},
|
||||
};
|
||||
let result: Parameters = {};
|
||||
let valid = false;
|
||||
await mount(
|
||||
createElement(StrategyParameterForm, {
|
||||
versionId: 'mixed',
|
||||
schema: mixed,
|
||||
onChange: (parameters, checked) => {
|
||||
result = parameters;
|
||||
valid = checked;
|
||||
},
|
||||
})
|
||||
);
|
||||
await flush(() => click('Validate parameters'));
|
||||
expect(request('/api/v2/strategy-versions/mixed/validate', 'POST').body).toEqual({
|
||||
parameters: { enabled: false, count: 0, budget: '000.10', choice: 0 },
|
||||
});
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/mixed/validate', 'POST'), {
|
||||
parameters: { enabled: false, count: 0, budget: '0.1', choice: 0 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
expect(valid).toBe(true);
|
||||
expect(result.budget).toBe('0.1');
|
||||
await flush(() => edit('count', '-1'));
|
||||
expect(valid).toBe(false);
|
||||
expect(host.textContent).toContain('outside the allowed range');
|
||||
expect(button('Validate parameters').disabled).toBe(true);
|
||||
});
|
||||
|
||||
test('parameter_form_validation: present empty strings survive defaults; omitted strings stay omitted', async () => {
|
||||
const strings: StrategyParameterSchema = {
|
||||
version: 1,
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['requiredText'],
|
||||
properties: {
|
||||
requiredText: { type: 'string' },
|
||||
optionalText: { type: 'string', default: 'fallback' },
|
||||
absent: { type: 'string' },
|
||||
},
|
||||
};
|
||||
let result: Parameters = {};
|
||||
await mount(
|
||||
createElement(StrategyParameterForm, {
|
||||
versionId: 'strings',
|
||||
schema: strings,
|
||||
initialParameters: { requiredText: '', optionalText: '' },
|
||||
onChange: next => {
|
||||
result = next;
|
||||
},
|
||||
})
|
||||
);
|
||||
expect((field('Include requiredText') as HTMLInputElement).checked).toBe(true);
|
||||
expect((field('Include optionalText') as HTMLInputElement).checked).toBe(true);
|
||||
expect((field('Include absent') as HTMLInputElement).checked).toBe(false);
|
||||
await flush(() => click('Validate parameters'));
|
||||
const payload = request('/api/v2/strategy-versions/strings/validate', 'POST');
|
||||
expect(payload.body).toEqual({ parameters: { requiredText: '', optionalText: '' } });
|
||||
await flush(() =>
|
||||
reply(payload, {
|
||||
parameters: { requiredText: '', optionalText: '' },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
expect(result).toEqual({ requiredText: '', optionalText: '' });
|
||||
await flush(() => (field('Include optionalText') as HTMLInputElement).click());
|
||||
expect(result).toEqual({ requiredText: '' });
|
||||
await flush(() => click('Validate parameters'));
|
||||
expect(request('/api/v2/strategy-versions/strings/validate', 'POST').body).toEqual({
|
||||
parameters: { requiredText: '' },
|
||||
});
|
||||
});
|
||||
|
||||
test('parameter_form_validation: a missing required string can be explicitly included as empty', async () => {
|
||||
const required: StrategyParameterSchema = {
|
||||
version: 1,
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['text'],
|
||||
properties: { text: { type: 'string' } },
|
||||
};
|
||||
await mount(
|
||||
createElement(StrategyParameterForm, {
|
||||
versionId: 'required',
|
||||
schema: required,
|
||||
onChange: () => {},
|
||||
})
|
||||
);
|
||||
expect(button('Validate parameters').disabled).toBe(true);
|
||||
expect(host.textContent).toContain('text: Required');
|
||||
await flush(() => (field('Include text') as HTMLInputElement).click());
|
||||
expect(button('Validate parameters').disabled).toBe(false);
|
||||
await flush(() => click('Validate parameters'));
|
||||
expect(request('/api/v2/strategy-versions/required/validate', 'POST').body).toEqual({
|
||||
parameters: { text: '' },
|
||||
});
|
||||
});
|
||||
|
||||
test('create-family double click is coalesced and late completion cannot navigate after unmount', async () => {
|
||||
await mount(createElement(StrategyListPage), '/strategies');
|
||||
await flush(() => reply(request('/api/v2/strategies'), { strategies: [] }));
|
||||
await flush(() => click('New strategy'));
|
||||
await flush(() => edit('Strategy name', 'One family'));
|
||||
await flush(() => {
|
||||
click('Create strategy');
|
||||
click('Create strategy');
|
||||
});
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
const pending = request('/api/v2/strategies', 'POST');
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(router.MemoryRouter, { initialEntries: ['/elsewhere'] }, createElement(Probe))
|
||||
)
|
||||
);
|
||||
await flush(() => reply(pending, { strategy: family('late') }, 201));
|
||||
expect(location).not.toBe('/strategies/late');
|
||||
});
|
||||
|
||||
test('parameter_form_validation: stale success cannot approve edited inputs; server cross-field error is visible', async () => {
|
||||
let valid = false;
|
||||
await mount(
|
||||
createElement(StrategyParameterForm, {
|
||||
versionId: 'version-one',
|
||||
schema,
|
||||
onChange: (_parameters, checked) => {
|
||||
valid = checked;
|
||||
},
|
||||
})
|
||||
);
|
||||
await flush(() => click('Validate parameters'));
|
||||
const old = request('/api/v2/strategy-versions/version-one/validate', 'POST');
|
||||
await flush(() => edit('fastPeriod', '20'));
|
||||
await flush(() =>
|
||||
reply(old, {
|
||||
parameters: { fastPeriod: 5, slowPeriod: 15 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
expect(valid).toBe(false);
|
||||
expect(field('fastPeriod').value).toBe('20');
|
||||
await flush(() => click('Validate parameters'));
|
||||
await flush(() =>
|
||||
reply(
|
||||
request('/api/v2/strategy-versions/version-one/validate', 'POST'),
|
||||
{ error: 'fastPeriod must be below slowPeriod' },
|
||||
400
|
||||
)
|
||||
);
|
||||
expect(host.textContent).toContain('fastPeriod must be below slowPeriod');
|
||||
expect(valid).toBe(false);
|
||||
});
|
||||
|
||||
test('immutable_version_selection: late version response cannot replace current route', async () => {
|
||||
await detail('/strategies/family/versions/version-one', [
|
||||
version(),
|
||||
version('version-two', { ordinal: 2 }),
|
||||
]);
|
||||
await flush(() => edit('Strategy version', 'version-two'));
|
||||
const old = request('/api/v2/strategy-versions/version-two');
|
||||
await flush(() => navigate('/strategies/family/versions/version-one'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one'), { version: version(), reviews: [] })
|
||||
);
|
||||
await flush(() => reply(old, { version: version('version-two', { ordinal: 2 }), reviews: [] }));
|
||||
expect(location).toBe('/strategies/family/versions/version-one');
|
||||
expect(host.textContent).toContain('Immutable version ID: version-one');
|
||||
expect(host.textContent).not.toContain('Immutable version ID: version-two');
|
||||
});
|
||||
|
||||
test('clone_revision_diff: clone retries exact frozen body/key and compares inert retained bundles to parent', async () => {
|
||||
await detail('/strategies/family/versions/version-one', [
|
||||
version('version-one', {
|
||||
origin: 'candidate',
|
||||
parentVersionId: 'parent',
|
||||
reviewStatus: 'pending',
|
||||
}),
|
||||
]);
|
||||
await flush(() => edit('Compare with version', 'parent'));
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/strategy-versions/version-one/artifact'), { package: pkg() });
|
||||
reply(request('/api/v2/strategy-versions/parent/artifact'), { package: pkg() });
|
||||
});
|
||||
expect(host.textContent).toContain('Identical artifact bytes');
|
||||
expect(host.querySelector('img')).toBeNull();
|
||||
expect((globalThis as Record<string, unknown>).CATALOG_MUST_NOT_EXECUTE).toBeUndefined();
|
||||
expect(host.querySelector('[aria-label="Selected bundled JavaScript"]')?.textContent).toContain(
|
||||
'<img src=x'
|
||||
);
|
||||
await flush(() => click('Clone version'));
|
||||
await flush(() => edit('Clone name', 'Cloned hypothesis'));
|
||||
await flush(() => click('Create clone'));
|
||||
const first = request('/api/v2/strategy-versions/version-one/clone', 'POST');
|
||||
await flush(() => fail(first));
|
||||
expect(field('Clone name').disabled).toBe(true);
|
||||
await flush(() => click('Retry clone'));
|
||||
const second = request('/api/v2/strategy-versions/version-one/clone', 'POST');
|
||||
expect(second.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(second.body).toEqual(first.body);
|
||||
await flush(() =>
|
||||
reply(
|
||||
second,
|
||||
{
|
||||
strategy: family('clone-family'),
|
||||
version: version('clone-version', {
|
||||
strategyId: 'clone-family',
|
||||
parentVersionId: 'version-one',
|
||||
origin: 'candidate',
|
||||
reviewStatus: 'pending',
|
||||
}),
|
||||
},
|
||||
201
|
||||
)
|
||||
);
|
||||
expect(location).toBe('/strategies/clone-family/versions/clone-version');
|
||||
});
|
||||
|
||||
test('clone source identity and retry key stay frozen across same-family history navigation', async () => {
|
||||
await detail('/strategies/family/versions/version-one', [
|
||||
version(),
|
||||
version('version-two', { ordinal: 2 }),
|
||||
]);
|
||||
await flush(() => click('Clone version'));
|
||||
await flush(() => edit('Clone name', 'Clone original version'));
|
||||
await flush(() => click('Create clone'));
|
||||
const first = request('/api/v2/strategy-versions/version-one/clone', 'POST');
|
||||
// Browser history can change the route even while the version select is disabled.
|
||||
await flush(() => navigate('/strategies/family/versions/version-two'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-two'), {
|
||||
version: version('version-two', { ordinal: 2 }),
|
||||
reviews: [],
|
||||
})
|
||||
);
|
||||
expect(host.textContent).toContain('Clone immutable version 1');
|
||||
expect(host.textContent).toContain('Clone source version ID: version-one');
|
||||
expect(host.textContent).toContain('even while you view version 2 (version-two)');
|
||||
const cloned = {
|
||||
strategy: family('clone-family'),
|
||||
version: version('clone-version', {
|
||||
strategyId: 'clone-family',
|
||||
parentVersionId: 'version-one',
|
||||
origin: 'candidate',
|
||||
reviewStatus: 'pending',
|
||||
}),
|
||||
};
|
||||
await flush(() => reply(first, cloned, 201));
|
||||
expect(location).toBe('/strategies/family/versions/version-two');
|
||||
expect(host.textContent).toContain('Clone immutable version 1');
|
||||
await flush(() => click('Retry clone'));
|
||||
const retry = request('/api/v2/strategy-versions/version-one/clone', 'POST');
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(retry.body).toEqual(first.body);
|
||||
expect(requests.some(item => item.path === '/api/v2/strategy-versions/version-two/clone')).toBe(
|
||||
false
|
||||
);
|
||||
await flush(() => reply(retry, cloned, 201));
|
||||
expect(location).toBe('/strategies/family/versions/version-two');
|
||||
expect(host.textContent).toContain('Clone source version ID: version-one');
|
||||
});
|
||||
|
||||
test('immutable_version_selection: create saves exact validated ID and parameters without any run request', async () => {
|
||||
let saved: unknown;
|
||||
await mount(
|
||||
createElement(CreateBacktestDialog, {
|
||||
initialSelection: {
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: { fastPeriod: 3, slowPeriod: 8 },
|
||||
},
|
||||
onClose: () => {},
|
||||
onCreated: value => {
|
||||
saved = value;
|
||||
},
|
||||
})
|
||||
);
|
||||
await selected();
|
||||
expect(button('Save').disabled).toBe(true);
|
||||
expect(button('Save and run').disabled).toBe(true);
|
||||
await flush(() => click('Validate parameters'));
|
||||
expect(request('/api/v2/strategy-versions/version-one/validate', 'POST').body).toEqual({
|
||||
parameters: { fastPeriod: 3, slowPeriod: 8 },
|
||||
});
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), {
|
||||
parameters: { fastPeriod: 3, slowPeriod: 8 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
await flush(() => {
|
||||
const input = host.querySelector('input[placeholder="My Strategy Backtest"]')!;
|
||||
Object.getOwnPropertyDescriptor(browser.HTMLInputElement.prototype, 'value')!.set!.call(
|
||||
input,
|
||||
'Saved research draft'
|
||||
);
|
||||
input.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event);
|
||||
});
|
||||
await flush(() => click('Save'));
|
||||
const post = request('/api/v2/backtests', 'POST');
|
||||
expect(post.body).toMatchObject({
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: { fastPeriod: 3, slowPeriod: 8 },
|
||||
autoStart: false,
|
||||
});
|
||||
expect((post.body as { config: object }).config).not.toHaveProperty('fastPeriod');
|
||||
await flush(() => reply(post, definition));
|
||||
expect(saved).toEqual(definition);
|
||||
expect(requests.some(item => item.path.endsWith('/runs'))).toBe(false);
|
||||
});
|
||||
|
||||
test('reopened catalog settings save exact version parameters without legacy pacing and keep notices outside heading', async () => {
|
||||
await mount(
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id',
|
||||
element: createElement(BacktestDetailPageV2),
|
||||
})
|
||||
),
|
||||
'/backtests/definition'
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/definition'), {
|
||||
...definition,
|
||||
config: { commission: 0, slippage: 0 },
|
||||
});
|
||||
reply(request('/api/v2/backtests/definition/runs'), []);
|
||||
});
|
||||
expect(host.querySelector('h1 p')).toBeNull();
|
||||
expect(host.querySelector('h1')?.textContent).not.toContain('save-only');
|
||||
expect(host.querySelector('a[href="/strategies/versions/version-one"]')).not.toBeNull();
|
||||
await flush(() => click('Settings'));
|
||||
await selected();
|
||||
expect(host.querySelector('input[name="speedMultiplier"]')).toBeNull();
|
||||
await flush(() => edit('fastPeriod', '2'));
|
||||
await flush(() => click('Validate parameters'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), {
|
||||
parameters: { fastPeriod: 2, slowPeriod: 15 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
await flush(() => click('Save'));
|
||||
const saved = request('/api/v2/backtests/definition', 'PUT');
|
||||
expect(saved.body).toMatchObject({
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 15 },
|
||||
});
|
||||
expect((saved.body as { config: object }).config).not.toHaveProperty('speedMultiplier');
|
||||
expect((saved.body as { config: object }).config).toMatchObject({
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataFrequency: '1d',
|
||||
dataSource: 'auto',
|
||||
});
|
||||
await flush(() =>
|
||||
reply(saved, { ...definition, strategyParameters: { fastPeriod: 2, slowPeriod: 15 } })
|
||||
);
|
||||
await selected();
|
||||
expect(field('fastPeriod').value).toBe('2');
|
||||
await flush(() => click('Runs'));
|
||||
expect(button('New Run').disabled).toBe(true);
|
||||
expect(requests.some(item => item.method === 'POST' && item.path.endsWith('/runs'))).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test('catalog authoritative archive/restore resets visible parameters and validation together', async () => {
|
||||
await mount(
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id',
|
||||
element: createElement(BacktestDetailPageV2),
|
||||
})
|
||||
),
|
||||
'/backtests/definition'
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/definition'), {
|
||||
...definition,
|
||||
config: { commission: 0, slippage: 0 },
|
||||
});
|
||||
reply(request('/api/v2/backtests/definition/runs'), []);
|
||||
});
|
||||
await flush(() => click('Settings'));
|
||||
await selected();
|
||||
await flush(() => edit('fastPeriod', '2'));
|
||||
await flush(() => click('Validate parameters'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), {
|
||||
parameters: { fastPeriod: 2, slowPeriod: 15 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
expect(button('Save').disabled).toBe(false);
|
||||
await flush(() => click('Validate parameters'));
|
||||
const staleValidation = request('/api/v2/strategy-versions/version-one/validate', 'POST');
|
||||
await flush(() => click('Archive backtest'));
|
||||
await flush(() => click('Confirm archive'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/backtests/definition/archive', 'POST'), {
|
||||
...definition,
|
||||
config: { commission: 0, slippage: 0 },
|
||||
archivedAt: '2026-01-02',
|
||||
})
|
||||
);
|
||||
await selected();
|
||||
expect(field('fastPeriod').value).toBe('5');
|
||||
expect(field('fastPeriod').disabled).toBe(true);
|
||||
expect(button('Save').disabled).toBe(true);
|
||||
await flush(() => click('Restore backtest'));
|
||||
await flush(() => click('Confirm restore'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/backtests/definition/archive', 'POST'), {
|
||||
...definition,
|
||||
config: { commission: 0, slippage: 0 },
|
||||
})
|
||||
);
|
||||
await selected();
|
||||
await flush(() =>
|
||||
reply(staleValidation, {
|
||||
parameters: { fastPeriod: 2, slowPeriod: 15 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
expect(field('fastPeriod').value).toBe('5');
|
||||
expect(field('fastPeriod').disabled).toBe(false);
|
||||
expect(button('Save').disabled).toBe(true);
|
||||
await flush(() => click('Validate parameters'));
|
||||
expect(request('/api/v2/strategy-versions/version-one/validate', 'POST').body).toEqual({
|
||||
parameters: { fastPeriod: 5, slowPeriod: 15 },
|
||||
});
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), {
|
||||
parameters: { fastPeriod: 5, slowPeriod: 15 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
await flush(() => click('Save'));
|
||||
expect(request('/api/v2/backtests/definition', 'PUT').body).toMatchObject({
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: { fastPeriod: 5, slowPeriod: 15 },
|
||||
});
|
||||
});
|
||||
|
||||
test('legacy settings retain the existing pacing field and submitted speed', async () => {
|
||||
await mount(
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id',
|
||||
element: createElement(BacktestDetailPageV2),
|
||||
})
|
||||
),
|
||||
'/backtests/definition'
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/definition'), {
|
||||
...definition,
|
||||
config: { commission: 0, slippage: 0 },
|
||||
strategy: 'moving-average',
|
||||
strategyVersionId: null,
|
||||
strategyParameters: null,
|
||||
});
|
||||
reply(request('/api/v2/backtests/definition/runs'), []);
|
||||
});
|
||||
await flush(() => click('Settings'));
|
||||
const speed = host.querySelector('input[name="speedMultiplier"]')!;
|
||||
expect(speed).not.toBeNull();
|
||||
await flush(() => {
|
||||
Object.getOwnPropertyDescriptor(browser.HTMLInputElement.prototype, 'value')!.set!.call(
|
||||
speed,
|
||||
'0.2'
|
||||
);
|
||||
speed.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event);
|
||||
});
|
||||
await flush(() => click('Save'));
|
||||
expect(request('/api/v2/backtests/definition', 'PUT').body).toMatchObject({
|
||||
strategy: 'moving-average',
|
||||
config: { speedMultiplier: 0.2 },
|
||||
});
|
||||
});
|
||||
|
||||
test('retained archived family is readable but cannot validate a new selection; existing saved selection can', async () => {
|
||||
let checked = false;
|
||||
function Selection({ retained = false }: { retained?: boolean }) {
|
||||
const [value, setValue] = useState<CatalogSelection>({
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: {},
|
||||
});
|
||||
return createElement(StrategySelection, {
|
||||
value,
|
||||
onChange: setValue,
|
||||
onValidityChange: valid => {
|
||||
checked = valid;
|
||||
},
|
||||
allowArchivedSelection: retained,
|
||||
});
|
||||
}
|
||||
await mount(createElement(Selection));
|
||||
await selected(true);
|
||||
expect(host.textContent).toContain('archived');
|
||||
expect(field('Immutable strategy version').disabled).toBe(true);
|
||||
expect(button('Validate parameters').disabled).toBe(true);
|
||||
expect(checked).toBe(false);
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(router.MemoryRouter, null, createElement(Selection, { retained: true }))
|
||||
)
|
||||
);
|
||||
// The retained selection stays loaded when its edit policy changes.
|
||||
expect(button('Validate parameters').disabled).toBe(false);
|
||||
});
|
||||
|
||||
test('missing selected version is not cleared; retry preserves exact ID and blocks saving', async () => {
|
||||
let selectedId: string | null | undefined = 'version-one';
|
||||
await mount(
|
||||
createElement(StrategySelection, {
|
||||
value: { strategyVersionId: selectedId },
|
||||
onChange: next => {
|
||||
selectedId = next.strategyVersionId;
|
||||
},
|
||||
onValidityChange: () => {},
|
||||
})
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/strategies'), { strategies: [] });
|
||||
reply(request('/api/v2/strategy-versions/version-one'), { error: 'Version missing' }, 404);
|
||||
});
|
||||
expect(host.textContent).toContain('selection has been retained');
|
||||
expect(selectedId).toBe('version-one');
|
||||
await flush(() => click('Retry strategy catalog'));
|
||||
expect(request('/api/v2/strategy-versions/version-one')).toBeDefined();
|
||||
});
|
||||
|
||||
test('legacy filtering preserves unsupported saved labels and offers only independently supported choices', async () => {
|
||||
await mount(createElement(LegacyStrategySelect, { value: 'custom', onChange: () => {} }));
|
||||
expect(field('Legacy strategy').value).toBe('custom');
|
||||
expect(host.querySelector('option[value="custom"]')?.hasAttribute('disabled')).toBe(true);
|
||||
expect(host.querySelector('option[value="pairs-trading"]')).toBeNull();
|
||||
expect(host.querySelector('option[value="ml-enhanced"]')).toBeNull();
|
||||
expect(host.querySelector('option[value="moving-average"]')).not.toBeNull();
|
||||
expect(host.querySelector('option[value="momentum"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
test('catalog execution stays blocked in the hook and controls; accepted run cancellation remains enabled', async () => {
|
||||
function Hook() {
|
||||
latest = useBacktestV2();
|
||||
return null;
|
||||
}
|
||||
await mount(createElement(Hook));
|
||||
await flush(() => {
|
||||
void latest.loadBacktest('definition');
|
||||
});
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/definition'), definition);
|
||||
reply(request('/api/v2/backtests/definition/runs'), []);
|
||||
});
|
||||
await flush(() => {
|
||||
void latest.createRun(null);
|
||||
});
|
||||
expect(latest.submissionError).toContain('save-only');
|
||||
expect(requests.some(item => item.method === 'POST')).toBe(false);
|
||||
let cancelled = false;
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(RunControlsCompact, {
|
||||
run: {
|
||||
id: 'accepted',
|
||||
backtestId: 'definition',
|
||||
runNumber: 1,
|
||||
status: 'running',
|
||||
speedMultiplier: null,
|
||||
progress: 10,
|
||||
createdAt: '2026-01-01',
|
||||
updatedAt: '2026-01-01',
|
||||
},
|
||||
cancelRequested: false,
|
||||
onCancel: () => {
|
||||
cancelled = true;
|
||||
},
|
||||
onRerun: () => {},
|
||||
executionUnavailable: true,
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(button('Run current settings').disabled).toBe(true);
|
||||
expect(button('Cancel run').disabled).toBe(false);
|
||||
await flush(() => click('Cancel run'));
|
||||
expect(cancelled).toBe(true);
|
||||
});
|
||||
});
|
||||
373
test/postgres/catalog-backtest-drafts.test.ts
Normal file
373
test/postgres/catalog-backtest-drafts.test.ts
Normal file
|
|
@ -0,0 +1,373 @@
|
|||
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 { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { createBacktestRoutes } from '../../apps/stock/web-api/src/routes/backtest.routes';
|
||||
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
||||
import {
|
||||
BacktestServiceV2,
|
||||
type BacktestRequest,
|
||||
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service';
|
||||
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('catalog-draft-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
const sql = (name: string) =>
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8');
|
||||
const hash = (text: string) => createHash('sha256').update(text).digest('hex');
|
||||
function pkg(): StrategyVersionPackage {
|
||||
const content = 'throw new Error("CANDIDATE_MUST_NOT_EXECUTE");';
|
||||
const lock = '{"lockfileVersion":1}';
|
||||
return {
|
||||
version: 1,
|
||||
program: {
|
||||
strategyId: 'draft-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,
|
||||
required: [],
|
||||
properties: {
|
||||
commission: { type: 'number', minimum: 0, default: 0 },
|
||||
enabled: { type: 'boolean', default: false },
|
||||
budget: { type: 'string', default: '100.25' },
|
||||
lookback: { type: 'integer', minimum: 1, default: 3 },
|
||||
label: { type: 'string', default: '📈' },
|
||||
},
|
||||
},
|
||||
source: { revision: 'a'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: 'fixture', target: 'browser' },
|
||||
};
|
||||
}
|
||||
const common = {
|
||||
name: 'Catalog draft',
|
||||
symbols: ['FIXTURE.TEST'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-01-05T00:00:00.000Z',
|
||||
initialCapital: 1000,
|
||||
config: { commission: 0.001, slippage: 0, dataFrequency: '1d' },
|
||||
};
|
||||
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 safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_drafts_' + 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();
|
||||
});
|
||||
for (const name of [
|
||||
'06-create-backtest-tables.sql',
|
||||
'08-create-runs-table.sql',
|
||||
'09-backtest-run-contract.sql',
|
||||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
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', { value: pool.query.bind(pool) });
|
||||
const api = new BacktestServiceV2({ postgres, logger });
|
||||
const catalog = new StrategyCatalogService({ postgres, logger });
|
||||
const family = await catalog.createStrategy({ name: 'Candidate' }, 'operator');
|
||||
const version = await catalog.publishVersion(family.id, pkg(), null, 'operator', 'initial');
|
||||
const second = await catalog.publishVersion(family.id, pkg(), null, 'operator', 'second');
|
||||
const draft = () => ({
|
||||
...common,
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: {},
|
||||
});
|
||||
const app = new Hono()
|
||||
.route('/', createBacktestV2Routes({ postgres, logger }))
|
||||
.route('/', createBacktestRoutes({ postgres, logger }));
|
||||
return { schema, pool, postgres, api, catalog, family, version, second, draft, app };
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('saved catalog backtest drafts on PostgreSQL', () => {
|
||||
test('normalizes exact defaults and separates financial settings from arbitrary strategy parameter names', async () => {
|
||||
const f = await fixture();
|
||||
const saved = await f.api.createBacktest(f.draft(), { autoStart: false });
|
||||
expect(saved.strategy).toBe('catalog');
|
||||
expect(saved.strategyVersionId).toBe(f.version.id);
|
||||
expect(saved.strategyParameters).toEqual({
|
||||
commission: 0,
|
||||
enabled: false,
|
||||
budget: '100.25',
|
||||
lookback: 3,
|
||||
label: '📈',
|
||||
});
|
||||
expect(saved.config.commission).toBe(0.001);
|
||||
expect((await f.api.getBacktest(saved.id))?.strategyParameters).toEqual(
|
||||
saved.strategyParameters!
|
||||
);
|
||||
const edited = await f.api.updateBacktest(saved.id, { name: 'Edited' });
|
||||
expect(edited?.strategyVersionId).toBe(f.version.id);
|
||||
expect(edited?.strategyParameters).toEqual(saved.strategyParameters!);
|
||||
const revised = await f.api.updateBacktest(saved.id, {
|
||||
strategyParameters: {
|
||||
commission: 0.04,
|
||||
enabled: false,
|
||||
budget: '0.00',
|
||||
lookback: 1,
|
||||
label: '東京',
|
||||
},
|
||||
});
|
||||
expect(revised?.config.commission).toBe(0.001);
|
||||
expect(revised?.strategyParameters?.budget).toBe('0.00');
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('strict save-only input, version integrity and invalid parameters fail atomically', async () => {
|
||||
const f = await fixture();
|
||||
for (const options of [{}, { autoStart: true }]) {
|
||||
await expect(f.api.createBacktest(f.draft(), options)).rejects.toThrow('autoStart:false');
|
||||
}
|
||||
const invalidInputs: BacktestRequest[] = [
|
||||
{ ...f.draft(), strategyVersionId: null },
|
||||
{ ...f.draft(), strategyParameters: null },
|
||||
{ ...f.draft(), config: { ...common.config, lookback: 9 } },
|
||||
{ ...f.draft(), strategyParameters: { unknown: 1 } },
|
||||
{ ...f.draft(), strategyParameters: { lookback: 0 } },
|
||||
{ ...f.draft(), strategyParameters: { enabled: 'false' } },
|
||||
{ ...f.draft(), strategyParameters: { budget: 100.25 } },
|
||||
{ ...f.draft(), strategyParameters: { label: 'bad\u0000text' } },
|
||||
{ ...f.draft(), strategyParameters: { label: '\ud800' } },
|
||||
{ ...f.draft(), strategyParameters: JSON.parse('{"__proto__":1}') },
|
||||
];
|
||||
for (const input of invalidInputs) {
|
||||
await expect(f.api.createBacktest(input, { autoStart: false })).rejects.toThrow();
|
||||
}
|
||||
await expect(
|
||||
f.api.createBacktest({ ...f.draft(), strategyVersionId: randomUUID() }, { autoStart: false })
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
const corrupt = pkg();
|
||||
corrupt.artifact.content += 'changed';
|
||||
const invalidVersionId = randomUUID();
|
||||
await f.pool.query(
|
||||
"INSERT INTO strategy_versions(id,strategy_id,ordinal,envelope,created_by,origin,submission_key,submission_fingerprint) VALUES($1,$2,3,$3,'operator','candidate','imported-corrupt',$4)",
|
||||
[invalidVersionId, f.family.id, JSON.stringify(corrupt), 'f'.repeat(64)]
|
||||
);
|
||||
await expect(
|
||||
f.api.createBacktest(
|
||||
{ ...f.draft(), strategyVersionId: invalidVersionId },
|
||||
{ autoStart: false }
|
||||
)
|
||||
).rejects.toThrow('hash mismatch');
|
||||
expect((await f.pool.query('SELECT * FROM backtests')).rows).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('partial edits retain selection, explicit changes require parameters, and neither mode silently converts', async () => {
|
||||
const f = await fixture();
|
||||
const saved = await f.api.createBacktest(f.draft(), { autoStart: false });
|
||||
await expect(
|
||||
f.api.updateBacktest(saved.id, { strategyVersionId: f.second.id })
|
||||
).rejects.toThrow('explicit strategyParameters');
|
||||
await expect(
|
||||
f.api.updateBacktest(saved.id, { strategyParameters: JSON.parse('{"__proto__":1}') })
|
||||
).rejects.toThrow('Unsupported strategy metadata key');
|
||||
expect((await f.api.getBacktest(saved.id))?.strategyParameters?.lookback).toBe(3);
|
||||
expect(
|
||||
(
|
||||
await f.api.updateBacktest(saved.id, {
|
||||
strategyVersionId: f.second.id,
|
||||
strategyParameters: { lookback: 8 },
|
||||
})
|
||||
)?.strategyParameters?.lookback
|
||||
).toBe(8);
|
||||
for (const update of [
|
||||
{ strategy: 'sma-crossover' },
|
||||
{ strategyVersionId: null },
|
||||
{ strategyParameters: null },
|
||||
{ strategyParameters: { lookback: -1 } },
|
||||
]) {
|
||||
await expect(f.api.updateBacktest(saved.id, update)).rejects.toThrow();
|
||||
}
|
||||
expect((await f.api.getBacktest(saved.id))?.strategyVersionId).toBe(f.second.id);
|
||||
const legacy = await f.api.createBacktest(
|
||||
{ ...common, strategy: 'sma-crossover' },
|
||||
{ autoStart: false }
|
||||
);
|
||||
await expect(f.api.updateBacktest(legacy.id, f.draft())).rejects.toThrow(
|
||||
'Retained strategy versions'
|
||||
);
|
||||
await expect(
|
||||
f.pool.query(
|
||||
"UPDATE backtests SET strategy='sma-crossover',strategy_version_id=NULL,strategy_parameters=NULL WHERE id=$1",
|
||||
[saved.id]
|
||||
)
|
||||
).rejects.toThrow('separate template');
|
||||
await expect(
|
||||
f.pool.query(
|
||||
"UPDATE backtests SET strategy='catalog',strategy_version_id=$2,strategy_parameters='{}' WHERE id=$1",
|
||||
[legacy.id, f.version.id]
|
||||
)
|
||||
).rejects.toThrow('separate template');
|
||||
});
|
||||
|
||||
test('family archive serializes new selection while existing selected draft remains editable', async () => {
|
||||
const f = await fixture();
|
||||
const saved = await f.api.createBacktest(f.draft(), { autoStart: false });
|
||||
const blocker = await f.pool.connect();
|
||||
await blocker.query('BEGIN');
|
||||
await blocker.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE', [f.family.id]);
|
||||
const admission = f.api.createBacktest(f.draft(), { autoStart: false }).then(
|
||||
() => null,
|
||||
error => error
|
||||
);
|
||||
let waiting = false;
|
||||
for (let n = 0; n < 100; n++) {
|
||||
if (
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'",
|
||||
[f.schema]
|
||||
)
|
||||
).rows.length
|
||||
) {
|
||||
waiting = true;
|
||||
break;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
expect(waiting).toBe(true);
|
||||
await blocker.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [f.family.id]);
|
||||
await blocker.query('COMMIT');
|
||||
blocker.release();
|
||||
expect(await admission).toMatchObject({ status: 409 });
|
||||
await expect(
|
||||
f.api.updateBacktest(saved.id, { strategyVersionId: f.second.id, strategyParameters: {} })
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
expect(
|
||||
(await f.api.updateBacktest(saved.id, { strategyParameters: { lookback: 4 } }))
|
||||
?.strategyParameters?.lookback
|
||||
).toBe(4);
|
||||
await f.api.archiveBacktest(saved.id, true);
|
||||
await expect(f.api.updateBacktest(saved.id, { name: 'Blocked' })).rejects.toMatchObject({
|
||||
code: 'backtest_archived',
|
||||
});
|
||||
});
|
||||
|
||||
test('all execution paths refuse catalog drafts and independent legacy receipts still replay unchanged', async () => {
|
||||
const f = await fixture();
|
||||
const saved = await f.api.createBacktest(f.draft(), { autoStart: false });
|
||||
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toMatchObject({
|
||||
code: 'catalog_execution_unavailable',
|
||||
});
|
||||
const repository = new PostgresBacktestRunRepository(f.postgres);
|
||||
const legacyConfig = parseBacktestRequest({
|
||||
...common,
|
||||
mode: 'backtest',
|
||||
strategy: 'sma-crossover',
|
||||
dataFrequency: '1d',
|
||||
backtestId: saved.id,
|
||||
});
|
||||
await expect(repository.start(legacyConfig)).rejects.toThrow('Catalog strategy execution');
|
||||
await expect(
|
||||
repository.start({ ...legacyConfig, strategyVersionId: f.version.id } as typeof legacyConfig)
|
||||
).rejects.toThrow('Retained strategy versions');
|
||||
await expect(
|
||||
f.pool.query(
|
||||
"INSERT INTO runs(backtest_id,run_number,status,request_snapshot) VALUES($1,1,'pending','{}')",
|
||||
[saved.id]
|
||||
)
|
||||
).rejects.toThrow('Catalog strategy execution');
|
||||
await expect(
|
||||
new BacktestService({ postgres: f.postgres, logger }).createBacktest(f.draft())
|
||||
).rejects.toThrow('Retained strategy versions');
|
||||
const legacy = await f.api.createBacktest(
|
||||
{ ...common, strategy: 'sma-crossover' },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const receipt = { principal: 'operator' as const, key: 'legacy' };
|
||||
const run = await f.api.createRun({ backtestId: legacy.id }, receipt);
|
||||
const before = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [run.id]))
|
||||
.rows[0].request_snapshot;
|
||||
await f.api.updateBacktest(legacy.id, { name: 'Later edit' });
|
||||
await f.api.archiveBacktest(legacy.id, true);
|
||||
expect((await f.api.createRun({ backtestId: legacy.id }, receipt)).id).toBe(run.id);
|
||||
expect(
|
||||
(await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [run.id])).rows[0]
|
||||
.request_snapshot
|
||||
).toEqual(before);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(1);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('HTTP persisted selection reopens, malformed drafts reject, and v1 cannot save or run them', async () => {
|
||||
const f = await fixture();
|
||||
const submit = (path: string, input: unknown) =>
|
||||
f.app.request(path, { method: 'POST', body: JSON.stringify(input) });
|
||||
for (const input of [
|
||||
f.draft(),
|
||||
{ ...f.draft(), autoStart: true },
|
||||
{ ...f.draft(), autoStart: false, extra: true },
|
||||
]) {
|
||||
expect((await submit('/api/v2/backtests', input)).status).toBe(400);
|
||||
}
|
||||
expect((await submit('/api/backtests', f.draft())).status).toBe(400);
|
||||
expect((await f.pool.query('SELECT * FROM backtests')).rows).toHaveLength(0);
|
||||
const created = await submit('/api/v2/backtests', { ...f.draft(), autoStart: false });
|
||||
expect(created.status).toBe(201);
|
||||
const saved = await created.json();
|
||||
expect(await (await f.app.request(`/api/v2/backtests/${saved.id}`)).json()).toMatchObject({
|
||||
strategyVersionId: f.version.id,
|
||||
strategyParameters: { enabled: false, budget: '100.25' },
|
||||
});
|
||||
const denied = await submit(`/api/v2/backtests/${saved.id}/runs`, {});
|
||||
expect(denied.status).toBe(409);
|
||||
expect(await denied.json()).toMatchObject({ code: 'catalog_execution_unavailable' });
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||
await f.pool.query(sql('18-backtest-strategy-versions.sql'));
|
||||
expect((await f.api.getBacktest(saved.id))?.strategyVersionId).toBe(f.version.id);
|
||||
const fks = await f.pool.query(
|
||||
"SELECT confdeltype FROM pg_constraint WHERE conrelid='backtests'::regclass AND conname='backtests_strategy_version_id_fkey'"
|
||||
);
|
||||
expect(fks.rows[0].confdeltype).toBe('r');
|
||||
await expect(
|
||||
f.pool.query('DELETE FROM strategy_versions WHERE id=$1', [f.version.id])
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
|
@ -69,7 +69,9 @@ async function fixture() {
|
|||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -80,7 +80,9 @@ async function fixture() {
|
|||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
@ -127,6 +129,16 @@ async function fixture() {
|
|||
},
|
||||
{ autoStart: false }
|
||||
);
|
||||
// A response DTO includes nullable catalog markers; legacy input deliberately omits them.
|
||||
const definitionInput = {
|
||||
name: definition.name,
|
||||
strategy: definition.strategy,
|
||||
symbols: definition.symbols,
|
||||
startDate: definition.startDate.toISOString(),
|
||||
endDate: definition.endDate.toISOString(),
|
||||
initialCapital: definition.initialCapital,
|
||||
config: definition.config,
|
||||
};
|
||||
const repository = new PostgresBacktestRunRepository(postgres, 2_000);
|
||||
const history = { reads: 0, unavailable: false };
|
||||
const storage = {
|
||||
|
|
@ -197,6 +209,7 @@ async function fixture() {
|
|||
postgres,
|
||||
api,
|
||||
definition,
|
||||
definitionInput,
|
||||
repository,
|
||||
runner,
|
||||
engine,
|
||||
|
|
@ -243,7 +256,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const f = await fixture();
|
||||
const second = await f.api.createBacktest(
|
||||
{
|
||||
...f.definition,
|
||||
...f.definitionInput,
|
||||
startDate: f.definition.startDate.toISOString(),
|
||||
endDate: f.definition.endDate.toISOString(),
|
||||
name: 'Second',
|
||||
|
|
@ -339,7 +352,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const app = new Hono();
|
||||
createHttpSecurity({ disabled: true, environment: 'test' }).mount(app);
|
||||
app.route('/', createBacktestV2Routes({ postgres: f.postgres, logger }));
|
||||
const body = { ...f.definition, autoStart: false };
|
||||
const body = { ...f.definitionInput, autoStart: false };
|
||||
expect(
|
||||
(
|
||||
await app.request('/api/v2/backtests', {
|
||||
|
|
@ -585,7 +598,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const f = await fixture();
|
||||
const runId = randomUUID();
|
||||
const snapshot = backtestRequestFromDefinition(
|
||||
{ ...f.definition, config: { ...f.definition.config, datasetHash: 'f'.repeat(64) } },
|
||||
{ ...f.definitionInput, config: { ...f.definition.config, datasetHash: 'f'.repeat(64) } },
|
||||
{ runId, backtestId: f.definition.id }
|
||||
);
|
||||
// Imported history can reference unavailable storage; retain its request and report the loss.
|
||||
|
|
@ -637,7 +650,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const snapshot = (
|
||||
await f.pool.query('SELECT request_snapshot FROM runs WHERE id = $1', [run.id])
|
||||
).rows[0].request_snapshot;
|
||||
const expected = backtestRequestFromDefinition(f.definition, {
|
||||
const expected = backtestRequestFromDefinition(f.definitionInput, {
|
||||
runId: run.id,
|
||||
backtestId: f.definition.id,
|
||||
speedMultiplier: 7,
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ const migrations = [
|
|||
'15-canonical-paper-intents.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
|
|||
|
|
@ -19,7 +19,8 @@ const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
|||
const cleanup: (() => Promise<void>)[] = [];
|
||||
const sql = (name: string) =>
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8');
|
||||
const retention = sql('17-research-retention.sql');
|
||||
const retention =
|
||||
sql('17-research-retention.sql') + '\n' + sql('18-backtest-strategy-versions.sql');
|
||||
const request = {
|
||||
name: 'Retained evidence',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
@ -34,7 +35,7 @@ afterEach(async () => {
|
|||
await close();
|
||||
}
|
||||
});
|
||||
async function fixture(install = true) {
|
||||
async function fixture() {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
|
|
@ -58,14 +59,11 @@ async function fixture(install = true) {
|
|||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
// The pre17 setup mode is only for constructing historical/corrupt imported rows.
|
||||
await pool.query('ALTER TABLE backtests ADD COLUMN archived_at timestamptz');
|
||||
if (install) {
|
||||
await pool.query(retention);
|
||||
}
|
||||
await pool.query(retention);
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
|
|
@ -391,18 +389,20 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
|
|||
});
|
||||
|
||||
test('preexisting corrupted datasets remain immutable and fail checksum verification on retrieval', async () => {
|
||||
const f = await fixture(false);
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const claim = await f.repository.start(await f.snapshot(run.id));
|
||||
const dataset = await f.repository.freezeDataset(
|
||||
const dataset = await f.dataset(run.id);
|
||||
const corrupt = structuredClone(dataset);
|
||||
corrupt.bars[0]!.volume = 0;
|
||||
await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2)', [
|
||||
dataset.manifest.hash,
|
||||
corrupt,
|
||||
]);
|
||||
await f.pool.query('UPDATE runs SET dataset_hash=$2 WHERE id=$1', [
|
||||
run.id,
|
||||
claim.attemptId,
|
||||
await f.dataset(run.id)
|
||||
);
|
||||
await f.pool.query(
|
||||
"UPDATE backtest_datasets SET payload=jsonb_set(payload,'{bars,0,volume}','0') WHERE hash=$1",
|
||||
[dataset.manifest.hash]
|
||||
);
|
||||
dataset.manifest.hash,
|
||||
]);
|
||||
await f.pool.query(retention);
|
||||
await expect(f.repository.loadDataset(run.id, claim.attemptId)).rejects.toThrow('hash/content');
|
||||
await expect(
|
||||
|
|
|
|||
|
|
@ -65,7 +65,9 @@ async function fixture() {
|
|||
'12-historical-datasets.sql',
|
||||
'13-strategy-recovery.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue