feat(research): cut over canonical runtime and enforce agent budgets

This commit is contained in:
Boki 2026-10-24 16:47:19 -04:00
parent ab08db82fd
commit bbf0dd4453
103 changed files with 6138 additions and 3112 deletions

View file

@ -216,7 +216,7 @@
},
"orchestrator": {
"port": 2004,
"defaultMode": "paper",
"defaultMode": "backtest",
"paperTradingCapital": 100000,
"enableWebSocket": true,
"backtesting": {

View file

@ -48,6 +48,10 @@
"./walk-forward": {
"types": "./dist/contracts/walk-forward.d.ts",
"default": "./dist/contracts/walk-forward.js"
},
"./research-agents": {
"types": "./dist/contracts/research-agents.d.ts",
"default": "./dist/contracts/research-agents.js"
}
},
"scripts": {

View file

@ -1,6 +1,10 @@
/** Prepared inputs only: this contract does not admit runs or certify out-of-sample evidence. */
import { z } from 'zod';
import type { CanonicalBacktestAnalytics, HistoricalDatasetManifestV2 } from '@stock-bot/types';
import type {
CanonicalBacktestAnalytics,
HistoricalDatasetManifestV2,
ResearchActor,
} from '@stock-bot/types';
import type { CanonicalRunRequest } from './canonical-research';
import {
experimentInputSchema,
@ -123,7 +127,7 @@ export interface ChronologicalValidationSelection {
previewHash: string;
selectionHash: string;
createdAt: string;
principal: 'operator' | 'service';
principal: ResearchActor;
/** Current original-version approval for the new holdout admissions. */
reviewId: string;
winner: ExperimentCandidate;
@ -139,7 +143,7 @@ export interface ChronologicalValidationReport {
selectionHash: string;
reportHash: string;
createdAt: string;
principal: 'operator' | 'service';
principal: ResearchActor;
/** Independent reset accounts. This is not a continuous portfolio equity curve. */
reset: 'initial-capital-empty-positions';
/** All training candidates in ascending original candidate index. */
@ -155,7 +159,7 @@ export interface ChronologicalValidationActionReceipt {
previewHash: string;
selectionHash: string;
createdAt: string;
principal: 'operator' | 'service';
principal: ResearchActor;
}
export interface ValidationActionCapability {
available: boolean;

View file

@ -3,6 +3,7 @@ import { z } from 'zod';
import type {
CanonicalBacktestAnalytics,
HistoricalDatasetManifestV2,
ResearchActor,
StrategyParameterValue,
} from '@stock-bot/types';
import type { CanonicalRunRequest } from './canonical-research';
@ -67,7 +68,7 @@ export interface ExperimentTrialRetry {
pausedAt: string | null;
failureUpdatedAt: string;
recordedAt: string;
principal: 'operator' | 'service';
principal: ResearchActor;
/** Current approval at retry admission; the original run snapshot stays immutable. */
reviewId: string;
}

View file

@ -0,0 +1,76 @@
import { z } from 'zod';
export const researchAgentIdSchema = z
.string()
.regex(/^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
const count = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);
export const researchAgentLimitsSchema = z
.object({
maxActiveTrials: count,
maxTrialsPerExperiment: count,
maxBarEvaluationsPerExperiment: count,
maxAttemptWallMs: count.max(2147483647),
maxAttempts: count.max(3),
})
.strict();
export type ResearchAgentLimits = z.infer<typeof researchAgentLimitsSchema>;
const ids = z
.array(
z
.string()
.uuid()
.transform(value => value.toLowerCase())
)
.refine(values => new Set(values).size === values.length, 'Duplicate identifiers');
export const createResearchAgentSchema = z
.object({
name: z.string().trim().min(1),
allowedProjectIds: ids,
allowedBacktestIds: ids,
limits: researchAgentLimitsSchema,
})
.strict();
export const updateResearchAgentSchema = createResearchAgentSchema
.partial()
.extend({
expectedRevision: count,
enabled: z.boolean().optional(),
})
.strict()
.refine(
value => Object.keys(value).some(key => key !== 'expectedRevision'),
'Supply a policy change'
);
export const researchAgentRecordSchema = z
.object({
id: researchAgentIdSchema,
name: z.string().min(1),
enabled: z.boolean(),
revision: count,
allowedProjectIds: ids,
grants: z.array(
z
.object({ backtestId: z.string().uuid(), policyHash: z.string().regex(/^[a-f0-9]{64}$/) })
.strict()
),
limits: researchAgentLimitsSchema,
createdAt: z.string().datetime(),
updatedAt: z.string().datetime(),
})
.strict();
export type ResearchAgentRecord = z.infer<typeof researchAgentRecordSchema>;
export const researchAgentBudgetSchema = z
.object({
agent: researchAgentRecordSchema,
activeTrials: z.number().int().nonnegative(),
remainingActiveTrials: z.number().int().nonnegative(),
})
.strict();
export type ResearchAgentBudget = z.infer<typeof researchAgentBudgetSchema>;
export interface ResearchAgentAuditEvent {
id: string;
agentId: string;
operation: string;
entityId: string;
createdAt: string;
}

View file

@ -1,8 +1,12 @@
import { z } from 'zod';
import { isResearchActor, type ResearchActor } from '@stock-bot/types';
import { assertStrategyJsonText } from './strategy';
export const researchIdSchema = z.string().uuid();
export const researchActorSchema = z.enum(['operator', 'service']);
export const researchActorSchema = z.custom<ResearchActor>(
isResearchActor,
'Invalid research actor'
);
const origin = z.enum(['human', 'ai', 'unknown']).optional();
const title = z.string().trim().min(1);
const ordinal = z.number().int().positive().max(2147483647);

View file

@ -1,5 +1,6 @@
/** A bounded collection of existing chronological validations, not a new execution engine. */
import { z } from 'zod';
import type { ResearchActor } from '@stock-bot/types';
import {
chronologicalValidationInputSchema,
type ChronologicalValidationDetail,
@ -70,7 +71,7 @@ export interface WalkForwardReport {
previewHash: string;
reportHash: string;
createdAt: string;
principal: 'operator' | 'service';
principal: ResearchActor;
reset: 'initial-capital-empty-positions';
/** Every frozen window in ascending index; absent evidence cannot be omitted. */
segments: WalkForwardSegment[];
@ -107,7 +108,7 @@ export interface WalkForwardReceipt {
previewHash: string;
reportHash: string;
createdAt: string;
principal: 'operator' | 'service';
principal: ResearchActor;
}
export interface WalkForwardActionResult {
receipt: WalkForwardReceipt;

View file

@ -85,7 +85,7 @@ export const stockAppSchema = baseAppSchema.extend({
orchestrator: z
.object({
port: z.number().default(3002),
defaultMode: z.enum(['backtest', 'paper', 'live']).default('paper'),
defaultMode: z.enum(['backtest', 'paper', 'live']).default('backtest'),
paperTradingCapital: z.number().default(100000),
// Validated by the orchestrator's canonical contract before opening resources.
canonicalPaper: z.record(z.unknown()).optional(),

View file

@ -60,19 +60,6 @@ impl BacktestEngine {
})
}
#[napi]
pub fn add_typescript_strategy(
&mut self,
_name: String,
_id: String,
_parameters: napi::JsObject,
_callback: napi::JsFunction,
) -> Result<()> {
Err(Error::from_reason(
"TypeScript strategy callbacks are not supported by the native engine",
))
}
#[napi]
pub fn add_native_strategy(
&mut self,

View file

@ -1,9 +1,13 @@
import { ServiceContainerBuilder } from '@stock-bot/di';
import { defined } from '@stock-bot/invariants';
import { registerOrchestratorServices } from '../src/container';
import { ModeManager } from '../src/core/ModeManager';
import { ExecutionService } from '../src/services/ExecutionService';
import { MarketDataService } from '../src/services/MarketDataService';
import { StorageService } from '../src/services/StorageService';
import { createBuiltinStrategyRegistry } from '../src/strategies/builtin-strategies';
import { StrategyManager } from '../src/strategies/StrategyManager';
import type { OrchestratorServices } from '../src/types';
/** Offline examples explicitly opt into seeded synthetic data. No provider credentials are used. */
/** Legacy algorithm examples only: no queue, HTTP server, durable runs, or paper account. */
export async function createExampleRuntime() {
const di = await new ServiceContainerBuilder()
.withOptions({
@ -16,18 +20,52 @@ export async function createExampleRuntime() {
enableProxy: false,
})
.build();
await registerOrchestratorServices(di, {
initializeMode: false,
const container = di.resolve('serviceContainer') as OrchestratorServices;
const storageService = new StorageService(container, null, null, null, {
allowSyntheticData: true,
syntheticSeed: 42,
});
const container = di.resolve('serviceContainer') as OrchestratorServices;
const marketDataService: MarketDataService = new MarketDataService({
logger: container.logger,
storage: storageService,
drainStrategies: () => strategyManager.drain(),
});
const executionService = new ExecutionService(container, storageService, {
allowedMode: 'backtest',
});
const registry = createBuiltinStrategyRegistry();
const strategyManager: StrategyManager = new StrategyManager({
logger: container.logger,
marketData: marketDataService,
execution: executionService,
createStrategy: config => registry.create(config, { modeManager, execution: executionService }),
});
const modeManager: ModeManager = new ModeManager({
allowedMode: 'backtest',
logger: container.logger,
marketData: marketDataService,
execution: executionService,
storage: storageService,
strategies: strategyManager,
});
const custom = container.custom ?? {};
if (!container.custom) {
Object.defineProperty(container, 'custom', { value: custom, enumerable: true });
}
Object.assign(custom, {
StorageService: storageService,
MarketDataService: marketDataService,
ExecutionService: executionService,
StrategyManager: strategyManager,
ModeManager: modeManager,
});
strategyManager.setupEventListeners();
return {
container,
storageService: defined(container.custom?.StorageService),
marketDataService: defined(container.custom?.MarketDataService),
executionService: defined(container.custom?.ExecutionService),
modeManager: defined(container.custom?.ModeManager),
strategyManager: defined(container.custom?.StrategyManager),
storageService,
marketDataService,
executionService,
modeManager,
strategyManager,
};
}

View file

@ -1,13 +1,14 @@
import type { BacktestRunner } from '../src/backtest/BacktestRunner';
import type { BacktestEngine } from '../src/backtest/BacktestEngine';
import { BacktestConfigSchema, type BacktestConfig } from '../src/types';
/**
* Call with the application's already-composed TypeScript runner and real historical range.
* Preserved offline prototype for older strategy algorithms; not a production research route.
* Importing this example starts no services, loads no model and submits no work.
* The caller owns runner/service shutdown; the ordinary runner persists the actual result.
* A standalone prototype engine owns this demonstration. It does not create durable research results.
* Production research uses approved retained versions and the canonical runner.
*/
export function runMultiStrategyBacktest(
runner: Pick<BacktestRunner, 'runBacktest'>,
runner: Pick<BacktestEngine, 'runBacktest'>,
range: Pick<BacktestConfig, 'symbols' | 'startDate' | 'endDate'>
) {
const request = BacktestConfigSchema.parse({

View file

@ -3,7 +3,7 @@ import { z } from 'zod';
import { defined } from '@stock-bot/invariants';
import { HistoricalDataRequestError } from '@stock-bot/types';
import { parseBacktestRequest } from '../../backtest/BacktestRunner';
import { BacktestCancelledError } from '../../backtest/execution-engine';
import { BacktestCancelledError, LEGACY_EXECUTION_RETIRED } from '../../backtest/execution-engine';
import { BacktestConflictError } from '../../backtest/run-repository';
import type { OrchestratorServices as IServiceContainer } from '../../types';
@ -239,60 +239,8 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
return new Response(stream);
});
// Validate backtest configuration
app.post('/validate', async c => {
try {
const body = await c.req.json();
const config = parseBacktestRequest(body);
// Additional validation logic
const validation = {
valid: true,
warnings: [] as string[],
estimatedDuration: 0,
};
// Check data availability
const startDate = new Date(config.startDate);
const endDate = new Date(config.endDate);
const days = (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24);
if (days > 365) {
validation.warnings.push('Large date range may take significant time to process');
}
if (config.symbols.length > 100) {
validation.warnings.push('Large number of symbols may impact performance');
}
// Estimate duration (simplified)
validation.estimatedDuration = days * config.symbols.length * 0.1; // seconds
return c.json(validation);
} catch (error) {
if (error instanceof BacktestConflictError) {
return c.json({ error: error.message }, 409);
}
if (error instanceof z.ZodError) {
return c.json(
{
valid: false,
error: 'Invalid configuration',
details: error.errors,
},
400
);
}
return c.json(
{
valid: false,
error: error instanceof Error ? error.message : 'Validation failed',
},
500
);
}
});
// The old route cannot approve unversioned strategies or mutable provider inputs.
app.post('/validate', c => c.json({ valid: false, error: LEGACY_EXECUTION_RETIRED }, 409));
return app;
}

View file

@ -3,22 +3,21 @@ import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import {
canonicalRunRequestSchema,
isCanonicalRunResult,
type CanonicalRunRequest,
type CanonicalRunResult,
type ResearchRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
import { prepareDataset } from '../data/historical-dataset';
import type { BacktestRunResult } from '@stock-bot/types';
import type { BacktestConfig } from '../types';
import { BacktestCancelledError, type BacktestExecutionEngine } from './execution-engine';
import { normalizeBacktestResult } from './result';
import {
BacktestCancelledError,
LEGACY_EXECUTION_RETIRED,
type BacktestExecutionEngine,
} from './execution-engine';
import {
BacktestConflictError,
BacktestLeaseLostError,
type BacktestRunRepository,
type CanonicalRunClaim,
type RunClaim,
} from './run-repository';
export { parseBacktestRequest };
@ -32,16 +31,16 @@ function parseDurableRequest(input: unknown): DurableRequest {
: parseBacktestRequest(input);
}
/** One application workflow for HTTP, jobs, and both execution backends. */
/** One canonical workflow for durably admitted research jobs. */
export class BacktestRunner extends EventEmitter {
private busy = false;
private active: RunClaim | CanonicalRunClaim | undefined;
private active: CanonicalRunClaim | undefined;
private leaseFailure: BacktestLeaseLostError | undefined;
private cancelled = false;
private progressWrites: Promise<void> = Promise.resolve();
private closing = false;
private phase: 'preparing' | 'executing' | 'persisting' = 'preparing';
private execution: Promise<ResearchRunResult> | undefined;
private execution: Promise<CanonicalRunResult> | undefined;
constructor(
private readonly dependencies: {
@ -51,20 +50,18 @@ export class BacktestRunner extends EventEmitter {
logger: Pick<Logger, 'error'>;
heartbeatMs?: number;
heartbeatTimeoutMs?: number;
prepare?: (config: BacktestConfig) => Promise<void>;
}
) {
super();
}
/** Retained only to diagnose obsolete callers; canonical work requires durable admission. */
async runBacktest(input: unknown): Promise<BacktestRunResult> {
return this.begin(parseBacktestRequest(input));
parseBacktestRequest(input);
throw new BacktestConflictError(LEGACY_EXECUTION_RETIRED);
}
private begin(config: BacktestConfig): Promise<BacktestRunResult>;
private begin(config: CanonicalRunRequest): Promise<CanonicalRunResult>;
private begin(config: DurableRequest): Promise<ResearchRunResult>;
private begin(config: DurableRequest): Promise<ResearchRunResult> {
private begin(config: CanonicalRunRequest): Promise<CanonicalRunResult> {
if (this.closing) {
throw new BacktestConflictError('Backtest runner is shutting down');
}
@ -101,15 +98,32 @@ export class BacktestRunner extends EventEmitter {
);
throw error;
}
const result = await this.begin({ ...snapshot, runId });
if (!isCanonicalRequest(snapshot)) {
await this.dependencies.repository.rejectPending(runId, LEGACY_EXECUTION_RETIRED);
const retired = await this.dependencies.repository.load(runId);
return { runId, status: retired?.status ?? 'missing' };
}
const result = await this.begin(snapshot);
return { runId, status: result.status };
}
private async execute(config: DurableRequest): Promise<ResearchRunResult> {
private async execute(config: CanonicalRunRequest): Promise<CanonicalRunResult> {
const started = performance.now();
this.progressWrites = Promise.resolve();
let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
let heartbeatWork: Promise<void> | undefined;
let executionDeadline: ReturnType<typeof setTimeout> | undefined;
let deadlineFailure: Error | undefined;
let deadlineStop: Promise<void> | undefined;
const checkDeadline = () => {
const deadline = this.active?.executionDeadlineAt;
if (deadline !== undefined && Date.now() >= deadline) {
deadlineFailure ??= new Error('Research attempt exceeded its admitted execution deadline');
}
if (deadlineFailure) {
throw deadlineFailure;
}
};
const heartbeat = async () => {
const active = this.active;
if (!active) {
@ -183,19 +197,43 @@ export class BacktestRunner extends EventEmitter {
};
this.dependencies.engine.on('progress', onProgress);
try {
if (isCanonicalRequest(config)) {
if (!this.dependencies.repository.startCanonical) {
throw new Error('Canonical run repository is unavailable');
}
this.active = await this.dependencies.repository.startCanonical(config);
} else {
this.active = await this.dependencies.repository.start(config);
if (!this.dependencies.repository.startCanonical) {
throw new Error('Canonical run repository is unavailable');
}
this.active = await this.dependencies.repository.startCanonical(config);
if (
this.active.executionDeadlineAt !== undefined &&
(!Number.isSafeInteger(this.active.executionDeadlineAt) ||
this.active.executionDeadlineAt - Date.now() > 2_147_483_647)
) {
throw new Error('Invalid admitted research execution deadline');
}
checkDeadline();
if (this.active.executionDeadlineAt !== undefined) {
executionDeadline = setTimeout(
() => {
deadlineFailure = new Error(
'Research attempt exceeded its admitted execution deadline'
);
if (this.phase === 'executing') {
deadlineStop = this.dependencies.engine.stopBacktest().catch(error => {
this.dependencies.logger.error('Could not stop expired research attempt', {
error,
});
});
}
},
Math.max(0, this.active.executionDeadlineAt - Date.now())
);
executionDeadline.unref();
}
const executionConfig = canonicalRunRequestSchema.parse(this.active.config);
if (
executionConfig.runId !== this.active.runId ||
executionConfig.backtestId !== this.active.backtestId
) {
throw new Error('Canonical claim identity mismatch');
}
const executionConfig = parseDurableRequest({
...this.active.config,
runId: this.active.runId,
backtestId: this.active.backtestId,
});
heartbeatTimer = setInterval(() => {
if (!heartbeatWork) {
heartbeatWork = heartbeat().finally(() => {
@ -205,15 +243,7 @@ export class BacktestRunner extends EventEmitter {
}, this.dependencies.heartbeatMs ?? 5_000);
heartbeatTimer.unref();
await heartbeat();
if (this.leaseFailure) {
throw this.leaseFailure;
}
if (this.cancelled) {
throw new BacktestCancelledError();
}
if (!isCanonicalRequest(executionConfig)) {
await this.dependencies.prepare?.(executionConfig);
}
checkDeadline();
if (this.leaseFailure) {
throw this.leaseFailure;
}
@ -221,8 +251,8 @@ export class BacktestRunner extends EventEmitter {
throw new BacktestCancelledError();
}
this.phase = 'executing';
let result: ResearchRunResult;
if (isCanonicalRequest(executionConfig)) {
let result: CanonicalRunResult;
{
const engine = this.dependencies.engine;
const repository = this.dependencies.repository;
const loadCanonicalDataset = repository.loadCanonicalDataset;
@ -254,89 +284,40 @@ export class BacktestRunner extends EventEmitter {
request: executionConfig,
...report,
};
} else {
let manifest: HistoricalDatasetManifest | undefined;
const claim = this.active;
const raw = await this.dependencies.engine.runBacktest(
executionConfig,
async (load, signal) => {
signal?.throwIfAborted();
const saved = await this.dependencies.repository.loadDataset(
claim.runId,
claim.attemptId,
executionConfig.datasetHash,
signal
);
const dataset = await prepareDataset(saved ?? (await load()), executionConfig, signal);
signal?.throwIfAborted();
const frozen =
saved ??
(await this.dependencies.repository.freezeDataset(
claim.runId,
claim.attemptId,
dataset,
signal
));
signal?.throwIfAborted();
manifest = frozen.manifest;
return frozen;
}
);
if (!manifest) {
throw new Error('Backtest engine did not resolve frozen execution inputs');
}
if (this.leaseFailure) {
throw this.leaseFailure;
}
try {
result = normalizeBacktestResult(
raw,
this.dependencies.engineName,
executionConfig,
this.active,
performance.now() - started,
this.cancelled,
manifest
);
} catch (error) {
throw new Error('Backtest engine returned an invalid result', { cause: error });
}
}
checkDeadline();
this.phase = 'persisting';
await this.progressWrites;
if (this.leaseFailure) {
throw this.leaseFailure;
}
if (isCanonicalRunResult(result)) {
const completeCanonical = this.dependencies.repository.completeCanonical;
if (!completeCanonical) {
throw new Error('Canonical result persistence is unavailable');
}
await completeCanonical.call(this.dependencies.repository, result, this.active.attemptId);
} else {
await this.dependencies.repository.complete(result, this.active.attemptId);
const completeCanonical = this.dependencies.repository.completeCanonical;
if (!completeCanonical) {
throw new Error('Canonical result persistence is unavailable');
}
checkDeadline();
await completeCanonical.call(this.dependencies.repository, result, this.active.attemptId);
// Observers cannot turn a committed success into a failed run.
this.publish('complete', result);
return result;
} catch (error) {
await this.progressWrites;
let failure = this.leaseFailure ?? error;
let failure = this.leaseFailure ?? deadlineFailure ?? error;
if (this.active && !(failure instanceof BacktestLeaseLostError)) {
try {
if (error instanceof BacktestCancelledError) {
if (failure instanceof BacktestCancelledError) {
await this.dependencies.repository.cancel(this.active.runId, this.active.attemptId);
} else {
await this.dependencies.repository.fail(
this.active.runId,
error instanceof Error ? error.message : String(error),
failure instanceof Error ? failure.message : String(failure),
this.active.attemptId
);
}
} catch (persistenceError) {
this.dependencies.logger.error('Could not record backtest failure', { persistenceError });
// A cancellation acknowledgement must never conceal a failed status write.
if (error instanceof BacktestCancelledError) {
if (failure instanceof BacktestCancelledError) {
failure = persistenceError;
}
}
@ -352,6 +333,10 @@ export class BacktestRunner extends EventEmitter {
}
throw failure;
} finally {
if (executionDeadline) {
clearTimeout(executionDeadline);
}
await deadlineStop;
if (heartbeatTimer) {
clearInterval(heartbeatTimer);
}

View file

@ -16,6 +16,7 @@ import {
import { canonicalWorkerUrl } from './canonical-build';
import {
nativeWorkerMessageSchema,
nativeWorkerRequestSchema,
parseRetainedStrategyResult,
retainedStrategyRequestSchema,
type NativeWorkerRequest,
@ -34,6 +35,7 @@ export class NativeBacktestWorker {
onProgress: (progress: { progress: number; message: string }) => void
): Promise<string> {
signal.throwIfAborted();
request = nativeWorkerRequestSchema.parse(request);
if (this.active) {
throw new BacktestConflictError('A native backtest worker is already running');
}

View file

@ -137,12 +137,12 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
const attemptId = randomUUID();
return this.ownedTransaction(request.runId, async client => {
const claimed = await client.query(
`UPDATE runs SET status='running', progress=0, error=NULL,
`UPDATE runs AS r SET status='running', progress=0, error=NULL,
started_at=NOW(), completed_at=NULL, paused_at=NULL, updated_at=NOW(),
attempt_id=$3, attempt_number=attempt_number+1,
lease_expires_at=clock_timestamp()+$4::interval
WHERE id=$1 AND backtest_id=$2 AND status='pending' AND NOT cancel_requested
AND request_snapshot IS NOT NULL RETURNING id,backtest_id,request_snapshot,dataset_hash`,
AND request_snapshot IS NOT NULL RETURNING id,backtest_id,request_snapshot,dataset_hash,(to_jsonb(r)->>'research_deadline_at')::timestamptz AS research_deadline_at`,
[request.runId, request.backtestId, attemptId, `${this.leaseMs} milliseconds`]
);
const row = claimed.rows[0];
@ -163,6 +163,9 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
backtestId: String(row.backtest_id),
attemptId,
config: frozen,
...(row.research_deadline_at
? { executionDeadlineAt: new Date(row.research_deadline_at).getTime() }
: {}),
};
});
}

View file

@ -1,24 +1,22 @@
import { EventEmitter } from 'node:events';
import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import {
canonicalRunRequestSchema,
type CanonicalRunRequest,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type { HistoricalDatasetV2 } from '@stock-bot/types';
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation';
import type { DatasetResolver } from '../data/historical-dataset';
import type { StorageService } from '../services/StorageService';
import type { BacktestConfig } from '../types';
import {
BacktestCancelledError,
BacktestTimeoutError,
LEGACY_EXECUTION_RETIRED,
type BacktestExecutionEngine,
} from './execution-engine';
import { nativeResultSchema, type NativeBacktestResult } from './native-result';
import { resolveNativeStrategies } from './native-strategies';
import { parseRetainedStrategyResult, type NativeWorkerRequest } from './native-worker-protocol';
import type { NativeBacktestResult } from './native-result';
import { parseRetainedStrategyResult } from './native-worker-protocol';
import { NativeBacktestWorker } from './NativeBacktestWorker';
export type BacktestResult = NativeBacktestResult;
@ -52,22 +50,10 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
}
async runBacktest(
input: BacktestConfig,
dataset?: DatasetResolver
_input: BacktestConfig,
_dataset?: DatasetResolver
): Promise<NativeBacktestResult> {
const config = parseBacktestRequest(input);
return this.runOwned(Date.parse(config.startDate), async (signal, aborted) => {
resolveNativeStrategies(config);
const data = await Promise.race([this.loadData(config, signal, dataset), aborted]);
signal.throwIfAborted();
const raw = await this.worker.execute({ type: 'run', config, data }, signal, progress => {
this.progress = progress.progress;
this.publish('progress', progress);
});
const result = nativeResultSchema.parse(JSON.parse(raw));
this.currentTime = Date.parse(config.endDate);
return result;
});
throw new Error(LEGACY_EXECUTION_RETIRED);
}
async runCanonical(
@ -95,7 +81,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
);
}
/** One ownership/deadline/cancellation lifecycle for legacy and canonical work. */
/** One ownership/deadline/cancellation lifecycle for canonical work. */
private async runOwned<Result>(
initialTime: number,
work: (signal: AbortSignal, aborted: Promise<never>) => Promise<Result>
@ -147,25 +133,6 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
}
}
private async loadData(
config: BacktestConfig,
signal: AbortSignal,
resolver?: DatasetResolver
): Promise<Extract<NativeWorkerRequest, { type: 'run' }>['data']> {
signal.throwIfAborted();
const dataset = await resolveDataset(this.dependencies.storage, config, resolver, signal);
signal.throwIfAborted();
const data: Extract<NativeWorkerRequest, { type: 'run' }>['data'] = [];
for (const bar of dataset.bars) {
data.push({ ...bar, type: 'bar' });
if (data.length % PREPARATION_BATCH_SIZE === 0) {
await preparationCheckpoint(signal);
}
}
signal.throwIfAborted();
return data;
}
private publish(event: string, data: unknown): void {
try {
this.emit(event, data);

View file

@ -46,3 +46,7 @@ export class BacktestTimeoutError extends Error {
this.name = 'BacktestTimeoutError';
}
}
/** Old requests remain readable, but must be explicitly reconfigured for canonical admission. */
export const LEGACY_EXECUTION_RETIRED =
'Legacy backtest execution is retired. Select an approved strategy version and retained canonical dataset.';

View file

@ -262,6 +262,15 @@ export interface ReplayController {
): FinancialStrategyDecision[];
committed?(outcome: ReplaySubmissionOutcome): void;
}
/** Restricted hosts communicate asynchronously; financial transitions still run
* on the same native session and the same ordered pull loop. */
export interface AsyncReplayController {
stage(
context: DecisionContext,
observations: readonly PublishedObservation[]
): Promise<FinancialStrategyDecision[]>;
committed?(outcome: ReplaySubmissionOutcome): Promise<void>;
}
/* eslint-disable no-redeclare -- TypeScript overloads preserve the existing trace result type. */
export function runReplayConformance(
session: NativeReplaySession,
@ -329,6 +338,63 @@ export function runReplaySession(
controller: ReplayController,
options: ReplayOptions = {}
) {
const loop = replaySteps(session, options);
try {
let step = loop.next();
while (!step.done) {
const action = step.value;
step = loop.next(
action.kind === 'stage'
? controller.stage(action.context, action.observations)
: controller.committed?.(action.outcome)
);
}
return step.value;
} finally {
// A controller may throw while the generator is suspended at a decision.
// Closing it runs the native disposal even without another advance call.
loop.return(undefined as never);
}
}
export async function runReplaySessionAsync(
session: NativeReplaySession,
controller: AsyncReplayController,
options: ReplayOptions = {}
) {
const loop = replaySteps(session, options);
try {
let step = loop.next();
while (!step.done) {
const action = step.value;
step = loop.next(
action.kind === 'stage'
? await controller.stage(action.context, action.observations)
: await controller.committed?.(action.outcome)
);
}
return step.value;
} finally {
loop.return(undefined as never);
}
}
type ReplayAction =
| {
kind: 'stage';
context: DecisionContext;
observations: readonly PublishedObservation[];
}
| { kind: 'committed'; outcome: ReplaySubmissionOutcome };
function* replaySteps(
session: NativeReplaySession,
options: ReplayOptions
): Generator<
ReplayAction,
{ result: ReplayOutput; metrics: ReplayMetrics },
FinancialStrategyDecision[] | void
> {
const metrics: ReplayMetrics = {
advanceCalls: 0,
submitCalls: 0,
@ -386,7 +452,10 @@ export function runReplaySession(
observations = [];
// Stage all decisions before one admission. A thrown fixture disposes
// the attempt; it cannot publish a partial barrier or successful run.
const decisions = controller.stage(context, publishedDelta);
const decisions = yield { kind: 'stage', context, observations: publishedDelta };
if (!Array.isArray(decisions)) {
throw new Error('Replay controller did not return decisions');
}
metrics.decisionMs += performance.now() - start;
const submitStart = performance.now(),
outcome = session.submit(context.barrier.barrier_id, decisions);
@ -395,11 +464,9 @@ export function runReplaySession(
if (typeof outcome.status === 'object') {
throw new Error(outcome.status.Failed.diagnostic);
}
if (controller.committed) {
const commitStart = performance.now();
controller.committed(outcome);
metrics.decisionMs += performance.now() - commitStart;
}
const commitStart = performance.now();
yield { kind: 'committed', outcome };
metrics.decisionMs += performance.now() - commitStart;
break;
}
}

View file

@ -11,28 +11,9 @@ import type { CanonicalBacktestAnalytics } from '@stock-bot/types';
import { replayTraceSchema } from '../contracts/native-replay';
import type { ReplayReportResult } from '../contracts/native-replay';
import { strategyReplayRequestSchema } from '../contracts/strategy-replay';
import { BacktestConfigSchema } from '../types';
import { buildCanonicalBacktestReport } from './canonical-result';
const finite = z.number().finite();
const legacyRequestSchema = z.object({
type: z.literal('run'),
config: BacktestConfigSchema,
data: z.array(
z.object({
symbol: z.string(),
timestamp: finite,
type: z.literal('bar'),
open: finite,
high: finite,
low: finite,
close: finite,
volume: finite,
vwap: finite,
})
),
});
export const retainedStrategyRequestSchema = z
.object({
type: z.literal('runRetainedStrategy'),
@ -42,7 +23,6 @@ export const retainedStrategyRequestSchema = z
.strict();
export const nativeWorkerRequestSchema = z.union([
legacyRequestSchema,
replayTraceSchema,
strategyReplayRequestSchema,
retainedStrategyRequestSchema,

View file

@ -1,5 +1,4 @@
import { createHash } from 'node:crypto';
import { BacktestEngine } from '@stock-bot/engine';
import type { StrategyProgram } from '../contracts/canonical-strategy';
import type { StrategyReplayResult } from '../contracts/strategy-replay';
import {
@ -10,7 +9,6 @@ import { freeze } from '../strategies/strategy-decision';
import { verifyCanonicalWorkerBuild } from './canonical-build';
import { buildCanonicalBacktestReport } from './canonical-result';
import { executeReplayTrace, prepareReplayLoad } from './native-replay';
import { resolveNativeStrategies } from './native-strategies';
import {
nativeWorkerRequestSchema,
type NativeWorkerMessage,
@ -138,34 +136,11 @@ process.once('message', async (input: unknown) => {
if (request.type === 'runReplayTrace') {
await send({ type: 'progress', progress: 0, message: 'Canonical replay trace started' });
// One load and a local pull loop; no per-observation IPC. The supervisor
// can still SIGKILL native work, exactly as for the legacy one-shot path.
// can still SIGKILL native work, without changing financial execution semantics.
const { result } = executeReplayTrace(request);
await send({ type: 'result', result: JSON.stringify(result) });
return;
}
const { config, data } = request;
const engine = new BacktestEngine({
name: config.name ?? 'Backtest',
strategy: config.strategy,
symbols: config.symbols,
startDate: config.startDate,
endDate: config.endDate,
initialCapital: config.initialCapital,
commission: config.commission ?? 0.001,
slippage: config.slippage ?? 0.0001,
dataFrequency: config.dataFrequency,
});
if (config.riskLimits) {
engine.updateRiskLimits(config.riskLimits);
}
for (const { strategy, name, id, parameters } of resolveNativeStrategies(config)) {
engine.addNativeStrategy(strategy, name, id, parameters);
}
data.sort((a, b) => a.timestamp - b.timestamp);
engine.loadMarketData(data);
await send({ type: 'progress', progress: 0, message: 'Native execution started' });
// This synchronous call is deliberately confined to the child process.
await send({ type: 'result', result: engine.run() });
} catch (error) {
await send({ type: 'error', message: error instanceof Error ? error.message : String(error) });
process.exitCode = 1;

View file

@ -15,6 +15,8 @@ export interface RunClaim extends RunIdentity {
}
export interface CanonicalRunClaim extends RunIdentity {
/** Authoritative per-attempt research budget deadline; outside financial semantics. */
executionDeadlineAt?: number;
attemptId: string;
config: CanonicalRunRequest;
}

View file

@ -1,39 +1,24 @@
/** Trusted synchronous programs on the canonical financial engine. Fresh
* attempts recompute from original inputs; diagnostics are not resume tokens. */
import type { FinancialStrategyDecision } from '@stock-bot/types';
import type {
DeepReadonly,
StrategyAdmissionFeedback,
StrategyDiagnostic,
StrategyDiagnosticSnapshot,
StrategyProgram,
} from '../contracts/canonical-strategy';
import {
nativeAdmissionOrders,
replayConfigSchema,
replayIdentitySchema,
type DecisionContext,
type PublishedObservation,
type ReplayIdentity,
type ReplayOutput,
type ReplayProjectionResult,
type ReplayReportResult,
type ReplayResult,
type ReplaySubmissionOutcome,
} from '../contracts/native-replay';
import {
freeze,
increment,
metadataSchema,
stageStrategyDecision,
stateCopy,
type Metadata,
} from '../strategies/strategy-decision';
import { StrategyController } from '../strategies/strategy-controller';
import { freeze } from '../strategies/strategy-decision';
import {
NativeReplaySession,
runReplaySession,
type prepareReplayLoad,
type ReplayController,
type ReplayMetrics,
type ReplayOptions,
} from './native-replay';
@ -57,169 +42,6 @@ export class StrategyReplayError extends Error {
}
}
interface Slot {
program: Metadata & { decide: StrategyProgram['decide'] };
diagnostic: DeepReadonly<StrategyDiagnostic>;
pendingObservations: PublishedObservation[];
}
class StrategyController implements ReplayController {
private slots: Map<string, Slot>;
private committedBarriers = 0;
private lastBarrierId: string | null = null;
private observed = 0;
private staged: {
barrierId: string;
expectedRevision: number;
owners: {
ownerId: string;
diagnostic: StrategyDiagnostic;
decision: FinancialStrategyDecision;
}[];
} | null = null;
constructor(
private readonly identity: ReplayIdentity,
programs: readonly StrategyProgram[],
config: ReturnType<typeof replayConfigSchema.parse>
) {
this.slots = new Map(
programs.map(program => {
const { ownerId, strategyId, strategyVersion, mode, seed } = program;
const metadata = metadataSchema.parse({ ownerId, strategyId, strategyVersion, mode, seed });
const decide = program.decide;
if (typeof decide !== 'function') {
throw new Error('Strategy decide must be synchronous callable code');
}
const diagnostic = freeze({
ownerId,
strategyId,
strategyVersion,
nextDecisionSequence: 0,
state: stateCopy(program.initialState),
rng: { algorithm: 'lcg32-v1' as const, seed, state: seed, draws: 0 },
observationCount: 0,
previousAdmission: null,
});
return [ownerId, { program: { ...metadata, decide }, diagnostic, pendingObservations: [] }];
})
);
const owners = config.matching.owners;
if (
this.slots.size !== programs.length ||
this.slots.size !== owners.length ||
owners.some(owner => this.slots.get(owner.ownerId)?.program.mode !== owner.mode.toLowerCase())
) {
throw new Error('Programs must exactly match configured owners and modes');
}
}
snapshot(): DeepReadonly<StrategyDiagnosticSnapshot> {
return freeze({
version: 1,
identity: this.identity,
committedBarriers: this.committedBarriers,
lastBarrierId: this.lastBarrierId,
strategies: [...this.slots.values()]
.sort((a, b) =>
a.program.ownerId < b.program.ownerId ? -1 : a.program.ownerId > b.program.ownerId ? 1 : 0
)
.map(slot => slot.diagnostic),
});
}
stage(context: DecisionContext, observations: readonly PublishedObservation[]) {
if (this.staged) {
throw new Error('Previous strategy barrier has not committed');
}
this.observed = increment(this.observed, observations.length);
const due = new Set(context.barrier.owner_ids);
if (
this.observed !== context.barrier.observation_count ||
due.size !== context.barrier.owner_ids.length ||
[...due].some(owner => !this.slots.has(owner)) ||
observations.some(observation => observation.available_at > context.barrier.at)
) {
throw new Error('Strategy barrier observation or owner mismatch');
}
const staged: NonNullable<StrategyController['staged']> = {
barrierId: context.barrier.barrier_id,
expectedRevision: increment(context.barrier.revision),
owners: [],
};
for (const slot of this.slots.values()) {
// Other owners may have slower cadence. Do not discard their warmup/prefix.
for (const observation of observations) {
slot.pendingObservations.push(observation);
}
if (!due.has(slot.program.ownerId)) {
continue;
}
staged.owners.push(
stageStrategyDecision(
this.identity.sessionId,
slot.program,
slot.diagnostic,
slot.pendingObservations,
context
)
);
}
this.staged = staged;
return staged.owners.map(owner => owner.decision);
}
committed(outcome: ReplaySubmissionOutcome): void {
const staged = this.staged;
if (
!staged ||
outcome.replayed ||
outcome.status !== 'Running' ||
outcome.revision !== staged.expectedRevision
) {
throw new Error('Unexpected strategy admission acknowledgement');
}
const orders = nativeAdmissionOrders(outcome.effects);
if (
orders.some(
order => !staged.owners.some(owner => owner.ownerId === order.order.decision.ownerId)
)
) {
throw new Error('Admission feedback belongs to an owner outside the barrier');
}
const nextCount = increment(this.committedBarriers);
const next = new Map(this.slots);
// Parse/detach ALL feedback before swapping any committed slot. Even an
// ambiguous/malformed acknowledgement leaves diagnostics at the old barrier.
for (const owner of staged.owners) {
const slot = this.slots.get(owner.ownerId);
if (!slot) {
throw new Error('Staged strategy owner is missing');
}
const previousAdmission: StrategyAdmissionFeedback = {
decision: owner.decision.decision,
revision: outcome.revision,
orders: orders
.filter(order => order.order.decision.ownerId === owner.ownerId)
.map(order => ({
orderId: order.order.orderId,
instrumentId: order.order.instrumentId,
decision: order.order.decision,
status: order.status,
})),
};
next.set(owner.ownerId, {
program: slot.program,
diagnostic: freeze({ ...owner.diagnostic, previousAdmission }),
pendingObservations: [],
});
}
this.slots = next;
this.committedBarriers = nextCount;
this.lastBarrierId = staged.barrierId;
this.staged = null;
}
}
/* eslint-disable no-redeclare -- Keep selected native result formats precise. */
export function runStrategyReplay(
load: ReturnType<typeof prepareReplayLoad>,

View file

@ -1,26 +1,18 @@
import { asValue, type AwilixContainer } from 'awilix';
import type { ServiceCradle as ServiceDefinitions } from '@stock-bot/di';
import { BacktestEngine } from './backtest/BacktestEngine';
import { BacktestRunner } from './backtest/BacktestRunner';
import type { BacktestExecutionEngine } from './backtest/execution-engine';
import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRepository';
import { UnavailableBacktestRunRepository } from './backtest/run-repository';
import { RustBacktestAdapter } from './backtest/RustBacktestAdapter';
import type { PaperConfigurationInput, PaperRuntime } from './contracts/paper-runtime';
import { ModeManager } from './core/ModeManager';
import { PostgresCanonicalExecutionRepository } from './execution/PostgresCanonicalExecutionRepository';
import { BacktestHandler } from './handlers/backtest/backtest.handler';
import { CanonicalPaperRuntime } from './paper/CanonicalPaperRuntime';
import { validatePaperConfiguration } from './paper/feed';
import { PaperTradingManager } from './paper/PaperTradingManager';
import { AnalyticsService } from './services/AnalyticsService';
import { ExecutionService } from './services/ExecutionService';
import { MarketDataService } from './services/MarketDataService';
import { StorageService } from './services/StorageService';
import { createBuiltinStrategyRegistry } from './strategies/builtin-strategies';
import { createBuiltinStrategy } from './strategies/canonical-builtins';
import { StrategyManager } from './strategies/StrategyManager';
import type { StrategyRegistry } from './strategies/StrategyRegistry';
import type { OrchestratorServices as IServiceContainer } from './types';
export type OrchestratorRole = 'paper' | 'research-only';
@ -32,10 +24,8 @@ export function assertSupportedComposition(role: OrchestratorRole, useRustEngine
if (typeof useRustEngine !== 'boolean') {
throw new Error('Runtime useRustEngine option must be a boolean');
}
if (role !== 'research-only' && !useRustEngine) {
throw new Error(
'Unsupported runtime combination: TypeScript backtests require a research-only composition; paper requires the isolated native engine'
);
if (!useRustEngine) {
throw new Error('Legacy financial execution is retired; the canonical Rust engine is required');
}
}
@ -51,12 +41,10 @@ export async function registerOrchestratorServices(
allowSyntheticData?: boolean;
syntheticSeed?: number;
nativeExecutionTimeoutMs?: number;
strategyRegistry?: StrategyRegistry;
canonicalPaper?: PaperConfigurationInput;
paperTradingCapital?: number;
} = {}
): Promise<void> {
const role = options.role === undefined ? 'paper' : options.role;
const role = options.role === undefined ? 'research-only' : options.role;
const useRustEngine = options.useRustEngine === undefined ? true : options.useRustEngine;
assertSupportedComposition(role, useRustEngine);
if (options.canonicalPaper !== undefined && role !== 'paper') {
@ -66,7 +54,11 @@ export async function registerOrchestratorServices(
options.canonicalPaper === undefined
? undefined
: validatePaperConfiguration(options.canonicalPaper);
const allowedMode = role === 'research-only' ? 'backtest' : 'paper';
if (role === 'paper' && !canonicalPaper) {
throw new Error(
'Paper composition requires explicit canonicalPaper configuration; accounts are never migrated automatically'
);
}
// Create a service adapter that provides the expected interface
const services = container.resolve('serviceContainer') as IServiceContainer;
@ -75,22 +67,18 @@ export async function registerOrchestratorServices(
Object.defineProperty(services, 'custom', { value: custom, enumerable: true });
}
if (
custom.CanonicalPaperRuntime ||
container.hasRegistration('CanonicalPaperRuntime') ||
(canonicalPaper &&
(
[
'ModeManager',
'ExecutionService',
'MarketDataService',
'StrategyManager',
'PaperTradingManager',
'BacktestEngine',
'BacktestRunner',
] as const
).some(key => custom[key] || container.hasRegistration(key)))
[
'CanonicalPaperRuntime',
'ModeManager',
'ExecutionService',
'MarketDataService',
'StrategyManager',
'PaperTradingManager',
'BacktestEngine',
'BacktestRunner',
].some(key => custom[key as keyof typeof custom] || container.hasRegistration(key))
) {
throw new Error('Canonical paper requires a fresh runtime composition');
throw new Error('Canonical execution requires a fresh runtime composition');
}
// Create storage service first as it's needed by other services
@ -102,181 +90,71 @@ export async function registerOrchestratorServices(
options
);
if (canonicalPaper) {
if (!services.postgres) {
throw new Error('Canonical paper requires durable PostgreSQL custody');
}
const paper = new CanonicalPaperRuntime({
repository: new PostgresCanonicalExecutionRepository(services.postgres),
programs: canonicalPaper.strategies.map(createBuiltinStrategy),
});
const engine = new RustBacktestAdapter(
{ logger: services.logger, storage: storageService },
{ timeoutMs: options.nativeExecutionTimeoutMs }
);
const runner = new BacktestRunner({
engine,
engineName: 'native',
repository: new PostgresBacktestRunRepository(services.postgres),
logger: services.logger,
});
const analytics = new AnalyticsService(services);
// No legacy order gateway, feed listener or mode initializer is exposed in
// this composition. Research still runs in the existing isolated worker.
Object.assign(custom, {
StorageService: storageService,
AnalyticsService: analytics,
CanonicalPaperRuntime: paper,
BacktestEngine: engine,
BacktestRunner: runner,
});
const canonicalContainer = container as AwilixContainer<
ServiceDefinitions & {
StorageService: StorageService;
AnalyticsService: AnalyticsService;
CanonicalPaperRuntime: PaperRuntime;
BacktestEngine: BacktestExecutionEngine;
BacktestRunner: BacktestRunner;
orchestratorServices: IServiceContainer;
}
>;
canonicalContainer.register({
StorageService: asValue(storageService),
AnalyticsService: asValue(analytics),
CanonicalPaperRuntime: asValue(paper),
BacktestEngine: asValue(engine),
BacktestRunner: asValue(runner),
orchestratorServices: asValue(services),
});
container
.resolve('handlerScanner')
.registerHandlerClass(BacktestHandler, { serviceName: 'orchestrator' });
try {
if (options.initializeMode !== false) {
await paper.initialize(canonicalPaper);
}
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });
} catch (error) {
await paper.shutdown().catch(() => {});
throw error;
}
return;
if (canonicalPaper && !services.postgres) {
throw new Error('Canonical paper requires durable PostgreSQL custody');
}
// Callbacks are invoked after composition: the feed drains the manager, and
// factories receive the current mode without either service locating its peers.
const marketDataService: MarketDataService = new MarketDataService({
logger: services.logger,
storage: storageService,
drainStrategies: () => strategyManager.drain(),
});
const executionService = new ExecutionService(services, storageService, { allowedMode });
const analyticsService = new AnalyticsService(services);
const registry = options.strategyRegistry ?? createBuiltinStrategyRegistry();
const strategyManager: StrategyManager = new StrategyManager({
logger: services.logger,
marketData: marketDataService,
execution: executionService,
createStrategy: config => registry.create(config, { modeManager, execution: executionService }),
});
const modeManager: ModeManager = new ModeManager({
allowedMode,
logger: services.logger,
marketData: marketDataService,
execution: executionService,
storage: storageService,
strategies: strategyManager,
});
const backtestEngine = useRustEngine
? new RustBacktestAdapter(
{ logger: services.logger, storage: storageService },
{
timeoutMs: options.nativeExecutionTimeoutMs,
}
)
: new BacktestEngine({
logger: services.logger,
storage: storageService,
strategies: strategyManager,
execution: executionService,
getTradingEngine: () => modeManager.getTradingEngine(),
});
const paperTradingManager = new PaperTradingManager(
services,
storageService,
marketDataService,
executionService
const paper =
canonicalPaper && services.postgres
? new CanonicalPaperRuntime({
repository: new PostgresCanonicalExecutionRepository(services.postgres),
programs: canonicalPaper.strategies.map(createBuiltinStrategy),
})
: undefined;
const engine = new RustBacktestAdapter(
{ logger: services.logger, storage: storageService },
{ timeoutMs: options.nativeExecutionTimeoutMs }
);
const backtestRunner = new BacktestRunner({
engine: backtestEngine,
engineName: useRustEngine ? 'native' : 'typescript',
const runner = new BacktestRunner({
engine,
engineName: 'native',
repository: services.postgres
? new PostgresBacktestRunRepository(services.postgres)
: new UnavailableBacktestRunRepository(),
logger: services.logger,
prepare: useRustEngine ? undefined : config => modeManager.initializeMode(config),
});
// Store custom services
const analytics = new AnalyticsService(services);
// Both roles share canonical research. Only an explicitly configured paper
// composition owns account custody; startup never activates it.
Object.assign(custom, {
StorageService: storageService,
MarketDataService: marketDataService,
ExecutionService: executionService,
AnalyticsService: analyticsService,
StrategyManager: strategyManager,
BacktestEngine: backtestEngine,
BacktestRunner: backtestRunner,
PaperTradingManager: paperTradingManager,
ModeManager: modeManager,
AnalyticsService: analytics,
BacktestEngine: engine,
BacktestRunner: runner,
...(paper ? { CanonicalPaperRuntime: paper } : {}),
});
// Register services in the Awilix container for resolution
const orchestratorContainer = container as AwilixContainer<
const canonicalContainer = container as AwilixContainer<
ServiceDefinitions & {
StorageService: StorageService;
MarketDataService: MarketDataService;
ExecutionService: ExecutionService;
AnalyticsService: AnalyticsService;
StrategyManager: StrategyManager;
CanonicalPaperRuntime: PaperRuntime;
BacktestEngine: BacktestExecutionEngine;
BacktestRunner: BacktestRunner;
PaperTradingManager: PaperTradingManager;
ModeManager: ModeManager;
orchestratorServices: IServiceContainer;
}
>;
orchestratorContainer.register({
canonicalContainer.register({
StorageService: asValue(storageService),
MarketDataService: asValue(marketDataService),
ExecutionService: asValue(executionService),
AnalyticsService: asValue(analyticsService),
StrategyManager: asValue(strategyManager),
BacktestEngine: asValue(backtestEngine),
BacktestRunner: asValue(backtestRunner),
PaperTradingManager: asValue(paperTradingManager),
ModeManager: asValue(modeManager),
AnalyticsService: asValue(analytics),
BacktestEngine: asValue(engine),
BacktestRunner: asValue(runner),
orchestratorServices: asValue(services),
...(paper ? { CanonicalPaperRuntime: asValue(paper) } : {}),
});
container
.resolve('handlerScanner')
.registerHandlerClass(BacktestHandler, { serviceName: 'orchestrator' });
// Setup event listeners after all services are registered
strategyManager.setupEventListeners();
// Initialize mode manager with default paper trading mode
if (role === 'paper' && options.initializeMode !== false) {
await modeManager.initializeMode({
mode: 'paper',
startingCapital: options.paperTradingCapital ?? 100000,
});
try {
if (paper && canonicalPaper && options.initializeMode !== false) {
await paper.initialize(canonicalPaper);
}
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });
} catch (error) {
await paper?.shutdown().catch(() => {});
throw error;
}
// Start job consumption only after the shared graph and initial mode are ready.
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });
}
// For backward compatibility, export a container getter
// Kept only as an explicit diagnostic for obsolete integration code.
export function getContainer(): IServiceContainer {
throw new Error(
'Container should be accessed through ServiceApplication. Update your code to use dependency injection.'

View file

@ -2,6 +2,7 @@ import { z } from 'zod';
import { BaseHandler, Handler, Operation } from '@stock-bot/handlers';
import { defined } from '@stock-bot/invariants';
import type { BacktestRunner } from '../../backtest/BacktestRunner';
import { LEGACY_EXECUTION_RETIRED } from '../../backtest/execution-engine';
import type { OrchestratorServices } from '../../types';
@Handler('orchestrator')
@ -22,10 +23,7 @@ export class BacktestHandler extends BaseHandler<OrchestratorServices> {
const { runId } = z.object({ runId: z.string().uuid() }).parse(payload);
return this.runner.runQueued(runId);
}
// Old jobs omitted these fields. Normalize the envelope, never the execution result.
const config = { mode: 'backtest', dataFrequency: '1d', ...payload };
const results = await this.runner.runBacktest(config);
return { success: true, backtestId: results.backtestId, runId: results.runId, results };
throw new Error(LEGACY_EXECUTION_RETIRED);
}
@Operation('cancel-backtest')

View file

@ -19,7 +19,7 @@ const logger = getLogger('orchestrator');
// Get service-specific config
const serviceConfig = config.services?.orchestrator || {
port: 2004,
defaultMode: 'paper',
defaultMode: 'backtest',
paperTradingCapital: 100000,
enableWebSocket: true,
};

View file

@ -1,30 +1,24 @@
import { Hono } from 'hono';
import { Server as SocketIOServer } from 'socket.io';
import type { Server as SocketIOServer } from 'socket.io';
import { createAnalyticsRoutes } from '../api/rest/analytics';
import { createBacktestRoutes } from '../api/rest/backtest';
import { createOrderRoutes } from '../api/rest/orders';
import { createPaperRoutes } from '../api/rest/paper';
import { createPositionRoutes } from '../api/rest/positions';
import { setupWebSocketHandlers } from '../api/websocket';
import type { OrchestratorServices as IServiceContainer } from '../types';
/**
* Create all routes for the orchestrator service
*/
export function createRoutes(services: IServiceContainer, io?: SocketIOServer): Hono {
export function createRoutes(services: IServiceContainer, _io?: SocketIOServer): Hono {
const app = new Hono();
services.logger.info('Creating orchestrator routes');
// Health check with mode status
app.get('/health', c => {
const modeManager = services.custom?.ModeManager;
return c.json({
status: 'healthy',
service: 'orchestrator',
mode: services.custom?.CanonicalPaperRuntime
? 'paper'
: modeManager?.getCurrentMode() || 'unknown',
execution: services.custom?.CanonicalPaperRuntime ? 'canonical-paper' : 'legacy',
mode: services.custom?.CanonicalPaperRuntime ? 'paper' : 'research-only',
execution: services.custom?.CanonicalPaperRuntime ? 'canonical-paper' : 'canonical-research',
timestamp: new Date().toISOString(),
});
});
@ -38,37 +32,28 @@ export function createRoutes(services: IServiceContainer, io?: SocketIOServer):
...(await services.custom.CanonicalPaperRuntime.status()),
});
}
const execution = services.custom?.ExecutionService;
if (!execution) {
return c.json({ error: 'Execution gateway unavailable' }, 503);
}
return c.json(await execution.getRecoveryStatus());
return c.json({ error: 'Research-only runtime has no account execution gateway' }, 503);
} catch (error) {
services.logger.error('Could not read strategy recovery status', { error });
return c.json({ error: 'Strategy recovery status unavailable' }, 503);
}
});
app.route('/api/paper', createPaperRoutes(services));
if (services.custom?.CanonicalPaperRuntime) {
// Legacy numeric gateways cannot operate on a controlled canonical account.
const unavailable = new Hono().all('*', c =>
c.json({ error: 'Legacy account gateway unavailable in canonical paper mode' }, 409)
);
app.route('/api/orders', unavailable);
app.route('/api/positions', unavailable);
} else {
app.route('/api/orders', createOrderRoutes(services));
app.route('/api/positions', createPositionRoutes(services));
}
// Retired gateways remain explicit diagnostics, never a fallback simulator.
const unavailable = new Hono().all('*', c =>
c.json(
{
error:
'Legacy account execution is retired; use the explicitly configured canonical paper runtime',
},
409
)
);
app.route('/api/orders', unavailable);
app.route('/api/positions', unavailable);
app.route('/api/analytics', createAnalyticsRoutes(services));
app.route('/api/backtest', createBacktestRoutes(services));
// Setup WebSocket handlers if Socket.IO is provided
if (io && !services.custom?.CanonicalPaperRuntime) {
setupWebSocketHandlers(io, services);
services.logger.info('WebSocket handlers configured');
}
// Add request logging middleware
app.use('*', async (c, next) => {
const start = Date.now();

View file

@ -20,9 +20,9 @@ export async function createContainer(
}
const role =
options.role === undefined
? settings?.defaultMode === 'backtest'
? 'research-only'
: 'paper'
? settings?.defaultMode === 'paper'
? 'paper'
: 'research-only'
: options.role;
const configuredEngine = config.services?.orchestrator?.backtesting?.useRustEngine;
const useRustEngine = configuredEngine === undefined ? true : configuredEngine;
@ -35,6 +35,11 @@ export async function createContainer(
settings?.canonicalPaper === undefined
? undefined
: validatePaperConfiguration(paperConfigurationSchema.parse(settings.canonicalPaper));
if (role === 'paper' && !canonicalPaper) {
throw new Error(
'Paper composition requires explicit canonicalPaper configuration; accounts are never migrated automatically'
);
}
if (canonicalPaper && !config.database?.postgres?.enabled) {
throw new Error('Canonical paper requires durable PostgreSQL custody');
}
@ -57,7 +62,6 @@ export async function createContainer(
syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42,
nativeExecutionTimeoutMs: config.services?.orchestrator?.backtesting?.executionTimeoutMs,
canonicalPaper,
paperTradingCapital: settings?.paperTradingCapital,
});
return container.resolve('serviceContainer') as OrchestratorServices;
}

View file

@ -0,0 +1,189 @@
/** Pure decision staging shared by trusted and OS-isolated strategy hosts.
* This module never imports a native engine, dataset loader or service container. */
import type { FinancialStrategyDecision } from '@stock-bot/types';
import type {
DeepReadonly,
StrategyAdmissionFeedback,
StrategyDiagnostic,
StrategyDiagnosticSnapshot,
StrategyProgram,
} from '../contracts/canonical-strategy';
import {
nativeAdmissionOrders,
type DecisionContext,
type PublishedObservation,
type replayConfigSchema,
type ReplayIdentity,
type ReplaySubmissionOutcome,
} from '../contracts/native-replay';
import {
freeze,
increment,
metadataSchema,
stageStrategyDecision,
stateCopy,
type Metadata,
} from '../strategies/strategy-decision';
interface Slot {
program: Metadata & { decide: StrategyProgram['decide'] };
diagnostic: DeepReadonly<StrategyDiagnostic>;
pendingObservations: PublishedObservation[];
}
export class StrategyController {
private slots: Map<string, Slot>;
private committedBarriers = 0;
private lastBarrierId: string | null = null;
private observed = 0;
private staged: {
barrierId: string;
expectedRevision: number;
owners: {
ownerId: string;
diagnostic: StrategyDiagnostic;
decision: FinancialStrategyDecision;
}[];
} | null = null;
constructor(
private readonly identity: ReplayIdentity,
programs: readonly StrategyProgram[],
config: ReturnType<typeof replayConfigSchema.parse>
) {
this.slots = new Map(
programs.map(program => {
const { ownerId, strategyId, strategyVersion, mode, seed } = program;
const metadata = metadataSchema.parse({ ownerId, strategyId, strategyVersion, mode, seed });
const decide = program.decide;
if (typeof decide !== 'function') {
throw new Error('Strategy decide must be synchronous callable code');
}
const diagnostic = freeze({
ownerId,
strategyId,
strategyVersion,
nextDecisionSequence: 0,
state: stateCopy(program.initialState),
rng: { algorithm: 'lcg32-v1' as const, seed, state: seed, draws: 0 },
observationCount: 0,
previousAdmission: null,
});
return [ownerId, { program: { ...metadata, decide }, diagnostic, pendingObservations: [] }];
})
);
const owners = config.matching.owners;
if (
this.slots.size !== programs.length ||
this.slots.size !== owners.length ||
owners.some(owner => this.slots.get(owner.ownerId)?.program.mode !== owner.mode.toLowerCase())
) {
throw new Error('Programs must exactly match configured owners and modes');
}
}
snapshot(): DeepReadonly<StrategyDiagnosticSnapshot> {
return freeze({
version: 1,
identity: this.identity,
committedBarriers: this.committedBarriers,
lastBarrierId: this.lastBarrierId,
strategies: [...this.slots.values()]
.sort((a, b) =>
a.program.ownerId < b.program.ownerId ? -1 : a.program.ownerId > b.program.ownerId ? 1 : 0
)
.map(slot => slot.diagnostic),
});
}
stage(context: DecisionContext, observations: readonly PublishedObservation[]) {
if (this.staged) {
throw new Error('Previous strategy barrier has not committed');
}
this.observed = increment(this.observed, observations.length);
const due = new Set(context.barrier.owner_ids);
if (
this.observed !== context.barrier.observation_count ||
due.size !== context.barrier.owner_ids.length ||
[...due].some(owner => !this.slots.has(owner)) ||
observations.some(observation => observation.available_at > context.barrier.at)
) {
throw new Error('Strategy barrier observation or owner mismatch');
}
const staged: NonNullable<StrategyController['staged']> = {
barrierId: context.barrier.barrier_id,
expectedRevision: increment(context.barrier.revision),
owners: [],
};
for (const slot of this.slots.values()) {
// Other owners may have slower cadence. Do not discard their warmup/prefix.
for (const observation of observations) {
slot.pendingObservations.push(observation);
}
if (!due.has(slot.program.ownerId)) {
continue;
}
staged.owners.push(
stageStrategyDecision(
this.identity.sessionId,
slot.program,
slot.diagnostic,
slot.pendingObservations,
context
)
);
}
this.staged = staged;
return staged.owners.map(owner => owner.decision);
}
committed(outcome: ReplaySubmissionOutcome): void {
const staged = this.staged;
if (
!staged ||
outcome.replayed ||
outcome.status !== 'Running' ||
outcome.revision !== staged.expectedRevision
) {
throw new Error('Unexpected strategy admission acknowledgement');
}
const orders = nativeAdmissionOrders(outcome.effects);
if (
orders.some(
order => !staged.owners.some(owner => owner.ownerId === order.order.decision.ownerId)
)
) {
throw new Error('Admission feedback belongs to an owner outside the barrier');
}
const nextCount = increment(this.committedBarriers);
const next = new Map(this.slots);
// Parse/detach ALL feedback before swapping any committed slot. Even an
// ambiguous/malformed acknowledgement leaves diagnostics at the old barrier.
for (const owner of staged.owners) {
const slot = this.slots.get(owner.ownerId);
if (!slot) {
throw new Error('Staged strategy owner is missing');
}
const previousAdmission: StrategyAdmissionFeedback = {
decision: owner.decision.decision,
revision: outcome.revision,
orders: orders
.filter(order => order.order.decision.ownerId === owner.ownerId)
.map(order => ({
orderId: order.order.orderId,
instrumentId: order.order.instrumentId,
decision: order.order.decision,
status: order.status,
})),
};
next.set(owner.ownerId, {
program: slot.program,
diagnostic: freeze({ ...owner.diagnostic, previousAdmission }),
pendingObservations: [],
});
}
this.slots = next;
this.committedBarriers = nextCount;
this.lastBarrierId = staged.barrierId;
this.staged = null;
}
}

View file

@ -67,7 +67,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
f === '24-chronological-validation.sql' ||
f === '25-walk-forward.sql' ||
f === '26-cost-sensitivity.sql' ||
f === '27-research-evidence-sources.sql')
f === '27-research-evidence-sources.sql' ||
f === '28-research-agents.sql')
) // Explicit additive migration allowlist; never replay destructive init migrations
.sort();

View file

@ -7,6 +7,7 @@ import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { createHttpSecurity, httpSecurityOptions, type HttpSecurity } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/handlers';
import { ResearchAgentsService } from '../services/research-agents.service';
import { createBacktestRoutes } from './backtest.routes';
import { createBacktestV2Routes } from './backtests-v2.routes';
import { createDatasetRoutes } from './datasets.routes';
@ -15,6 +16,7 @@ import { createExperimentRoutes } from './experiments.routes';
import { createHealthRoutes } from './health.routes';
import { createMonitoringRoutes } from './monitoring.routes';
import { createPipelineRoutes } from './pipeline.routes';
import { createResearchAgentRoutes } from './research-agents.routes';
import { createResearchRoutes } from './research.routes';
import { createStrategyRoutes } from './strategies.routes';
@ -22,10 +24,15 @@ import { createStrategyRoutes } from './strategies.routes';
// the old 1 MiB restriction; normalizers still validate every submitted record.
export const WEB_API_MAX_REQUEST_BODY_SIZE = Number.MAX_SAFE_INTEGER;
export function createRoutes(
container: IServiceContainer,
security: HttpSecurity = createHttpSecurity({ ...httpSecurityOptions(), browserSessions: true })
): Hono {
export function createRoutes(container: IServiceContainer, suppliedSecurity?: HttpSecurity): Hono {
const agents = new ResearchAgentsService(container);
const security =
suppliedSecurity ??
createHttpSecurity({
...httpSecurityOptions(),
browserSessions: true,
resolveResearchCredential: request => agents.authenticate(request),
});
const app = new Hono();
// Add CORS middleware
@ -58,6 +65,7 @@ export function createRoutes(
app.route('/', createDatasetRoutes(container));
app.route('/', createStrategyRoutes(container));
app.route('/', createResearchRoutes(container));
app.route('/', createResearchAgentRoutes(container, security.researchEnabled));
app.route('/', createExperimentRoutes(container));
return app;

View file

@ -1,6 +1,6 @@
import { Hono, type MiddlewareHandler } from 'hono';
import { z } from 'zod';
import { getCredentialHttpPrincipal } from '@stock-bot/di';
import { getResearchHttpPrincipal } from '@stock-bot/di';
import { getLogger } from '@stock-bot/logger';
import type { IServiceContainer } from '@stock-bot/services';
import { ChronologicalValidationService } from '../services/chronological-validation.service';
@ -17,6 +17,7 @@ import {
} from '../services/experiment-input';
import { parseExperimentRetry } from '../services/experiment-retry';
import { ExperimentsService } from '../services/experiments.service';
import { researchAgentDatabaseError, ResearchAgentError } from '../services/research-agent-budget';
import {
parseValidationFinalization,
parseValidationSelection,
@ -39,7 +40,7 @@ export function createExperimentRoutes(container: IServiceContainer) {
const logger = getLogger('experiments-api');
const credentials: MiddlewareHandler = async (c, next) => {
c.header('Cache-Control', 'no-store');
if (!['GET', 'HEAD'].includes(c.req.method) && !getCredentialHttpPrincipal(c.req.raw)) {
if (!['GET', 'HEAD'].includes(c.req.method) && !getResearchHttpPrincipal(c.req.raw)) {
return c.json({ error: 'Verified credential principal required' }, 401);
}
await next();
@ -48,6 +49,17 @@ export function createExperimentRoutes(container: IServiceContainer) {
app.use('/api/v2/experiments', credentials);
app.use('/api/v2/experiments/*', credentials);
app.onError((error, c) => {
const agentError =
error instanceof ResearchAgentError ? error : researchAgentDatabaseError(error);
if (agentError) {
return c.json(
{
error: agentError.message,
code: agentError.status === 429 ? 'research_budget_exceeded' : 'research_access_denied',
},
agentError.status
);
}
if (error instanceof ExperimentError) {
return c.json({ error: error.message }, error.status);
}
@ -71,7 +83,7 @@ export function createExperimentRoutes(container: IServiceContainer) {
const experiment = await service.submitCosts(
input,
experimentReceipt({
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
principal: getResearchHttpPrincipal(c.req.raw) ?? '',
key: c.req.header('Idempotency-Key') ?? '',
})
);
@ -86,7 +98,7 @@ export function createExperimentRoutes(container: IServiceContainer) {
const walkForward = await walkForwards.submit(
input,
experimentReceipt({
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
principal: getResearchHttpPrincipal(c.req.raw) ?? '',
key: c.req.header('Idempotency-Key') ?? '',
})
);
@ -107,7 +119,7 @@ export function createExperimentRoutes(container: IServiceContainer) {
id,
input,
experimentReceipt({
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
principal: getResearchHttpPrincipal(c.req.raw) ?? '',
key: c.req.header('Idempotency-Key') ?? '',
})
),
@ -135,7 +147,7 @@ export function createExperimentRoutes(container: IServiceContainer) {
const validation = await validations.submit(
input,
experimentReceipt({
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
principal: getResearchHttpPrincipal(c.req.raw) ?? '',
key: c.req.header('Idempotency-Key') ?? '',
})
);
@ -156,7 +168,7 @@ export function createExperimentRoutes(container: IServiceContainer) {
id,
input,
experimentReceipt({
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
principal: getResearchHttpPrincipal(c.req.raw) ?? '',
key: c.req.header('Idempotency-Key') ?? '',
})
),
@ -171,7 +183,7 @@ export function createExperimentRoutes(container: IServiceContainer) {
id,
input,
experimentReceipt({
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
principal: getResearchHttpPrincipal(c.req.raw) ?? '',
key: c.req.header('Idempotency-Key') ?? '',
})
),
@ -197,7 +209,7 @@ export function createExperimentRoutes(container: IServiceContainer) {
app.post('/api/v2/experiments', async c => {
const input = parseExperimentSubmission(await body(c.req.raw));
const receipt = experimentReceipt({
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
principal: getResearchHttpPrincipal(c.req.raw) ?? '',
key: c.req.header('Idempotency-Key') ?? '',
});
const experiment = await service.submit(input, receipt);
@ -250,7 +262,7 @@ export function createExperimentRoutes(container: IServiceContainer) {
runId = experimentId(c.req.param('runId'));
const input = parseExperimentRetry(await body(c.req.raw));
const receipt = experimentReceipt({
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
principal: getResearchHttpPrincipal(c.req.raw) ?? '',
key: c.req.header('Idempotency-Key') ?? '',
});
const result = await service.retryTrial(id, runId, input, receipt);

View file

@ -0,0 +1,63 @@
import { Hono, type MiddlewareHandler } from 'hono';
import { z } from 'zod';
import { getCredentialHttpPrincipal, getResearchHttpPrincipal } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/services';
import { isResearchAgent } from '@stock-bot/types';
import { ResearchAgentError } from '../services/research-agent-budget';
import { ResearchAgentsService } from '../services/research-agents.service';
export function createResearchAgentRoutes(container: IServiceContainer, researchEnabled = false) {
const app = new Hono(),
service = new ResearchAgentsService(container);
const operatorOnly: MiddlewareHandler = async (c, next) => {
c.header('Cache-Control', 'no-store');
if (!researchEnabled) {
return c.json(
{
error:
'Research credentials require enabled authentication and the web research resolver',
},
403
);
}
if (getCredentialHttpPrincipal(c.req.raw) !== 'operator') {
return c.json({ error: 'Human operator credentials required' }, 403);
}
await next();
return undefined;
};
app.use('/api/v2/research-agents', operatorOnly);
app.use('/api/v2/research-agents/*', operatorOnly);
app.use('/api/v2/research-agent/*', async (c, next) => {
c.header('Cache-Control', 'no-store');
await next();
});
app.onError((error, c) => {
if (error instanceof ResearchAgentError) {
return c.json({ error: error.message }, error.status);
}
if (error instanceof z.ZodError || error instanceof SyntaxError) {
return c.json({ error: 'Invalid research principal policy' }, 400);
}
container.logger.error('Research principal operation failed', { error });
return c.json({ error: 'Research principal operation unavailable' }, 500);
});
app.get('/api/v2/research-agents', async c => c.json({ agents: await service.list() }));
app.post('/api/v2/research-agents', async c =>
c.json(await service.create(await c.req.json()), 201)
);
app.patch('/api/v2/research-agents/:id', async c =>
c.json({ agent: await service.update(c.req.param('id'), await c.req.json()) })
);
app.get('/api/v2/research-agents/:id/budget', async c =>
c.json(await service.budget(c.req.param('id'), true))
);
app.get('/api/v2/research-agent/budget', async c => {
const principal = getResearchHttpPrincipal(c.req.raw);
if (!isResearchAgent(principal)) {
throw new ResearchAgentError(403, 'Research credentials required');
}
return c.json(await service.budget(principal));
});
return app;
}

View file

@ -1,8 +1,9 @@
import { Hono, type MiddlewareHandler } from 'hono';
import { z } from 'zod';
import { getCredentialHttpPrincipal } from '@stock-bot/di';
import { getResearchHttpPrincipal } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/services';
import { archiveResearchSchema, parseResearchInput } from '@stock-bot/stock-config/research';
import { researchAgentDatabaseError, ResearchAgentError } from '../services/research-agent-budget';
import { ResearchError } from '../services/research-errors';
import { ResearchService } from '../services/research.service';
@ -29,7 +30,7 @@ export function createResearchRoutes(container: IServiceContainer) {
const service = new ResearchService(container);
const credentials: MiddlewareHandler = async (c, next) => {
c.header('Cache-Control', 'no-store');
if (!['GET', 'HEAD'].includes(c.req.method) && !getCredentialHttpPrincipal(c.req.raw)) {
if (!['GET', 'HEAD'].includes(c.req.method) && !getResearchHttpPrincipal(c.req.raw)) {
return c.json({ error: 'Verified credential principal required' }, 401);
}
await next();
@ -44,6 +45,17 @@ export function createResearchRoutes(container: IServiceContainer) {
app.use(path, credentials);
}
app.onError((error, c) => {
const agentError =
error instanceof ResearchAgentError ? error : researchAgentDatabaseError(error);
if (agentError) {
return c.json(
{
error: agentError.message,
code: agentError.status === 429 ? 'research_budget_exceeded' : 'research_access_denied',
},
agentError.status
);
}
if (error instanceof ResearchError) {
return c.json({ error: error.message }, error.status);
}
@ -54,7 +66,7 @@ export function createResearchRoutes(container: IServiceContainer) {
return c.json({ error: 'Research workspace unavailable' }, 500);
});
const actor = (request: Request) => {
const principal = getCredentialHttpPrincipal(request);
const principal = getResearchHttpPrincipal(request);
if (!principal) {
throw new ResearchError(401, 'Verified credential principal required');
}

View file

@ -1,7 +1,8 @@
import { Hono, type MiddlewareHandler } from 'hono';
import { z } from 'zod';
import { getCredentialHttpPrincipal } from '@stock-bot/di';
import { getResearchHttpPrincipal } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/services';
import { researchAgentDatabaseError, ResearchAgentError } from '../services/research-agent-budget';
import { StrategyCatalogError, StrategyCatalogService } from '../services/strategy-catalog.service';
const publication = z
@ -15,7 +16,7 @@ export function createStrategyRoutes(container: IServiceContainer) {
const service = new StrategyCatalogService(container);
const credentials: MiddlewareHandler = async (c, next) => {
c.header('Cache-Control', 'no-store');
if (!['GET', 'HEAD'].includes(c.req.method) && !getCredentialHttpPrincipal(c.req.raw)) {
if (!['GET', 'HEAD'].includes(c.req.method) && !getResearchHttpPrincipal(c.req.raw)) {
return c.json({ error: 'Verified credential principal required' }, 401);
}
await next();
@ -29,6 +30,17 @@ export function createStrategyRoutes(container: IServiceContainer) {
app.use(path, credentials);
}
app.onError((error, c) => {
const agentError =
error instanceof ResearchAgentError ? error : researchAgentDatabaseError(error);
if (agentError) {
return c.json(
{
error: agentError.message,
code: agentError.status === 429 ? 'research_budget_exceeded' : 'research_access_denied',
},
agentError.status
);
}
if (error instanceof StrategyCatalogError) {
return c.json({ error: error.message }, error.status);
}
@ -41,7 +53,7 @@ export function createStrategyRoutes(container: IServiceContainer) {
// The mounted security layer establishes read access. Writes additionally require
// actual credentials, including on development listeners with auth bypass enabled.
const actor = (request: Request) => {
const value = getCredentialHttpPrincipal(request);
const value = getResearchHttpPrincipal(request);
if (!value) {
throw new StrategyCatalogError(401, 'Verified credential principal required');
}

View file

@ -48,14 +48,14 @@ export class BacktestDispatcher {
// Recovery is independent of Redis availability. Every terminal write fences the old owner.
await this.postgres.transaction(async client => {
await client.query(
`UPDATE runs SET
`UPDATE runs AS r SET
status = CASE WHEN cancel_requested THEN 'cancelled'::run_status
WHEN attempt_number >= $1 THEN 'failed'::run_status ELSE 'pending'::run_status END,
WHEN (attempt_number >= LEAST($1,COALESCE((to_jsonb(r)#>>'{research_limits,maxAttempts}')::integer,$1)) OR ((to_jsonb(r)->>'research_deadline_at')::timestamptz <= clock_timestamp())) THEN 'failed'::run_status ELSE 'pending'::run_status END,
error = CASE WHEN cancel_requested THEN NULL
WHEN attempt_number >= $1 THEN 'Execution lease expired; retry limit reached' ELSE NULL END,
completed_at = CASE WHEN cancel_requested OR attempt_number >= $1 THEN NOW() ELSE NULL END,
WHEN (attempt_number >= LEAST($1,COALESCE((to_jsonb(r)#>>'{research_limits,maxAttempts}')::integer,$1)) OR ((to_jsonb(r)->>'research_deadline_at')::timestamptz <= clock_timestamp())) THEN CASE WHEN ((to_jsonb(r)->>'research_deadline_at')::timestamptz <= clock_timestamp()) THEN 'Research attempt wall time exceeded' ELSE 'Execution lease expired; retry limit reached' END ELSE NULL END,
completed_at = CASE WHEN cancel_requested OR (attempt_number >= LEAST($1,COALESCE((to_jsonb(r)#>>'{research_limits,maxAttempts}')::integer,$1)) OR ((to_jsonb(r)->>'research_deadline_at')::timestamptz <= clock_timestamp())) THEN NOW() ELSE NULL END,
attempt_id = NULL, lease_expires_at = NULL, updated_at = NOW()
WHERE status IN ('running', 'paused') AND lease_expires_at <= clock_timestamp()`,
WHERE status IN ('running', 'paused') AND (lease_expires_at <= clock_timestamp() OR ((to_jsonb(r)->>'research_deadline_at')::timestamptz <= clock_timestamp()))`,
[this.options.maxAttempts]
);
});

View file

@ -27,7 +27,11 @@ import {
canonicalStrategyJson,
validateStrategyParameters,
} from '@stock-bot/stock-config/strategy';
import type { BacktestRunDatasetSelection, StrategyParameterValue } from '@stock-bot/types';
import type {
BacktestRunDatasetSelection,
ResearchActor,
StrategyParameterValue,
} from '@stock-bot/types';
import { HistoricalDataRequestError } from '@stock-bot/types';
import { buildCanonicalBacktestReport } from '../../../orchestrator/src/backtest/canonical-result';
import { getWebSocketHandler } from '../websocket/run-updates';
@ -107,7 +111,7 @@ export interface RunRequest {
}
export interface RunSubmission {
principal: 'operator' | 'service';
principal: ResearchActor;
key: string;
}
@ -443,6 +447,11 @@ export class BacktestServiceV2 {
}
const definition = this.mapBacktest(at(parent.rows, 0));
const catalog = definition.strategyVersionId !== null || definition.strategy === 'catalog';
if (!catalog) {
throw new CatalogExecutionUnavailableError(
'Legacy backtest execution is retired. Select an approved strategy version and retained canonical dataset.'
);
}
if (catalog && multiplier !== null) {
throw new CatalogExecutionUnavailableError('Canonical research runs at maximum speed');
}

View file

@ -16,6 +16,7 @@ import type {
ValidationResultEvidence,
} from '@stock-bot/stock-config/chronological-validation';
import type { ExperimentPreview } from '@stock-bot/stock-config/experiments';
import type { ResearchActor } from '@stock-bot/types';
import { HistoricalDataRequestError } from '@stock-bot/types';
import { validateDatasetV2 } from '../../../orchestrator/src/data/historical-dataset-v2';
import { BacktestServiceV2 } from './backtest-v2.service';
@ -28,6 +29,7 @@ import {
experimentTrialRequest,
} from './experiment-input';
import { ExperimentsService } from './experiments.service';
import { lockExperimentResearchAgent, lockResearchAgent } from './research-agent-budget';
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
import {
parseValidationFinalization,
@ -89,6 +91,7 @@ export class ChronologicalValidationService {
submission,
});
return this.database.transaction(async client => {
await lockResearchAgent(client, identity.principal);
const replay = async () => {
const row = (
await client.query(
@ -144,7 +147,7 @@ export class ChronologicalValidationService {
prepared: ReturnType<typeof prepareChronologicalValidation>,
identity: {
id: string;
principal: 'operator' | 'service';
principal: ResearchActor;
key: string;
hash: string;
membership?: { id: string; index: number };
@ -225,12 +228,14 @@ export class ChronologicalValidationService {
const operation = 'select-and-admit-holdouts' as const;
const hash = experimentHash({ version: 1, operation, validationId: id, input });
return this.database.transaction(async client => {
await lockResearchAgent(client, identity.principal);
const replay = () =>
this.actionReplay(client, 'validation_selection', operation, identity, hash);
const prior = await replay();
if (prior) {
return prior;
}
await lockExperimentResearchAgent(client, id, identity.principal, true);
const { root, parent } = await this.lockRoot(client, id);
const concurrent = await replay();
if (concurrent) {
@ -357,6 +362,7 @@ export class ChronologicalValidationService {
const operation = 'finalize-report' as const,
hash = experimentHash({ version: 1, operation, validationId: id, input });
return this.database.transaction(async client => {
await lockResearchAgent(client, identity.principal);
const replay = () =>
this.actionReplay(client, 'validation_report', operation, identity, hash);
const prior = await replay();

View file

@ -13,6 +13,7 @@ import {
type ExperimentPreview,
type ExperimentSubmission,
} from '@stock-bot/stock-config/experiments';
import { researchActorSchema } from '@stock-bot/stock-config/research';
import {
assertStrategyJsonText,
builtinStrategySelectionSchema,
@ -58,7 +59,7 @@ export function experimentId(input: unknown): string {
export function experimentReceipt(input: { principal: string; key: string }) {
const parsed = z
.object({
principal: z.enum(['operator', 'service']),
principal: researchActorSchema,
key: z.string().regex(/^[\x21-\x7e]{1,200}$/),
})
.strict()

View file

@ -39,6 +39,7 @@ import {
PREVIEW_RUN_ID,
} from './experiment-input';
import { mapExperimentRetry, parseExperimentRetry, retryColumns } from './experiment-retry';
import { lockExperimentResearchAgent, lockResearchAgent } from './research-agent-budget';
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
import { StrategyCatalogError } from './strategy-catalog.service';
import { parseChronologicalValidation, prepareChronologicalValidation } from './validation-preview';
@ -222,6 +223,7 @@ export class ExperimentsService {
submission,
});
return this.database.transaction(async client => {
await lockResearchAgent(client, receipt.principal);
const replay = async () => {
const row = (
await client.query(
@ -412,6 +414,7 @@ export class ExperimentsService {
...input,
});
return this.database.transaction(async client => {
await lockResearchAgent(client, receipt.principal);
const replay = async (): Promise<WorkbenchExperimentRetryResult | null> => {
const saved = (
await client.query(
@ -437,6 +440,7 @@ export class ExperimentsService {
if (previous) {
return previous;
}
await lockExperimentResearchAgent(client, id, receipt.principal);
// Same ordering as admission, followed by the existing original-family verification lock.
const parent = (
await client.query(

View file

@ -0,0 +1,94 @@
import { createHash } from 'node:crypto';
import type { QueryResultRow } from 'pg';
import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { isResearchAgent } from '@stock-bot/types';
export type AgentQuery = {
query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }>;
};
export class ResearchAgentError extends Error {
constructor(
readonly status: 400 | 401 | 403 | 404 | 409 | 429,
message: string
) {
super(message);
}
}
/** Economic inputs are pinned. Only transport identity and strategy parameter variation are excluded. */
export function researchGrantPolicy(request: CanonicalRunRequest) {
const policy = structuredClone(request.policy);
policy.matching.risk.ledger.sessionId = 'agent-grant-run';
policy.matching.risk.ledger.accountId = 'agent-grant-account';
return {
datasetHash: request.datasetHash,
versionId: request.strategy.versionId,
ownerBudget: request.strategy.selection.ownerBudget,
seed: request.strategy.selection.seed,
policy,
analyticsPolicy: request.analyticsPolicy,
build: request.build,
modelArtifacts: request.modelArtifacts,
};
}
export const researchGrantHash = (policy: ReturnType<typeof researchGrantPolicy>) =>
createHash('sha256').update(canonicalStrategyJson(policy)).digest('hex');
/** First lock for every agent admission. Existing receipt replay follows this authentication fence. */
export async function lockResearchAgent(database: AgentQuery, principal: string): Promise<void> {
if (!isResearchAgent(principal)) {
return;
}
const row = (
await database.query('SELECT id,enabled FROM research_agents WHERE id=$1 FOR UPDATE', [
principal,
])
).rows[0];
if (!row?.enabled) {
throw new ResearchAgentError(403, 'Research principal is disabled or unavailable');
}
}
/** SQL guards are authoritative; map only the deliberately typed guard diagnostics. */
export function researchAgentDatabaseError(error: unknown): ResearchAgentError | null {
if (
error &&
typeof error === 'object' &&
'code' in error &&
'message' in error &&
error.code === 'P0001' &&
typeof error.message === 'string'
) {
if (error.message.startsWith('research_budget:')) {
return new ResearchAgentError(429, error.message.slice('research_budget:'.length));
}
if (error.message.startsWith('research_access:')) {
return new ResearchAgentError(403, error.message.slice('research_access:'.length));
}
}
return null;
}
/** Operator interventions must reserve the owning agent before the existing parent/resource locks. */
export async function lockExperimentResearchAgent(
database: AgentQuery,
experimentId: string,
principal: string,
ownerOnly = false
): Promise<void> {
const owner = (
await database.query('SELECT submission_principal FROM research_experiments WHERE id=$1', [
experimentId,
])
).rows[0]?.submission_principal;
if (isResearchAgent(principal) && owner !== undefined && owner !== principal) {
throw new ResearchAgentError(403, 'Research action requires its owning principal');
}
if (ownerOnly && isResearchAgent(owner) && owner !== principal) {
throw new ResearchAgentError(
403,
'New holdouts must be selected by the owning research principal'
);
}
if (isResearchAgent(owner) && owner !== principal) {
await lockResearchAgent(database, owner);
}
}

View file

@ -0,0 +1,327 @@
import { createHash, randomBytes, randomUUID } from 'node:crypto';
import type { PoolClient, QueryResultRow } from 'pg';
import { z } from 'zod';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import {
createResearchAgentSchema,
researchAgentIdSchema,
updateResearchAgentSchema,
type ResearchAgentBudget,
type ResearchAgentRecord,
} from '@stock-bot/stock-config/research-agents';
import { HistoricalDataRequestError, isResearchAgent } from '@stock-bot/types';
import { admitCanonicalRequest } from './canonical-research.service';
import { PREVIEW_RUN_ID } from './experiment-input';
import {
ResearchAgentError,
researchGrantHash,
researchGrantPolicy,
} from './research-agent-budget';
import { StrategyCatalogError } from './strategy-catalog.service';
const tokenHash = (token: string) => createHash('sha256').update(token).digest('hex');
function record(row: QueryResultRow): ResearchAgentRecord {
return {
id: row.id,
name: row.name,
enabled: row.enabled,
revision: row.revision,
allowedProjectIds: row.policy.allowedProjectIds,
grants: row.policy.grants.map((grant: { backtestId: string; policyHash: string }) => ({
backtestId: grant.backtestId,
policyHash: grant.policyHash,
})),
limits: row.policy.limits,
createdAt: new Date(row.created_at).toISOString(),
updatedAt: new Date(row.updated_at).toISOString(),
};
}
const uuid = '[0-9a-fA-F-]{36}';
function permitted(request: Request): boolean {
const path = new URL(request.url).pathname,
method = request.method;
if (method === 'GET' || method === 'HEAD') {
return (
/^\/api\/v2\/(research-projects|hypotheses|analysis-artifacts|strategies|strategy-versions|experiments|backtests|runs)(\/|$)/.test(
path
) || path === '/api/v2/research-agent/budget'
);
}
if (method === 'PUT') {
return new RegExp(`^/api/v2/research-projects/${uuid}/strategies/${uuid}$`).test(path);
}
if (method !== 'POST') {
return false;
}
return (
path === '/api/v2/strategies' ||
new RegExp(`^/api/v2/strategies/${uuid}/versions$`).test(path) ||
new RegExp(`^/api/v2/strategy-versions/${uuid}/(clone|validate)$`).test(path) ||
new RegExp(`^/api/v2/research-projects/${uuid}/(hypotheses|analysis-artifacts)$`).test(path) ||
new RegExp(`^/api/v2/(hypotheses|analysis-artifacts)/${uuid}/revisions$`).test(path) ||
/^\/api\/v2\/experiments(?:\/(?:preview|cost-sensitivity(?:\/preview)?|validation(?:\/preview)?|walk-forward(?:\/preview)?))?$/.test(
path
) ||
new RegExp(
`^/api/v2/experiments/(?:validation/|walk-forward/)?${uuid}/(?:cancel|select|finalize)$`
).test(path) ||
new RegExp(`^/api/v2/experiments/${uuid}/trials/${uuid}/retry$`).test(path)
);
}
export class ResearchAgentsService {
private readonly database;
constructor(private readonly container: IServiceContainer) {
this.database = requireServices(container, 'postgres').postgres;
}
private async policy(
client: PoolClient,
input: {
allowedProjectIds: string[];
allowedBacktestIds: string[];
limits: ResearchAgentRecord['limits'];
}
) {
for (const id of input.allowedProjectIds) {
if (
!(
await client.query(
'SELECT id FROM research_projects WHERE id=$1 AND archived_at IS NULL',
[id]
)
).rows.length
) {
throw new ResearchAgentError(400, 'Choose existing active research projects');
}
}
// Lock every parent before acquiring any family lock; interleaving these can deadlock
// a concurrent admission on another granted template sharing the same family.
const parents = (
await client.query(
'SELECT * FROM backtests WHERE id=ANY($1::uuid[]) ORDER BY id FOR UPDATE',
[input.allowedBacktestIds]
)
).rows;
if (
parents.length !== input.allowedBacktestIds.length ||
parents.some(row => row.archived_at)
) {
throw new ResearchAgentError(400, 'Choose existing active canonical templates');
}
await client.query(
'SELECT id FROM strategies WHERE id IN (SELECT strategy_id FROM strategy_versions WHERE id=ANY($1::uuid[])) ORDER BY id FOR UPDATE',
[parents.map(row => row.strategy_version_id).filter(Boolean)]
);
const grants = [];
for (const row of parents) {
const id = row.id as string;
let request;
try {
request = await admitCanonicalRequest(
client,
this.container,
{
name: row.name,
strategyVersionId: row.strategy_version_id,
strategyParameters: row.strategy_parameters,
symbols: row.symbols,
startDate: row.start_date,
endDate: row.end_date,
initialCapital: Number(row.initial_capital),
config: row.config,
},
id,
PREVIEW_RUN_ID
);
} catch (error) {
if (
!(
error instanceof HistoricalDataRequestError ||
error instanceof StrategyCatalogError ||
error instanceof z.ZodError
)
) {
throw error;
}
throw new ResearchAgentError(
400,
'Agent grants require currently approved canonical templates'
);
}
const policy = researchGrantPolicy(request);
grants.push({ backtestId: id, policyHash: researchGrantHash(policy), policy });
}
return { version: 1, allowedProjectIds: input.allowedProjectIds, grants, limits: input.limits };
}
async create(raw: unknown) {
const input = createResearchAgentSchema.parse(raw),
token = `sb-research.${randomBytes(32).toString('base64url')}`;
const agent = await this.database.transaction(async client => {
const policy = await this.policy(client, input);
const row = (
await client.query(
'INSERT INTO research_agents(id,name,token_hash,policy) VALUES($1,$2,$3,$4::jsonb) RETURNING *',
[`agent:${randomUUID()}`, input.name, tokenHash(token), JSON.stringify(policy)]
)
).rows[0];
if (!row) {
throw new Error('Research agent was not created');
}
return record(row);
});
return { agent, token };
}
async list(): Promise<ResearchAgentRecord[]> {
return (
await this.database.query('SELECT * FROM research_agents ORDER BY created_at,id')
).rows.map(record);
}
async update(id: string, raw: unknown): Promise<ResearchAgentRecord> {
researchAgentIdSchema.parse(id);
const input = updateResearchAgentSchema.parse(raw);
return this.database.transaction(async client => {
const old = (await client.query('SELECT * FROM research_agents WHERE id=$1 FOR UPDATE', [id]))
.rows[0];
if (!old) {
throw new ResearchAgentError(404, 'Research principal not found');
}
if (old.revision !== input.expectedRevision) {
throw new ResearchAgentError(
409,
'Research principal policy changed; reload before editing'
);
}
const policy =
input.allowedBacktestIds === undefined
? {
...old.policy,
allowedProjectIds: input.allowedProjectIds ?? old.policy.allowedProjectIds,
limits: input.limits ?? old.policy.limits,
}
: await this.policy(client, {
allowedProjectIds: input.allowedProjectIds ?? old.policy.allowedProjectIds,
allowedBacktestIds: input.allowedBacktestIds,
limits: input.limits ?? old.policy.limits,
});
if (input.allowedProjectIds) {
for (const projectId of input.allowedProjectIds) {
if (
!(
await client.query(
'SELECT id FROM research_projects WHERE id=$1 AND archived_at IS NULL',
[projectId]
)
).rows.length
) {
throw new ResearchAgentError(400, 'Choose existing active research projects');
}
}
}
const row = (
await client.query(
'UPDATE research_agents SET name=$2,enabled=$3,policy=$4::jsonb,revision=revision+1,updated_at=NOW() WHERE id=$1 RETURNING *',
[id, input.name ?? old.name, input.enabled ?? old.enabled, JSON.stringify(policy)]
)
).rows[0];
if (!row) {
throw new Error('Research principal update disappeared');
}
return record(row);
});
}
async budget(id: string, allowDisabled = false): Promise<ResearchAgentBudget> {
const row = (
await this.database.query(
`SELECT a.*,(SELECT count(*)::integer FROM runs r WHERE r.research_agent_id=a.id AND r.status IN ('pending','running','paused')) AS active_trials FROM research_agents a WHERE a.id=$1`,
[researchAgentIdSchema.parse(id)]
)
).rows[0];
if (!row || (!allowDisabled && !row.enabled)) {
throw new ResearchAgentError(403, 'Research principal is disabled or unavailable');
}
const agent = record(row),
activeTrials = Number(row.active_trials);
return {
agent,
activeTrials,
remainingActiveTrials: Math.max(0, agent.limits.maxActiveTrials - activeTrials),
};
}
async authenticate(
request: Request
): Promise<{ principal: `agent:${string}` } | Response | undefined> {
const match = /^Bearer (sb-research\.[A-Za-z0-9_-]+)$/i.exec(
request.headers.get('authorization') ?? ''
);
if (!match?.[1]) {
return undefined;
}
const row = (
await this.database.query(
'SELECT id,enabled,policy FROM research_agents WHERE token_hash=$1',
[tokenHash(match[1])]
)
).rows[0];
if (!row?.enabled || !isResearchAgent(row.id)) {
return undefined;
}
const deny = () =>
Response.json(
{ error: 'Research credential does not permit this operation' },
{ status: 403, headers: { 'Cache-Control': 'no-store' } }
);
if (!permitted(request)) {
return deny();
}
if (!['GET', 'HEAD'].includes(request.method)) {
const path = new URL(request.url).pathname;
const project = new RegExp(`^/api/v2/research-projects/(${uuid})/`).exec(path);
if (project && !row.policy.allowedProjectIds.includes(project[1]?.toLowerCase())) {
return deny();
}
const experiment = new RegExp(
`^/api/v2/experiments/(walk-forward/|validation/)?(${uuid})/`
).exec(path);
if (experiment) {
const table =
experiment[1] === 'walk-forward/' ? 'research_walk_forwards' : 'research_experiments';
const owned = (
await this.database.query(`SELECT submission_principal FROM ${table} WHERE id=$1`, [
experiment[2],
])
).rows[0];
if (owned?.submission_principal !== row.id) {
return deny();
}
}
const family = new RegExp(`^/api/v2/strategies/(${uuid})/versions$`).exec(path);
if (
family &&
(
await this.database.query('SELECT owner_principal FROM strategies WHERE id=$1', [
family[1],
])
).rows[0]?.owner_principal !== row.id
) {
return deny();
}
const narrative = new RegExp(
`^/api/v2/(hypotheses|analysis-artifacts)/(${uuid})/revisions$`
).exec(path);
if (narrative) {
const table = narrative[1] === 'hypotheses' ? 'research_hypotheses' : 'analysis_artifacts';
const owned = (
await this.database.query(`SELECT owner_principal,project_id FROM ${table} WHERE id=$1`, [
narrative[2],
])
).rows[0];
if (
owned?.owner_principal !== row.id ||
!row.policy.allowedProjectIds.includes(owned.project_id)
) {
return deny();
}
}
}
return { principal: row.id };
}
}

View file

@ -13,6 +13,7 @@ import type {
import type { WorkbenchExperimentPreview } from '@stock-bot/stock-config/cost-sensitivity';
import type { ExperimentCandidate } from '@stock-bot/stock-config/experiments';
import type { WalkForwardSegment } from '@stock-bot/stock-config/walk-forward';
import { isResearchActor } from '@stock-bot/types';
import type { ResearchEvidenceReference, ResearchFindingSource } from '@stock-bot/types';
import type { BacktestResultQuery } from './backtest-v2.service';
import { retainedWorkbenchPreview, workbenchTrialRequest } from './cost-sensitivity-input';
@ -44,7 +45,7 @@ function documentMetadata(value: Record<string, unknown>, report: boolean): void
/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value.id) &&
typeof value.createdAt === 'string' &&
Number.isFinite(Date.parse(value.createdAt)) &&
(value.principal === 'operator' || value.principal === 'service') &&
isResearchActor(value.principal) &&
typeof receipt?.key === 'string' &&
/^[!-~]{1,200}$/.test(receipt.key) &&
typeof receipt.hash === 'string' &&

View file

@ -28,6 +28,7 @@ import type {
ResearchProject,
StrategyRecord,
} from '@stock-bot/types';
import { lockResearchAgent } from './research-agent-budget';
import { ResearchError } from './research-errors';
import { ResearchEvidenceResolver } from './research-evidence';
import { StrategyCatalogService } from './strategy-catalog.service';
@ -47,12 +48,16 @@ function required(row: QueryResultRow | undefined, label: string): QueryResultRo
}
function authorship(actor: ResearchActor, origin?: ResearchContentOrigin): ResearchAuthorship {
researchActorSchema.parse(actor);
if (actor === 'service' && origin === 'human') {
throw new ResearchError(403, 'Service credentials cannot declare human authorship');
if (actor.startsWith('agent:') && origin !== undefined && origin !== 'ai') {
throw new ResearchError(403, 'Research principals must declare AI authorship');
}
if (actor !== 'operator' && origin === 'human') {
throw new ResearchError(403, 'Only operator credentials can declare human authorship');
}
return {
submittedBy: actor,
contentOrigin: origin ?? (actor === 'operator' ? 'human' : 'unknown'),
contentOrigin:
origin ?? (actor === 'operator' ? 'human' : actor.startsWith('agent:') ? 'ai' : 'unknown'),
};
}
function project(row: QueryResultRow): ResearchProject {
@ -169,6 +174,7 @@ export class ResearchService {
throw new ResearchError(400, 'Supply a project change');
}
return this.database.transaction(async client => {
await lockResearchAgent(client, actor);
const old = await this.projectRow(client, id, true);
expectRevision(old.revision, data.expectedRevision);
if (
@ -217,6 +223,7 @@ export class ResearchService {
researchIdSchema.parse(strategyId);
researchActorSchema.parse(actor);
await this.database.transaction(async client => {
await lockResearchAgent(client, actor);
active(await this.projectRow(client, projectId, true), 'Project');
const selected = required(
(await client.query('SELECT * FROM strategies WHERE id=$1 FOR UPDATE', [strategyId]))
@ -241,6 +248,7 @@ export class ResearchService {
researchIdSchema.parse(strategyId);
researchActorSchema.parse(actor);
await this.database.transaction(async client => {
await lockResearchAgent(client, actor);
active(await this.projectRow(client, projectId, true), 'Project');
const removed = await client.query(
'DELETE FROM research_project_strategies WHERE project_id=$1 AND strategy_id=$2 RETURNING project_id',
@ -274,6 +282,7 @@ export class ResearchService {
const data = parseResearchInput(createResearchHypothesisSchema, input);
const author = authorship(actor, data.contentOrigin);
return this.database.transaction(async client => {
await lockResearchAgent(client, actor);
active(await this.projectRow(client, projectId, true), 'Project');
const row = required(
(
@ -313,6 +322,7 @@ export class ResearchService {
const data = parseResearchInput(reviseResearchHypothesisSchema, input);
const author = authorship(actor, data.contentOrigin);
return this.database.transaction(async client => {
await lockResearchAgent(client, actor);
const row = await this.lockHypothesis(client, id);
active(row, 'Hypothesis');
const current = await this.hypothesis(client, row);
@ -339,6 +349,7 @@ export class ResearchService {
const data = parseResearchInput(archiveResearchSchema, input);
researchActorSchema.parse(actor);
return this.database.transaction(async client => {
await lockResearchAgent(client, actor);
await this.lockHypothesis(client, id);
const row = required(
(
@ -377,6 +388,7 @@ export class ResearchService {
const author = authorship(actor, data.contentOrigin);
this.requireFindingEvidence(data.kind, data.evidence);
return this.database.transaction(async client => {
await lockResearchAgent(client, actor);
active(await this.projectRow(client, projectId, true), 'Project');
if (data.hypothesisRevisionId) {
const linked = (
@ -440,6 +452,7 @@ export class ResearchService {
const data = parseResearchInput(reviseResearchArtifactSchema, input);
const author = authorship(actor, data.contentOrigin);
return this.database.transaction(async client => {
await lockResearchAgent(client, actor);
const row = await this.lockArtifact(client, id);
active(row, 'Artifact');
this.requireFindingEvidence(row.kind, data.evidence);
@ -482,6 +495,7 @@ export class ResearchService {
const data = parseResearchInput(archiveResearchSchema, input);
researchActorSchema.parse(actor);
return this.database.transaction(async client => {
await lockResearchAgent(client, actor);
await this.lockArtifact(client, id);
const row = required(
(

View file

@ -2,6 +2,7 @@ import { createHash, randomUUID } from 'node:crypto';
import type { PoolClient, QueryResultRow } from 'pg';
import { z } from 'zod';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import { researchActorSchema } from '@stock-bot/stock-config/research';
import {
assertStrategyJsonText,
builtinCatalogDescriptors,
@ -11,15 +12,17 @@ import {
} from '@stock-bot/stock-config/strategy';
import type {
ParameterValidationResult,
ResearchActor,
StrategyRecord,
StrategyReviewEvent,
StrategyVersionPackage,
StrategyVersionSummary,
} from '@stock-bot/types';
import { lockResearchAgent } from './research-agent-budget';
export type { StrategyRecord, StrategyVersionSummary } from '@stock-bot/types';
export type StrategyActor = 'operator' | 'service';
export type StrategyActor = ResearchActor;
export class StrategyCatalogError extends Error {
constructor(
public readonly status: 400 | 401 | 403 | 404 | 409,
@ -29,7 +32,7 @@ export class StrategyCatalogError extends Error {
}
}
const id = z.string().uuid();
const actorSchema = z.enum(['operator', 'service']);
const actorSchema = researchActorSchema;
const keySchema = z.string().regex(/^[\x21-\x7e]{1,200}$/);
const createSchema = z
.object({ name: z.string().trim().min(1), description: z.string().default('') })
@ -144,6 +147,7 @@ export class StrategyCatalogService {
const data = updateSchema.parse(input);
checkText(data);
return this.database.transaction(async client => {
await lockResearchAgent(client, actor);
const old = await this.lock(client, strategyId, false);
const row = (
await client.query(
@ -303,6 +307,7 @@ export class StrategyCatalogService {
let versionId: string;
try {
versionId = await this.database.transaction(async client => {
await lockResearchAgent(client, actor);
const old = await this.receipt(client, actor, key, fingerprint);
return old ?? (await work(client));
});
@ -476,6 +481,7 @@ export class StrategyCatalogService {
const data = reviewSchema.parse(input);
checkText(data);
await this.database.transaction(async client => {
await lockResearchAgent(client, actor);
const row = (
await client.query('SELECT strategy_id FROM strategy_versions WHERE id=$1', [versionId])
).rows[0];

View file

@ -19,6 +19,7 @@ import {
experimentReceipt,
} from './experiment-input';
import { ExperimentsService } from './experiments.service';
import { lockResearchAgent } from './research-agent-budget';
import { validationEqual } from './validation-evidence';
import {
parseWalkForwardFinalization,
@ -93,6 +94,7 @@ export class WalkForwardService {
{ previewHash, ...input } = submission;
const hash = experimentHash({ version: 1, operation: 'submit-walk-forward', submission });
return this.database.transaction(async client => {
await lockResearchAgent(client, identity.principal);
const replay = async () => {
const row = (
await client.query(
@ -212,6 +214,7 @@ export class WalkForwardService {
input,
});
return this.database.transaction(async client => {
await lockResearchAgent(client, identity.principal);
const replay = async () => {
const row = (
await client.query(

View file

@ -12,7 +12,7 @@ import {
} from '@/features/experiments';
import { MonitoringPage } from '@/features/monitoring';
import { PipelinePage } from '@/features/pipeline';
import { ResearchListPage, ResearchProjectPage } from '@/features/research';
import { ResearchAgentsPage, ResearchListPage, ResearchProjectPage } from '@/features/research';
import { StrategyDetailPage, StrategyListPage, StrategyVersionPage } from '@/features/strategies';
import { SymbolDetailPage, SymbolsPage } from '@/features/symbols';
import { AuthGate } from './AuthGate';
@ -53,6 +53,7 @@ export function App() {
</Route>
<Route path="research">
<Route index element={<ResearchListPage />} />
<Route path="agents" element={<ResearchAgentsPage />} />
<Route path=":projectId" element={<ResearchProjectPage />} />
</Route>
<Route path="experiments">

View file

@ -3,10 +3,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { isCanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
import { SaveFindingDialog } from '@/features/research/components/SaveFindingDialog';
import {
catalogExecutionReason,
supportedLegacyStrategy,
} from '@/features/strategies/components/StrategySelection';
import { catalogExecutionReason } from '@/features/strategies/components/StrategySelection';
import { useWebSocket } from '@/hooks/useWebSocket';
import { ArchiveBacktestDialog } from './components/ArchiveBacktestDialog';
import { BacktestConfiguration } from './components/BacktestConfiguration';
@ -77,9 +74,7 @@ export function BacktestDetailPageV2() {
? runResults
: null;
const catalog = Boolean(backtest?.strategyVersionId) || backtest?.strategy === 'catalog';
const unsupportedLegacy = Boolean(
backtest && !catalog && !supportedLegacyStrategy(backtest.strategy)
);
const unsupportedLegacy = Boolean(backtest && !catalog);
const executionUnavailable = catalog ? !canonicalCapability?.available : unsupportedLegacy;
const canSubmit = (!archived && !executionUnavailable) || hasPendingSubmission;
@ -572,8 +567,8 @@ export function BacktestDetailPageV2() {
)}
{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.
Legacy execution is retired. Create a catalog backtest to run with retained canonical
inputs. Its existing history remains readable.
</p>
)}
{archived && (

View file

@ -199,9 +199,9 @@ export function BacktestListPageV2() {
}
void loadBacktests();
}}
onCreated={(created, run) => {
onCreated={created => {
setShowCreateDialog(false);
navigate(`/backtests/${created.id}${run ? `/run/${run.id}` : ''}`);
navigate(`/backtests/${created.id}`);
}}
/>
)}

View file

@ -1,7 +1,6 @@
import { XMarkIcon } from '@heroicons/react/24/solid';
import { useEffect, useRef, useState } from 'react';
import {
LegacyStrategySelect,
StrategySelection,
type CatalogSelection,
} from '@/features/strategies/components/StrategySelection';
@ -9,14 +8,14 @@ import {
confirmDiscard,
useUnsavedWarning,
} from '@/features/strategies/components/useUnsavedWarning';
import { backtestApiV2, type Backtest, type Run } from '../services/backtestApiV2';
import { backtestApiV2, type Backtest } 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;
onCreated: (backtest: Backtest) => void;
}
export function CreateBacktestDialog({
@ -27,14 +26,12 @@ export function CreateBacktestDialog({
const [formData, setFormData] = useState<
HistoricalSelection & {
name: string;
strategy: string;
initialCapital: number;
commission: number;
slippage: number;
}
>({
name: '',
strategy: 'moving-average',
symbols: ['AAPL.US'],
startDate: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
endDate: new Date().toISOString().slice(0, 10),
@ -46,17 +43,14 @@ export function CreateBacktestDialog({
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 [phase, setPhase] = useState<'idle' | 'saving'>('idle');
const isSubmitting = phase !== 'idle';
const [error, setError] = useState<string | null>(null);
const saved = useRef<Backtest | null>(null);
const submission = useRef<{ key: string; body: { speedMultiplier: null } } | null>(null);
const pending = useRef(false);
const active = useRef(true);
@ -69,23 +63,18 @@ export function CreateBacktestDialog({
const close = () => {
// A list refresh before this write settles could miss the newly saved row.
if (pending.current && !saved.current) {
if (pending.current) {
return;
}
if (!saved.current && !confirmDiscard(edited)) {
if (!confirmDiscard(edited)) {
return;
}
active.current = false;
onClose();
};
const handleSubmit = async (runAfterSave: boolean) => {
if (
pending.current ||
!active.current ||
(!saved.current && (!historicalValid || (catalogMode && !strategyValid))) ||
(runAfterSave && catalogMode)
) {
const handleSubmit = async () => {
if (pending.current || !active.current || !historicalValid || !strategyValid) {
return;
}
@ -95,56 +84,36 @@ export function CreateBacktestDialog({
}
pending.current = true;
setPhase(saved.current ? 'submitting' : 'saving');
setPhase('saving');
setError(null);
try {
if (!saved.current) {
const created = await backtestApiV2.createBacktest({
name: formData.name,
strategy: catalogMode ? 'catalog' : formData.strategy,
...(catalogMode ? selection : {}),
symbols: formData.symbols,
startDate: formData.startDate,
endDate: formData.endDate,
initialCapital: formData.initialCapital,
config: {
commission: formData.commission,
slippage: formData.slippage,
dataFrequency: formData.dataFrequency,
dataSource: formData.dataSource,
datasetHash: formData.datasetHash,
dataPolicy: {
adjustment: formData.priceAdjustment ?? 'raw',
timestamp: formData.dataFrequency === '1d' ? 'utc-session-date' : 'utc-instant',
},
const created = await backtestApiV2.createBacktest({
name: formData.name,
strategy: 'catalog',
...selection,
symbols: formData.symbols,
startDate: formData.startDate,
endDate: formData.endDate,
initialCapital: formData.initialCapital,
config: {
commission: formData.commission,
slippage: formData.slippage,
dataFrequency: formData.dataFrequency,
dataSource: formData.dataSource,
datasetHash: formData.datasetHash,
dataPolicy: {
adjustment: formData.priceAdjustment ?? 'raw',
timestamp: formData.dataFrequency === '1d' ? 'utc-session-date' : 'utc-instant',
},
});
if (!active.current) {
return;
}
saved.current = created;
}
let run: Run | undefined;
if (runAfterSave) {
setPhase('submitting');
submission.current ??= { key: crypto.randomUUID(), body: { speedMultiplier: null } };
run = await backtestApiV2.createRun(
saved.current.id,
submission.current.body,
submission.current.key
);
}
},
});
if (active.current) {
onCreated(saved.current, run);
onCreated(created);
}
} catch (err) {
if (active.current) {
const detail = err instanceof Error ? err.message : 'Please try again.';
setError(
saved.current
? `Backtest saved, but run submission failed. Retry submission to recover the same run. ${detail}`
: `Failed to save backtest. ${detail}`
);
setError(`Failed to save backtest. ${detail}`);
}
} finally {
pending.current = false;
@ -177,12 +146,12 @@ export function CreateBacktestDialog({
<form
onSubmit={e => {
e.preventDefault();
void handleSubmit(saved.current !== null);
void handleSubmit();
}}
className="space-y-6"
onChange={() => setEdited(true)}
>
<fieldset disabled={isSubmitting || saved.current !== null} className="space-y-6">
<fieldset disabled={isSubmitting} className="space-y-6">
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Backtest Name
@ -197,41 +166,22 @@ export function CreateBacktestDialog({
/>
</div>
<label className="block text-sm text-text-secondary">
Strategy mode
<select
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="legacy">Legacy strategy</option>
<option value="catalog">Catalog version (save only)</option>
</select>
</label>
{catalogMode ? (
<StrategySelection
value={selection}
onChange={setSelection}
onValidityChange={setStrategyValid}
disabled={isSubmitting || saved.current !== null}
/>
) : (
<LegacyStrategySelect
value={formData.strategy}
onChange={strategy => setFormData(previous => ({ ...previous, strategy }))}
/>
)}
<p className="text-sm text-text-secondary">
Select an immutable strategy version. After saving, configure a retained dataset and
financial policies before running a canonical backtest.
</p>
<StrategySelection
value={selection}
onChange={setSelection}
onValidityChange={setStrategyValid}
disabled={isSubmitting}
/>
<HistoricalDataSelection
value={formData}
onChange={selection => setFormData(previous => ({ ...previous, ...selection }))}
onValidityChange={setHistoricalValid}
disabled={isSubmitting || saved.current !== null}
disabled={isSubmitting}
/>
<div>
@ -295,32 +245,19 @@ export function CreateBacktestDialog({
</button>
<button
type="submit"
disabled={
isSubmitting ||
(!saved.current && (!historicalValid || (catalogMode && !strategyValid)))
}
disabled={isSubmitting || !historicalValid || !strategyValid}
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
>
{isSubmitting
? 'Saving / submitting...'
: saved.current
? 'Retry submission'
: 'Save'}
{isSubmitting ? 'Saving...' : 'Save'}
</button>
<button
type="button"
disabled
title="Save first, then configure the retained dataset and financial policies."
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium opacity-50"
>
Save and run
</button>
{!saved.current && (
<button
type="button"
disabled={isSubmitting || catalogMode || (!saved.current && !historicalValid)}
onClick={e => {
if (e.currentTarget.form?.reportValidity()) {
void handleSubmit(true);
}
}}
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors disabled:opacity-50"
>
Save and run
</button>
)}
</div>
</form>
</div>

View file

@ -1,9 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research';
import {
catalogExecutionReason,
supportedLegacyStrategy,
} from '@/features/strategies/components/StrategySelection';
import { catalogExecutionReason } from '@/features/strategies/components/StrategySelection';
import { backtestApiV2, RunResultsUnavailableError } from '../services/backtestApiV2';
import type {
Backtest,
@ -423,30 +420,30 @@ export function useBacktestV2() {
}, []);
const createRun = useCallback(
async (speedMultiplier: number | null = null) => {
async (_speedMultiplier: number | null = null) => {
if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) {
return undefined;
}
if (backtest.archivedAt && !submission.current) {
setSubmissionError('Restore this archived backtest before starting a new run.');
return undefined;
}
if (catalog && !canonicalCapability?.available && !submission.current) {
setSubmissionError(
capabilityError ?? canonicalCapability?.reason ?? catalogExecutionReason
);
return undefined;
}
if (!catalog && !supportedLegacyStrategy(backtest.strategy) && !submission.current) {
if (!catalog && !submission.current) {
setSubmissionError(
'This legacy strategy is not supported for new submissions by this form.'
'Legacy execution is retired. Create a catalog backtest to run with retained canonical inputs.'
);
return undefined;
}
if (backtest.archivedAt && !submission.current) {
setSubmissionError('Restore this archived backtest before starting a new run.');
return undefined;
}
const intent = (submission.current ??= {
backtestId: backtest.id,
key: crypto.randomUUID(),
body: { speedMultiplier: catalog ? null : speedMultiplier },
body: { speedMultiplier: null },
pending: false,
});
intent.pending = true;

View file

@ -9,6 +9,7 @@ import {
type ChronologicalValidationSummary,
type ValidationResultEvidence,
} from '@stock-bot/stock-config/chronological-validation';
import { researchActorSchema } from '@stock-bot/stock-config/research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { API_BASE_URL, apiFetch } from '@/lib/api';
import {
@ -49,7 +50,7 @@ const candidate = z.object({
trialKey: hash,
parameters: z.record(z.union([z.string(), z.number().finite(), z.boolean()])),
});
const actor = z.enum(['operator', 'service']);
const actor = researchActorSchema;
const summary = z.object({
id: uuid,
name: z.string().min(1),

View file

@ -20,6 +20,7 @@ import {
type ExperimentSummary,
type ExperimentTrialRetry,
} from '@stock-bot/stock-config/experiments';
import { researchActorSchema } from '@stock-bot/stock-config/research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { API_BASE_URL, apiFetch } from '@/lib/api';
@ -165,7 +166,7 @@ const retryReceipt = z.object({
pausedAt: z.string().nullable(),
failureUpdatedAt: z.string().min(1),
recordedAt: z.string().min(1),
principal: z.enum(['operator', 'service']),
principal: researchActorSchema,
reviewId: z.string().uuid(),
});
/** Immutable source identity captured when the operator reviews a failed trial. */

View file

@ -1,4 +1,5 @@
import { z } from 'zod';
import { researchActorSchema } from '@stock-bot/stock-config/research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import {
MAX_WALK_FORWARD_RUNS,
@ -173,7 +174,7 @@ const report = z.object({
previewHash: hash,
reportHash: hash,
createdAt: z.string().min(1),
principal: z.enum(['operator', 'service']),
principal: researchActorSchema,
reset: z.literal('initial-capital-empty-positions'),
segments: z
.array(
@ -395,7 +396,7 @@ export const walkForwardApi = {
previewHash: hash,
reportHash: hash,
createdAt: z.string().min(1),
principal: z.enum(['operator', 'service']),
principal: researchActorSchema,
})
.parse(envelope(body, 'receipt'));
const value = parseWalkForwardDetail(envelope(body, 'walkForward')),

View file

@ -0,0 +1,354 @@
import { useEffect, useRef, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import {
createResearchAgentSchema,
type ResearchAgentBudget,
type ResearchAgentLimits,
type ResearchAgentRecord,
} from '@stock-bot/stock-config/research-agents';
import { actionClass, fieldClass } from '../strategies/components/StrategyParameterForm';
import { useUnsavedWarning } from '../strategies/components/useUnsavedWarning';
import { ResearchAgentApiError, researchAgentsApi } from './services/researchAgentsApi';
const limitFields: Array<[keyof ResearchAgentLimits, string, string]> = [
['maxActiveTrials', 'Maximum active trials', '1'],
['maxTrialsPerExperiment', 'Maximum trials per experiment', '10'],
['maxBarEvaluationsPerExperiment', 'Maximum bar evaluations per experiment', '100000'],
['maxAttemptWallMs', 'Maximum attempt time (ms)', '60000'],
['maxAttempts', 'Maximum attempts per run', '3'],
];
const identifiers = (value: string) => value.split(/[\s,]+/).filter(Boolean);
const message = (cause: unknown) =>
cause instanceof Error ? cause.message : 'Research agent request failed';
export function ResearchAgentsPage() {
const [search] = useSearchParams();
const [agents, setAgents] = useState<ResearchAgentRecord[]>([]);
const [budgets, setBudgets] = useState<Record<string, ResearchAgentBudget>>({});
const [name, setName] = useState('');
const [projects, setProjects] = useState(search.get('projectId') ?? '');
const [backtests, setBacktests] = useState('');
const [limits, setLimits] = useState<Record<string, string>>(() =>
Object.fromEntries(limitFields.map(([key, , value]) => [key, value]))
);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [writeError, setWriteError] = useState('');
const [uncertain, setUncertain] = useState(false);
const [uncertainListChecked, setUncertainListChecked] = useState(false);
const [pending, setPending] = useState(false);
const [refresh, setRefresh] = useState(0);
const [token, setToken] = useState<string | null>(null);
const alive = useRef(false);
const writing = useRef(false);
const generation = useRef(0);
const budgetRequests = useRef(new Map<string, number>());
useUnsavedWarning(Boolean(name || backtests || token || uncertain));
useEffect(() => {
alive.current = true;
return () => {
alive.current = false;
generation.current++;
};
}, []);
useEffect(() => {
const current = ++generation.current;
const controller = new AbortController();
setLoading(true);
setError('');
setBudgets({});
void researchAgentsApi
.list(controller.signal)
.then(({ agents: next }) => {
if (alive.current && current === generation.current) {
setAgents(next);
setUncertainListChecked(true);
}
})
.catch(cause => {
if (!controller.signal.aborted && current === generation.current) {
setError(message(cause));
}
})
.finally(() => {
if (alive.current && current === generation.current) {
setLoading(false);
}
});
return () => controller.abort();
}, [refresh]);
async function create(event: React.FormEvent) {
event.preventDefault();
if (writing.current || loading || uncertain || token) {
return;
}
const parsed = createResearchAgentSchema.safeParse({
name,
allowedProjectIds: identifiers(projects),
allowedBacktestIds: identifiers(backtests),
limits: Object.fromEntries(limitFields.map(([key]) => [key, Number(limits[key])])),
});
if (!parsed.success) {
setWriteError(
parsed.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; ')
);
return;
}
writing.current = true;
setPending(true);
setWriteError('');
generation.current++;
try {
const result = await researchAgentsApi.create(parsed.data);
if (alive.current) {
setAgents(previous => [
result.agent,
...previous.filter(agent => agent.id !== result.agent.id),
]);
setToken(result.token);
setName('');
setBacktests('');
}
} catch (cause) {
if (alive.current) {
setWriteError(message(cause));
setUncertain(!(cause instanceof ResearchAgentApiError) || cause.uncertain);
setUncertainListChecked(false);
}
} finally {
writing.current = false;
if (alive.current) {
setPending(false);
setLoading(false);
}
}
}
async function toggle(agent: ResearchAgentRecord) {
if (writing.current) {
return;
}
writing.current = true;
setPending(true);
setWriteError('');
generation.current++;
try {
const { agent: updated } = await researchAgentsApi.update(agent.id, {
expectedRevision: agent.revision,
enabled: !agent.enabled,
});
if (alive.current) {
setAgents(previous => previous.map(value => (value.id === updated.id ? updated : value)));
}
} catch (cause) {
if (alive.current) {
setWriteError(`${message(cause)} Refresh to verify the saved policy before retrying.`);
setRefresh(value => value + 1);
}
} finally {
writing.current = false;
if (alive.current) {
setPending(false);
setLoading(false);
}
}
}
async function budget(agent: ResearchAgentRecord) {
const current = generation.current;
const request = (budgetRequests.current.get(agent.id) ?? 0) + 1;
budgetRequests.current.set(agent.id, request);
const isCurrent = () =>
alive.current &&
current === generation.current &&
budgetRequests.current.get(agent.id) === request;
try {
const value = await researchAgentsApi.budget(agent.id);
if (isCurrent() && value.agent.id === agent.id) {
setBudgets(previous => ({ ...previous, [agent.id]: value }));
}
} catch (cause) {
if (isCurrent()) {
setError(message(cause));
}
}
}
return (
<div className="space-y-5 text-text-primary">
<Link to="/research" className="text-primary-500">
Back to research
</Link>
<h1 className="text-xl font-semibold">Research agent access</h1>
<p>
Grant research writes to specific projects and experiments on saved canonical backtests.
Research catalog and historical results remain readable. The server freezes each backtest’s
financial policy. Research credentials cannot control paper or live trading.
</p>
{writeError && <p role="alert">{writeError}</p>}
{token && (
<section
aria-label="New research credential"
className="space-y-3 border border-border p-4"
>
<p>
This credential is shown once. Store it in the authorized research client before
dismissing.
</p>
<textarea aria-label="New research token" className={fieldClass} value={token} readOnly />
<button className={actionClass} onClick={() => setToken(null)}>
I have saved the credential
</button>
</section>
)}
{uncertain && (
<section aria-label="Uncertain research credential creation" className="space-y-2">
<p>
The response was incomplete. A credential may have been created, but its token cannot be
recovered. Refresh the saved list and disable any unwanted credential before creating
another.
</p>
<button
className={actionClass}
disabled={pending || loading}
onClick={() => setRefresh(value => value + 1)}
>
Check saved agents
</button>
<button
className={actionClass}
disabled={pending || loading || Boolean(error) || !uncertainListChecked}
onClick={() => {
setUncertain(false);
setWriteError('');
}}
>
I have checked the saved agents
</button>
</section>
)}
<form
onSubmit={event => void create(event)}
className="space-y-3 border border-border rounded p-4"
>
<h2 className="font-semibold">Create research credential</h2>
<fieldset
disabled={loading || pending || uncertain || Boolean(token)}
className="space-y-3"
>
<label className="block">
Agent name
<input
aria-label="Agent name"
className={fieldClass}
value={name}
onChange={event => setName(event.target.value)}
required
/>
</label>
<label className="block">
Allowed project IDs
<textarea
aria-label="Allowed project IDs"
className={fieldClass}
value={projects}
onChange={event => setProjects(event.target.value)}
/>
</label>
<label className="block">
Allowed backtest IDs
<textarea
aria-label="Allowed backtest IDs"
className={fieldClass}
value={backtests}
onChange={event => setBacktests(event.target.value)}
/>
</label>
<p className="text-sm text-text-secondary">
Separate IDs with commas or whitespace. Empty lists grant no access. Backtests must
already have an eligible immutable version, retained dataset and canonical policy.
</p>
{limitFields.map(([key, label]) => (
<label key={key} className="block">
{label}
<input
aria-label={label}
type="number"
min="1"
step="1"
required
className={fieldClass}
value={limits[key]}
onChange={event =>
setLimits(previous => ({ ...previous, [key]: event.target.value }))
}
/>
</label>
))}
<button
type="submit"
className={actionClass}
disabled={loading || pending || uncertain || Boolean(token)}
>
{pending ? 'Saving...' : 'Create credential'}
</button>
</fieldset>
</form>
<section aria-label="Saved research agents" className="space-y-3">
<h2 className="font-semibold">Saved research agents</h2>
<button
className={actionClass}
disabled={pending || loading}
onClick={() => setRefresh(value => value + 1)}
>
Refresh agents
</button>
{loading ? (
<p role="status">Loading research agents...</p>
) : error ? (
<p role="alert">{error}</p>
) : !agents.length ? (
<p>No research agents configured.</p>
) : (
agents.map(agent => (
<article key={agent.id} className="space-y-2 border border-border p-4">
<h3 className="font-semibold">{agent.name}</h3>
<p>
{agent.id} · {agent.enabled ? 'Enabled' : 'Disabled'} · Revision {agent.revision}
</p>
<p>Projects: {agent.allowedProjectIds.join(', ') || 'None'}</p>
<ul>
{agent.grants.map(grant => (
<li key={grant.backtestId}>
<Link to={`/backtests/${grant.backtestId}`} className="text-primary-500">
{grant.backtestId}
</Link>{' '}
· Policy {grant.policyHash}
</li>
))}
</ul>
<dl>
{limitFields.map(([key, label]) => (
<div key={key}>
<dt className="inline">{label}: </dt>
<dd className="inline">{agent.limits[key]}</dd>
</div>
))}
</dl>
{budgets[agent.id] && (
<p role="status">
Active trials: {budgets[agent.id]?.activeTrials}; available slots:{' '}
{budgets[agent.id]?.remainingActiveTrials}
</p>
)}
<button className={actionClass} disabled={pending} onClick={() => void budget(agent)}>
Check budget for {agent.name}
</button>{' '}
<button className={actionClass} disabled={pending} onClick={() => void toggle(agent)}>
{agent.enabled ? 'Disable' : 'Enable'} {agent.name}
</button>
</article>
))
)}
</section>
</div>
);
}

View file

@ -83,6 +83,9 @@ export function ResearchListPage() {
};
return (
<div className="space-y-5 text-text-primary">
<Link to="/research/agents" className="text-primary-500">
Research agent access
</Link>
<div className="flex items-center justify-between">
<h1 className="text-lg font-bold">Research</h1>
<button className={actionClass} onClick={() => setOpen(true)}>

View file

@ -1,2 +1,3 @@
export { ResearchListPage } from './ResearchListPage';
export { ResearchProjectPage } from './ResearchProjectPage';
export { ResearchAgentsPage } from './ResearchAgentsPage';

View file

@ -0,0 +1,79 @@
import { z } from 'zod';
import {
createResearchAgentSchema,
researchAgentBudgetSchema,
researchAgentRecordSchema,
updateResearchAgentSchema,
} from '@stock-bot/stock-config/research-agents';
import { API_BASE_URL, apiFetch } from '@/lib/api';
export class ResearchAgentApiError extends Error {
constructor(
message: string,
readonly status: number
) {
super(message);
}
get uncertain() {
return this.status >= 500 || this.status === 408;
}
}
async function request<T>(path: string, schema: z.ZodType<T>, init?: RequestInit) {
const response = await apiFetch(`${API_BASE_URL}/api/v2/research-agents${path}`, init);
const body: unknown = await response.json().catch(() => null);
if (!response.ok) {
throw new ResearchAgentApiError(
body && typeof body === 'object' && 'error' in body && typeof body.error === 'string'
? body.error
: `Research agent request failed (${response.status})`,
response.status
);
}
return schema.parse(body);
}
const json = (method: string, body: unknown): RequestInit => ({
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const record = z.object({ agent: researchAgentRecordSchema }).strict();
export const researchAgentsApi = {
list: (signal?: AbortSignal) =>
request('', z.object({ agents: z.array(researchAgentRecordSchema) }).strict(), { signal }),
create: (input: z.input<typeof createResearchAgentSchema>) =>
request(
'',
record.extend({ token: z.string().min(1) }),
json('POST', createResearchAgentSchema.parse(input))
),
update: async (id: string, input: z.input<typeof updateResearchAgentSchema>) => {
const result = await request(
`/${encodeURIComponent(id)}`,
record,
json('PATCH', updateResearchAgentSchema.parse(input))
);
if (
result.agent.id !== id ||
result.agent.revision !== input.expectedRevision + 1 ||
(input.enabled !== undefined && result.agent.enabled !== input.enabled)
) {
throw new Error('Research agent update identity or revision mismatch');
}
return result;
},
budget: async (id: string, signal?: AbortSignal) => {
const result = await request(`/${encodeURIComponent(id)}/budget`, researchAgentBudgetSchema, {
signal,
});
if (
result.agent.id !== id ||
result.remainingActiveTrials !==
Math.max(0, result.agent.limits.maxActiveTrials - result.activeTrials)
) {
throw new Error('Research agent budget identity or capacity mismatch');
}
return result;
},
};

View file

@ -0,0 +1,535 @@
-- Explicit research principals. Existing financial snapshots, actors and receipts remain unchanged.
CREATE TABLE IF NOT EXISTS research_agents (
id TEXT PRIMARY KEY CHECK(id ~ '^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'),
name TEXT NOT NULL CHECK(length(btrim(name))>0),
token_hash TEXT NOT NULL UNIQUE CHECK(token_hash ~ '^[a-f0-9]{64}$'),
enabled BOOLEAN NOT NULL DEFAULT TRUE,
revision INTEGER NOT NULL DEFAULT 1 CHECK(revision>0),
policy JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS research_agent_audit (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
agent_id TEXT NOT NULL REFERENCES research_agents(id) ON DELETE RESTRICT,
operation TEXT NOT NULL, entity_id TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
ALTER TABLE runs ADD COLUMN IF NOT EXISTS research_agent_id TEXT REFERENCES research_agents(id) ON DELETE RESTRICT;
ALTER TABLE runs ADD COLUMN IF NOT EXISTS research_limits JSONB;
ALTER TABLE runs ADD COLUMN IF NOT EXISTS research_deadline_at TIMESTAMPTZ;
CREATE INDEX IF NOT EXISTS research_agent_active_runs ON runs(research_agent_id,status) WHERE research_agent_id IS NOT NULL;
CREATE OR REPLACE FUNCTION is_research_actor(value TEXT) RETURNS BOOLEAN LANGUAGE SQL STABLE AS $$
SELECT value IN ('operator','service') OR EXISTS(SELECT 1 FROM research_agents WHERE id=value)
$$;
CREATE OR REPLACE FUNCTION research_grant_policy(request JSONB) RETURNS JSONB LANGUAGE SQL IMMUTABLE AS $$
SELECT jsonb_build_object('datasetHash',request->'datasetHash','versionId',request#>'{strategy,versionId}',
'ownerBudget',request#>'{strategy,selection,ownerBudget}','seed',request#>'{strategy,selection,seed}',
'policy',jsonb_set(jsonb_set(request->'policy','{matching,risk,ledger,sessionId}','"agent-grant-run"'),'{matching,risk,ledger,accountId}','"agent-grant-account"'),
'analyticsPolicy',request->'analyticsPolicy','build',request->'build','modelArtifacts',request->'modelArtifacts')
$$;
CREATE OR REPLACE FUNCTION validate_research_agent_policy() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE key TEXT; value JSONB; item JSONB;
BEGIN
IF TG_OP='UPDATE' AND (NEW.id IS DISTINCT FROM OLD.id OR NEW.token_hash IS DISTINCT FROM OLD.token_hash OR NEW.created_at IS DISTINCT FROM OLD.created_at OR NEW.revision<>OLD.revision+1) THEN
RAISE EXCEPTION 'Research principal identity is immutable and policy updates require the next revision' USING ERRCODE='23514';
END IF;
IF (jsonb_typeof(NEW.policy)='object' AND NEW.policy->>'version'='1' AND jsonb_typeof(NEW.policy->'allowedProjectIds')='array' AND jsonb_typeof(NEW.policy->'grants')='array' AND jsonb_typeof(NEW.policy->'limits')='object'
AND NEW.policy-ARRAY['version','allowedProjectIds','grants','limits']='{}'::jsonb
AND (NEW.policy->'limits')-ARRAY['maxActiveTrials','maxTrialsPerExperiment','maxBarEvaluationsPerExperiment','maxAttemptWallMs','maxAttempts']='{}'::jsonb) IS NOT TRUE THEN
RAISE EXCEPTION 'Invalid research principal policy' USING ERRCODE='23514';
END IF;
FOREACH key IN ARRAY ARRAY['maxActiveTrials','maxTrialsPerExperiment','maxBarEvaluationsPerExperiment','maxAttemptWallMs','maxAttempts'] LOOP
value:=NEW.policy->'limits'->key;
IF jsonb_typeof(value) IS DISTINCT FROM 'number' THEN RAISE EXCEPTION 'Invalid research resource limit' USING ERRCODE='23514'; END IF;
IF (value::text)::numeric<1 OR (value::text)::numeric>9007199254740991 OR trunc((value::text)::numeric)<>(value::text)::numeric THEN RAISE EXCEPTION 'Invalid research resource limit' USING ERRCODE='23514'; END IF;
END LOOP;
IF (NEW.policy#>>'{limits,maxAttempts}')::numeric>3 OR (NEW.policy#>>'{limits,maxAttemptWallMs}')::numeric>2147483647 THEN RAISE EXCEPTION 'Invalid research attempt budget' USING ERRCODE='23514'; END IF;
FOR item IN SELECT jsonb_array_elements(NEW.policy->'grants') LOOP
IF (jsonb_typeof(item)='object' AND item-ARRAY['backtestId','policyHash','policy']='{}'::jsonb AND item->>'backtestId' ~ '^[0-9a-f-]{36}$' AND item->>'policyHash' ~ '^[a-f0-9]{64}$' AND jsonb_typeof(item->'policy')='object') IS NOT TRUE THEN RAISE EXCEPTION 'Invalid research template grant' USING ERRCODE='23514'; END IF;
END LOOP;
RETURN NEW;
END $$;
DROP TRIGGER IF EXISTS research_agents_policy ON research_agents;
CREATE TRIGGER research_agents_policy BEFORE INSERT OR UPDATE ON research_agents FOR EACH ROW EXECUTE FUNCTION validate_research_agent_policy();
DROP TRIGGER IF EXISTS research_agents_retained ON research_agents;
CREATE TRIGGER research_agents_retained BEFORE DELETE OR TRUNCATE ON research_agents FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();
DROP TRIGGER IF EXISTS research_agent_audit_immutable ON research_agent_audit;
CREATE TRIGGER research_agent_audit_immutable BEFORE UPDATE OR DELETE OR TRUNCATE ON research_agent_audit FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();
CREATE OR REPLACE FUNCTION audit_research_agent_policy() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
INSERT INTO research_agent_audit(agent_id,operation,entity_id) VALUES(NEW.id,'operator-policy-'||lower(TG_OP),NEW.id||':'||NEW.revision::text); RETURN NEW;
END $$;
DROP TRIGGER IF EXISTS research_agents_audit ON research_agents;
CREATE TRIGGER research_agents_audit AFTER INSERT OR UPDATE ON research_agents FOR EACH ROW EXECUTE FUNCTION audit_research_agent_policy();
-- Only explicitly named historical role checks are widened. Unknown definitions fail the migration.
DO $$ DECLARE spec TEXT[]; table_name TEXT; column_name TEXT; constraint_name TEXT; definition TEXT; BEGIN
FOREACH spec SLICE 1 IN ARRAY ARRAY[
['strategies','owner_principal'],['strategies','updated_by'],['strategy_versions','created_by'],
['research_projects','owner_principal'],['research_projects','updated_by'],
['research_hypotheses','owner_principal'],['research_hypotheses','updated_by'],['research_hypothesis_revisions','submitted_by'],
['analysis_artifacts','owner_principal'],['analysis_artifacts','updated_by'],['analysis_artifact_revisions','submitted_by'],['research_project_strategies','added_by'],
['research_experiments','submission_principal'],['experiment_trial_retries','principal'],['research_walk_forwards','submission_principal']
] LOOP
table_name:=spec[1]; column_name:=spec[2]; constraint_name:=table_name||'_'||column_name||'_check';
IF to_regclass(table_name) IS NULL THEN CONTINUE; END IF;
SELECT pg_get_constraintdef(oid) INTO definition FROM pg_constraint WHERE conrelid=to_regclass(table_name) AND conname=constraint_name;
IF definition IS NULL OR (position('operator' IN definition)=0 AND position('is_research_actor' IN definition)=0) OR (position('service' IN definition)=0 AND position('is_research_actor' IN definition)=0) THEN RAISE EXCEPTION 'Unexpected role constraint %',constraint_name; END IF;
IF position('is_research_actor' IN definition)=0 THEN
EXECUTE format('ALTER TABLE %I DROP CONSTRAINT %I',table_name,constraint_name);
EXECUTE format('ALTER TABLE %I ADD CONSTRAINT %I CHECK(is_research_actor(%I) IS TRUE)',table_name,constraint_name,column_name);
END IF;
END LOOP;
END $$;
CREATE OR REPLACE FUNCTION research_agent_authority(experiment research_experiments) RETURNS JSONB LANGUAGE plpgsql STABLE AS $$
DECLARE root research_experiments;
BEGIN
IF experiment.validation_phase='train' THEN RETURN experiment.validation_manifest#>'{source,request}'; END IF;
IF experiment.validation_parent_id IS NOT NULL THEN SELECT * INTO root FROM research_experiments WHERE id=experiment.validation_parent_id; RETURN root.validation_manifest#>'{source,request}'; END IF;
IF experiment.preview->>'version'='cost-sensitivity-preview/v1' THEN RETURN experiment.preview#>'{source,request}'; END IF;
RETURN experiment.preview->'request';
END $$;
CREATE OR REPLACE FUNCTION assert_research_agent_grant(agent research_agents, backtest_id UUID, request JSONB) RETURNS void LANGUAGE plpgsql AS $$ BEGIN
IF agent.enabled IS DISTINCT FROM TRUE OR NOT EXISTS(SELECT 1 FROM jsonb_array_elements(agent.policy->'grants') g WHERE g->>'backtestId'=backtest_id::text AND g->'policy'=research_grant_policy(request)) THEN
RAISE EXCEPTION 'research_access:Operator approval of this exact template, dataset and financial policy is required';
END IF;
END $$;
CREATE OR REPLACE FUNCTION research_validation_work(preview JSONB) RETURNS NUMERIC LANGUAGE SQL IMMUTABLE AS $$
SELECT COALESCE((preview#>>'{partitions,0,dataset,barCount}')::numeric,0)*jsonb_array_length(preview#>'{source,candidates}') + COALESCE((preview#>>'{partitions,1,dataset,barCount}')::numeric,0)+COALESCE((preview#>>'{partitions,2,dataset,barCount}')::numeric,0)
$$;
CREATE OR REPLACE FUNCTION guard_agent_experiment() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE agent research_agents; planned NUMERIC; work NUMERIC; root_owner TEXT;
BEGIN
IF NEW.validation_parent_id IS NOT NULL THEN
SELECT submission_principal INTO root_owner FROM research_experiments WHERE id=NEW.validation_parent_id;
IF root_owner LIKE 'agent:%' AND NEW.submission_principal IS DISTINCT FROM root_owner THEN RAISE EXCEPTION 'research_access:Holdouts must retain their owning research principal'; END IF;
END IF;
IF NEW.submission_principal NOT LIKE 'agent:%' THEN RETURN NEW; END IF;
SELECT * INTO agent FROM research_agents WHERE id=NEW.submission_principal FOR UPDATE;
PERFORM assert_research_agent_grant(agent,NEW.backtest_id,research_agent_authority(NEW));
IF NEW.validation_phase='train' THEN planned:=jsonb_array_length(NEW.validation_manifest#>'{source,candidates}')+2; work:=research_validation_work(NEW.validation_manifest);
ELSE planned:=jsonb_array_length(NEW.preview->'candidates'); work:=planned*(NEW.preview#>>'{dataset,barCount}')::numeric; END IF;
IF (planned <= (agent.policy#>>'{limits,maxTrialsPerExperiment}')::numeric AND work <= (agent.policy#>>'{limits,maxBarEvaluationsPerExperiment}')::numeric) IS NOT TRUE THEN RAISE EXCEPTION 'research_budget:Experiment exceeds its operator trial or observation budget'; END IF;
INSERT INTO research_agent_audit(agent_id,operation,entity_id) VALUES(agent.id,'experiment-admitted',NEW.id::text);
RETURN NEW;
END $$;
DROP TRIGGER IF EXISTS aa_agent_experiment ON research_experiments;
CREATE TRIGGER aa_agent_experiment BEFORE INSERT ON research_experiments FOR EACH ROW EXECUTE FUNCTION guard_agent_experiment();
CREATE OR REPLACE FUNCTION guard_agent_walk_forward() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE agent research_agents; work NUMERIC;
BEGIN
IF NEW.submission_principal NOT LIKE 'agent:%' THEN RETURN NEW; END IF;
SELECT * INTO agent FROM research_agents WHERE id=NEW.submission_principal FOR UPDATE;
PERFORM assert_research_agent_grant(agent,NEW.backtest_id,NEW.preview#>'{source,request}');
SELECT sum(research_validation_work(segment->'preview')) INTO work FROM jsonb_array_elements(NEW.preview->'windows') segment;
IF ((NEW.preview#>>'{counts,totalRuns}')::numeric <= (agent.policy#>>'{limits,maxTrialsPerExperiment}')::numeric AND work <= (agent.policy#>>'{limits,maxBarEvaluationsPerExperiment}')::numeric) IS NOT TRUE THEN RAISE EXCEPTION 'research_budget:Walk-forward exceeds its operator trial or observation budget'; END IF;
INSERT INTO research_agent_audit(agent_id,operation,entity_id) VALUES(agent.id,'walk-forward-admitted',NEW.id::text);
RETURN NEW;
END $$;
DROP TRIGGER IF EXISTS aa_agent_walk_forward ON research_walk_forwards;
CREATE TRIGGER aa_agent_walk_forward BEFORE INSERT ON research_walk_forwards FOR EACH ROW EXECUTE FUNCTION guard_agent_walk_forward();
CREATE OR REPLACE FUNCTION guard_agent_run_budget() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE principal TEXT; agent research_agents; experiment research_experiments; active_count BIGINT;
BEGIN
IF TG_OP='INSERT' THEN
SELECT * INTO experiment FROM research_experiments WHERE id=NEW.experiment_id;
principal:=CASE WHEN experiment.submission_principal LIKE 'agent:%' THEN experiment.submission_principal ELSE NULL END;
IF principal IS NULL THEN
IF NEW.research_agent_id IS NOT NULL OR NEW.research_limits IS NOT NULL OR NEW.research_deadline_at IS NOT NULL THEN RAISE EXCEPTION 'research_access:Only admitted research experiments may carry agent budgets'; END IF;
RETURN NEW;
END IF;
SELECT * INTO agent FROM research_agents WHERE id=principal FOR UPDATE;
PERFORM assert_research_agent_grant(agent,NEW.backtest_id,research_agent_authority(experiment));
IF NEW.research_agent_id IS NOT NULL AND NEW.research_agent_id<>principal THEN RAISE EXCEPTION 'research_access:Agent run attribution mismatch'; END IF;
IF NEW.research_limits IS NOT NULL OR NEW.research_deadline_at IS NOT NULL THEN RAISE EXCEPTION 'research_access:Agent execution budget is server-owned'; END IF;
NEW.research_agent_id:=principal; NEW.research_limits:=agent.policy->'limits';
ELSE
IF NEW.research_agent_id IS DISTINCT FROM OLD.research_agent_id OR NEW.research_limits IS DISTINCT FROM OLD.research_limits THEN RAISE EXCEPTION 'research_access:Agent run attribution and resource envelope are immutable'; END IF;
IF OLD.research_agent_id IS NULL THEN
IF NEW.research_deadline_at IS NOT NULL THEN RAISE EXCEPTION 'research_access:Unexpected agent deadline'; END IF;
RETURN NEW;
END IF;
principal:=OLD.research_agent_id;
IF NEW.research_deadline_at IS DISTINCT FROM OLD.research_deadline_at THEN RAISE EXCEPTION 'research_access:Agent deadline is server-owned'; END IF;
IF NEW.attempt_number<OLD.attempt_number THEN RAISE EXCEPTION 'research_access:Agent attempt budget cannot be reset'; END IF;
IF NEW.status='running' AND NEW.attempt_id IS DISTINCT FROM OLD.attempt_id THEN
IF OLD.status<>'pending' OR NEW.attempt_number<>OLD.attempt_number+1 OR NEW.attempt_number>(OLD.research_limits->>'maxAttempts')::integer THEN RAISE EXCEPTION 'research_budget:Research attempt budget exhausted'; END IF;
NEW.research_deadline_at:=clock_timestamp()+(OLD.research_limits->>'maxAttemptWallMs')::bigint*interval '1 millisecond';
ELSIF NEW.attempt_number IS DISTINCT FROM OLD.attempt_number THEN RAISE EXCEPTION 'research_access:Agent attempts advance only at claim'; END IF;
IF NEW.status IN ('running','paused') AND (NEW.attempt_id IS NULL OR NEW.research_deadline_at IS NULL OR NEW.lease_expires_at IS NULL) THEN RAISE EXCEPTION 'research_access:Active research work requires a complete bounded claim'; END IF;
IF NEW.status='completed' AND (NEW.research_deadline_at IS NULL OR clock_timestamp()>=NEW.research_deadline_at) THEN RAISE EXCEPTION 'research_budget:Research attempt wall time exceeded'; END IF;
END IF;
IF TG_OP='INSERT' OR (NEW.status='pending' AND OLD.status IN ('failed','completed','cancelled')) THEN
SELECT * INTO agent FROM research_agents WHERE id=principal FOR UPDATE;
IF NOT agent.enabled THEN RAISE EXCEPTION 'research_access:Research principal is disabled'; END IF;
IF TG_OP='UPDATE' THEN
SELECT * INTO experiment FROM research_experiments WHERE id=NEW.experiment_id;
PERFORM assert_research_agent_grant(agent,NEW.backtest_id,research_agent_authority(experiment));
END IF;
IF NEW.attempt_number >= (NEW.research_limits->>'maxAttempts')::integer THEN RAISE EXCEPTION 'research_budget:Research attempt budget exhausted'; END IF;
SELECT count(*) INTO active_count FROM runs WHERE research_agent_id=principal AND status IN ('pending','running','paused') AND id<>NEW.id;
IF active_count >= (agent.policy#>>'{limits,maxActiveTrials}')::bigint THEN RAISE EXCEPTION 'research_budget:Active trial capacity exhausted; wait for completion or cancellation'; END IF;
INSERT INTO research_agent_audit(agent_id,operation,entity_id) VALUES(principal,CASE WHEN TG_OP='INSERT' THEN 'trial-admitted' ELSE 'trial-retried' END,NEW.id::text);
END IF;
RETURN NEW;
END $$;
DROP TRIGGER IF EXISTS aa_agent_run_budget ON runs;
CREATE TRIGGER aa_agent_run_budget BEFORE INSERT OR UPDATE ON runs FOR EACH ROW EXECUTE FUNCTION guard_agent_run_budget();
-- Recheck at transaction completion as persistence can outlast the worker's timer.
CREATE OR REPLACE FUNCTION require_agent_result_deadline() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE owner runs;
BEGIN
SELECT * INTO owner FROM runs WHERE id=NEW.run_id;
IF owner.research_agent_id IS NOT NULL AND (owner.research_deadline_at IS NULL OR clock_timestamp()>=owner.research_deadline_at) THEN
RAISE EXCEPTION 'research_budget:Research attempt wall time exceeded before result commit';
END IF;
RETURN NEW;
END $$;
DROP TRIGGER IF EXISTS research_result_deadline ON backtest_results;
CREATE CONSTRAINT TRIGGER research_result_deadline AFTER INSERT ON backtest_results DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION require_agent_result_deadline();
-- Additional actor ownership fence; API admissions already hold the agent as their first lock.
-- These downward mutation triggers never acquire an agent lock after a resource row lock.
CREATE OR REPLACE FUNCTION assert_research_agent_owner(principal TEXT, owner TEXT) RETURNS void LANGUAGE plpgsql AS $$ BEGIN
IF principal LIKE 'agent:%' AND (principal IS DISTINCT FROM owner OR NOT EXISTS(SELECT 1 FROM research_agents WHERE id=principal AND enabled)) THEN
RAISE EXCEPTION 'research_access:Research action requires its enabled owning principal';
END IF;
END $$;
CREATE OR REPLACE FUNCTION guard_research_action_owner() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE owner TEXT;
BEGIN
IF TG_TABLE_NAME='experiment_trial_retries' THEN
SELECT submission_principal INTO owner FROM research_experiments WHERE id=NEW.experiment_id;
PERFORM assert_research_agent_owner(NEW.principal,owner);
ELSIF TG_TABLE_NAME='research_experiments' THEN
IF OLD.validation_selection IS NULL AND NEW.validation_selection IS NOT NULL AND NEW.submission_principal LIKE 'agent:%' AND NEW.validation_selection->>'principal' IS DISTINCT FROM NEW.submission_principal THEN RAISE EXCEPTION 'research_access:New holdouts must be selected by the owning research principal'; END IF;
IF OLD.validation_selection IS NULL AND NEW.validation_selection IS NOT NULL THEN PERFORM assert_research_agent_owner(NEW.validation_selection->>'principal',NEW.submission_principal); END IF;
IF OLD.validation_report IS NULL AND NEW.validation_report IS NOT NULL THEN PERFORM assert_research_agent_owner(NEW.validation_report->>'principal',NEW.submission_principal); END IF;
ELSIF OLD.report IS NULL AND NEW.report IS NOT NULL THEN PERFORM assert_research_agent_owner(NEW.report->>'principal',NEW.submission_principal);
END IF;
RETURN NEW;
END $$;
DROP TRIGGER IF EXISTS aa_research_action_owner ON experiment_trial_retries;
CREATE TRIGGER aa_research_action_owner BEFORE INSERT ON experiment_trial_retries FOR EACH ROW EXECUTE FUNCTION guard_research_action_owner();
DROP TRIGGER IF EXISTS aa_research_action_owner ON research_experiments;
CREATE TRIGGER aa_research_action_owner BEFORE UPDATE ON research_experiments FOR EACH ROW EXECUTE FUNCTION guard_research_action_owner();
DROP TRIGGER IF EXISTS aa_research_action_owner ON research_walk_forwards;
CREATE TRIGGER aa_research_action_owner BEFORE UPDATE ON research_walk_forwards FOR EACH ROW EXECUTE FUNCTION guard_research_action_owner();
-- Agent narratives are scoped to granted projects and owned candidates; human labels cannot be forged.
CREATE OR REPLACE FUNCTION guard_research_agent_metadata() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE value JSONB:=to_jsonb(NEW); principal TEXT; agent research_agents; project_id TEXT; owner TEXT;
BEGIN
principal:=CASE WHEN TG_TABLE_NAME='strategy_versions' THEN value->>'created_by'
WHEN TG_TABLE_NAME IN ('research_hypothesis_revisions','analysis_artifact_revisions') THEN value->>'submitted_by'
WHEN TG_TABLE_NAME='research_project_strategies' THEN value->>'added_by'
WHEN TG_OP='INSERT' THEN value->>'owner_principal' ELSE value->>'updated_by' END;
IF principal NOT LIKE 'agent:%' THEN RETURN NEW; END IF;
SELECT * INTO agent FROM research_agents WHERE id=principal FOR UPDATE;
IF NOT FOUND OR NOT agent.enabled THEN RAISE EXCEPTION 'research_access:Research principal is disabled'; END IF;
IF TG_TABLE_NAME='research_projects' THEN RAISE EXCEPTION 'research_access:Only an operator provisions research projects'; END IF;
IF value ? 'content_origin' AND value->>'content_origin' IS DISTINCT FROM 'ai' THEN RAISE EXCEPTION 'research_access:Research principals must declare AI authorship'; END IF;
IF TG_TABLE_NAME='strategies' THEN
IF TG_OP='UPDATE' AND OLD.owner_principal<>principal THEN RAISE EXCEPTION 'research_access:Candidate family is not owned by this principal'; END IF;
ELSIF TG_TABLE_NAME='strategy_versions' THEN
SELECT owner_principal INTO owner FROM strategies WHERE id=(value->>'strategy_id')::uuid;
IF owner IS DISTINCT FROM principal OR value->>'origin'<>'candidate' THEN RAISE EXCEPTION 'research_access:Research principals may only publish owned candidate versions'; END IF;
ELSE
project_id:=value->>'project_id';
IF TG_TABLE_NAME='research_hypothesis_revisions' THEN SELECT h.project_id::text,h.owner_principal INTO project_id,owner FROM research_hypotheses h WHERE h.id=(value->>'hypothesis_id')::uuid;
ELSIF TG_TABLE_NAME='analysis_artifact_revisions' THEN SELECT a.project_id::text,a.owner_principal INTO project_id,owner FROM analysis_artifacts a WHERE a.id=(value->>'artifact_id')::uuid;
ELSIF TG_TABLE_NAME='research_project_strategies' THEN SELECT owner_principal INTO owner FROM strategies WHERE id=(value->>'strategy_id')::uuid;
ELSIF TG_OP='UPDATE' THEN owner:=to_jsonb(OLD)->>'owner_principal';
ELSE owner:=principal; END IF;
IF owner IS DISTINCT FROM principal OR NOT (agent.policy->'allowedProjectIds' ? project_id) THEN RAISE EXCEPTION 'research_access:Research project or narrative ownership is not permitted'; END IF;
END IF;
INSERT INTO research_agent_audit(agent_id,operation,entity_id) VALUES(principal,TG_TABLE_NAME||'-'||lower(TG_OP),COALESCE(value->>'id',value->>'project_id'));
RETURN NEW;
END $$;
DO $$ DECLARE name TEXT; BEGIN
FOREACH name IN ARRAY ARRAY['strategies','strategy_versions','research_projects','research_hypotheses','research_hypothesis_revisions','analysis_artifacts','analysis_artifact_revisions','research_project_strategies'] LOOP
IF to_regclass(name) IS NOT NULL THEN
EXECUTE format('DROP TRIGGER IF EXISTS aa_research_agent_metadata ON %I',name);
EXECUTE format('CREATE TRIGGER aa_research_agent_metadata BEFORE INSERT OR UPDATE ON %I FOR EACH ROW EXECUTE FUNCTION guard_research_agent_metadata()',name);
END IF;
END LOOP;
END $$;
-- Preserved 24-chronological-validation.sql body; only accepted principal identity predicate is extended.
CREATE OR REPLACE FUNCTION protect_validation_evidence() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE document JSONB; candidate JSONB; item JSONB; idx INTEGER; winner_index INTEGER; best numeric; score numeric;
selected RECORD; approval RECORD; root research_experiments; phase TEXT; child_id UUID;
BEGIN
IF NEW.validation_manifest IS DISTINCT FROM OLD.validation_manifest OR NEW.validation_parent_id IS DISTINCT FROM OLD.validation_parent_id
OR NEW.validation_phase IS DISTINCT FROM OLD.validation_phase THEN
RAISE EXCEPTION 'Validation preparation and phase lineage are immutable' USING ERRCODE='23514';
END IF;
IF OLD.validation_selection IS NOT NULL AND NEW.validation_selection IS DISTINCT FROM OLD.validation_selection THEN
RAISE EXCEPTION 'Validation selection is write once' USING ERRCODE='23514';
END IF;
IF OLD.validation_report IS NOT NULL AND NEW.validation_report IS DISTINCT FROM OLD.validation_report THEN
RAISE EXCEPTION 'Validation report is write once' USING ERRCODE='23514';
END IF;
IF OLD.validation_selection IS NULL AND NEW.validation_selection IS NOT NULL THEN
document:=NEW.validation_selection;
IF (NEW.validation_phase='train' AND NOT NEW.cancel_requested AND OLD.validation_report IS NULL
AND document->>'version'='chronological-validation-selection/v1' AND document->>'validationId'=NEW.id::text
AND document->>'previewHash'=NEW.validation_manifest->>'previewHash' AND document->>'selectionHash' ~ '^[a-f0-9]{64}$'
AND document->>'id' ~ '^[a-f0-9-]{36}$' AND (document->>'createdAt')::timestamptz IS NOT NULL
AND is_research_actor(document->>'principal') AND document#>>'{_receipt,key}' ~ '^[!-~]{1,200}$'
AND document#>>'{_receipt,hash}' ~ '^[a-f0-9]{64}$' AND jsonb_typeof(document->'training')='array'
AND jsonb_array_length(document->'training')=jsonb_array_length(NEW.preview->'candidates')
AND (SELECT count(*) FROM runs WHERE experiment_id=NEW.id)=jsonb_array_length(NEW.preview->'candidates')
AND NOT EXISTS (SELECT 1 FROM research_experiments WHERE validation_parent_id=NEW.id)
AND document#>>'{holdoutExperimentIds,validation}' ~ '^[a-f0-9-]{36}$'
AND document#>>'{holdoutExperimentIds,test}' ~ '^[a-f0-9-]{36}$'
AND document#>>'{holdoutExperimentIds,validation}'<>document#>>'{holdoutExperimentIds,test}') IS NOT TRUE THEN
RAISE EXCEPTION 'Selection requires a complete uncancelled training experiment and immutable receipt' USING ERRCODE='23514';
END IF;
idx:=0; best:=NULL; winner_index:=NULL;
FOR item IN SELECT value FROM jsonb_array_elements(document->'training') LOOP
score:=assert_validation_evidence(item,NEW.id,'train',idx);
candidate:=NEW.preview->'candidates'->idx;
IF item->>'trialKey' IS DISTINCT FROM candidate->>'trialKey' THEN RAISE EXCEPTION 'Training evidence must follow original candidate order' USING ERRCODE='23514'; END IF;
IF best IS NULL OR score>best THEN best:=score; winner_index:=idx; END IF;
idx:=idx+1;
END LOOP;
IF document->'winner' IS DISTINCT FROM NEW.preview->'candidates'->winner_index THEN
RAISE EXCEPTION 'Winner must maximize training return with original-index tie break' USING ERRCODE='23514';
END IF;
SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id
WHERE v.id::text=NEW.validation_manifest#>>'{source,request,strategy,versionId}' FOR UPDATE OF s;
SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1;
IF (selected.origin='builtin' AND selected.family_archived IS NULL AND approval.decision='approve'
AND document->>'reviewId'=approval.id::text AND NEW.validation_manifest#>'{source,request,strategy,package}'=selected.envelope) IS NOT TRUE THEN
RAISE EXCEPTION 'New holdouts require current approval of their original version' USING ERRCODE='23514';
END IF;
END IF;
IF OLD.validation_report IS NULL AND NEW.validation_report IS NOT NULL THEN
document:=NEW.validation_report;
IF (NEW.validation_phase='train' AND NOT NEW.cancel_requested AND OLD.validation_selection IS NOT NULL
AND document->>'version'='chronological-validation-report/v1' AND document->>'validationId'=NEW.id::text
AND document->>'previewHash'=NEW.validation_manifest->>'previewHash' AND document->>'selectionHash'=OLD.validation_selection->>'selectionHash'
AND document->>'reportHash' ~ '^[a-f0-9]{64}$' AND document->>'id' ~ '^[a-f0-9-]{36}$' AND (document->>'createdAt')::timestamptz IS NOT NULL
AND is_research_actor(document->>'principal') AND document#>>'{_receipt,key}' ~ '^[!-~]{1,200}$'
AND document#>>'{_receipt,hash}' ~ '^[a-f0-9]{64}$' AND document->'training'=OLD.validation_selection->'training'
AND document->>'reset'='initial-capital-empty-positions' AND jsonb_typeof(document->'limitations')='array') IS NOT TRUE THEN
RAISE EXCEPTION 'Report requires exact frozen selection and independent reset evidence' USING ERRCODE='23514';
END IF;
idx:=0;
FOR item IN SELECT value FROM jsonb_array_elements(document->'training') LOOP
PERFORM assert_validation_evidence(item,NEW.id,'train',idx); idx:=idx+1;
END LOOP;
FOREACH phase IN ARRAY ARRAY['validation','test'] LOOP
child_id:=(OLD.validation_selection#>>ARRAY['holdoutExperimentIds',phase])::uuid;
IF NOT EXISTS (SELECT 1 FROM research_experiments WHERE id=child_id AND validation_parent_id=NEW.id AND validation_phase=phase AND NOT cancel_requested)
OR (SELECT count(*) FROM runs WHERE experiment_id=child_id)<>1 THEN
RAISE EXCEPTION 'Report requires each exact complete holdout child' USING ERRCODE='23514';
END IF;
PERFORM assert_validation_evidence(document->phase,child_id,phase,(OLD.validation_selection#>>'{winner,index}')::integer);
END LOOP;
END IF;
RETURN NEW;
END $$;
-- Preserved 25-walk-forward.sql body; only accepted principal identity predicate is extended.
CREATE OR REPLACE FUNCTION protect_walk_forward_evidence() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE document JSONB; member research_experiments; expected JSONB; item JSONB; segment JSONB; idx INTEGER:=0; training_index INTEGER;
BEGIN
IF NEW.id IS DISTINCT FROM OLD.id OR NEW.backtest_id IS DISTINCT FROM OLD.backtest_id OR NEW.name IS DISTINCT FROM OLD.name
OR NEW.preview IS DISTINCT FROM OLD.preview OR NEW.preview_hash IS DISTINCT FROM OLD.preview_hash OR NEW.member_ids IS DISTINCT FROM OLD.member_ids
OR NEW.submission_principal IS DISTINCT FROM OLD.submission_principal OR NEW.submission_key IS DISTINCT FROM OLD.submission_key
OR NEW.submission_hash IS DISTINCT FROM OLD.submission_hash OR NEW.created_at IS DISTINCT FROM OLD.created_at OR (OLD.cancel_requested AND NOT NEW.cancel_requested)
OR (OLD.report IS NOT NULL AND NEW.report IS DISTINCT FROM OLD.report) THEN
RAISE EXCEPTION 'Walk-forward inputs, receipt and report are immutable; cancellation is permanent' USING ERRCODE='23514';
END IF;
IF OLD.report IS NULL AND NEW.report IS NOT NULL THEN
document:=NEW.report;
IF (NOT NEW.cancel_requested AND document->>'version'='walk-forward-report/v1' AND document->>'walkForwardId'=NEW.id::text
AND document->>'previewHash'=NEW.preview_hash AND document->>'reportHash' ~ '^[a-f0-9]{64}$'
AND document->>'id' ~ '^[a-f0-9-]{36}$' AND (document->>'createdAt')::timestamptz IS NOT NULL
AND is_research_actor(document->>'principal') AND document#>>'{_receipt,key}' ~ '^[!-~]{1,200}$'
AND document#>>'{_receipt,hash}' ~ '^[a-f0-9]{64}$' AND document->>'reset'='initial-capital-empty-positions'
AND jsonb_typeof(document->'segments')='array' AND jsonb_array_length(document->'segments')=cardinality(NEW.member_ids)
AND jsonb_typeof(document->'limitations')='array') IS NOT TRUE THEN
RAISE EXCEPTION 'Walk-forward report requires all independent reset segments and a sealed receipt' USING ERRCODE='23514';
END IF;
FOR segment IN SELECT value FROM jsonb_array_elements(document->'segments') LOOP
SELECT * INTO member FROM research_experiments WHERE id=NEW.member_ids[idx+1] AND walk_forward_id=NEW.id AND walk_forward_index=idx;
IF (member.id IS NOT NULL AND NOT member.cancel_requested AND member.validation_report IS NOT NULL
AND member.validation_manifest=NEW.preview#>ARRAY['windows',idx::text,'preview']
AND member.validation_report->>'previewHash'=member.validation_manifest->>'previewHash'
AND member.validation_report->>'selectionHash'=member.validation_selection->>'selectionHash'
AND member.validation_report->'training'=member.validation_selection->'training') IS NOT TRUE THEN
RAISE EXCEPTION 'Every walk-forward member must have uncancelled sealed evidence matching its exact preparation' USING ERRCODE='23514';
END IF;
training_index:=0;
FOR item IN SELECT value FROM jsonb_array_elements(member.validation_report->'training') LOOP
PERFORM assert_validation_evidence(item,member.id,'train',training_index); training_index:=training_index+1;
END LOOP;
IF training_index<>jsonb_array_length(member.preview->'candidates') THEN RAISE EXCEPTION 'All training evidence is required' USING ERRCODE='23514'; END IF;
PERFORM assert_validation_evidence(member.validation_report->'validation',(member.validation_selection#>>'{holdoutExperimentIds,validation}')::uuid,'validation',(member.validation_selection#>>'{winner,index}')::integer);
PERFORM assert_validation_evidence(member.validation_report->'test',(member.validation_selection#>>'{holdoutExperimentIds,test}')::uuid,'test',(member.validation_selection#>>'{winner,index}')::integer);
expected:=jsonb_build_object('index',idx,'validationId',member.id::text,'previewHash',member.validation_manifest->'previewHash',
'selectionHash',member.validation_report->'selectionHash','reportId',member.validation_report->'id','reportHash',member.validation_report->'reportHash',
'validation',member.validation_report->'validation','test',member.validation_report->'test');
IF segment IS DISTINCT FROM expected THEN RAISE EXCEPTION 'Walk-forward segments must copy exact ordered sealed member reports' USING ERRCODE='23514'; END IF;
idx:=idx+1;
END LOOP;
END IF;
RETURN NEW;
END $$;
-- Preserved 26-cost-sensitivity.sql body; only accepted principal identity predicate is extended.
CREATE OR REPLACE FUNCTION require_active_backtest_for_new_run() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE parent RECORD; selected RECORD; approval RECORD; retained JSONB; snapshot JSONB; original RECORD; expected JSONB; experiment RECORD; candidate JSONB;
BEGIN
SELECT * INTO parent FROM backtests WHERE id=NEW.backtest_id FOR UPDATE;
IF NOT FOUND THEN RETURN NEW; END IF;
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;
snapshot := NEW.request_snapshot;
IF NEW.experiment_id IS NOT NULL THEN
SELECT * INTO experiment FROM research_experiments WHERE id=NEW.experiment_id FOR UPDATE;
candidate := experiment.preview->'candidates'->NEW.trial_index;
IF (experiment.id IS NOT NULL AND experiment.backtest_id=NEW.backtest_id AND NOT experiment.cancel_requested
AND NEW.trial_index>=0 AND candidate->>'index'=NEW.trial_index::text
AND candidate->>'trialKey'=NEW.trial_key
AND NEW.original_run_id IS NULL AND NEW.submission_principal IS NULL
AND NEW.submission_key IS NULL AND NEW.submission_hash IS NULL
AND NEW.status='pending' AND NEW.speed_multiplier IS NULL
AND NEW.dataset_hash=experiment.preview#>>'{request,datasetHash}') IS NOT TRUE THEN
RAISE EXCEPTION 'Experiment trial requires its uncancelled manifest, exact candidate and no individual receipt or lineage' USING ERRCODE='23514';
END IF;
SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id
WHERE v.id::text=experiment.preview#>>'{request,strategy,versionId}' FOR UPDATE OF s;
SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1;
IF (selected.origin='builtin' AND selected.family_archived IS NULL AND approval.decision='approve'
AND experiment.preview#>>'{request,strategy,reviewId}'=approval.id::text
AND experiment.preview#>>'{request,strategy,familyId}'=selected.strategy_id::text
AND experiment.preview#>'{request,strategy,package}'=selected.envelope) IS NOT TRUE THEN
RAISE EXCEPTION 'Experiment requires its current approved original retained built-in version' USING ERRCODE='23514';
END IF;
expected := experiment_trial_request(experiment.preview,NEW.trial_index,NEW.id);
IF snapshot IS DISTINCT FROM expected THEN
RAISE EXCEPTION 'Experiment trial must preserve its exact frozen request and candidate parameters' USING ERRCODE='23514';
END IF;
SELECT payload INTO retained FROM backtest_datasets WHERE hash=NEW.dataset_hash;
IF (retained#>>'{manifest,version}'='2' AND retained#>>'{manifest,eligibility}'='eligible'
AND retained->'manifest'=experiment.preview->'dataset'
AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1
AND jsonb_array_length(retained#>'{manifest,series}')=1
AND snapshot#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
AND snapshot#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}') IS NOT TRUE THEN
RAISE EXCEPTION 'Experiment requires the same eligible retained single-asset dataset' USING ERRCODE='23514';
END IF;
RETURN NEW;
END IF;
IF NEW.original_run_id IS NOT NULL THEN
SELECT r.*,br.canonical_result INTO original FROM runs r
LEFT JOIN backtest_results br ON br.run_id=r.id WHERE r.id=NEW.original_run_id;
IF (original.id IS NOT NULL AND original.id<>NEW.id
AND original.backtest_id=NEW.backtest_id AND original.status='completed'
AND original.request_snapshot->>'kind'='canonical-research/v1'
AND original.request_snapshot->>'runId'=original.id::text
AND original.request_snapshot->>'backtestId'=NEW.backtest_id::text
AND original.request_snapshot->>'datasetHash'=original.dataset_hash
AND original.canonical_result->>'kind'='canonical-result/v1'
AND original.canonical_result->>'status'='completed'
AND original.canonical_result->>'runId'=original.id::text
AND original.canonical_result->>'backtestId'=NEW.backtest_id::text
AND original.canonical_result->'request'=original.request_snapshot
AND original.canonical_result->>'financialEngine'='rust'
AND original.canonical_result->>'strategyExecution'='typescript-retained-builtin/v1'
AND NEW.dataset_hash=original.dataset_hash
AND NEW.status='pending' AND NEW.speed_multiplier IS NULL
AND is_research_actor(NEW.submission_principal)
AND NEW.submission_key ~ '^[!-~]{1,200}$'
AND NEW.submission_hash ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN
RAISE EXCEPTION 'Reproduction requires a completed canonical source in the same backtest and a submission receipt' USING ERRCODE='23514';
END IF;
SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v
JOIN strategies s ON s.id=v.strategy_id
WHERE v.id::text=original.request_snapshot#>>'{strategy,versionId}' FOR UPDATE OF s;
SELECT id,decision INTO approval FROM strategy_review_events
WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1;
IF (selected.origin='builtin' AND selected.family_archived IS NULL
AND approval.decision='approve'
AND original.request_snapshot#>>'{strategy,origin}'='builtin'
AND original.request_snapshot#>>'{strategy,familyId}'=selected.strategy_id::text
AND original.request_snapshot#>'{strategy,package}'=selected.envelope) IS NOT TRUE THEN
RAISE EXCEPTION 'Reproduction requires the currently approved original retained built-in version' USING ERRCODE='23514';
END IF;
expected := jsonb_set(original.request_snapshot, '{runId}', to_jsonb(NEW.id::text));
expected := jsonb_set(expected, '{policy,matching,risk,ledger,sessionId}', to_jsonb(NEW.id::text));
expected := jsonb_set(expected, '{policy,matching,risk,ledger,accountId}', to_jsonb('research:'||NEW.id::text));
expected := jsonb_set(expected, '{strategy,reviewId}', to_jsonb(approval.id::text));
IF snapshot IS DISTINCT FROM expected THEN
RAISE EXCEPTION 'Reproduction must preserve the original frozen request except run identities and current approval' USING ERRCODE='23514';
END IF;
SELECT payload INTO retained FROM backtest_datasets WHERE hash=NEW.dataset_hash;
IF (retained#>>'{manifest,version}'='2'
AND retained#>>'{manifest,eligibility}'='eligible'
AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1
AND jsonb_array_length(retained#>'{manifest,series}')=1
AND jsonb_array_length(snapshot#>'{policy,matching,series}')=1
AND jsonb_array_length(snapshot#>'{policy,matching,owners}')=1
AND jsonb_array_length(snapshot#>'{policy,matching,risk,ledger,ownerIds}')=1
AND snapshot#>>'{policy,allow_exploratory}'='false'
AND snapshot#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
AND snapshot#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}') IS NOT TRUE THEN
RAISE EXCEPTION 'Reproduction requires the original eligible retained single-asset dataset' USING ERRCODE='23514';
END IF;
RETURN NEW;
END IF;
IF parent.strategy_version_id IS NULL AND parent.strategy <> 'catalog' THEN
IF snapshot->>'kind'='canonical-research/v1' THEN
RAISE EXCEPTION 'Canonical research requires a catalog template' USING ERRCODE='23514';
END IF;
RETURN NEW;
END IF;
IF (snapshot->>'kind'='canonical-research/v1'
AND snapshot->>'runId'=NEW.id::text
AND snapshot->>'backtestId'=NEW.backtest_id::text
AND snapshot#>>'{strategy,versionId}'=parent.strategy_version_id::text
AND snapshot->>'datasetHash'=NEW.dataset_hash
AND NEW.status='pending' AND NEW.speed_multiplier IS NULL) IS NOT TRUE THEN
RAISE EXCEPTION 'Catalog strategy execution requires an admitted canonical request' USING ERRCODE='23514';
END IF;
-- This is the same family lock used by operator review and archive. Later
-- review changes affect new admissions, never rewrite accepted snapshots.
SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v
JOIN strategies s ON s.id=v.strategy_id WHERE v.id=parent.strategy_version_id FOR UPDATE OF s;
SELECT id,decision INTO approval FROM strategy_review_events
WHERE version_id=parent.strategy_version_id ORDER BY ordinal DESC LIMIT 1;
IF (selected.origin='builtin' AND selected.family_archived IS NULL
AND approval.decision='approve'
AND snapshot#>>'{strategy,origin}'='builtin'
AND snapshot#>>'{strategy,familyId}'=selected.strategy_id::text
AND snapshot#>>'{strategy,reviewId}'=approval.id::text
AND snapshot#>'{strategy,package}'=selected.envelope
AND snapshot#>'{strategy,selection,parameters}'=parent.strategy_parameters
AND snapshot#>>'{strategy,selection,ownerId}'='strategy:'||selected.id::text) IS NOT TRUE THEN
RAISE EXCEPTION 'Canonical research requires the exact approved retained built-in version' USING ERRCODE='23514';
END IF;
SELECT payload INTO retained FROM backtest_datasets WHERE hash=NEW.dataset_hash;
IF (retained#>>'{manifest,version}'='2'
AND retained#>>'{manifest,eligibility}'='eligible'
AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1
AND jsonb_array_length(retained#>'{manifest,series}')=1
AND jsonb_array_length(snapshot#>'{policy,matching,series}')=1
AND jsonb_array_length(snapshot#>'{policy,matching,owners}')=1
AND jsonb_array_length(snapshot#>'{policy,matching,risk,ledger,ownerIds}')=1
AND snapshot#>>'{policy,allow_exploratory}'='false'
AND snapshot#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
AND snapshot#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}'
AND snapshot#>>'{policy,matching,series,0,instrumentId}'=snapshot#>>'{strategy,selection,instrumentId}'
AND snapshot#>>'{policy,matching,series,0,seriesId}'=snapshot#>>'{strategy,selection,seriesId}') IS NOT TRUE THEN
RAISE EXCEPTION 'Canonical research requires one eligible retained v2 execution asset' USING ERRCODE='23514';
END IF;
RETURN NEW;
END $$;

View file

@ -1,6 +1,6 @@
# Revised development roadmap
**Thirty-six waves committed; completion of the remaining scheduled tasks is in progress.** Stored EOD preparation is committed as `0c6aec4`. Currently **38/45 scheduled tasks are complete (84% by count; R07 measurement validated, awaiting commit)**. The owner authorized finishing the remaining scheduled work, including required measurements; conditional deferred optimizations retain their evidence gates.
**Canonical default and bounded research access are validated.** R05/S06/A01 and the R07 measurement are complete: **41/45 scheduled tasks (91% by count)**. Remaining: A02 isolated candidate execution, P04 bounded concurrent trials, A04 human-reviewed paper promotion, and A03 the evidence-linked research client. Six conditional tasks remain deferred with their original evidence gates.
Authorization update: the owner requested “commit and continue with the rest of the tasks till 100%”. Commit `0c6aec4` records the validated stored-source slice. Complete scheduled R05/R07/S06/P04/A01–A04 with independent review. Required table/concurrency measurements resume; conditional optimizations remain evidence-driven. The default cutover supports canonical single-asset research; unsupported multi-asset policy and real paper/live activation remain gated.
@ -729,3 +729,14 @@ Supported source preparation is now available before admission. Remaining substa
## Scheduled-backlog completion — 2026-10-24
The first parallel group owns: (1) R05/S06 canonical single-asset default and retirement of active competing execution, preserving historical readers/accounts/calculations; (2) A01 operator-provisioned research principals, transactional durable budgets and attribution; (3) R07 production-browser table measurements. Separate worktrees use base `0c6aec4`. Root owns UI cutover/integration and reviews contracts; overlapping runner/admission edits are exchanged as coordinated patches. Next are P04 bounded independent runner slots, A02 OS isolation, A04 human-reviewed paper deployment and A03 the typed evidence-linked client. No task closes until its required tests and review pass. Deferred IDs are not silently marked complete.
## Thirty-seventh-wave handoff — 2026-10-24
R05/S06/A01 are accepted. Production starts canonical research by default; explicit canonical paper remains halted until existing operator/feed/recovery checks pass. New legacy research and old native worker commands refuse, while historical results, prototype algorithms, calculations and durable recovery remain. Single-asset admission stays enforced; no simultaneous multi-asset policy is approved by this cutover.
Research credentials are hash-only, project/template scoped and independently revocable. SQL enforces active capacity, complete recipe work, attempt limits and deadlines across retries and validation phases. Operator UI provisioning, usage and revocation work against real APIs. Independent review closed retry/phase-budget bypasses and stale UI responses before acceptance. Accepted bounded work may finish after credential revocation.
Evidence: 1233 integration/tooling tests, 254 PostgreSQL tests, 17 real-browser workflows, 150 active Rust tests; four existing Rust tests remain ignored. Final types/lint/format and production builds pass. Exact source archives, native hash, logs and limitations: manifest `thirty_seventh_wave_validation`. The async replay/controller extraction is tested groundwork for A02; arbitrary candidate execution is not claimed complete.
Next owners: A02 owns candidate contracts/SQL29/sandbox/worker; P04 owns pool and research composition; A04 owns SQL30, promotion/evidence and paper runtime/UI. Root owns migration registration, bootstrap merge, shared navigation/browser integration and acceptance. A04 can build components in parallel but candidate release waits for A02. A03 follows candidate admission. No agent independently changes financial policy.

View file

@ -1,6 +1,6 @@
# Canonical development backlog
**Thirty-six waves committed; completion of the remaining scheduled tasks is in progress.** Stored EOD preparation is committed as `0c6aec4`. Currently **38/45 scheduled tasks are complete (84% by count; R07 measurement validated, awaiting commit)**. The owner authorized finishing the remaining scheduled work, including required measurements; conditional deferred optimizations retain their evidence gates.
**Canonical default and bounded research access are validated.** R05/S06/A01 and the R07 measurement are complete: **41/45 scheduled tasks (91% by count)**. Remaining: A02 isolated candidate execution, P04 bounded concurrent trials, A04 human-reviewed paper promotion, and A03 the evidence-linked research client. Six conditional tasks remain deferred with their original evidence gates.
## One source of truth
@ -57,7 +57,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
| [S03 Adapt durable paper transactions to Rust financial reducers](tasks/S03.md) | P0 / done | S01, C06, ADR-005 | — | Durable execution/Rust integration / L |
| [S04 Establish a verified paper feed and operator safety gate](tasks/S04.md) | P1 / done | S02, S03 | — | TypeScript trading infrastructure / M |
| [S05 Add a small composable multi-signal regime example](tasks/S05.md) | P2 / done | S02, F08 | R08 | Quant strategy research / M |
| [S06 Retire duplicate simulator paths after cutover proof](tasks/S06.md) | P2 / blocked | S03, S04, R05 | — | TypeScript trading infrastructure / M |
| [S06 Retire duplicate simulator paths after cutover proof](tasks/S06.md) | P2 / done | S03, S04, R05 | — | TypeScript trading infrastructure / M |
### E5 — Existing web backtest vertical slice
@ -76,9 +76,9 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
| [R02 Deliver strategy catalog and version-aware backtest setup](tasks/R02.md) | P1 / done | R01, W03, ADR-006 | W04 | Full-stack research product / M |
| [R03 Add projects, hypotheses and evidence-linked findings APIs](tasks/R03.md) | P1 / done | R01, R10, ADR-006 | — | Full-stack research product / M |
| [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / done | R03, W02, ADR-006 | W04 | Full-stack research product / M |
| [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / in_progress | 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 / done | 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 / done | Accepted R05 retained-input component; R01/R10/F08/S02/D01/W03/C06/R12, ADR-006 | — | Full-stack research product / M |
| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / done (measurement validated; awaiting commit) | R06, ADR-006 | W04 | Full-stack research product / M |
| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / done (measurement committed ab08db8) | R06, ADR-006 | W04 | Full-stack research product / M |
| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / done | R06, ADR-006 | — | Quantitative research integrity / M |
| [R09 Expose validation, cost and regime evidence in the workbench](tasks/R09.md) | P1 / done | R08, committed R07 functional component, 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 / done | R01, ADR-006 | — | Full-stack research product / M |
@ -92,7 +92,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
| [P01 Measure existing research paths before extending the benchmark](tasks/P01.md) | P2 / done | None | — | Performance/infrastructure engineering / M |
| [P02 Remove measured replay queue and hot-loop overhead](tasks/P02.md) | P2 / merged → F06 | None | — | Performance/infrastructure engineering / M |
| [P03 Reuse validated datasets within bounded native workers](tasks/P03.md) | P2 / deferred | F07, P01, ADR-004, ADR-008 | — | Performance/infrastructure engineering / M |
| [P04 Schedule deterministic batches across a bounded worker pool](tasks/P04.md) | P2 / blocked | F07, R06, C06, P01, ADR-008 | — | Performance/infrastructure engineering / M |
| [P04 Schedule deterministic batches across a bounded worker pool](tasks/P04.md) | P2 / ready | F07, R06, C06, P01, ADR-008 | — | Performance/infrastructure engineering / M |
| [P05 Separate result summaries from paged detail payloads](tasks/P05.md) | P2 / deferred | R06, P01 | — | Performance/infrastructure engineering / M |
| [P06 Conditionally add a minimal Rust-executed strategy plan](tasks/P06.md) | P2 / deferred | P04, S01, ADR-008 | — | Rust/TS performance compiler boundary / M |
| [P07 Profile representative canonical replay workloads](tasks/P07.md) | P1 / done | F07, P01 | F09 for compact comparisons | Performance/test infrastructure / M |
@ -102,10 +102,10 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
| --- | --- | --- | --- | --- |
| [A01 Add research-only principals and durable job budgets](tasks/A01.md) | P1 / blocked | R06, O01, ADR-007 | — | Backend security/durable scheduling / M |
| [A02 Isolate untrusted TypeScript strategy builds and decisions](tasks/A02.md) | P1 / blocked | A01, S01, P01, ADR-007 | — | Process isolation/security / L |
| [A01 Add research-only principals and durable job budgets](tasks/A01.md) | P1 / done | R06, O01, ADR-007 | — | Backend security/durable scheduling / M |
| [A02 Isolate untrusted TypeScript strategy builds and decisions](tasks/A02.md) | P1 / ready | A01, S01, P01, ADR-007 | — | Process isolation/security / L |
| [A03 Implement an evidence-linked AI research workflow client](tasks/A03.md) | P2 / blocked | A02, R08, R03, ADR-007 | — | AI research integration / M |
| [A04 Add human-reviewed promotion to paper deployment](tasks/A04.md) | P2 / blocked | S04, R09, A01, R01, ADR-007, ADR-005 | — | Full-stack paper trading integration / M |
| [A04 Add human-reviewed promotion to paper deployment](tasks/A04.md) | P2 / ready | S04, R09, A01, R01, ADR-007, ADR-005 | — | Full-stack paper trading integration / M |
### E9 — Migration and operational safeguards

View file

@ -1,38 +1,28 @@
{
"schema_version": 1,
"plan_revision": "2026-10-24.74",
"plan_revision": "2026-10-24.75",
"repository_base": "b7aeca4",
"plan_status": "scheduled_backlog_completion_in_progress",
"execution_authorized": true,
"execution_scope": {
"authorized_by": "User: how far in backlog, commit and continue; wave35 accepted and committed 366bee810b8c1881172fe5553a1a61a2242ffbe5",
"tasks": ["R05"],
"authorized_by": "Owner: commit and continue with the rest of the tasks till 100%",
"tasks": ["R05", "R07", "S06", "A01", "A02", "A03", "A04", "P04"],
"permissions": [
"R05 explicit stored EOD intraday source materialization before existing retained-data admission; reuse source preview/retention and canonical setup, no inferred metadata."
"Complete all45 scheduled tasks with independent review and relevant gates; commit validated increments.",
"Required R07/P04/A02 measurements and bounded1/2/4 trial concurrency.",
"Canonical single-asset default; research-only credentials and OS isolation; explicit human paper promotion workflow."
],
"excluded": [
"performance_profiling_or_optimization",
"performance_benchmarks",
"new_wave_commits_without_further_approval",
"push",
"pull_requests",
"live_or_paper_operations",
"default_engine_cutover",
"candidate_execution",
"provider_to_v2_inference",
"multi_asset_activation",
"AI_execution_or_credentials",
"historical_binary_provisioning",
"cross_experiment_ranking",
"strategy_performance_conclusions",
"cost_parameter_cartesian_optimization",
"cost_source_run_selector",
"cost_walk_forward_joint_studies"
"actual paper or live activation",
"existing account migration",
"unapproved multi-asset simultaneous-mark policy",
"conditional speculative optimization without its existing evidence/approval gate"
],
"pending_policy_decisions": [
"ADR-007",
"ADR-008",
"Simultaneous multi-asset mark/risk policy before default activation"
"Simultaneous multi-asset mark/risk semantics before multi-asset default activation",
"Conditional DSL/cache/distributed optimization go/no-go"
]
},
"canonical_metadata": "This manifest alone owns task status, dependency edges, approvals, assignments and write locks. Task Markdown owns scope and acceptance criteria. Index/roadmap are derived views.",
@ -80,12 +70,16 @@
{
"id": "ADR-007",
"file": "architecture/decisions/007-ai-boundary.md",
"status": "approval_required"
"status": "approved",
"approved_by": "Owner scheduled-completion instruction; implementation only, human paper activation remains explicit",
"approved_on": "2026-10-24"
},
{
"id": "ADR-008",
"file": "architecture/decisions/008-performance.md",
"status": "proposed_with_measurement_gate"
"status": "approved_for_scheduled_measurements",
"approved_by": "Owner scheduled-completion instruction; conditional optimization gates unchanged",
"approved_on": "2026-10-24"
}
],
"epics": [
@ -967,7 +961,7 @@
"epic": "E4",
"priority": "P2",
"severity": "Medium",
"status": "in_progress",
"status": "done",
"dependencies": ["S03", "S04", "R05"],
"decision_dependencies": [],
"task_file": "backlog/tasks/S06.md",
@ -980,9 +974,13 @@
"branch": null,
"pull_request": null,
"completed_commit": null,
"blocker": "Integrated after R05 canonical single-asset cutover; shared owner preserves history and inventories callers before removal.",
"blocker": null,
"release_gates": [],
"worktree": "/tmp/stock-bot-wave37.v0zgbc/cutover"
"worktree": "/tmp/stock-bot-wave37.v0zgbc/cutover",
"integration_state": "validated_uncommitted",
"verification_reference": "ROADMAP.md#thirty-seventh-wave-handoff--2026-10-24",
"reviewed_by": "/root and independent cross-owner review",
"review_notes": "Accepted canonical default/custody preservation and bounded research authorization. Full native/database/browser gates passed; actual trading unchanged."
},
{
"id": "W01",
@ -1287,7 +1285,7 @@
"epic": "E6",
"priority": "P0",
"severity": "Critical",
"status": "in_progress",
"status": "done",
"dependencies": ["F08", "S02", "R01", "R10", "D01", "W03", "C06"],
"decision_dependencies": ["ADR-006"],
"task_file": "backlog/tasks/R05.md",
@ -1302,9 +1300,9 @@
"completed_commit": null,
"blocker": null,
"release_gates": [
"Explicit owner disposition of the simultaneous multi-asset mark/risk policy before canonical default activation"
"Multi-asset default remains unavailable pending explicit owner simultaneous-mark policy; canonical single-asset default is accepted."
],
"integration_state": "cutover_in_progress",
"integration_state": "validated_uncommitted",
"integration_base": "366bee810b8c1881172fe5553a1a61a2242ffbe5",
"worktree": "/tmp/stock-bot-wave37.v0zgbc/cutover",
"implementation_slices": [
@ -1323,16 +1321,13 @@
"scope": "Shared DTO, actual adapter/native browser proof, combined gates and deliberate before-admission planning simplification"
}
],
"reviewed_by": "/root/r04_review",
"verification_reference": "ROADMAP.md#thirty-sixth-wave-handoff--2026-10-24",
"review_notes": "Independent exact-source review and final repository/PostgreSQL/Chromium gates passed. Supported stored EOD source preparation materializes and retains before canonical admission; former in-run preparation proposal explicitly superseded. R05 remains partial for broader cutover/default gates; S06 is not unblocked.",
"reviewed_by": "/root and independent cross-owner review",
"verification_reference": "ROADMAP.md#thirty-seventh-wave-handoff--2026-10-24",
"review_notes": "Accepted canonical default/custody preservation and bounded research authorization. Full native/database/browser gates passed; actual trading unchanged.",
"partial_commit": "0c6aec4",
"execution_component": "Explicit stored EOD intraday metadata + raw bars materialized once before existing content retention and canonical admission",
"execution_component": "Full canonical single-asset default cutover, supported source preparation before immutable admission, preserved history and durable behavior",
"component_exclusions": [
"No default/multiasset/candidate/AI/paper/live activation, new run kind, SQL/runner mutation, source-query receipt or scheduler.",
"Source-query-inside-run proposal intentionally superseded by prepare-and-retain before canonical admission; not claimed implemented.",
"Stored-source scope1m/5m/1h EOD raw interval-start and explicitly assumed interval-end availability. No daily/QuestDB/auto/synthetic path or inferred evidence.",
"Performance and R07 measurement remain paused."
"Unsupported multi-asset activation and automatic paper/live operation; candidate isolation remains A02."
],
"source_preparation_disposition": "Canonical source inputs are materialized, reviewed and retained before admission. Existing atomic request/hash admission and worker binding verification remain authoritative. This replaces earlier pending-query/fenced-first-binding work with fewer states and no loss of frozen-input correctness; wider cutover remains incomplete."
},
@ -1403,10 +1398,10 @@
"assignment": "/root/r12_frontend",
"branch": null,
"pull_request": null,
"completed_commit": null,
"completed_commit": "ab08db82fda451243b9e12603810a9c92af247ac",
"blocker": null,
"release_gates": ["W04"],
"integration_state": "validated_uncommitted",
"integration_state": "validated_committed",
"integration_base": "397cd0e1603b7ccd01bf80c9ff3930ba2a1b9963",
"worktree": "/tmp/stock-bot-wave37.v0zgbc/table",
"execution_component": "Read-only cross-experiment comparison with explicit reference and retained input compatibility",
@ -1759,7 +1754,7 @@
"epic": "E7",
"priority": "P2",
"severity": "Medium",
"status": "blocked",
"status": "ready",
"dependencies": ["F07", "R06", "C06", "P01"],
"decision_dependencies": ["ADR-008"],
"task_file": "backlog/tasks/P04.md",
@ -1768,12 +1763,14 @@
"specialization": "Performance/infrastructure engineering",
"write_locks": ["worker-pool", "web-backtest-dispatch"],
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
"assignment": null,
"assignment": "/root/r12_frontend",
"branch": null,
"pull_request": null,
"completed_commit": null,
"blocker": null,
"release_gates": []
"release_gates": [],
"integration_state": "ready_for_isolated_implementation",
"worktree": "/tmp/stock-bot-wave38.PuFhtc/pool"
},
{
"id": "P05",
@ -1885,7 +1882,7 @@
"epic": "E8",
"priority": "P1",
"severity": "High",
"status": "in_progress",
"status": "done",
"dependencies": ["R06", "O01"],
"decision_dependencies": ["ADR-007"],
"task_file": "backlog/tasks/A01.md",
@ -1900,7 +1897,11 @@
"completed_commit": null,
"blocker": null,
"release_gates": [],
"worktree": "/tmp/stock-bot-wave37.v0zgbc/principals"
"worktree": "/tmp/stock-bot-wave37.v0zgbc/principals",
"integration_state": "validated_uncommitted",
"verification_reference": "ROADMAP.md#thirty-seventh-wave-handoff--2026-10-24",
"reviewed_by": "/root and independent cross-owner review",
"review_notes": "Accepted canonical default/custody preservation and bounded research authorization. Full native/database/browser gates passed; actual trading unchanged."
},
{
"id": "A02",
@ -1908,7 +1909,7 @@
"epic": "E8",
"priority": "P1",
"severity": "High",
"status": "blocked",
"status": "ready",
"dependencies": ["A01", "S01", "P01"],
"decision_dependencies": ["ADR-007"],
"task_file": "backlog/tasks/A02.md",
@ -1917,12 +1918,14 @@
"specialization": "Process isolation/security",
"write_locks": ["sandbox-contract", "worker-protocol"],
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
"assignment": null,
"assignment": "/root/r04_review",
"branch": null,
"pull_request": null,
"completed_commit": null,
"blocker": null,
"release_gates": []
"release_gates": [],
"integration_state": "ready_for_isolated_implementation",
"worktree": "/tmp/stock-bot-wave38.PuFhtc/candidate"
},
{
"id": "A03",
@ -1952,7 +1955,7 @@
"epic": "E8",
"priority": "P2",
"severity": "Medium",
"status": "blocked",
"status": "ready",
"dependencies": ["S04", "R09", "A01", "R01"],
"decision_dependencies": ["ADR-007", "ADR-005"],
"task_file": "backlog/tasks/A04.md",
@ -1961,12 +1964,16 @@
"specialization": "Full-stack paper trading integration",
"write_locks": ["paper-runtime", "web-strategies", "sql-migrations"],
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
"assignment": null,
"assignment": "/root/r12_backend",
"branch": null,
"pull_request": null,
"completed_commit": null,
"blocker": null,
"release_gates": []
"release_gates": [
"A02 candidate artifact/retained-factory integration and actual candidate evidence/browser proof; component implementation may run in parallel."
],
"integration_state": "ready_for_isolated_implementation",
"worktree": "/tmp/stock-bot-wave38.PuFhtc/paper"
},
{
"id": "O01",
@ -7899,6 +7906,112 @@
],
"verification": "20 production browser samples; exact all-row/status/parameter/metric/null/link/reference/current-response checks. Author strict types/lint/format passed.8 harness tests/495 assertions passed in author and integrated roots.",
"limitations": "Synthetic compact DTOs, UI only. Shared browser and fresh contexts, not cold OS/disk cache. External Google Fonts blocked and fallback fonts reported. Five samples per workload; no p95/SLO/statistical certification, financial engine, API/database storage or research-throughput claim.",
"decision": "Keep current tables. No measured need for virtualization at current100-trial limits."
"decision": "Keep current tables. No measured need for virtualization at current100-trial limits.",
"completed_commit": "ab08db82fda451243b9e12603810a9c92af247ac"
},
"previous_execution_scope": {
"authorized_by": "User: how far in backlog, commit and continue; wave35 accepted and committed 366bee810b8c1881172fe5553a1a61a2242ffbe5",
"tasks": ["R05"],
"permissions": [
"R05 explicit stored EOD intraday source materialization before existing retained-data admission; reuse source preview/retention and canonical setup, no inferred metadata."
],
"excluded": [
"performance_profiling_or_optimization",
"performance_benchmarks",
"new_wave_commits_without_further_approval",
"push",
"pull_requests",
"live_or_paper_operations",
"default_engine_cutover",
"candidate_execution",
"provider_to_v2_inference",
"multi_asset_activation",
"AI_execution_or_credentials",
"historical_binary_provisioning",
"cross_experiment_ranking",
"strategy_performance_conclusions",
"cost_parameter_cartesian_optimization",
"cost_source_run_selector",
"cost_walk_forward_joint_studies"
],
"pending_policy_decisions": [
"ADR-007",
"ADR-008",
"Simultaneous multi-asset mark/risk policy before default activation"
]
},
"thirty_seventh_wave_validation": {
"date": "2026-10-24",
"tasks": ["R05", "S06", "A01"],
"base": "ab08db82fda451243b9e12603810a9c92af247ac",
"review": "Cutover preservation inventory reviewed by root; A01 independent final source review accepted by r12_frontend. Root async/controller/UI additions independently reviewed by r12_backend; two UI race findings corrected and regression-tested.",
"behavior": [
"Default Rust canonical single-asset research; explicit canonical paper starts halted. Old new-run paths refuse; historical results/accounts/prototypes/calculations/recovery remain.",
"Research-only hashed credentials and frozen write grants, SQL-authoritative active/trial/work/attempt/deadline budgets, receipts and actor ownership; no paper/live/credential administration.",
"Web agent management, loss-of-response recovery and stale-budget fencing; canonical create/configure/run/reopen and retained legacy history browser flows.",
"Shared synchronous/asynchronous replay lifecycle and pure controller extraction are tested A02 foundations, not completed candidate isolation."
],
"tests": {
"integration_and_tooling": "1233 passed /21755 assertions /105 files",
"postgres": "254 passed; see exact log for assertion count",
"browser": "17 passed /636 assertions",
"rust": "150 passed /4 preexisting ignored",
"reviewed_ui": "8 passed /41 assertions"
},
"checks": [
"Repository check passed before narrow final A01/UI review deltas; final full integration/tooling/PostgreSQL suites passed.",
"Final application typecheck, strict authored-test types, app/lib lint and affected-test lint/format passed.",
"Production UI and release native builds passed."
],
"native_sha256": "f47e2c8bfe5a04e96dd755f2cc444a673a7b4a73b1127b862102cf4b83aa387c",
"author_archives": {
"cutover": {
"path": "/tmp/stock-bot-wave37.v0zgbc/cutover-final.tar",
"sha256": "4d33fdd31db123343b98efe6e93cf954a604a1bcdf931c241d076688d2f74363"
},
"principals": {
"path": "/tmp/stock-bot-wave37.v0zgbc/agent-final.tar.gz",
"sha256": "e87726e2524bf20cc5161873dcc633d8de9dbd80672003679b020d481f5ba13d"
}
},
"root_deltas": [
"Frontend/default and async replay foundation; actual-native browser fixtures and new agent workflow; migration28 registry; legacy reproduction/workspace fixtures; UI review fixes."
],
"limitations": [
"Singleasset/singleseries canonical production policy. No migration/activation of real paper/live accounts.",
"Candidate sandbox, pool, AI client and paper promotion are not done.",
"Four preexisting manual Rust tests ignored; existing Rust dead-code/frontend chunk warnings retained.",
"Disposable test databases only; .env unchanged."
],
"logs": {
"integration-check.log": {
"path": "/tmp/stock-bot-wave37.v0zgbc/integration-check.log",
"sha256": "b8954c1b1c6a1b494a70dca3642c933193e105896998691464573839e5a28696"
},
"integration-accepted-tests.log": {
"path": "/tmp/stock-bot-wave37.v0zgbc/integration-accepted-tests.log",
"sha256": "0ff419e893c10e8cf80c96c4a3c41ebe08c14f80bd5e94ffb6c5899223d6fef8"
},
"integration-postgres-final.log": {
"path": "/tmp/stock-bot-wave37.v0zgbc/integration-postgres-final.log",
"sha256": "55881156923902ae0b3b05e3e3bca7db32247c872afe5b6e91d7a5f0bd3d75d4"
},
"integration-browser.log": {
"path": "/tmp/stock-bot-wave37.v0zgbc/integration-browser.log",
"sha256": "037e5c7ca2c77758a52fb8532836210a179060022277321f9269c5e127758678"
},
"integration-final-lint.log": {
"path": "/tmp/stock-bot-wave37.v0zgbc/integration-final-lint.log",
"sha256": "a732e46ee09271886b7567d0ca1cfcea6e2fd6b9e4f150ffe3a5fdc0eb82eb85"
},
"root-test-types.log": {
"path": "/tmp/stock-bot-wave37.v0zgbc/root-test-types.log",
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"agent-ui-reviewfix-tests.log": {
"path": "/tmp/stock-bot-wave37.v0zgbc/agent-ui-reviewfix-tests.log",
"sha256": "5adaef7869575738b46a6d4cd2588d104c3ed9128aac07ee5c16f7b7cb081aba"
}
}
}
}

View file

@ -63,3 +63,10 @@ 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.
## Accepted completion — 2026-10-24
Operator-provisioned hashed research credentials, scoped write grants, explicit AI authorship, SQL-budgeted admissions/retries/validation phases and bounded attempts/deadlines are implemented. Shared historical reads remain permitted; paper/live and credential administration reject research principals. Browser provisioning/usage/revocation, receipt recovery and stale response fencing are verified.
Independent review and final repository/native/PostgreSQL/browser gates pass. Exact results and source identities: manifest `thirty_seventh_wave_validation` and the [handoff](../../ROADMAP.md#thirty-seventh-wave-handoff--2026-10-24). No real account migration or paper/live activation occurred.

View file

@ -139,3 +139,10 @@ The stored EOD component is independently reviewed and `partial_validated_uncomm
Final gates: fullcheck1126 integration/150 Rust (+93 tooling/43 utility/44 calculation); PostgreSQL242/2196; Chromium16/612; strict affected/new-test types and all11-file lint/format/hash/DAG/diff checks. Four preexisting Rust cases remain ignored. Both disposable containers removed. Exact evidence: `manifest.json` → `thirty_sixth_wave_validation`, [roadmap handoff](../../ROADMAP.md#thirty-sixth-wave-handoff--2026-10-24).
The before-admission disposition above replaces deferred preparation rather than claiming to implement it. Full R05 stays `in_progress` for wider cutover/default policy; S06 remains blocked. Daily/QuestDB/v1 adapters are optional, not mandatory work to postpone owner decisions. No performance or AI/paper/live activation. New changes await the next authorized commit.
## Accepted completion — 2026-10-24
Canonical single-asset research is now the default. New legacy admission and worker commands refuse with explicit diagnostics; old results remain readable. Full stored/export preparation precedes immutable admission. Unsupported multi-asset policy remains a capability gate, not an assertion that it was implemented.
Independent review and final repository/native/PostgreSQL/browser gates pass. Exact results and source identities: manifest `thirty_seventh_wave_validation` and the [handoff](../../ROADMAP.md#thirty-seventh-wave-handoff--2026-10-24). No real account migration or paper/live activation occurred.

View file

@ -59,3 +59,10 @@ 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.
## Accepted completion — 2026-10-24
Production import reachability and composition no longer select competing TypeScript or old native simulators. Prototype strategies/engines, calculation utilities, historic result readers and recovery fixtures remain. Only the unsupported native callback stub was removed. Canonical durable failure/lease/cancel/SSE/process recovery proofs replace retired production execution tests.
Independent review and final repository/native/PostgreSQL/browser gates pass. Exact results and source identities: manifest `thirty_seventh_wave_validation` and the [handoff](../../ROADMAP.md#thirty-seventh-wave-handoff--2026-10-24). No real account migration or paper/live activation occurred.

View file

@ -4,6 +4,15 @@ import type { Hono, MiddlewareHandler } from 'hono';
type Role = 'read' | 'admin' | 'service';
const verifiedPrincipals = new WeakMap<Request, 'operator' | 'service'>();
const credentialRequests = new WeakSet<Request>();
const researchPrincipals = new WeakMap<Request, `agent:${string}`>();
const researchBearer = (request: Request) =>
/^Bearer sb-research\./i.test(request.headers.get('authorization') ?? '');
/** Research routes opt into this accessor; privileged service/operator accessors never impersonate agents. */
export function getResearchHttpPrincipal(
request: Request
): 'operator' | 'service' | `agent:${string}` | undefined {
return researchPrincipals.get(request) ?? getCredentialHttpPrincipal(request);
}
/** Server-owned identity established only after successful HTTP authorization. */
export function getVerifiedHttpPrincipal(request: Request): 'operator' | 'service' | undefined {
@ -22,6 +31,10 @@ export interface HttpSecurityOptions {
hostname?: string;
origins?: string[];
browserSessions?: boolean;
/** Explicit web API HTTP capability; never used by synchronous authorize or WebSocket upgrades. */
resolveResearchCredential?: (
request: Request
) => Promise<{ principal: `agent:${string}` } | Response | undefined>;
}
const cookieName = 'stock_bot_session';
const sessionSeconds = 3600;
@ -153,7 +166,14 @@ export function createHttpSecurity(options: HttpSecurityOptions = httpSecurityOp
return { role, cookie: true };
}
function authorize(request: Request, admin = false): Response | undefined {
researchPrincipals.delete(request);
verifiedPrincipals.delete(request);
if (researchBearer(request)) {
return Response.json(
{ error: 'Research credentials are unavailable on this interface' },
{ status: 403, headers: { 'Cache-Control': 'no-store' } }
);
}
credentialRequests.delete(request);
const identity = authenticate(request);
if (!identity) {
@ -193,6 +213,28 @@ export function createHttpSecurity(options: HttpSecurityOptions = httpSecurityOp
await next();
return undefined;
}
if (researchBearer(context.req.raw)) {
context.header('Cache-Control', 'no-store');
if (disabled || !options.resolveResearchCredential || context.req.header('upgrade')) {
return context.json(
{ error: 'Research credentials are unavailable on this interface' },
403
);
}
if (context.req.header('origin') && !originAllowed(context.req.raw)) {
return context.json({ error: 'Untrusted request origin' }, 403);
}
const resolved = await options.resolveResearchCredential(context.req.raw);
if (resolved instanceof Response) {
return resolved;
}
if (!resolved) {
return context.json({ error: 'Invalid or disabled research credential' }, 401);
}
researchPrincipals.set(context.req.raw, resolved.principal);
await next();
return undefined;
}
const admin =
!['GET', 'HEAD'].includes(context.req.method) ||
/^\/api\/(queue|operations|handlers)(\/|$)/.test(path);
@ -243,6 +285,12 @@ export function createHttpSecurity(options: HttpSecurityOptions = httpSecurityOp
if (token.length > 4096) {
return context.json({ error: 'Invalid access token' }, 401);
}
if (token.startsWith('sb-research.')) {
return context.json(
{ error: 'Research credentials cannot establish browser sessions' },
403
);
}
const role = disabled ? 'admin' : roleForToken(token);
if (!role || role === 'service') {
return context.json({ error: 'Invalid access token' }, 401);
@ -266,7 +314,13 @@ export function createHttpSecurity(options: HttpSecurityOptions = httpSecurityOp
return context.json({ authenticated: false });
});
}
return { mount, authorize, hostname, allowedOrigins };
return {
mount,
authorize,
hostname,
allowedOrigins,
researchEnabled: !disabled && !!options.resolveResearchCredential,
};
}
export type HttpSecurity = ReturnType<typeof createHttpSecurity>;

View file

@ -8,6 +8,7 @@ export {
authenticatedServiceFetch,
getVerifiedHttpPrincipal,
getCredentialHttpPrincipal,
getResearchHttpPrincipal,
} from './http/security';
export type { HttpSecurity, HttpSecurityOptions } from './http/security';
export { calculatePoolSize, getServicePoolSize, getHandlerPoolSize } from './pool-size-calculator';

View file

@ -160,3 +160,4 @@ export type {
} from './historical-data';
export type * from './research';
export { isResearchActor, isResearchAgent } from './research';

View file

@ -1,5 +1,16 @@
/** Research narrative and citations. Referencing a measurement never validates prose. */
export type ResearchActor = 'operator' | 'service';
export type ResearchActor = 'operator' | 'service' | `agent:${string}`;
export function isResearchActor(value: unknown): value is ResearchActor {
return (
value === 'operator' ||
value === 'service' ||
(typeof value === 'string' &&
/^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value))
);
}
export function isResearchAgent(value: unknown): value is `agent:${string}` {
return isResearchActor(value) && value.startsWith('agent:');
}
export type ResearchContentOrigin = 'human' | 'ai' | 'unknown';
export type ResearchMetricsVersion = 'canonical-analytics/v1' | 'legacy-display/v1';

View file

@ -1,3 +1,4 @@
import type { ResearchActor } from './research';
import type { StrategyParameterValue, StrategyVersionPackage } from './strategy-version';
export type StrategyPackageMetadata = Omit<
@ -11,8 +12,8 @@ export interface StrategyRecord {
id: string;
name: string;
description: string;
ownerPrincipal: 'operator' | 'service';
updatedBy: 'operator' | 'service';
ownerPrincipal: ResearchActor;
updatedBy: ResearchActor;
archived: boolean;
createdAt: string;
updatedAt: string;
@ -22,7 +23,7 @@ export interface StrategyVersionSummary {
strategyId: string;
ordinal: number;
parentVersionId: string | null;
createdBy: 'operator' | 'service';
createdBy: ResearchActor;
origin: 'candidate' | 'builtin';
createdAt: string;
package: StrategyPackageMetadata;

View file

@ -10,13 +10,16 @@ const files = [...new Bun.Glob('**/*.ts').scanSync({ cwd: root })].map(file => j
const imports = new Map(files.map(file => [file, runtimeImports(file)]));
function localFile(from: string, specifier: string): string | undefined {
if (!specifier.startsWith('.')) return undefined;
if (!specifier.startsWith('.')) {
return undefined;
}
const path = resolve(dirname(from), specifier);
const target = [path, `${path}.ts`, join(path, 'index.ts')].find(
file => existsSync(file) && imports.has(file)
);
if (!target)
if (!target) {
throw new Error(`Unresolved local runtime import: ${relative(root, from)} -> ${specifier}`);
}
return target;
}
const graph = new Map(
@ -29,9 +32,13 @@ const graph = new Map(
);
function reachable(file: string, seen = new Set<string>()): Set<string> {
if (seen.has(file)) return seen;
if (seen.has(file)) {
return seen;
}
seen.add(file);
for (const next of graph.get(file) ?? []) reachable(next, seen);
for (const next of graph.get(file) ?? []) {
reachable(next, seen);
}
return seen;
}
@ -39,15 +46,22 @@ describe('orchestrator architecture boundaries', () => {
it('local runtime dependencies are acyclic', () => {
const done = new Set<string>();
function visit(file: string, stack: string[]) {
if (stack.includes(file))
if (stack.includes(file)) {
throw new Error(
`Runtime dependency cycle: ${[...stack, file].map(file => relative(root, file)).join(' -> ')}`
);
if (done.has(file)) return;
for (const next of graph.get(file) ?? []) visit(next, [...stack, file]);
}
if (done.has(file)) {
return;
}
for (const next of graph.get(file) ?? []) {
visit(next, [...stack, file]);
}
done.add(file);
}
for (const file of files) visit(file, []);
for (const file of files) {
visit(file, []);
}
});
it('contracts and native worker protocol cannot load services, storage or server adapters', () => {
@ -66,9 +80,19 @@ describe('orchestrator architecture boundaries', () => {
path === 'backtest/canonical-result.ts'
).toBe(true);
for (const specifier of imports.get(file) ?? []) {
expect(specifier.startsWith('.') || ['zod', '@stock-bot/types', '@stock-bot/stock-config/backtest', '@stock-bot/stock-config/strategy', '@stock-bot/stock-config/canonical-replay', '@stock-bot/stock-config/canonical-research', '@stock-bot/calculations/analytics', '@stock-bot/calculations/returns'].includes(specifier)).toBe(
true
);
expect(
specifier.startsWith('.') ||
[
'zod',
'@stock-bot/types',
'@stock-bot/stock-config/backtest',
'@stock-bot/stock-config/strategy',
'@stock-bot/stock-config/canonical-replay',
'@stock-bot/stock-config/canonical-research',
'@stock-bot/calculations/analytics',
'@stock-bot/calculations/returns',
].includes(specifier)
).toBe(true);
}
}
}
@ -76,7 +100,11 @@ describe('orchestrator architecture boundaries', () => {
it('the shared backtest contract loads no configuration manager, services or application runtime', async () => {
const entry = resolve(root, '../../config/src/contracts/backtest.ts');
expect(runtimeImports(entry).sort()).toEqual(['./canonical-research', '@stock-bot/types', 'zod']);
expect(runtimeImports(entry).sort()).toEqual([
'./canonical-research',
'@stock-bot/types',
'zod',
]);
const bundle = await Bun.build({ entrypoints: [entry], target: 'browser' });
expect(bundle.success).toBe(true);
const code = await bundle.outputs[0]?.text();
@ -88,26 +116,50 @@ describe('orchestrator architecture boundaries', () => {
it('shared strategy catalog contracts cannot import strategy execution or application services', async () => {
const directory = resolve(root, '../../config/src/contracts');
for (const name of ['strategy.ts', 'builtin-strategy.ts', 'strategy-names.ts', 'canonical-research.ts', 'canonical-replay.ts', 'research.ts']) {
for (const name of [
'strategy.ts',
'builtin-strategy.ts',
'strategy-names.ts',
'canonical-research.ts',
'canonical-replay.ts',
'research.ts',
]) {
for (const specifier of runtimeImports(join(directory, name))) {
expect(['zod', '@stock-bot/types', './builtin-strategy', './strategy-names', './strategy', './canonical-replay'].includes(specifier)).toBe(true);
expect(
[
'zod',
'@stock-bot/types',
'./builtin-strategy',
'./strategy-names',
'./strategy',
'./canonical-replay',
].includes(specifier)
).toBe(true);
}
}
const bundle = await Bun.build({
entrypoints: [join(directory, 'strategy.ts')], target: 'browser',
plugins: [{
name: 'current-contract-types',
setup(builder) {
builder.onResolve({ filter: /^@stock-bot\/types$/ }, () => ({
path: fileURLToPath(new URL('../../libs/core/types/src/index.ts', import.meta.url)),
}));
entrypoints: [join(directory, 'strategy.ts')],
target: 'browser',
plugins: [
{
name: 'current-contract-types',
setup(builder) {
builder.onResolve({ filter: /^@stock-bot\/types$/ }, () => ({
path: fileURLToPath(new URL('../../libs/core/types/src/index.ts', import.meta.url)),
}));
},
},
}],
],
});
expect(bundle.success).toBe(true);
const code = await bundle.outputs[0]?.text();
expect(code).toBeDefined();
for (const forbidden of ['config-instance', 'PostgresClient', 'engine.node', 'createBuiltinStrategy']) {
for (const forbidden of [
'config-instance',
'PostgresClient',
'engine.node',
'createBuiltinStrategy',
]) {
expect(code).not.toContain(forbidden);
}
});
@ -162,11 +214,15 @@ describe('orchestrator architecture boundaries', () => {
expect(source).not.toMatch(/\b(OrchestratorServices|IServiceContainer)\b/);
const tree = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
function visit(node: ts.Node) {
if (ts.isPropertyAccessExpression(node)) expect(node.name.text).not.toBe('custom');
if (ts.isPropertyAccessExpression(node)) {
expect(node.name.text).not.toBe('custom');
}
if (ts.isElementAccessExpression(node) && ts.isStringLiteral(node.argumentExpression)) {
expect(node.argumentExpression.text).not.toBe('custom');
}
if (ts.isNewExpression(node)) expect(node.expression.getText(tree)).not.toBe('StorageService');
if (ts.isNewExpression(node)) {
expect(node.expression.getText(tree)).not.toBe('StorageService');
}
ts.forEachChild(node, visit);
}
visit(tree);
@ -178,7 +234,9 @@ describe('orchestrator architecture boundaries', () => {
const owner = relative(root, file);
for (const dependency of dependencies) {
const target = relative(root, dependency);
if (!/^strategies\/(builtin|experimental)\//.test(target)) continue;
if (!/^strategies\/(builtin|experimental)\//.test(target)) {
continue;
}
expect(
owner === 'strategies/builtin-strategies.ts' ||
/^strategies\/(builtin|experimental)\//.test(owner)
@ -196,7 +254,9 @@ describe('orchestrator architecture boundaries', () => {
'strategies/RustStrategy.ts',
'strategies/StrategyExecutor.ts',
];
for (const file of retired) expect(existsSync(join(root, file))).toBe(false);
for (const file of retired) {
expect(existsSync(join(root, file))).toBe(false);
}
for (const file of files) {
expect(relative(root, file)).not.toMatch(
/^strategies\/(examples|rust|position|risk|signals|indicators)\//
@ -212,7 +272,6 @@ describe('orchestrator architecture boundaries', () => {
);
expect(nativeEntrypoints.map(file => relative(root, file)).sort()).toEqual([
'backtest/native-replay.ts',
'backtest/native-worker.ts',
]);
for (const file of files) {
const path = relative(root, file);
@ -244,7 +303,7 @@ describe('orchestrator architecture boundaries', () => {
!binding.isTypeOnly &&
(binding.propertyName ?? binding.name).text === 'BacktestEngine'
) {
expect(path).toBe('backtest/native-worker.ts');
throw new Error(`Retired native simulator imported by ${path}`);
}
if (
!binding.isTypeOnly &&
@ -271,7 +330,9 @@ describe('orchestrator architecture boundaries', () => {
? callee.argumentExpression.text
: undefined;
expect(method).not.toBe('addTypescriptStrategy');
if (path.startsWith('strategies/')) expect(method).not.toBe('submitOrder');
if (path.startsWith('strategies/')) {
expect(method).not.toBe('submitOrder');
}
}
ts.forEachChild(node, visit);
}
@ -279,6 +340,38 @@ describe('orchestrator architecture boundaries', () => {
}
});
it('production research and paper entrypoints cannot reach prototype financial execution', () => {
const forbidden = [
'backtest/BacktestEngine.ts',
'backtest/BacktestMarket.ts',
'core/ModeManager.ts',
'execution/SimulationExecution.ts',
'execution/model.ts',
'services/ExecutionService.ts',
'paper/PaperTradingManager.ts',
'api/rest/orders.ts',
'api/rest/positions.ts',
'api/websocket/index.ts',
];
for (const entry of [
'index.ts',
'container.ts',
'simple-container.ts',
'backtest/native-worker.ts',
]) {
const production = [...reachable(join(root, entry))].map(file => relative(root, file));
for (const prototype of forbidden) {
expect(production).not.toContain(prototype);
}
}
expect(readFileSync(join(root, 'backtest/native-worker-protocol.ts'), 'utf8')).not.toContain(
"z.literal('run')"
);
expect(readFileSync(join(root, 'backtest/BacktestRunner.ts'), 'utf8')).not.toContain(
'engine.runBacktest('
);
});
it('backtest playback cannot depend on trading, data, reporting or service adapters', () => {
const dependencies = [...reachable(join(root, 'backtest/BacktestPlayback.ts'))]
.map(file => relative(root, file))

View file

@ -113,9 +113,8 @@ describe('generated native bindings', () => {
slippage: 0,
dataFrequency: '1d',
});
expect(() =>
engine.addTypescriptStrategy('unsupported', 'unsupported', {}, () => '{}')
).toThrow('TypeScript strategy callbacks are not supported');
expect(engine).not.toHaveProperty('addTypescriptStrategy');
expect(engine).not.toHaveProperty('addTypescriptStrategy');
expect(() =>
engine.addNativeStrategy('sma_crossover', 'invalid', 'invalid', {
fastPeriod: 0,

View file

@ -10,15 +10,13 @@ import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { Queue } from '@stock-bot/queue';
import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research';
import type { HistoricalDatasetV2 } from '@stock-bot/types';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import type { NativeBacktestResult } from '../../apps/stock/orchestrator/src/backtest/native-result';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import {
loadDataset,
type DatasetResolver,
} from '../../apps/stock/orchestrator/src/data/historical-dataset';
import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
import type { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
import type { BacktestConfig } from '../../apps/stock/orchestrator/src/types';
import {
@ -30,6 +28,7 @@ import {
handleWebSocketConnection,
} from '../../apps/stock/web-api/src/routes/websocket.routes';
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
import {
getWebSocketHandler,
@ -139,23 +138,26 @@ export async function retainDataset(pool: Pool, overrides: Partial<BacktestConfi
return dataset;
}
/** Fixed UI lifecycle data, NOT a financial simulator or correctness oracle. */
/** Controlled lifecycle around the real canonical engine; no fixture accounting. */
class FixtureEngine extends EventEmitter {
completion = gate();
cancellation = gate();
stopped = gate();
mode: 'trades' | 'empty' | 'fail' = 'trades';
private cancelled = false;
async runBacktest(
config: BacktestConfig,
resolver?: DatasetResolver
): Promise<NativeBacktestResult> {
if (!resolver) {
throw new Error('Fixture must exercise durable dataset resolution');
}
const dataset = await resolver(() => loadDataset(storage, config));
private readonly engine = new RustBacktestAdapter({ logger, storage }, { timeoutMs: 15000 });
async runBacktest(): Promise<never> {
throw new Error('Legacy execution is retired');
}
async runCanonical(
request: CanonicalRunRequest,
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
) {
this.cancelled = false;
this.emit('progress', { progress: 25, currentDate: config.startDate });
this.emit('progress', {
progress: 25,
currentDate: new Date(request.policy.matching.risk.ledger.riskSession.startsAt).toISOString(),
});
await this.completion.promise;
if (this.cancelled) {
throw new BacktestCancelledError();
@ -163,53 +165,14 @@ class FixtureEngine extends EventEmitter {
if (this.mode === 'fail') {
throw new Error('Injected fixture worker failure');
}
return {
backtestId: config.backtestId!,
status: 'completed',
completedAt: '2024-03-15T00:00:00.000Z',
config: {
name: config.name!,
symbols: config.symbols,
startDate: config.startDate,
endDate: config.endDate,
initialCapital: config.initialCapital,
},
metrics: {
totalReturn: 0,
sharpeRatio: 0,
maxDrawdown: 0,
winRate: 0,
totalTrades: 0,
profitFactor: null,
avgWin: 0,
avgLoss: 0,
},
equity: [{ date: config.startDate, value: config.initialCapital }],
trades:
this.mode === 'empty'
? []
: [
{
id: 'fixture-fill',
symbol: config.symbols[0]!,
timestamp: config.startDate,
side: 'buy',
price: 100,
quantity: 3,
commission: 0,
positionAfter: 3,
},
],
positions: [],
analytics: { exposureTime: 0 },
executionTime: 0,
ohlcData: Object.fromEntries(
config.symbols.map(symbol => [symbol, dataset.bars.filter(bar => bar.symbol === symbol)])
),
};
// Empty outcomes use an admitted strategy with insufficient warmup; never edit the result.
return this.engine.runCanonical(request, resolveDataset);
}
async stopBacktest() {
this.cancelled = true;
if (this.engine.getStatus().isRunning) {
await this.engine.stopBacktest();
}
this.stopped.resolve();
await this.cancellation.promise;
this.completion.resolve();
@ -227,6 +190,7 @@ class FixtureEngine extends EventEmitter {
async shutdown() {
this.cancellation.resolve();
this.completion.resolve();
await this.engine.shutdown();
}
}
@ -313,6 +277,7 @@ export async function fixture(browser: Browser, native = false) {
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
'28-research-agents.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
@ -435,6 +400,7 @@ export async function fixture(browser: Browser, native = false) {
},
} as unknown as NonNullable<IServiceContainer['mongodb']>;
const container = { postgres, mongodb, logger } as IServiceContainer;
const researchAgents = new ResearchAgentsService(container);
const token = randomUUID() + randomUUID();
const security = createHttpSecurity({
adminToken: token,
@ -442,6 +408,7 @@ export async function fixture(browser: Browser, native = false) {
browserSessions: true,
environment: 'test',
origins: [],
resolveResearchCredential: request => researchAgents.authenticate(request),
});
const routes = createRoutes(container, security);
const wsRoute = createWebSocketRoute(container, security);
@ -476,6 +443,8 @@ export async function fixture(browser: Browser, native = false) {
!pathname.startsWith('/api/v2/strategies') &&
!pathname.startsWith('/api/v2/strategy-versions') &&
!pathname.startsWith('/api/v2/research-projects') &&
!pathname.startsWith('/api/v2/research-agents') &&
!pathname.startsWith('/api/v2/research-agent/') &&
!pathname.startsWith('/api/v2/experiments') &&
!pathname.startsWith('/api/v2/hypotheses/') &&
!pathname.startsWith('/api/v2/analysis-artifacts/') &&
@ -657,16 +626,6 @@ export async function fixture(browser: Browser, 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.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();
await page.waitForURL(run ? /\/backtests\/[^/]+\/run\/[^/]+$/ : /\/backtests\/[^/]+$/);
}
export async function submitInBrowser(page: Page) {
await page.getByRole('button', { name: 'New Run', exact: true }).click();
const response = page.waitForResponse(

View file

@ -25,6 +25,7 @@ import type {
ExperimentRetryResult,
ExperimentTrialRetry,
} from '@stock-bot/stock-config/experiments';
import type { ResearchAgentRecord } from '@stock-bot/stock-config/research-agents';
import type {
WalkForwardActionResult,
WalkForwardDetail,
@ -43,7 +44,6 @@ import { chronologicalDataset } from '../fixtures/chronological-validation';
import { walkForwardDataset } from '../fixtures/walk-forward';
import {
fixture as createFixture,
createInBrowser,
gate,
retainDataset,
submitInBrowser,
@ -63,6 +63,174 @@ afterAll(async () => {
});
const fixture = (native = false) => createFixture(browser, native);
test('operator_provisions_bounded_agent_views_usage_and_revokes_without_corrupting_accepted_work_browser', async () => {
const f = await fixture(true);
try {
await f.login();
const { id: backtestId } = await createCanonicalInBrowser(f, 'Agent baseline');
const { project } = await f.request('/api/v2/research-projects', 'POST', {
title: 'Agent research',
});
await f.page.goto(`${f.origin}/research/agents?projectId=${project.id}`);
await visible(f.page, 'No research agents configured.');
await f.page.getByLabel('Agent name', { exact: true }).fill('Bounded browser researcher');
await f.page.getByLabel('Allowed backtest IDs', { exact: true }).fill(backtestId);
await f.page.getByLabel('Maximum active trials', { exact: true }).fill('1');
await f.page.getByLabel('Maximum trials per experiment', { exact: true }).fill('2');
await f.page.getByLabel('Maximum attempt time (ms)', { exact: true }).fill('30000');
const creating = f.page.waitForResponse(
response =>
response.request().method() === 'POST' && response.url().endsWith('/api/v2/research-agents')
);
await f.page.getByRole('button', { name: 'Create credential', exact: true }).click();
const response = await creating;
expect(response.status()).toBe(201);
const created = (await response.json()) as { agent: ResearchAgentRecord; token: string };
expect(await f.page.getByLabel('New research token', { exact: true }).inputValue()).toBe(
created.token
);
expect(created.agent.allowedProjectIds).toEqual([project.id]);
expect(created.agent.grants.map(grant => grant.backtestId)).toEqual([backtestId]);
const agentRequest = (path: string, method = 'GET', body?: unknown, key?: string) =>
fetch(`${f.origin}${path}`, {
method,
headers: {
Authorization: `Bearer ${created.token}`,
'Content-Type': 'application/json',
...(key ? { 'Idempotency-Key': key } : {}),
},
body: body === undefined ? undefined : JSON.stringify(body),
});
const hypothesis = await agentRequest(
`/api/v2/research-projects/${project.id}/hypotheses`,
'POST',
{
title: 'Agent proposal awaiting validation',
proposition: 'A controlled hypothesis, not proof of profitability.',
contentOrigin: 'ai',
}
);
expect(hypothesis.status).toBe(201);
expect(JSON.stringify(await hypothesis.json())).toContain(created.agent.id);
const input = {
backtestId,
name: 'Bounded existing strategy experiment',
grid: { fastPeriod: [2] },
};
const previewResponse = await agentRequest('/api/v2/experiments/preview', 'POST', input);
expect(previewResponse.status).toBe(200);
const { preview } = (await previewResponse.json()) as { preview: ExperimentPreview };
const body = { ...input, previewHash: preview.previewHash };
const accepted = await agentRequest('/api/v2/experiments', 'POST', body, randomUUID());
expect(accepted.status).toBe(202);
const { experiment } = (await accepted.json()) as { experiment: ExperimentDetail };
expect((await agentRequest('/api/v2/experiments', 'POST', body, randomUUID())).status).toBe(
429
);
expect(
(await agentRequest(`/api/v2/backtests/${backtestId}`, 'PUT', { initialCapital: 999999 }))
.status
).toBe(403);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
const row = (
await f.pool.query('SELECT * FROM research_agents WHERE id=$1', [created.agent.id])
).rows[0];
expect(JSON.stringify(row)).not.toContain(created.token);
await f.page.getByRole('button', { name: 'I have saved the credential', exact: true }).click();
await f.page
.getByRole('button', { name: 'Check budget for Bounded browser researcher', exact: true })
.click();
await visible(f.page, 'Active trials: 1; available slots: 0');
await f.page
.getByRole('button', { name: 'Disable Bounded browser researcher', exact: true })
.click();
await visible(f.page, /Disabled · Revision 2/);
expect((await agentRequest('/api/v2/research-agent/budget')).status).toBe(401);
// Revocation denies new access. Previously accepted bounded work retains its frozen owner/budget.
f.dispatcher.start();
const trial = experiment.trials[0];
if (!trial?.runId) {
throw new Error('Expected admitted agent trial');
}
await until(
async () =>
(await f.pool.query('SELECT status FROM runs WHERE id=$1', [trial.runId])).rows[0]
?.status === 'completed',
'accepted agent trial completes on canonical Rust'
);
const result = (await f.request(`/api/v2/runs/${trial.runId}/results`)) as CanonicalRunResult;
expect(result.financialEngine).toBe('rust');
expect(result.request).toMatchObject({
datasetHash: preview.request.datasetHash,
strategy: { versionId: preview.request.strategy.versionId },
});
await f.page
.getByRole('button', { name: 'Check budget for Bounded browser researcher', exact: true })
.click();
await visible(f.page, 'Active trials: 0; available slots: 1');
await f.page.reload();
await visible(f.page, /Disabled · Revision 2/);
expect(await f.page.getByLabel('New research token', { exact: true }).count()).toBe(0);
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
/** Lifecycle tests create via the real catalog UI; policy setup is seeded through
* the same public API. The full setup UI is exercised by the research workflow below. */
async function createCanonicalInBrowser(
f: Awaited<ReturnType<typeof fixture>>,
name: string,
run = false
) {
const { dataset } = canonicalSmaFixture();
await retainResearchDataset(f.pool, dataset);
const version = (await f.seedCatalog()).find(
item => item.package.program.strategyId === 'sma_crossover'
)!;
if (version.reviewStatus !== 'approved') {
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
decision: 'approve',
reason: 'Reviewed canonical lifecycle fixture',
});
}
await f.page.getByRole('button', { name: 'New Backtest', exact: true }).click();
await f.page.getByPlaceholder('My Strategy Backtest').fill(name);
await f.page.getByLabel('Strategy family', { exact: true }).selectOption(version.strategyId);
await f.page.getByLabel('Immutable strategy version', { exact: true }).selectOption(version.id);
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
await visible(f.page, /Parameters validated/);
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 id = f.page.url().split('/').at(-1)!;
await f.request(`/api/v2/backtests/${id}`, 'PUT', {
strategy: 'catalog',
strategyVersionId: version.id,
strategyParameters: { fastPeriod: 2, slowPeriod: f.controlled.mode === 'empty' ? 100 : 3 },
symbols: dataset.manifest.executionSeries.map(series => series.instrumentId),
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
initialCapital: 10000,
config: {
datasetHash: dataset.manifest.hash,
dataFrequency: '1m',
canonical: canonicalSettings,
},
});
await f.page.reload();
await visible(f.page, /Canonical execution is available/);
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
if (run) {
await submitInBrowser(f.page);
}
return { id, dataset, version };
}
/** Uses real retained native measurements, then reopens the exact source from immutable history. */
async function saveSourceFindingInBrowser(
f: Awaited<ReturnType<typeof fixture>>,
@ -1438,14 +1606,16 @@ test('browser_saved_run_lifecycle', async () => {
try {
await f.login();
expect(await f.page.locator('tbody tr').count()).toBe(0);
await createInBrowser(f.page, 'Saved browser lifecycle');
const { dataset } = await createCanonicalInBrowser(f, 'Saved browser lifecycle');
const definition = (await f.pool.query('SELECT * FROM backtests')).rows[0];
expect(definition.name).toBe('Saved browser lifecycle');
expect(Number(definition.initial_capital)).toBe(100000);
expect(Number(definition.initial_capital)).toBe(10000);
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: 'Settings', exact: true }).click();
expect(await f.page.locator('input[type="date"]').first().inputValue()).toBe('2024-01-01');
expect(
await f.page.locator('dl[aria-label="Canonical dataset bounds"]').textContent()
).toContain(new Date(dataset.manifest.bounds.tradeStart).toISOString());
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
const response = await submitInBrowser(f.page);
expect(response.status()).toBe(202);
@ -1453,7 +1623,7 @@ test('browser_saved_run_lifecycle', async () => {
expect(response.headers().location).toBe(`/api/v2/runs/${run.id}`);
expect(response.request().headers()['idempotency-key']).toBeTruthy();
await visible(f.page, 'Pending');
await visible(f.page, /Source request \(auto\) — unpinned/);
await visible(f.page, /Pinned dataset hash/);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(1);
expect(await f.page.getByRole('button', { name: /pause|resume/i }).count()).toBe(0);
@ -1479,26 +1649,26 @@ test('browser_saved_run_lifecycle', async () => {
).toBe(25);
f.controlled.completion.resolve();
await visible(f.page, 'Completed');
await visible(f.page, 'Research only · Unverified economics');
await f.page
.getByText('Configuration, provenance and simulation limitations', { exact: true })
.click();
await visible(f.page, 'Canonical research result');
await f.page.getByText('Immutable configuration and reporting policy', { exact: true }).click();
const result = await f.request(`/api/v2/runs/${run.id}/results`);
expect(result.config.dataset.hash).toMatch(/^[a-f0-9]{64}$/);
await visible(f.page, result.config.dataset.hash);
expect(await f.page.locator('pre').textContent()).toContain('"initialCapital": 100000');
expect(result.request.datasetHash).toMatch(/^[a-f0-9]{64}$/);
await visible(f.page, result.request.datasetHash);
expect(await f.page.locator('pre').textContent()).toContain(
'"initialCapital": "10000.00000000"'
);
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'BUY');
await visible(f.page, '$100.00');
await visible(f.page, 'buy');
await visible(f.page, '5.00000000');
const savedUrl = f.page.url();
await f.page.reload();
await visible(f.page, 'Completed');
expect(f.page.url()).toBe(savedUrl);
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'BUY');
await visible(f.page, 'buy');
await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click();
await f.page.getByText('Saved browser lifecycle', { exact: true }).click();
await f.page.getByText('#1', { exact: true }).click();
await f.page.getByText(/^#1\s*Canonical$/).click();
await visible(f.page, 'Completed');
expect(f.page.url()).toBe(savedUrl);
expect(
@ -1515,7 +1685,7 @@ test('browser_cancel_failure', async () => {
const f = await fixture();
try {
await f.login();
await createInBrowser(f.page, 'Cancel browser run', true);
await createCanonicalInBrowser(f, 'Cancel browser run', true);
const runId = f.page.url().split('/').at(-1)!;
f.dispatcher.start();
await visible(f.page, 'Running');
@ -1542,7 +1712,7 @@ test('browser_cancel_failure', async () => {
).toBe(0);
f.controlled.mode = 'fail';
await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click();
await createInBrowser(f.page, 'Failed browser run', true);
await createCanonicalInBrowser(f, 'Failed browser run', true);
await visible(f.page, 'Run failed: Injected fixture worker failure');
const failedId = f.page.url().split('/').at(-1)!;
expect(
@ -1553,24 +1723,32 @@ test('browser_cancel_failure', async () => {
).toBe(0);
f.controlled.mode = 'empty';
await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click();
await createInBrowser(f.page, 'Empty completed browser run', true);
await createCanonicalInBrowser(f, 'Empty completed browser run', true);
await visible(f.page, 'Completed');
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'No trades executed in this backtest.');
await visible(f.page, 'No fills were executed in this completed run.');
const emptyId = f.page.url().split('/').at(-1)!;
expect((await f.request(`/api/v2/runs/${emptyId}/results`)).trades).toEqual([]);
expect((await f.request(`/api/v2/runs/${emptyId}/results`)).financial.projection.fills).toEqual(
[]
);
// A saved completed row whose result is unavailable must not appear as zero trades.
const missingResultId = randomUUID();
const definitionId = f.page.url().split('/')[4]!;
const missingDefinitionId = randomUUID();
await f.pool.query(
"INSERT INTO runs(id,backtest_id,run_number,status) VALUES ($1,$2,2,'completed')",
[missingResultId, definitionId]
`INSERT INTO backtests(id,name,strategy,symbols,start_date,end_date,initial_capital) VALUES ($1,'Historical missing result','moving-average','["AAPL.US"]','2024-01-01','2024-02-01',10000)`,
[missingDefinitionId]
);
await f.page.goto(f.page.url().replace(emptyId, missingResultId));
await f.pool.query(
"INSERT INTO runs(id,backtest_id,run_number,status) VALUES ($1,$2,1,'completed')",
[missingResultId, missingDefinitionId]
);
await f.page.goto(`${f.origin}/backtests/${missingDefinitionId}/run/${missingResultId}`);
await visible(f.page, 'Run completed, but saved results are unavailable.');
await visible(f.page, 'Retry results');
expect(
await f.page.getByText('No trades executed in this backtest.', { exact: true }).count()
await f.page
.getByText('No fills were executed in this completed run.', { exact: true })
.count()
).toBe(0);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
@ -1589,7 +1767,7 @@ test('browser_reopen_and_switch', async () => {
f.page.on('requestfailed', settled);
try {
await f.login();
await createInBrowser(f.page, 'Selection and reconnect', true);
await createCanonicalInBrowser(f, 'Selection and reconnect', true);
const firstUrl = f.page.url();
const firstId = firstUrl.split('/').at(-1)!;
const definitionId = firstUrl.split('/')[4]!;
@ -1637,17 +1815,17 @@ test('browser_reopen_and_switch', async () => {
f.controlled.completion.resolve();
await visible(f.page, 'Completed');
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
await visible(f.page, '#1');
await visible(f.page, /^#1\s*Canonical$/);
delayed = f.delayResponse(`/api/v2/runs/${firstId}/results`);
const selectionRequest = f.page.waitForRequest(
request => new URL(request.url()).pathname === `/api/v2/runs/${firstId}/results`
);
await f.page.getByText('#1', { exact: true }).click();
await f.page.getByText(/^#1\s*Canonical$/).click();
const requested = await selectionRequest;
await delayed.captured.wait('selected run A result request');
await visible(f.page, 'Loading run data...');
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
await f.page.getByText('#2', { exact: true }).click();
await f.page.getByText(/^#2\s*Canonical$/).click();
await visible(f.page, 'Completed');
delayed.release.resolve();
await delayed.delivered.wait('delayed result response settlement');
@ -1658,9 +1836,7 @@ test('browser_reopen_and_switch', async () => {
await f.page.evaluate(
() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))
);
await f.page
.getByText('Configuration, provenance and simulation limitations', { exact: true })
.click();
await f.page.getByText('Immutable configuration and reporting policy', { exact: true }).click();
await visible(f.page, secondId);
expect(f.page.url()).toBe(secondUrl);
expect(await f.page.getByText(firstId, { exact: true }).count()).toBe(0);
@ -1685,83 +1861,135 @@ test('browser_reopen_and_switch', async () => {
}
});
test('native_smoke', async () => {
test('canonical_native_smoke', async () => {
const f = await fixture(true);
try {
await f.login();
await createInBrowser(f.page, 'Actual Rust browser smoke', true);
await createCanonicalInBrowser(f, 'Actual Rust browser smoke', true);
const runId = f.page.url().split('/').at(-1)!;
f.dispatcher.start();
await visible(f.page, 'Completed');
const result = await f.request(`/api/v2/runs/${runId}/results`);
expect(result.engine).toBe('native');
expect(result.config.dataset.barCount).toBe(70);
expect(result.config.dataset.hash).toMatch(/^[a-f0-9]{64}$/);
expect(result.trades.length).toBeGreaterThan(0);
expect(result.financialEngine).toBe('rust');
expect(result.request.strategy.origin).toBe('builtin');
expect(result.request.datasetHash).toMatch(/^[a-f0-9]{64}$/);
expect(result.financial.projection.fills.length).toBeGreaterThan(0);
expect(
(await f.pool.query('SELECT status,attempt_number FROM runs WHERE id=$1', [runId])).rows[0]
).toEqual({ status: 'completed', attempt_number: 1 });
expect(
(await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id=$1', [runId])).rowCount
).toBe(1);
await visible(f.page, 'Research only · Unverified economics');
await visible(f.page, 'Canonical research result');
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, result.trades[0].side.toUpperCase());
await visible(f.page, `$${result.trades[0].price.toFixed(2)}`);
await visible(f.page, result.financial.projection.fills[0].side);
await visible(f.page, result.financial.projection.fills[0].price);
await f.page.reload();
await visible(f.page, 'Completed');
await f.page
.getByText('Configuration, provenance and simulation limitations', { exact: true })
.click();
await visible(f.page, result.config.dataset.hash);
await f.page.getByText('Immutable configuration and reporting policy', { exact: true }).click();
await visible(f.page, result.request.datasetHash);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('browser_frozen_dataset_native_run_and_reopen', async () => {
const f = await fixture(true);
test('browser_legacy_frozen_history_reopens_without_reactivating_retired_execution', async () => {
const f = await fixture();
try {
const dataset = await retainDataset(f.pool);
const hash = dataset.manifest.hash;
await f.login();
await f.page.getByRole('button', { name: 'New Backtest', exact: true }).click();
await f.page.getByPlaceholder('My Strategy Backtest').fill('Frozen dataset browser run');
await f.page.getByLabel('Historical data input', { exact: true }).selectOption('frozen');
await f.page.getByLabel('Frozen dataset', { exact: true }).selectOption(hash);
expect(await f.page.getByLabel('Start date (UTC)', { exact: true }).inputValue()).toBe(
'2024-01-01'
const backtestId = randomUUID(),
runId = randomUUID();
const config = {
name: 'Historical frozen dataset',
strategy: 'moving-average',
symbols: ['AAPL.US'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-03-15T00:00:00.000Z',
initialCapital: 100000,
commission: 0,
slippage: 0,
dataFrequency: '1d',
parameters: {},
dataset: dataset.manifest,
};
// Explicit pre-cutover history fixture, never an alternative simulator.
await f.pool.query(
`INSERT INTO backtests(id,name,strategy,symbols,start_date,end_date,initial_capital,config)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`,
[
backtestId,
config.name,
config.strategy,
JSON.stringify(config.symbols),
config.startDate,
config.endDate,
config.initialCapital,
JSON.stringify({ datasetHash: hash, dataFrequency: '1d' }),
]
);
expect(await f.page.getByLabel('Start date (UTC)', { exact: true }).isDisabled()).toBe(true);
await f.page.getByRole('button', { name: 'Save and run', exact: true }).click();
await f.page.waitForURL(/\/backtests\/[^/]+\/run\/[^/]+$/);
const runId = f.page.url().split('/').at(-1)!;
await visible(f.page, 'Pending');
const pending = await f.request(`/api/v2/runs/${runId}`);
expect(pending.dataset).toMatchObject({
requestedHash: hash,
pinnedHash: null,
state: 'requested',
});
expect(
await f.page.getByRole('region', { name: 'Run dataset', exact: true }).textContent()
).toContain(hash);
f.dispatcher.start();
await f.pool.query(
`INSERT INTO runs(id,backtest_id,run_number,status,dataset_hash)
VALUES ($1,$2,1,'completed',$3)`,
[runId, backtestId, hash]
);
await f.pool.query(
`INSERT INTO backtest_results(run_id,completed_at,engine,configuration,metrics,equity_curve,ohlc_data,trades,positions,analytics,execution_time)
VALUES ($1,NOW(),'native',$2,$3,'[]','{}',$4,'[]','{}',1)`,
[
runId,
JSON.stringify(config),
JSON.stringify({
totalReturn: 0,
sharpeRatio: null,
maxDrawdown: 0,
winRate: 0,
totalTrades: 0,
profitFactor: null,
avgWin: 0,
avgLoss: 0,
}),
JSON.stringify([
{
kind: 'fill',
id: 'historical-fill',
symbol: 'AAPL.US',
timestamp: '2024-01-02T00:00:00.000Z',
side: 'buy',
price: 100,
quantity: 1,
commission: 0,
},
]),
]
);
await f.login();
await f.page.goto(`${f.origin}/backtests/${backtestId}/run/${runId}`);
await visible(f.page, 'Completed');
await visible(f.page, 'Research only · Unverified economics');
const result = await f.request(`/api/v2/runs/${runId}/results`);
expect(result.config.dataset.hash).toBe(hash);
expect(result.engine).toBe('native');
expect(result.trades.length).toBeGreaterThan(0);
expect((await f.pool.query('SELECT count(*) FROM backtest_datasets')).rows[0].count).toBe('1');
await visible(f.page, 'Research only · Unverified economics');
const runDataset = f.page.getByRole('region', { name: 'Run dataset', exact: true });
expect(await runDataset.textContent()).toContain('Pinned dataset hash');
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'BUY');
await f.page.reload();
await visible(f.page, 'Completed');
expect(await runDataset.textContent()).toContain(hash);
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, result.trades[0].side.toUpperCase());
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
expect(await f.page.getByRole('button', { name: 'New Run', exact: true }).isDisabled()).toBe(
true
);
await expect(
f.request(
`/api/v2/backtests/${backtestId}/runs`,
'POST',
{},
{ 'Idempotency-Key': randomUUID() }
)
).rejects.toThrow('409');
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
expect(await f.request(`/api/v2/runs/${runId}/results`)).toEqual(result);
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
@ -1775,9 +2003,16 @@ test('browser_intraday_dataset_exact_settings_and_incompatible_submission', asyn
const endDate = '2024-01-02T15:30:00.456Z';
const dataset = await retainDataset(f.pool, { startDate, endDate, dataFrequency: '1m' });
const hash = dataset.manifest.hash;
const version = (await f.seedCatalog()).find(
item => item.package.program.strategyId === 'sma_crossover'
)!;
await f.login();
await f.page.getByRole('button', { name: 'New Backtest', exact: true }).click();
await f.page.getByPlaceholder('My Strategy Backtest').fill('Exact intraday frozen settings');
await f.page.getByLabel('Strategy family', { exact: true }).selectOption(version.strategyId);
await f.page.getByLabel('Immutable strategy version', { exact: true }).selectOption(version.id);
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
await visible(f.page, /Parameters validated/);
await f.page.getByLabel('Historical data input', { exact: true }).selectOption('frozen');
await f.page.getByLabel('Frozen dataset', { exact: true }).selectOption(hash);
await f.page.getByRole('button', { name: 'Save', exact: true }).click();
@ -1790,6 +2025,8 @@ test('browser_intraday_dataset_exact_settings_and_incompatible_submission', asyn
expect(await f.page.getByLabel('End instant (UTC)', { exact: true }).inputValue()).toBe(
endDate
);
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
await visible(f.page, /Parameters validated/);
const saved = f.page.waitForResponse(
response =>
response.request().method() === 'PUT' &&
@ -1817,15 +2054,17 @@ test('browser_intraday_dataset_exact_settings_and_incompatible_submission', asyn
[backtestId]
);
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
await f.page.getByRole('button', { name: 'New Run', exact: true }).click();
const rejected = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith(`/api/v2/backtests/${backtestId}/runs`)
expect(await f.page.getByRole('button', { name: 'New Run', exact: true }).isDisabled()).toBe(
true
);
await f.page.getByRole('button', { name: 'Run current settings', exact: true }).click();
expect((await rejected).status()).toBe(400);
await visible(f.page, /Frozen dataset does not match/);
await expect(
f.request(
`/api/v2/backtests/${backtestId}/runs`,
'POST',
{},
{ 'Idempotency-Key': randomUUID() }
)
).rejects.toThrow('409');
expect((await f.pool.query('SELECT count(*) FROM runs')).rows[0].count).toBe('0');
expect((await f.pool.query('SELECT count(*) FROM backtest_dispatch')).rows[0].count).toBe('0');
expect(f.unexpectedNetwork).toEqual([]);
@ -1838,7 +2077,7 @@ test('browser_archive_retains_history_and_restore_admits_new_work', async () =>
const f = await fixture();
try {
await f.login();
await createInBrowser(f.page, 'Retained browser evidence', true);
await createCanonicalInBrowser(f, 'Retained browser evidence', true);
const savedUrl = f.page.url();
const runId = savedUrl.split('/').at(-1)!;
const definitionId = savedUrl.split('/')[4]!;
@ -1847,7 +2086,7 @@ test('browser_archive_retains_history_and_restore_admits_new_work', async () =>
await f.page.getByRole('button', { name: 'Confirm archive', exact: true }).click();
await visible(f.page, 'Restore backtest');
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
expect(await f.page.getByPlaceholder('My Strategy Backtest').isDisabled()).toBe(true);
expect(await f.page.getByLabel('Backtest name', { exact: true }).isDisabled()).toBe(true);
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
expect(await f.page.getByRole('button', { name: 'New Run', exact: true }).isDisabled()).toBe(
true
@ -1862,13 +2101,13 @@ test('browser_archive_retains_history_and_restore_admits_new_work', async () =>
f.controlled.completion.resolve();
await visible(f.page, 'Completed');
const result = await f.request(`/api/v2/runs/${runId}/results`);
expect(result.config.dataset.hash).toMatch(/^[a-f0-9]{64}$/);
expect(result.request.datasetHash).toMatch(/^[a-f0-9]{64}$/);
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'BUY');
await visible(f.page, 'buy');
await f.page.reload();
await visible(f.page, 'Restore backtest');
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'BUY');
await visible(f.page, 'buy');
expect(f.page.url()).toBe(savedUrl);
await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click();
await f.page.getByRole('checkbox', { name: 'Show archived backtests', exact: true }).waitFor();
@ -1879,14 +2118,14 @@ test('browser_archive_retains_history_and_restore_admits_new_work', async () =>
await f.page.getByRole('checkbox', { name: 'Show archived backtests', exact: true }).check();
await f.page.getByText('Retained browser evidence').click();
await visible(f.page, 'Restore backtest');
await f.page.getByText('#1', { exact: true }).click();
await f.page.getByText(/^#1\s*Canonical$/).click();
await visible(f.page, 'Completed');
expect(f.page.url()).toBe(savedUrl);
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 f.page.getByRole('button', { name: 'Settings', exact: true }).click();
expect(await f.page.getByPlaceholder('My Strategy Backtest').isEnabled()).toBe(true);
expect(await f.page.getByLabel('Backtest name', { exact: true }).isEnabled()).toBe(true);
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
const accepted = await submitInBrowser(f.page);
expect(accepted.status()).toBe(202);

View file

@ -17,16 +17,21 @@ if (
!schema ||
!/^stock_bot_safety_[a-f0-9]+$/.test(schema) ||
!runId
)
) {
throw new Error('Unsafe crash fixture target');
}
const logger = getLogger('crash-owner');
const pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` });
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
const repository = new PostgresBacktestRunRepository(postgres, 500);
repository.loadCanonicalDataset = async () => {
process.send?.({ type: 'claimed' });
return new Promise(() => {});
};
const runner = new BacktestRunner({
engine: new RustBacktestAdapter({
logger,
@ -36,9 +41,5 @@ const runner = new BacktestRunner({
repository,
logger,
heartbeatMs: 50,
prepare: async () => {
process.send?.({ type: 'claimed' });
await new Promise<void>(() => {});
},
});
await runner.runQueued(runId);

75
test/fixtures/canonical-admission.ts vendored Normal file
View file

@ -0,0 +1,75 @@
import { readFileSync } from 'node:fs';
import type { Pool } from 'pg';
import type { PostgreSQLClient } from '@stock-bot/postgres';
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
import { canonicalSettings } from './canonical-research';
import { canonicalSmaFixture } from './canonical-sma';
import { logger } from './execution';
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
/** Real approved admission on a caller-owned disposable PostgreSQL schema. */
export async function canonicalAdmissionFixture(
pool: Pool,
postgres: PostgreSQLClient,
initializeTables = true
) {
for (const name of initializeTables
? [
'06-create-backtest-tables.sql',
'07-fix-execution-time-type.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',
'19-canonical-research.sql',
'21-run-reproduction.sql',
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
]
: []) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
);
}
if (!Object.hasOwn(postgres, 'query')) {
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
}
const dataset = canonicalSmaFixture().dataset;
const api = new BacktestServiceV2({ postgres, logger });
const catalog = new StrategyCatalogService({ postgres, logger });
const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!;
const version = await catalog.seedBuiltin('Cutover retained SMA', pkg, 'seed');
await catalog.reviewVersion(
version.id,
{ decision: 'approve', reason: 'Cutover native fixture' },
'operator'
);
await retainResearchDataset(pool, dataset);
const definition = {
name: 'Canonical cutover fixture',
strategy: 'catalog',
strategyVersionId: version.id,
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
symbols: dataset.manifest.executionSeries.map(series => series.instrumentId),
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
initialCapital: 10000,
config: {
datasetHash: dataset.manifest.hash,
dataFrequency: dataset.manifest.series[0]!.interval,
canonical: canonicalSettings,
},
};
const draft = await api.createBacktest(definition, { autoStart: false });
return { api, catalog, version, draft, definition, dataset };
}

192
test/fixtures/canonical-runner.ts vendored Normal file
View file

@ -0,0 +1,192 @@
import { randomUUID } from 'node:crypto';
import { EventEmitter } from 'node:events';
import { expect } from 'bun:test';
import {
canonicalRunRequestSchema,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type { HistoricalDatasetV2 } from '@stock-bot/types';
import { builtinCatalogDescriptors } from '../../apps/stock/config/src/contracts/strategy';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import { type BacktestExecutionEngine } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import { type BacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/run-repository';
import { canonicalSmaFixture } from './canonical-sma';
const logger = { error() {} };
export function canonicalRunnerFixture() {
const versionId = randomUUID(),
runId = randomUUID(),
ownerId = `strategy:${versionId}`;
const { dataset, config, selections } = canonicalSmaFixture([ownerId]);
config.matching.risk.ledger.sessionId = runId;
config.matching.risk.ledger.accountId = `research:${runId}`;
const descriptor = builtinCatalogDescriptors.find(d => d.program.strategyId === 'sma_crossover')!;
const request = canonicalRunRequestSchema.parse({
kind: 'canonical-research/v1',
runId,
backtestId: randomUUID(),
name: 'Runner boundary',
strategy: {
familyId: randomUUID(),
versionId,
origin: 'builtin',
reviewId: randomUUID(),
selection: selections[0],
package: {
version: 1,
program: descriptor.program,
parameterSchema: descriptor.parameterSchema,
artifact: {
format: 'esm-bundle/v1',
entryExport: descriptor.entryExport,
content: 'not executed by this lifecycle fixture',
sha256: 'a'.repeat(64),
},
dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) },
source: { revision: 'c'.repeat(40), dirty: false },
build: { tool: 'bun', version: 'fixture', target: 'browser' },
},
},
datasetHash: dataset.manifest.hash,
policy: config,
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
modelArtifacts: [],
build: {
version: 1,
workerSha256: 'd'.repeat(64),
engineWrapperSha256: 'e'.repeat(64),
engineBinarySha256: 'f'.repeat(64),
dependencyLockSha256: 'b'.repeat(64),
runtime: 'bun',
runtimeVersion: 'fixture',
platform: 'linux',
arch: 'x64',
},
});
const events: string[] = [];
let result: CanonicalRunResult | undefined;
let heartbeatFailure = false;
let status = 'pending';
const repo: BacktestRunRepository = {
async start() {
throw new Error('legacy claim must not run');
},
async startCanonical(input) {
events.push('claim');
status = 'running';
return {
runId,
backtestId: request.backtestId,
attemptId: 'attempt',
config: structuredClone(input),
};
},
async load() {
return { status, config: structuredClone(request) };
},
async rejectPending() {
events.push('reject');
status = 'failed';
},
async heartbeat() {
events.push('heartbeat');
if (heartbeatFailure) {
throw new Error('lost');
}
return { cancelRequested: false };
},
async loadDataset() {
throw new Error('v1 data must not run');
},
async freezeDataset() {
throw new Error('provider freeze must not run');
},
async loadCanonicalDataset(_id, _attempt, hash) {
expect(hash).toBe(dataset.manifest.hash);
events.push('dataset');
return dataset;
},
async complete() {
throw new Error('legacy completion must not run');
},
async completeCanonical(input) {
events.push('complete');
result = input;
status = 'completed';
},
async updateProgress() {
events.push('progress');
},
async fail() {
events.push('fail');
status = 'failed';
},
async cancel() {
events.push('cancel');
status = 'cancelled';
},
async updateControl() {},
};
const engine = Object.assign(new EventEmitter(), {
async runBacktest(): Promise<never> {
throw new Error('legacy simulator must not run');
},
async runCanonical(
_input: typeof request,
resolve: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
) {
await resolve(new AbortController().signal);
events.push('execute');
// Economic validation belongs to the actual worker/SQL fixtures; this fixture probes lifecycle only.
return {
financial: {} as CanonicalRunResult['financial'],
analytics: {} as CanonicalRunResult['analytics'],
};
},
async stopBacktest() {
events.push('stop');
},
async pauseBacktest() {},
async resumeBacktest() {},
setSpeedMultiplier() {},
getStatus() {
return { isRunning: false, isPaused: false, progress: 0, currentTime: 0 };
},
async shutdown() {},
}) satisfies BacktestExecutionEngine;
const runner = new BacktestRunner({
engine,
repository: repo,
engineName: 'native',
logger,
heartbeatMs: 5,
heartbeatTimeoutMs: 50,
});
return {
request,
dataset,
repo,
engine,
runner,
events,
get result() {
return result;
},
setStatus(next: string) {
status = next;
},
loseLease() {
heartbeatFailure = true;
},
};
}
export function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (error: Error) => void;
const promise = new Promise<T>((a, b) => {
resolve = a;
reject = b;
});
return { promise, resolve, reject };
}

62
test/fixtures/historical-run.ts vendored Normal file
View file

@ -0,0 +1,62 @@
import { createHash, randomUUID } from 'node:crypto';
import type { Pool } from 'pg';
import { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest';
import type {
BacktestServiceV2,
RunSubmission,
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
/** Insert an already accepted pre-cutover row for read/custody compatibility tests.
* This is not an admission API or executable simulator, and cannot seed catalog requests.
*/
export async function seedHistoricalRun(
pool: Pool,
api: BacktestServiceV2,
input: { backtestId: string },
receipt?: RunSubmission
) {
const definition = await api.getBacktest(input.backtestId);
if (!definition || definition.strategyVersionId !== null || definition.strategy === 'catalog') {
throw new Error('Historical fixture requires a legacy template');
}
const runId = randomUUID();
const snapshot = backtestRequestFromDefinition(
{
name: definition.name,
strategy: definition.strategy,
symbols: definition.symbols,
startDate: definition.startDate.toISOString(),
endDate: definition.endDate.toISOString(),
initialCapital: definition.initialCapital,
config: definition.config,
},
{ runId, backtestId: definition.id, speedMultiplier: null }
);
const hash = receipt
? createHash('sha256')
.update(JSON.stringify({ version: 1, backtestId: definition.id, speedMultiplier: null }))
.digest('hex')
: null;
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [definition.id]);
await client.query(
`INSERT INTO runs(id,backtest_id,run_number,request_snapshot,submission_principal,submission_key,submission_hash)
SELECT $1,$2,COALESCE(MAX(run_number),0)+1,$3,$4,$5,$6 FROM runs WHERE backtest_id=$2`,
[runId, definition.id, snapshot, receipt?.principal ?? null, receipt?.key ?? null, hash]
);
await client.query('INSERT INTO backtest_dispatch(run_id) VALUES($1)', [runId]);
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
const saved = await api.getRun(runId);
if (!saved) {
throw new Error('Historical fixture row missing');
}
return saved;
}

View file

@ -1,3 +1,4 @@
import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay';
import {
nativeWorkerRequestSchema,
type NativeWorkerMessage,
@ -11,13 +12,13 @@ function send(message: NativeWorkerMessage | { invalid: boolean }): Promise<void
process.once('message', async (input: unknown) => {
const request = nativeWorkerRequestSchema.parse(input);
if (request.type !== 'run') {
throw new Error('Legacy fixture only');
if (request.type !== 'runReplayTrace') {
throw new Error('Canonical replay lifecycle fixture only');
}
const { config } = request;
// Fixture controls are run labels, not unsupported production strategy parameters.
const behavior = config.name?.startsWith('fixture:')
? config.name.slice('fixture:'.length)
const behavior = config.matching.risk.ledger.sessionId.startsWith('fixture:')
? config.matching.risk.ledger.sessionId.slice('fixture:'.length)
: undefined;
if (!behavior) {
// The same adapter can recover and run the actual Rust engine after a failed worker.
@ -49,7 +50,7 @@ process.once('message', async (input: unknown) => {
process.exit(0);
return;
case 'result-then-block':
await send({ type: 'result', result: '{}' });
await send({ type: 'result', result: JSON.stringify(executeReplayTrace(request).result) });
while (true) {
Math.sqrt(Math.random());
}

View file

@ -0,0 +1,123 @@
import { expect, test } from 'bun:test';
import { parseFinancialDecimal } from '@stock-bot/types';
import {
NativeReplaySession,
prepareReplayLoad,
runReplaySessionAsync,
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
import type { ReplayResultFormat } from '../../apps/stock/orchestrator/src/contracts/native-replay';
import { StrategyController } from '../../apps/stock/orchestrator/src/strategies/strategy-controller';
import { nativeReplayFixture } from '../fixtures/native-replay';
function setup() {
const fixture = nativeReplayFixture(8, 1, ['A', 'B']);
const load = prepareReplayLoad(fixture.dataset, fixture.config);
const programs: StrategyProgram<number>[] = ['A', 'B'].map(ownerId => ({
ownerId,
strategyId: 'async-parity',
strategyVersion: '1',
mode: 'target',
seed: ownerId === 'A' ? 12 : 34,
initialState: 0,
decide(context) {
expect(context.observations.every(bar => bar.available_at <= context.now)).toBe(true);
expect(context.positions.every(position => position.ownerId === ownerId)).toBe(true);
expect(context.previousAdmission?.decision.ownerId ?? ownerId).toBe(ownerId);
return {
nextState: context.state + 1,
intent: {
mode: 'target',
targets: [
{
instrumentId: 'X0.US',
quantity: parseFinancialDecimal(context.random() > 0.5 ? '1' : '0'),
},
],
},
};
},
}));
const controller = new StrategyController(load.identity, programs, load.config);
return { load, programs, controller };
}
for (const resultFormat of ['trace', 'projection', 'report'] satisfies ReplayResultFormat[]) {
test(`async controller preserves synchronous ${resultFormat} economics, state and admission order`, async () => {
const { load, programs, controller } = setup();
const synchronous = runStrategyReplay(load, programs, { resultFormat, eventBudget: 1 });
const phases: string[] = [];
const asynchronous = await runReplaySessionAsync(
new NativeReplaySession(load),
{
async stage(context, observations) {
phases.push('stage');
await Promise.resolve();
expect(Object.isFrozen(context.view)).toBe(true);
expect(Object.isFrozen(observations)).toBe(true);
return controller.stage(context, observations);
},
async committed(outcome) {
phases.push('commit');
await Promise.resolve();
controller.committed(outcome);
},
},
{ resultFormat, eventBudget: 256 }
);
expect(asynchronous.result).toEqual(synchronous.result);
expect(controller.snapshot()).toEqual(synchronous.diagnostics);
expect(phases).toEqual(Array.from({ length: 7 }, () => ['stage', 'commit']).flat());
expect(asynchronous.metrics.submitCalls).toBe(synchronous.metrics.submitCalls);
});
}
for (const phase of ['stage', 'commit'] as const) {
test(`async ${phase} rejection disposes the native session and preserves only acknowledged diagnostics`, async () => {
const { load, controller } = setup();
const session = new NativeReplaySession(load);
const dispose = session.dispose.bind(session);
let disposals = 0;
session.dispose = () => {
disposals++;
dispose();
};
await expect(
runReplaySessionAsync(session, {
async stage(context, observations) {
await Promise.resolve();
if (phase === 'stage') {
throw new Error('isolated stage lost');
}
return controller.stage(context, observations);
},
async committed() {
await Promise.resolve();
throw new Error('isolated commit lost');
},
})
).rejects.toThrow(`isolated ${phase} lost`);
expect(disposals).toBe(1);
expect(controller.snapshot().committedBarriers).toBe(0);
expect(() => session.advance(1)).toThrow();
});
}
test('async malformed financial decisions fail before an acknowledgement and still dispose', async () => {
const { load } = setup();
const session = new NativeReplaySession(load);
let acknowledged = false;
await expect(
runReplaySessionAsync(session, {
async stage() {
return [{ intent: { mode: 'target', targets: [] } }] as never;
},
async committed() {
acknowledged = true;
},
})
).rejects.toThrow();
expect(acknowledged).toBe(false);
expect(() => session.advance(1)).toThrow();
});

View file

@ -45,6 +45,13 @@ const timers = new Map<
{ at: number; delay: number; callback: () => void; repeat: boolean }
>();
function submittedBody(request: { body?: string }): string {
if (typeof request.body !== 'string') {
throw new Error('Submission body is missing');
}
return request.body;
}
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason: Error) => void;
@ -68,7 +75,9 @@ 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}`);
if (!found) {
throw new Error(`No pending ${method} ${path}`);
}
return found;
}
function reply(pending: Request, body: unknown, status = 200) {
@ -115,18 +124,21 @@ const results = (id: string): RunResult => ({
winRate: 0,
totalTrades: 0,
profitFactor: null,
avgWin: 0,
avgLoss: 0,
},
equity: [],
ohlcData: {},
positions: [],
trades: [],
analytics: {},
analytics: { exposureTime: null },
executionTime: 0,
});
const definition = {
id: 'definition',
name: 'Fixture',
strategy: 'sma',
strategy: 'catalog',
strategyVersionId: 'version-one',
symbols: ['A.US'],
startDate: '2024-01-01',
endDate: '2024-02-01',
@ -174,9 +186,13 @@ async function advance(ms: number) {
const due = [...timers].filter(([, timer]) => timer.at <= now);
await flush(() => {
for (const [id, timer] of due) {
if (!timers.has(id)) continue;
if (!timers.has(id)) {
continue;
}
timers.delete(id);
if (timer.repeat) timers.set(id, { ...timer, at: now + timer.delay });
if (timer.repeat) {
timers.set(id, { ...timer, at: now + timer.delay });
}
timer.callback();
}
});
@ -187,7 +203,9 @@ function click(label: string) {
const button =
buttons.find(item => item.textContent?.trim() === label) ??
buttons.find(item => item.getAttribute('aria-label') === label);
if (!button) throw new Error(`Missing button ${label}`);
if (!button) {
throw new Error(`Missing button ${label}`);
}
button.click();
}
function HookHost({ socket = false }: { socket?: boolean }) {
@ -196,7 +214,9 @@ function HookHost({ socket = false }: { socket?: boolean }) {
useWebSocket({
runId: socket ? (latest.currentRun?.id ?? null) : null,
onMessage: message => {
if (message.type !== 'pong') void latest.refreshRun(message.runId);
if (message.type !== 'pong') {
void latest.refreshRun(message.runId);
}
},
});
return latest.currentRun
@ -210,7 +230,13 @@ function HookHost({ socket = false }: { socket?: boolean }) {
}
async function mount(element: ReactElement = createElement(HookHost)) {
root = createRoot(host);
await flush(() => root!.render(element));
await flush(() =>
root!.render(
element.type === CreateBacktestDialog
? createElement(router.MemoryRouter, null, element)
: element
)
);
}
async function select(id: string) {
await flush(() => {
@ -260,8 +286,9 @@ beforeAll(async () => {
WebSocket: TestSocket,
ResizeObserver: browser.ResizeObserver,
IS_REACT_ACT_ENVIRONMENT: true,
}))
})) {
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
}
({ createRoot } = await import('react-dom/client'));
({ useBacktestV2 } = await import(
'../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2'
@ -291,6 +318,9 @@ beforeEach(() => {
host = browser.document.createElement('div') as unknown as HTMLDivElement;
browser.document.body.append(host as never);
browser.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
if (new URL(String(input)).pathname.endsWith('/canonical-capability')) {
return Promise.resolve(Response.json({ available: true, reason: null }));
}
const pending: Request = {
...deferred<Response>(),
path: new URL(String(input)).pathname,
@ -304,10 +334,12 @@ beforeEach(() => {
requests.push(pending);
// Deliberately ignore abort: guards must also reject a late server continuation.
return pending.promise;
}) as typeof browser.fetch;
}) as unknown as typeof browser.fetch;
const schedule = (repeat: boolean, original: typeof setTimeout) =>
((callback: () => void, delay?: number, ...args: unknown[]) => {
if (![1000, 3000, 30000].includes(delay ?? 0)) return original(callback, delay, ...args);
if (![1000, 3000, 30000].includes(delay ?? 0)) {
return original(callback, delay, ...args);
}
const id = ++timerId;
timers.set(id, { at: now + delay!, delay: delay!, callback, repeat });
return id;
@ -315,16 +347,22 @@ beforeEach(() => {
globalThis.setTimeout = schedule(false, realTimeout);
globalThis.setInterval = schedule(true, realInterval as typeof setTimeout) as typeof setInterval;
globalThis.clearTimeout = ((id: number) => {
if (!timers.delete(id)) realClearTimeout(id);
if (!timers.delete(id)) {
realClearTimeout(id);
}
}) as typeof clearTimeout;
globalThis.clearInterval = ((id: number) => {
if (!timers.delete(id)) realClearInterval(id);
if (!timers.delete(id)) {
realClearInterval(id);
}
}) as typeof clearInterval;
});
afterEach(async () => {
let leakedTimers = 0;
try {
if (root) await flush(() => root!.unmount());
if (root) {
await flush(() => root!.unmount());
}
leakedTimers = timers.size;
} finally {
root = undefined;
@ -343,8 +381,11 @@ afterAll(async () => {
} finally {
for (const key of globals) {
const descriptor = savedGlobals.get(key);
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
if (descriptor) {
Object.defineProperty(globalThis, key, descriptor);
} else {
Reflect.deleteProperty(globalThis, key);
}
}
}
});
@ -607,6 +648,45 @@ describe('actual detail page result states', () => {
});
async function nameBacktest() {
const family = { id: 'family', name: 'Test strategy', archived: false };
const version = {
id: 'version-one',
strategyId: 'family',
ordinal: 1,
origin: 'builtin',
package: {
parameterSchema: {
type: 'object',
properties: {},
required: [],
additionalProperties: false,
},
},
};
await flush(() => reply(request('/api/v2/strategies'), { strategies: [family] }));
const choose = (label: string, value: string) => {
const select = host.querySelector(`select[aria-label="${label}"]`)!;
Object.getOwnPropertyDescriptor(browser.HTMLSelectElement.prototype, 'value')!.set!.call(
select,
value
);
select.dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event);
};
await flush(() => choose('Strategy family', 'family'));
await flush(() => reply(request('/api/v2/strategies/family/versions'), { versions: [version] }));
await flush(() => choose('Immutable strategy version', 'version-one'));
await flush(() =>
reply(request('/api/v2/strategy-versions/version-one'), { version, reviews: [] })
);
await flush(() => reply(request('/api/v2/strategies/family'), { strategy: family }));
await flush(() => click('Validate parameters'));
await flush(() =>
reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), {
parameters: {},
runnable: false,
reason: 'Configure canonical settings',
})
);
await flush(() => {
const input = host.querySelector('input[placeholder="My Strategy Backtest"]')!;
Object.getOwnPropertyDescriptor(browser.HTMLInputElement.prototype, 'value')!.set!.call(
@ -643,175 +723,109 @@ describe('explicit save and repeat-safe run submission', () => {
});
const saving = request('/api/v2/backtests', 'POST');
expect(JSON.parse(saving.body!).autoStart).toBe(false);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
expect(
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'POST')
).toHaveLength(1);
await flush(() => reply(saving, definition));
expect(created).toEqual([definition]);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
expect(
requests.filter(item => item.path.endsWith('/runs') && item.method === 'POST')
).toHaveLength(0);
});
for (const failure of ['rejection', 'lost successful response'] as const) {
test(`save_and_run_failure: ${failure} retries the saved definition, frozen body and key`, async () => {
const created: { definition: Backtest; run?: Run }[] = [];
await mount(
createElement(CreateBacktestDialog, {
onClose: () => {},
onCreated: (value, submitted) => created.push({ definition: value, run: submitted }),
})
);
await nameBacktest();
await flush(() => {
click('Save and run');
click('Save and run');
});
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
const first = request('/api/v2/backtests/definition/runs', 'POST');
expect(first.headers.get('Idempotency-Key')).toBeTruthy();
expect(JSON.parse(first.body!)).toEqual({ speedMultiplier: null });
// In the lost-response case the server has accepted A; the transport fails.
await flush(() =>
failure === 'rejection'
? reply(first, { error: 'Submission unavailable' }, 503)
: fail(first)
);
expect(created).toHaveLength(0);
expect(host.textContent).toContain('Backtest saved, but run submission failed');
expect(host.querySelector('fieldset')!.disabled).toBe(true);
await flush(() => {
click('Retry submission');
click('Retry submission');
});
const retry = request('/api/v2/backtests/definition/runs', 'POST');
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
expect(retry.body).toBe(first.body);
expect(requests.filter(item => item.path === '/api/v2/backtests')).toHaveLength(1);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(3);
await flush(() => reply(retry, run('A', 'pending'), 202));
expect(created).toEqual([{ definition, run: run('A', 'pending') }]);
});
}
test('new dialog cannot submit legacy or unconfigured execution', async () => {
await mount(createElement(CreateBacktestDialog, { onClose: () => {}, onCreated: () => {} }));
expect(host.querySelector('[aria-label="Strategy mode"]')).toBeNull();
await nameBacktest();
await flush(() => click('Save and run'));
expect(requests.some(item => item.path === '/api/v2/backtests' && item.method === 'POST')).toBe(
false
);
expect(host.textContent).toContain('financial policies before running');
});
for (const boundary of ['definition', 'submission'] as const) {
test(`dialog unmount during ${boundary} ignores late completion and navigation`, async () => {
let navigated = false;
await mount(
createElement(CreateBacktestDialog, {
onClose: () => {},
onCreated: () => {
navigated = true;
},
})
);
await nameBacktest();
await flush(() => click('Save and run'));
if (boundary === 'submission') {
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
}
await flush(() => root!.unmount());
root = undefined;
await flush(() =>
reply(
request(
boundary === 'definition' ? '/api/v2/backtests' : '/api/v2/backtests/definition/runs',
'POST'
),
boundary === 'definition' ? definition : run('A')
)
);
expect(navigated).toBe(false);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(
boundary === 'definition' ? 1 : 2
);
});
}
test('dialog unmount during save ignores late completion and navigation', async () => {
let navigated = false;
await mount(
createElement(CreateBacktestDialog, {
onClose: () => {},
onCreated: () => {
navigated = true;
},
})
);
await nameBacktest();
await flush(() => click('Save'));
await flush(() => root!.unmount());
root = undefined;
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
expect(navigated).toBe(false);
expect(requests.some(item => item.path.endsWith('/runs') && item.method === 'POST')).toBe(
false
);
});
test('closing cannot race the definition write and refresh a list before the row exists', async () => {
await mount(createElement(router.MemoryRouter, null, createElement(BacktestListPageV2)));
test('save rejects double clicks and close while pending, then navigates to configure', async () => {
await mount(
createElement(
router.MemoryRouter,
{ initialEntries: ['/backtests'] },
createElement(
router.Routes,
null,
createElement(router.Route, {
path: '/backtests',
element: createElement(BacktestListPageV2),
}),
createElement(router.Route, {
path: '/backtests/:id',
element: createElement('p', null, 'Saved definition'),
})
),
createElement(LocationProbe)
)
);
await flush(() => reply(request('/api/v2/backtests'), []));
await flush(() => click('New Backtest'));
await nameBacktest();
// The ref guard must work before the disabled state has rendered.
await flush(() => {
click('Save and run');
click('Save');
click('Save');
click('Close backtest dialog');
click('Close');
});
expect(host.querySelector('[aria-label="Close backtest dialog"]')).not.toBeNull();
expect(
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET')
).toHaveLength(1);
await flush(() => click('Close'));
expect(
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET')
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'POST')
).toHaveLength(1);
expect(pageLocation).toBe('/backtests');
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
const submitting = request('/api/v2/backtests/definition/runs', 'POST');
await flush(() => click('Close'));
await flush(() => reply(request('/api/v2/backtests'), [definition]));
await flush(() => reply(submitting, run('A', 'pending'), 202));
expect(host.textContent).toContain('Create and manage backtest configurations');
expect(host.querySelector('[aria-label="Close backtest dialog"]')).toBeNull();
expect(pageLocation).toBe('/backtests/definition');
expect(requests.some(item => item.path.endsWith('/runs') && item.method === 'POST')).toBe(
false
);
});
test('closing saved-but-failed dialog reloads the real list without navigating', async () => {
await mount(createElement(router.MemoryRouter, null, createElement(BacktestListPageV2)));
await flush(() => reply(request('/api/v2/backtests'), []));
await flush(() => click('New Backtest'));
await nameBacktest();
await flush(() => click('Save and run'));
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
await flush(() => fail(request('/api/v2/backtests/definition/runs', 'POST')));
await flush(() => click('Close'));
await flush(() => reply(request('/api/v2/backtests'), [definition]));
// Virtualized rows need real layout (W04). Here verify the refetch and that
// the real list, not a detail route, remains mounted after closing.
expect(
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET')
).toHaveLength(2);
expect(host.textContent).toContain('Create and manage backtest configurations');
expect(host.textContent).not.toContain('Retry submission');
});
for (const intent of ['Save', 'Save and run'] as const) {
test(`real list ${intent} navigates only after the requested operation succeeds`, async () => {
await mount(
createElement(
router.MemoryRouter,
{ initialEntries: ['/backtests'] },
createElement(
router.Routes,
null,
createElement(router.Route, {
path: '/backtests',
element: createElement(BacktestListPageV2),
}),
createElement(router.Route, {
path: '/backtests/:id',
element: createElement('p', null, 'Saved definition'),
}),
createElement(router.Route, {
path: '/backtests/:id/run/:runId',
element: createElement('p', null, 'Submitted run'),
})
),
createElement(LocationProbe)
)
);
await flush(() => reply(request('/api/v2/backtests'), []));
await flush(() => click('New Backtest'));
await nameBacktest();
await flush(() => click(intent));
expect(pageLocation).toBe('/backtests');
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
if (intent === 'Save and run') {
expect(pageLocation).toBe('/backtests');
await flush(() =>
reply(request('/api/v2/backtests/definition/runs', 'POST'), run('A', 'pending'), 202)
);
}
expect(pageLocation).toBe(
`/backtests/definition${intent === 'Save and run' ? '/run/A' : ''}`
);
test('legacy template stays readable but never creates a new run', async () => {
await mount();
await flush(() => {
void latest.loadBacktest('definition');
});
}
await flush(() => {
reply(request('/api/v2/backtests/definition'), {
...definition,
strategy: 'sma',
strategyVersionId: null,
});
reply(request('/api/v2/backtests/definition/runs'), []);
});
await flush(() => {
void latest.createRun();
});
expect(latest.submissionError).toContain('Legacy execution is retired');
expect(requests.some(item => item.method === 'POST')).toBe(false);
expect(latest.backtest?.name).toBe('Fixture');
});
test('closing new-run confirmation prevents late successful submission from navigating', async () => {
await mountPage('failed');
@ -852,7 +866,7 @@ describe('explicit save and repeat-safe run submission', () => {
expect(host.textContent).toContain('Run failed: B failure');
await flush(() => click('Retry submission'));
const retry = request('/api/v2/backtests/definition/runs', 'POST');
expect(retry.body).toBe(submitting.body);
expect(submittedBody(retry)).toBe(submittedBody(submitting));
expect(retry.headers.get('Idempotency-Key')).toBe(submitting.headers.get('Idempotency-Key'));
});
@ -880,7 +894,7 @@ describe('explicit save and repeat-safe run submission', () => {
void latest.createRun(9);
});
const retry = request('/api/v2/backtests/definition/runs', 'POST');
expect(retry.body).toBe(first.body);
expect(submittedBody(retry)).toBe(submittedBody(first));
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
await flush(() => reply(retry, run('A', 'pending'), 202));
expect(latest.runs.filter(item => item.id === 'A')).toHaveLength(1);
@ -889,7 +903,7 @@ describe('explicit save and repeat-safe run submission', () => {
});
const next = request('/api/v2/backtests/definition/runs', 'POST');
expect(next.headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key'));
expect(JSON.parse(next.body!)).toEqual({ speedMultiplier: 9 });
expect(JSON.parse(next.body!)).toEqual({ speedMultiplier: null });
await flush(() => reply(next, run('B', 'pending'), 202));
expect(latest.runs.map(item => item.id)).toEqual(['B', 'A']);
});
@ -913,7 +927,7 @@ describe('explicit save and repeat-safe run submission', () => {
await flush(() => click('Retry submission'));
const retry = request('/api/v2/backtests/definition/runs', 'POST');
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
expect(retry.body).toBe(first.body);
expect(submittedBody(retry)).toBe(submittedBody(first));
});
for (const change of ['selection', 'backtest', 'unmount'] as const) {
@ -1051,7 +1065,7 @@ describe('template archive and restore', () => {
void latest.createRun(9);
});
const retry = request('/api/v2/backtests/definition/runs', 'POST');
expect(retry.body).toBe(first.body);
expect(submittedBody(retry)).toBe(submittedBody(first));
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
await flush(() => reply(retry, run('A', 'completed'), 202));
expect(latest.hasPendingSubmission).toBe(false);
@ -1074,7 +1088,7 @@ describe('template archive and restore', () => {
});
const fresh = request('/api/v2/backtests/definition/runs', 'POST');
expect(fresh.headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key'));
expect(JSON.parse(fresh.body!)).toEqual({ speedMultiplier: 9 });
expect(JSON.parse(fresh.body!)).toEqual({ speedMultiplier: null });
await flush(() => reply(fresh, run('B', 'pending'), 202));
expect(latest.runResults).toBe(savedResults);
});
@ -1090,7 +1104,7 @@ describe('template archive and restore', () => {
expect(button('Retry submission').disabled).toBe(false);
await flush(() => click('Retry submission'));
const retry = request('/api/v2/backtests/definition/runs', 'POST');
expect(retry.body).toBe(first.body);
expect(submittedBody(retry)).toBe(submittedBody(first));
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
await flush(() => reply(retry, run('A', 'running'), 202));
expect(button('Run current settings').disabled).toBe(true);
@ -1132,6 +1146,9 @@ describe('template archive and restore', () => {
409
)
);
if (typeof failure !== 'string') {
throw new Error('Expected a retained-history refusal');
}
expect(failure).toContain('Archive it');
expect(latest.error).toBe(failure);
expect(latest.backtest?.id).toBe('definition');

File diff suppressed because it is too large Load diff

View file

@ -1,201 +1,10 @@
import { randomUUID } from 'node:crypto';
import { EventEmitter } from 'node:events';
import { describe, expect, test } from 'bun:test';
import {
canonicalRunRequestSchema,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type { HistoricalDatasetV2 } from '@stock-bot/types';
import { builtinCatalogDescriptors } from '../../apps/stock/config/src/contracts/strategy';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import {
BacktestCancelledError,
type BacktestExecutionEngine,
} from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import {
BacktestLeaseLostError,
type BacktestRunRepository,
} from '../../apps/stock/orchestrator/src/backtest/run-repository';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
const logger = { error() {} };
function setup() {
const versionId = randomUUID(),
runId = randomUUID(),
ownerId = `strategy:${versionId}`;
const { dataset, config, selections } = canonicalSmaFixture([ownerId]);
config.matching.risk.ledger.sessionId = runId;
config.matching.risk.ledger.accountId = `research:${runId}`;
const descriptor = builtinCatalogDescriptors.find(d => d.program.strategyId === 'sma_crossover')!;
const request = canonicalRunRequestSchema.parse({
kind: 'canonical-research/v1',
runId,
backtestId: randomUUID(),
name: 'Runner boundary',
strategy: {
familyId: randomUUID(),
versionId,
origin: 'builtin',
reviewId: randomUUID(),
selection: selections[0],
package: {
version: 1,
program: descriptor.program,
parameterSchema: descriptor.parameterSchema,
artifact: {
format: 'esm-bundle/v1',
entryExport: descriptor.entryExport,
content: 'not executed by this lifecycle fixture',
sha256: 'a'.repeat(64),
},
dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) },
source: { revision: 'c'.repeat(40), dirty: false },
build: { tool: 'bun', version: 'fixture', target: 'browser' },
},
},
datasetHash: dataset.manifest.hash,
policy: config,
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
modelArtifacts: [],
build: {
version: 1,
workerSha256: 'd'.repeat(64),
engineWrapperSha256: 'e'.repeat(64),
engineBinarySha256: 'f'.repeat(64),
dependencyLockSha256: 'b'.repeat(64),
runtime: 'bun',
runtimeVersion: 'fixture',
platform: 'linux',
arch: 'x64',
},
});
const events: string[] = [];
let result: CanonicalRunResult | undefined;
let heartbeatFailure = false;
let status = 'pending';
const repo: BacktestRunRepository = {
async start() {
throw new Error('legacy claim must not run');
},
async startCanonical(input) {
events.push('claim');
status = 'running';
return {
runId,
backtestId: request.backtestId,
attemptId: 'attempt',
config: structuredClone(input),
};
},
async load() {
return { status, config: structuredClone(request) };
},
async rejectPending() {
events.push('reject');
status = 'failed';
},
async heartbeat() {
events.push('heartbeat');
if (heartbeatFailure) {
throw new Error('lost');
}
return { cancelRequested: false };
},
async loadDataset() {
throw new Error('v1 data must not run');
},
async freezeDataset() {
throw new Error('provider freeze must not run');
},
async loadCanonicalDataset(_id, _attempt, hash) {
expect(hash).toBe(dataset.manifest.hash);
events.push('dataset');
return dataset;
},
async complete() {
throw new Error('legacy completion must not run');
},
async completeCanonical(input) {
events.push('complete');
result = input;
status = 'completed';
},
async updateProgress() {
events.push('progress');
},
async fail() {
events.push('fail');
status = 'failed';
},
async cancel() {
events.push('cancel');
status = 'cancelled';
},
async updateControl() {},
};
const engine = Object.assign(new EventEmitter(), {
async runBacktest(): Promise<never> {
throw new Error('legacy simulator must not run');
},
async runCanonical(
_input: typeof request,
resolve: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
) {
await resolve(new AbortController().signal);
events.push('execute');
// Economic validation belongs to the actual worker/SQL fixtures; this fixture probes lifecycle only.
return {
financial: {} as CanonicalRunResult['financial'],
analytics: {} as CanonicalRunResult['analytics'],
};
},
async stopBacktest() {
events.push('stop');
},
async pauseBacktest() {},
async resumeBacktest() {},
setSpeedMultiplier() {},
getStatus() {
return { isRunning: false, isPaused: false, progress: 0, currentTime: 0 };
},
async shutdown() {},
}) satisfies BacktestExecutionEngine;
const runner = new BacktestRunner({
engine,
repository: repo,
engineName: 'native',
logger,
heartbeatMs: 5,
heartbeatTimeoutMs: 50,
async prepare() {
throw new Error('legacy preparation must not run');
},
});
return {
request,
dataset,
repo,
engine,
runner,
events,
get result() {
return result;
},
loseLease() {
heartbeatFailure = true;
},
};
}
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (error: Error) => void;
const promise = new Promise<T>((a, b) => {
resolve = a;
reject = b;
});
return { promise, resolve, reject };
}
import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository';
import { deferred, canonicalRunnerFixture as setup } from '../fixtures/canonical-runner';
describe('canonical jobs share the durable runner lifecycle', () => {
test('queued canonical result preserves admitted request and bypasses every legacy seam', async () => {

View file

@ -0,0 +1,150 @@
import { expect, test } from 'bun:test';
import {
BacktestCancelledError,
BacktestTimeoutError,
} from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { canonicalRunnerFixture, deferred } from '../fixtures/canonical-runner';
import { nativeReplayFixture } from '../fixtures/native-replay';
const workerUrl = new URL('../fixtures/native-backtest-worker.ts', import.meta.url);
function start(behavior: string) {
const fixture = nativeReplayFixture(),
ready = deferred<number>(),
controller = new AbortController();
fixture.config.matching.risk.ledger.sessionId = `fixture:${behavior}`;
const worker = new NativeBacktestWorker(workerUrl);
const result = worker
.execute(
{
type: 'runReplayTrace',
version: 1,
dataset: fixture.dataset,
config: fixture.config,
trace: [1, 2].map(offset => ({
at: fixture.start + offset * fixture.minute,
ownerId: 'A',
intent: { mode: 'target' as const, targets: [] },
})),
resultFormat: 'report',
eventBudget: 1,
},
controller.signal,
progress => {
if (progress.message.startsWith('Fixture worker ready:')) {
ready.resolve(Number(progress.message.split(':')[1]));
}
}
)
.catch(error => {
ready.reject(error);
return error;
});
return { result, ready: ready.promise, controller };
}
function exited(pid: number) {
expect(pid).toBeGreaterThan(0);
expect(() => process.kill(pid, 0)).toThrow();
}
test.each(['crash', 'no-result', 'malformed', 'invalid-result', 'reported-error'])(
'canonical worker %s cannot publish a result and is reaped before rejection',
async behavior => {
const execution = start(behavior),
pid = await execution.ready;
expect(await execution.result).toBeInstanceOf(Error);
exited(pid);
}
);
test('blocking canonical worker can be killed without blocking the parent event loop', async () => {
const execution = start('block'),
pid = await execution.ready;
let tick = false;
await new Promise<void>(resolve =>
setTimeout(() => {
tick = true;
resolve();
}, 5)
);
expect(tick).toBe(true);
execution.controller.abort(new BacktestCancelledError());
expect(await execution.result).toBeInstanceOf(BacktestCancelledError);
exited(pid);
});
test('a deadline kills a noncooperative worker and preserves its timeout reason', async () => {
const execution = start('block'),
pid = await execution.ready;
execution.controller.abort(new BacktestTimeoutError(10));
expect(await execution.result).toBeInstanceOf(BacktestTimeoutError);
exited(pid);
});
test('valid financial result is not accepted while the child is still alive', async () => {
const execution = start('result-then-block'),
pid = await execution.ready;
let settled = false;
execution.result.then(() => {
settled = true;
});
await new Promise(resolve => setTimeout(resolve, 20));
expect(settled).toBe(false);
execution.controller.abort(new BacktestCancelledError());
expect(await execution.result).toBeInstanceOf(BacktestCancelledError);
exited(pid);
});
test('canonical adapter cancellation during retained dataset reads prevents a late worker', async () => {
const f = canonicalRunnerFixture(),
entered = deferred<void>(),
release = deferred<void>();
let providerReads = 0,
progress = 0;
const engine = new RustBacktestAdapter({
logger: { error() {} },
storage: {
async getHistoricalBars() {
providerReads++;
return [];
},
},
});
engine.on('progress', () => progress++);
const result = engine
.runCanonical(f.request, async () => {
entered.resolve();
await release.promise;
return f.dataset;
})
.catch(error => error);
await entered.promise;
await engine.stopBacktest();
expect(await result).toBeInstanceOf(BacktestCancelledError);
release.resolve();
await Promise.resolve();
expect(providerReads).toBe(0);
expect(progress).toBe(0);
expect(engine.getStatus().isRunning).toBe(false);
await engine.shutdown();
await f.runner.shutdown();
});
test('canonical adapter timeout covers retained input loading and shutdown closes later work', async () => {
const f = canonicalRunnerFixture();
const engine = new RustBacktestAdapter(
{
logger: { error() {} },
storage: {
async getHistoricalBars() {
throw new Error('provider must not run');
},
},
},
{ timeoutMs: 20 }
);
await expect(
engine.runCanonical(f.request, async () => new Promise(() => {}))
).rejects.toBeInstanceOf(BacktestTimeoutError);
expect(engine.getStatus().isRunning).toBe(false);
await engine.shutdown();
await expect(engine.runCanonical(f.request, async () => f.dataset)).rejects.toThrow(
'shutting down'
);
await f.runner.shutdown();
});

View file

@ -20,8 +20,25 @@ import type {
} from '@stock-bot/stock-config/experiments';
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
import { parseValidationDetail } from '../../apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi';
import { nativeReplayFixture } from '../fixtures/native-replay';
test('saved validation decodes explicit research agent actors without accepting malformed identities', () => {
const value = document('reported');
if (!value.selection || !value.report) {
throw new Error('Reported fixture needs immutable selection and report');
}
const actor = 'agent:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
value.selection.principal = actor;
value.report.principal = actor;
const parsed = parseValidationDetail(value);
expect(parsed.selection?.principal).toBe(actor);
expect(parsed.report?.principal).toBe(actor);
expect(() =>
parseValidationDetail({ ...value, report: { ...value.report, principal: 'agent:operator' } })
).toThrow();
});
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
const keys = ['window', 'document', 'Event', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT'] as const;
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));

View file

@ -717,7 +717,7 @@ describe('immutable retry failure history', () => {
expect(host.textContent).toContain('Retry 1 · previous attempt 1');
expect(host.textContent).not.toContain('No accepted manual retries');
});
test('history is lazy and renders empty/loading states then exact nullable failure snapshots', async () => {
test('history renders loading/empty states, exact nullable failure snapshots and research agent authorship', async () => {
const value = failure(0, 0);
value.trials[0]!.error = null;
await show(value);
@ -728,6 +728,7 @@ describe('immutable retry failure history', () => {
expect(host.textContent).toContain('No accepted manual retries for this trial');
await flush(() => button('Refresh retry history for trial 1').click());
const saved = receipt(value);
saved.principal = 'agent:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
await flush(() => reply(request(historyPath()), { retries: [saved] }));
expect(host.textContent).toContain('Retry 1 · previous attempt 0');
expect(host.textContent).toContain('No error was recorded for this failure');
@ -736,6 +737,7 @@ describe('immutable retry failure history', () => {
expect(host.textContent).toContain(saved.completedAt!);
expect(host.textContent).toContain(saved.recordedAt);
expect(host.textContent).toContain(saved.reviewId);
expect(host.textContent).toContain(saved.principal);
expect(host.textContent).toContain('not a complete history of automatic recovery attempts');
});
test.each(['partial', 'foreign', 'unordered', 'duplicate', 'http'] as const)(

View file

@ -266,7 +266,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
validateDataset(first, { ...datasetConfig(), datasetHash: 'f'.repeat(64) })
).toThrow('does not match');
});
test('replays stored provider fixtures and produces identical trades and metrics', async () => {
test('stored provider fixtures normalize into identical frozen inputs before admission', async () => {
const { documents, mongodb } = memoryStore();
await persistEodPrices(mongodb, identity, fixture);
await persistEodPrices(mongodb, identity, fixture);
@ -287,16 +287,11 @@ describe('deterministic ingestion → storage → native backtest', () => {
slippage: 0,
config: { fastPeriod: 3, slowPeriod: 7 },
});
const engine = new RustBacktestAdapter({ logger, storage });
const first = await engine.runBacktest(config);
const second = await engine.runBacktest(config);
expect(first.status).toBe('completed');
expect(first.trades.length).toBeGreaterThan(0);
expect(first.trades).toEqual(second.trades);
expect(first.metrics).toEqual(second.metrics);
expect(first.equity).toEqual(second.equity);
expect(first.metrics.totalReturn).toBeFinite();
expect(engine.getStatus().isRunning).toBe(false);
const first = await loadDataset(storage, config);
const second = await loadDataset(storage, config);
expect(first).toEqual(second);
expect(first.bars).toHaveLength(fixture.length);
expect(first.manifest.hash).toBe(second.manifest.hash);
});
test('all listings retain their first same-timestamp bar and deterministic tie ordering', async () => {
@ -310,16 +305,14 @@ describe('deterministic ingestion → storage → native backtest', () => {
config: { fastPeriod: 3, slowPeriod: 7 },
};
const storage = new StorageService({ logger }, mongodb, null, null);
const engine = new RustBacktestAdapter({ logger, storage });
const first = await engine.runBacktest(config);
const second = await engine.runBacktest(config);
const first = await loadDataset(storage, config);
const second = await loadDataset(storage, config);
for (const id of config.symbols) {
expect(first.ohlcData[id]).toHaveLength(fixture.length);
expect(first.ohlcData[id]?.[0]?.timestamp).toBe(start.getTime());
const bars = first.bars.filter(bar => bar.symbol === id);
expect(bars).toHaveLength(fixture.length);
expect(bars[0]?.timestamp).toBe(start.getTime());
}
expect(first.trades).toEqual(second.trades);
expect(first.metrics).toEqual(second.metrics);
expect(first.equity).toEqual(second.equity);
expect(first).toEqual(second);
});
test('rejects malformed provider records before writing anything', async () => {
@ -347,7 +340,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
);
});
test('empty storage and unknown strategies fail without leaving the engine running', async () => {
test('retired provider-at-execution entry refuses before storage or native strategy resolution', async () => {
const { mongodb } = memoryStore();
const storage = new StorageService({ logger }, mongodb, null, null);
const engine = new RustBacktestAdapter({ logger, storage });
@ -360,9 +353,11 @@ describe('deterministic ingestion → storage → native backtest', () => {
initialCapital: 100000,
dataFrequency: '1d',
});
await expect(engine.runBacktest(config)).rejects.toThrow('No historical data');
await expect(engine.runBacktest(config)).rejects.toThrow(
'Legacy backtest execution is retired'
);
await expect(engine.runBacktest({ ...config, strategy: 'does-not-exist' })).rejects.toThrow(
'Unknown native strategy'
'Legacy backtest execution is retired'
);
expect(engine.getStatus().isRunning).toBe(false);
});

View file

@ -118,7 +118,7 @@ const config = () =>
});
describe('EOD intraday ingestion → research storage', () => {
test('ingest_5m_freeze_replay: real writer/admission, v2 freeze and legacy native replay', async () => {
test('ingest_5m_freeze: real writer, v2 freeze and historical v1 compatibility', async () => {
const store = memoryStore();
const response = intradayResponse();
expect(await ingest(store.mongodb, response)).toEqual({
@ -166,7 +166,7 @@ describe('EOD intraday ingestion → research storage', () => {
).toBe(true);
expect(validateDatasetV2(JSON.parse(JSON.stringify(dataset)))).toEqual(dataset);
// V1 runtime stays V1. This checks storage compatibility, not future F06 replay correctness.
// Historical V1 payloads remain readable; production execution requires V2 admission.
const legacy = await loadDataset(storage, config());
expect(
legacy.bars.map(({ timestamp, open, high, low, close, volume }) => ({
@ -182,19 +182,10 @@ describe('EOD intraday ingestion → research storage', () => {
legacy.manifest.hash
);
const engine = new RustBacktestAdapter({ logger, storage });
try {
const first = await engine.runBacktest(config(), async () => legacy);
const second = await engine.runBacktest(config(), async () => legacy);
expect(first.status).toBe('completed');
expect(first.ohlcData[identity.eodSearchCode]).toHaveLength(78);
expect(first.ohlcData[identity.eodSearchCode]?.[0]?.timestamp).toBe(start.getTime());
expect(first.trades.length).toBeGreaterThan(0);
expect(first.trades).toEqual(second.trades);
expect(first.equity).toEqual(second.equity);
expect(first.metrics).toEqual(second.metrics);
} finally {
await engine.shutdown();
}
await expect(engine.runBacktest(config(), async () => legacy)).rejects.toThrow(
'Legacy backtest execution is retired'
);
await engine.shutdown();
});
test('supported collections, UTC seconds and half-open fractional boundaries', async () => {
@ -210,7 +201,7 @@ describe('EOD intraday ingestion → research storage', () => {
['1m', 'eodIntraday1M'],
['5m', 'eodIntraday5M'],
['1h', 'eodIntraday1H'],
]) {
] as const) {
const bars = await storage.getHistoricalBars(
identity.eodSearchCode,
new Date(start.getTime() + 1),

View file

@ -25,6 +25,7 @@ test('canonical paper rejects invalid role/configuration before resolving servic
config.matching.series[0]!.mode = 'Open';
await expect(
registerOrchestratorServices(container, {
role: 'paper',
canonicalPaper: config,
})
).rejects.toThrow('Quote execution only');
@ -40,6 +41,6 @@ test('live defaults, research canonical configuration and missing custody fail b
createContainer(config({ defaultMode: 'backtest', canonicalPaper: paperFeedConfiguration() }))
).rejects.toThrow('requires a paper composition');
await expect(
createContainer(config({ canonicalPaper: paperFeedConfiguration() }))
createContainer(config({ defaultMode: 'paper', canonicalPaper: paperFeedConfiguration() }))
).rejects.toThrow('requires durable PostgreSQL');
});

View file

@ -361,7 +361,8 @@ describe('canonical paper HTTP failure and legacy gateway isolation', () => {
const response = await f.app.request(path, { method, headers });
expect(response.status).toBe(409);
expect(await response.json()).toEqual({
error: 'Legacy account gateway unavailable in canonical paper mode',
error:
'Legacy account execution is retired; use the explicitly configured canonical paper runtime',
});
}
}

View file

@ -0,0 +1,203 @@
import { randomUUID } from 'node:crypto';
import { expect, mock, test } from 'bun:test';
import { Hono } from 'hono';
import {
createHttpSecurity,
getCredentialHttpPrincipal,
getResearchHttpPrincipal,
} from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/services';
import { createResearchAgentSchema } from '@stock-bot/stock-config/research-agents';
import { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes';
import { researchAgentDatabaseError } from '../../apps/stock/web-api/src/services/research-agent-budget';
import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
const agent = `agent:${randomUUID()}` as const;
const token = 'sb-research.fixture-token';
const adminToken = 'operator-test-secret-12345678901234567890';
const serviceToken = 'service-test-secret-123456789012345678901';
const limits = {
maxActiveTrials: 2,
maxTrialsPerExperiment: 4,
maxBarEvaluationsPerExperiment: 1000,
maxAttemptWallMs: 1000,
maxAttempts: 2,
};
function boundary(disabled = false, resolver = true) {
const resolve = mock(async () => ({ principal: agent }));
const security = createHttpSecurity({
adminToken,
serviceToken,
disabled,
environment: 'test',
browserSessions: true,
...(resolver ? { resolveResearchCredential: resolve } : {}),
});
const app = new Hono();
security.mount(app);
app.all('/api/v2/experiments', c =>
c.json({
principal: getResearchHttpPrincipal(c.req.raw),
privileged: getCredentialHttpPrincipal(c.req.raw) ?? null,
})
);
return { app, security, resolve };
}
test('research HTTP identity is distinct; Origin and upgrades are fenced before asynchronous resolution', async () => {
const f = boundary();
for (const headers of [{ Origin: 'https://evil.invalid' }, { Upgrade: 'websocket' }] as Record<
string,
string
>[]) {
const response = await f.app.request('/api/v2/experiments', {
method: 'POST',
headers: { Authorization: `Bearer ${token}`, ...headers },
});
expect(response.status).toBe(403);
expect(response.headers.get('cache-control')).toBe('no-store');
}
expect(f.resolve).toHaveBeenCalledTimes(0);
const response = await f.app.request('/api/v2/experiments', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
});
expect(response.status).toBe(200);
expect(await response.json()).toEqual({ principal: agent, privileged: null });
expect(
f.security.authorize(
new Request('http://localhost/api/v2/experiments', {
headers: { Authorization: `Bearer ${token}` },
})
)?.status
).toBe(403);
});
test('research credential never becomes a privileged session or bypasses disabled/unrelated authentication', async () => {
for (const f of [boundary(true), boundary(false, false)]) {
const response = await f.app.request('/api/v2/experiments', {
headers: { Authorization: `Bearer ${token}` },
});
expect(response.status).toBe(403);
expect(f.resolve).toHaveBeenCalledTimes(0);
expect(f.security.researchEnabled).toBe(false);
const login = await f.app.request('/api/auth/session', {
method: 'POST',
headers: { Origin: 'http://localhost', 'Content-Type': 'application/json' },
body: JSON.stringify({ token }),
});
expect(login.status).toBe(403);
expect(login.headers.get('set-cookie')).toBeNull();
}
const f = boundary();
const login = await f.app.request('/api/auth/session', {
method: 'POST',
headers: { Origin: 'http://localhost', 'Content-Type': 'application/json' },
body: JSON.stringify({ token }),
});
expect(login.status).toBe(403);
expect(login.headers.get('set-cookie')).toBeNull();
});
test('operator-only provisioning fails closed without enabled research authentication before storage', async () => {
const query = mock(async () => {
throw new Error('denied operation touched storage');
});
const container = {
postgres: { query },
logger: { error: mock(() => {}) },
} as unknown as IServiceContainer;
for (const disabled of [false, true]) {
const f = boundary(disabled);
f.app.route('/', createResearchAgentRoutes(container, f.security.researchEnabled));
for (const bearer of [token, serviceToken, ...(disabled ? [adminToken] : [])]) {
const response = await f.app.request('/api/v2/research-agents', {
method: 'POST',
headers: { Authorization: `Bearer ${bearer}`, 'Content-Type': 'application/json' },
body: '{}',
});
expect(response.status).toBe(403);
}
}
expect(query).toHaveBeenCalledTimes(0);
});
test('resolver exact write capabilities refuse trading, operators, foreign evidence and ownership impersonation', async () => {
const projectId = randomUUID(),
experimentId = randomUUID(),
familyId = randomUUID();
const query = mock(async (sql: string) => ({
rows: sql.includes('token_hash')
? [{ id: agent, enabled: true, policy: { allowedProjectIds: [projectId] } }]
: [{ submission_principal: 'operator', owner_principal: 'operator', project_id: projectId }],
}));
const service = new ResearchAgentsService({
postgres: { query },
} as unknown as IServiceContainer);
const check = (path: string, method = 'POST') =>
service.authenticate(
new Request(`http://localhost${path}`, {
method,
headers: { Authorization: `Bearer ${token}` },
})
);
for (const path of [
'/api/v2/research-agents',
'/api/v2/backtests',
'/api/v2/datasets/retain',
'/api/v2/strategy-versions/' + familyId + '/review',
'/api/operations/start',
'/api/v2/runs/' + experimentId + '/reproduce',
`/api/v2/experiments/${experimentId}/cancel`,
`/api/v2/strategies/${familyId}/versions`,
`/api/v2/research-projects/${randomUUID()}/hypotheses`,
]) {
expect(await check(path)).toBeInstanceOf(Response);
expect(((await check(path)) as Response).status).toBe(403);
}
expect(await check(`/api/v2/research-projects/${projectId}/hypotheses`)).toEqual({
principal: agent,
});
expect(await check('/api/v2/experiments/preview')).toEqual({ principal: agent });
expect(await check(`/api/v2/experiments/${experimentId}`, 'GET')).toEqual({ principal: agent });
expect(await check('/api/v2/research-agents', 'GET')).toBeInstanceOf(Response);
});
test('quota diagnostics remain distinguishable from arbitrary database failures; policy is strict and bounded', () => {
expect(
researchAgentDatabaseError({ code: 'P0001', message: 'research_budget:capacity' })?.status
).toBe(429);
expect(
researchAgentDatabaseError({ code: 'P0001', message: 'research_access:denied' })?.status
).toBe(403);
expect(researchAgentDatabaseError(new Error('database unavailable'))).toBeNull();
expect(
researchAgentDatabaseError({ code: '23514', message: 'research_budget:spoof' })
).toBeNull();
expect(
createResearchAgentSchema.parse({
name: 'Agent',
allowedProjectIds: [],
allowedBacktestIds: [],
limits,
}).limits
).toEqual(limits);
for (const bad of [
{ ...limits, maxAttempts: 4 },
{ ...limits, maxActiveTrials: 0 },
{ ...limits, maxAttemptWallMs: 2147483648 },
]) {
expect(
createResearchAgentSchema.safeParse({
name: 'Agent',
allowedProjectIds: [],
allowedBacktestIds: [],
limits: bad,
}).success
).toBe(false);
}
expect(
createResearchAgentSchema.safeParse({
name: 'Agent',
allowedProjectIds: [],
allowedBacktestIds: [],
limits,
ownerPrincipal: 'operator',
}).success
).toBe(false);
});

View file

@ -0,0 +1,345 @@
import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test';
import { GlobalWindow } from 'happy-dom';
import { act, createElement } from 'react';
import type { Root } from 'react-dom/client';
import type { ResearchAgentRecord } from '@stock-bot/stock-config/research-agents';
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
const names = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const;
const globals = names.map(
name => [name, Object.getOwnPropertyDescriptor(globalThis, name)] as const
);
let createRoot: typeof import('react-dom/client').createRoot;
let router: typeof import('react-router-dom');
let Page: typeof import('../../apps/stock/web-app/src/features/research/ResearchAgentsPage').ResearchAgentsPage;
let api: typeof import('../../apps/stock/web-app/src/features/research/services/researchAgentsApi').researchAgentsApi;
let root: Root | undefined;
let host: HTMLDivElement;
const agentId = 'agent:11111111-1111-4111-8111-111111111111';
const projectId = '22222222-2222-4222-8222-222222222222';
const backtestId = '33333333-3333-4333-8333-333333333333';
const record = (extra: Partial<ResearchAgentRecord> = {}): ResearchAgentRecord => ({
id: agentId,
name: 'Research worker',
enabled: true,
revision: 1,
allowedProjectIds: [projectId],
grants: [{ backtestId, policyHash: 'a'.repeat(64) }],
limits: {
maxActiveTrials: 1,
maxTrialsPerExperiment: 10,
maxBarEvaluationsPerExperiment: 100000,
maxAttemptWallMs: 60000,
maxAttempts: 3,
},
createdAt: '2026-10-24T12:00:00.000Z',
updatedAt: '2026-10-24T12:00:00.000Z',
...extra,
});
type Pending = {
path: string;
method: string;
body: unknown;
resolve: (response: Response) => void;
reject: (error: Error) => void;
settled: boolean;
};
const calls: Pending[] = [];
function pending(path = '', method = 'GET') {
const value = calls.find(
call =>
!call.settled && call.path === `/api/v2/research-agents${path}` && call.method === method
);
if (!value) {
throw new Error(`Missing request ${method} ${path}`);
}
return value;
}
function reply(call: Pending, body: unknown, status = 200) {
call.settled = true;
call.resolve(Response.json(body, { status }));
}
async function flush(action: () => void = () => {}) {
await act(async () => {
action();
await Promise.resolve();
});
}
function button(text: string) {
const value = [...host.querySelectorAll('button')].find(
item => item.textContent?.trim() === text
);
if (!value) {
throw new Error(`Missing button ${text}`);
}
return value;
}
async function fill(label: string, value: string) {
await flush(() => {
const input = host.querySelector(`[aria-label="${label}"]`)!;
const prototype =
input.tagName === 'TEXTAREA'
? browser.HTMLTextAreaElement.prototype
: browser.HTMLInputElement.prototype;
Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value);
input.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event);
});
}
async function mount(agents: ResearchAgentRecord[] = []) {
root = createRoot(host);
await flush(() =>
root!.render(
createElement(
router.MemoryRouter,
{ initialEntries: [`/research/agents?projectId=${projectId}`] },
createElement(Page)
)
)
);
await flush(() => reply(pending(), { agents }));
}
async function draft() {
await fill('Agent name', 'Research worker');
await fill('Allowed backtest IDs', backtestId);
}
beforeAll(async () => {
for (const [name, value] of Object.entries({
window: browser,
document: browser.document,
IS_REACT_ACT_ENVIRONMENT: true,
})) {
Object.defineProperty(globalThis, name, { configurable: true, writable: true, value });
}
({ createRoot } = await import('react-dom/client'));
router = await import('react-router-dom');
({ ResearchAgentsPage: Page } = await import(
'../../apps/stock/web-app/src/features/research/ResearchAgentsPage'
));
({ researchAgentsApi: api } = await import(
'../../apps/stock/web-app/src/features/research/services/researchAgentsApi'
));
});
beforeEach(() => {
calls.length = 0;
host = browser.document.createElement('div') as unknown as HTMLDivElement;
browser.document.body.append(host as never);
browser.fetch = ((input: RequestInfo | URL, init?: RequestInit) =>
new Promise<Response>((resolve, reject) => {
calls.push({
path: new URL(String(input)).pathname,
method: init?.method ?? 'GET',
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
resolve,
reject,
settled: false,
});
})) as unknown as typeof browser.fetch;
});
afterEach(async () => {
if (root) {
await flush(() => root!.unmount());
}
root = undefined;
host.remove();
});
afterAll(() => {
browser.happyDOM.abort();
for (const [name, descriptor] of globals) {
if (descriptor) {
Object.defineProperty(globalThis, name, descriptor);
} else {
Reflect.deleteProperty(globalThis, name);
}
}
});
test('explicit scoped creation posts one bounded policy, shows credential once and never starts work', async () => {
await mount();
expect(host.textContent).toContain('No research agents configured.');
expect(
(host.querySelector('[aria-label="Allowed project IDs"]') as HTMLTextAreaElement).value
).toBe(projectId);
await draft();
await flush(() => {
button('Create credential').click();
button('Create credential').click();
});
const request = pending('', 'POST');
expect(request.body).toEqual({
name: 'Research worker',
allowedProjectIds: [projectId],
allowedBacktestIds: [backtestId],
limits: record().limits,
});
expect(calls.filter(call => call.method === 'POST')).toHaveLength(1);
await flush(() =>
reply(request, { agent: record(), token: 'fixture-generated-credential' }, 201)
);
expect(
(host.querySelector('[aria-label="New research token"]') as HTMLTextAreaElement).value
).toBe('fixture-generated-credential');
expect(button('Create credential').disabled).toBe(true);
expect(host.textContent).toContain('Revision 1');
expect(host.textContent).toContain('a'.repeat(64));
await flush(() => button('I have saved the credential').click());
expect(host.querySelector('[aria-label="New research token"]')).toBeNull();
expect(calls.some(call => /runs|experiments|paper/.test(call.path))).toBe(false);
});
test('malformed scope and invalid budgets preserve draft without writing', async () => {
await mount();
await draft();
await fill('Maximum active trials', '0');
await flush(() =>
host
.querySelector('form')!
.dispatchEvent(
new browser.Event('submit', { bubbles: true, cancelable: true }) as unknown as Event
)
);
expect(host.textContent).toContain('limits.maxActiveTrials');
expect(calls.some(call => call.method === 'POST')).toBe(false);
await fill('Maximum active trials', '1');
await fill('Allowed project IDs', 'not-a-uuid');
await flush(() => button('Create credential').click());
expect(host.textContent).toContain('allowedProjectIds');
expect(calls.some(call => call.method === 'POST')).toBe(false);
expect((host.querySelector('[aria-label="Agent name"]') as HTMLInputElement).value).toBe(
'Research worker'
);
});
test('ambiguous creation forbids blind retry and permits inspecting and disabling the retained credential', async () => {
await mount();
await draft();
await flush(() => button('Create credential').click());
const request = pending('', 'POST');
await flush(() => {
request.settled = true;
request.reject(new Error('Response lost'));
});
expect(host.textContent).toContain('token cannot be recovered');
expect(button('Create credential').disabled).toBe(true);
expect(button('I have checked the saved agents').disabled).toBe(true);
await flush(() => button('I have checked the saved agents').click());
expect(button('Create credential').disabled).toBe(true);
await flush(() => button('Create credential').click());
expect(calls.filter(call => call.method === 'POST')).toHaveLength(1);
await flush(() => button('Check saved agents').click());
await flush(() => reply(pending(), { error: 'List unavailable' }, 503));
expect(button('I have checked the saved agents').disabled).toBe(true);
await flush(() => button('Check saved agents').click());
expect(button('I have checked the saved agents').disabled).toBe(true);
await flush(() => reply(pending(), { agents: [record()] }));
expect(button('I have checked the saved agents').disabled).toBe(false);
await flush(() => button('Disable Research worker').click());
expect(pending(`/${encodeURIComponent(agentId)}`, 'PATCH').body).toEqual({
expectedRevision: 1,
enabled: false,
});
await flush(() =>
reply(pending(`/${encodeURIComponent(agentId)}`, 'PATCH'), {
agent: record({ enabled: false, revision: 2 }),
})
);
expect(host.textContent).toContain('Disabled');
expect(button('Create credential').disabled).toBe(true);
await flush(() => button('I have checked the saved agents').click());
expect(button('Create credential').disabled).toBe(false);
});
test('failed list is explicit and refresh recovers; obsolete budget response cannot replace refreshed state', async () => {
await mount([record()]);
await flush(() => button('Check budget for Research worker').click());
const old = pending(`/${encodeURIComponent(agentId)}/budget`);
await flush(() => button('Refresh agents').click());
await flush(() => reply(pending(), { error: 'Store unavailable' }, 503));
expect(host.textContent).toContain('Store unavailable');
expect(host.textContent).not.toContain('No research agents configured');
await flush(() => button('Refresh agents').click());
await flush(() => reply(pending(), { agents: [record()] }));
await flush(() => reply(old, { agent: record(), activeTrials: 1, remainingActiveTrials: 0 }));
expect(host.textContent).not.toContain('Active trials:');
await flush(() => button('Check budget for Research worker').click());
await flush(() =>
reply(pending(`/${encodeURIComponent(agentId)}/budget`), {
agent: record(),
activeTrials: 1,
remainingActiveTrials: 0,
})
);
expect(host.textContent).toContain('Active trials: 1; available slots: 0');
});
test('policy conflict refreshes rather than overwriting the newer revision', async () => {
await mount([record()]);
await flush(() => button('Disable Research worker').click());
await flush(() =>
reply(pending(`/${encodeURIComponent(agentId)}`, 'PATCH'), { error: 'Revision changed' }, 409)
);
expect(host.textContent).toContain('Refresh to verify');
await flush(() => reply(pending(), { agents: [record({ revision: 3, enabled: false })] }));
expect(host.textContent).toContain('Revision 3');
expect(calls.filter(call => call.method === 'PATCH')).toHaveLength(1);
});
test('budget identity/capacity and update identity/revision mismatches reject', async () => {
const budget = api.budget(agentId);
reply(pending(`/${encodeURIComponent(agentId)}/budget`), {
agent: record(),
activeTrials: 1,
remainingActiveTrials: 1,
});
await expect(budget).rejects.toThrow('capacity mismatch');
const update = api.update(agentId, { expectedRevision: 1, enabled: false });
reply(pending(`/${encodeURIComponent(agentId)}`, 'PATCH'), {
agent: record({ revision: 1, enabled: false }),
});
await expect(update).rejects.toThrow('revision mismatch');
});
test('unmount fences late credential response', async () => {
await mount();
await draft();
await flush(() => button('Create credential').click());
const request = pending('', 'POST');
await flush(() => root!.unmount());
root = undefined;
await flush(() => reply(request, { agent: record(), token: 'fixture-late-credential' }, 201));
expect(host.textContent).toBe('');
});
test('per-agent budget request order fences older success and failure responses', async () => {
await mount([record()]);
const path = `/${encodeURIComponent(agentId)}/budget`;
const newerRequest = () => {
const value = calls
.filter(call => !call.settled && call.path === `/api/v2/research-agents${path}`)
.at(-1);
if (!value) {
throw new Error('Missing newer budget request');
}
return value;
};
await flush(() => button('Check budget for Research worker').click());
const olderSuccess = pending(path);
await flush(() => button('Check budget for Research worker').click());
const newestSuccess = newerRequest();
expect(newestSuccess).not.toBe(olderSuccess);
await flush(() =>
reply(newestSuccess, { agent: record(), activeTrials: 0, remainingActiveTrials: 1 })
);
await flush(() =>
reply(olderSuccess, { agent: record(), activeTrials: 1, remainingActiveTrials: 0 })
);
expect(host.textContent).toContain('Active trials: 0; available slots: 1');
await flush(() => button('Check budget for Research worker').click());
const olderFailure = pending(path);
await flush(() => button('Check budget for Research worker').click());
await flush(() =>
reply(newerRequest(), { agent: record(), activeTrials: 1, remainingActiveTrials: 0 })
);
await flush(() => reply(olderFailure, { error: 'Obsolete unavailable response' }, 503));
expect(host.textContent).toContain('Active trials: 1; available slots: 0');
expect(host.textContent).not.toContain('Obsolete unavailable response');
});

View file

@ -2,19 +2,19 @@ import { asFunction, asValue, createContainer as createDiContainer } from 'awili
import { afterEach, describe, expect, test } from 'bun:test';
import { ServiceContainerBuilder, type ServiceCradle } from '@stock-bot/di';
import type { StockAppConfig } from '@stock-bot/stock-config';
import { BacktestEngine } from '../../apps/stock/orchestrator/src/backtest/BacktestEngine';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
import { defaultRiskLimits } from '../../apps/stock/orchestrator/src/execution/model';
import { createRoutes } from '../../apps/stock/orchestrator/src/routes/create-routes';
import { createContainer } from '../../apps/stock/orchestrator/src/simple-container';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { config, logger, makeExecution } from '../fixtures/execution';
import { logger } from '../fixtures/execution';
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) await close();
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function compose(options: Parameters<typeof registerOrchestratorServices>[1] = {}) {
const container = await new ServiceContainerBuilder()
.withOptions({
@ -30,42 +30,44 @@ async function compose(options: Parameters<typeof registerOrchestratorServices>[
const services: OrchestratorServices = { logger };
container.register({ serviceContainer: asValue(services) });
await registerOrchestratorServices(container, options);
const runtime = services.custom!;
cleanup.push(async () => {
await runtime.BacktestRunner!.shutdown();
await runtime.ModeManager!.shutdown();
await runtime.StrategyManager!.shutdown();
await services.custom!.BacktestRunner!.shutdown();
await container.dispose();
});
return runtime;
return { services, container };
}
describe('research runtime composition admission', () => {
test.each([true, false])(
'legacy_paper_combination_rejected_before_prepare (initializeMode=%s)',
async initializeMode => {
describe('canonical research-only default composition', () => {
test.each(['paper', 'research-only'] as const)(
'%s refuses retired TypeScript financial execution before resolving services',
async role => {
let resolved = 0;
const container = createDiContainer<ServiceCradle>();
container.register({
serviceContainer: asFunction(() => {
resolved++;
throw new Error('Runtime services must not be resolved');
throw new Error('must not resolve');
}),
});
await expect(
registerOrchestratorServices(container, { useRustEngine: false, initializeMode })
).rejects.toThrow('TypeScript backtests require a research-only composition');
registerOrchestratorServices(container, { role, useRustEngine: false })
).rejects.toThrow('Legacy financial execution is retired');
expect(resolved).toBe(0);
}
);
test('unsafe application startup fails before connection setup', async () => {
const config = {
services: { orchestrator: { backtesting: { useRustEngine: false } } },
} as StockAppConfig;
await expect(createContainer(config)).rejects.toThrow('Unsupported runtime combination');
test('paper requires explicit canonical configuration before connections, including initializeMode false', async () => {
const container = createDiContainer<ServiceCradle>();
await expect(
registerOrchestratorServices(container, { role: 'paper', initializeMode: false })
).rejects.toThrow('explicit canonicalPaper');
await expect(
createContainer({ services: { orchestrator: { defaultMode: 'paper' } } } as StockAppConfig)
).rejects.toThrow('explicit canonicalPaper');
await expect(
createContainer({
services: { orchestrator: { backtesting: { useRustEngine: false } } },
} as StockAppConfig)
).rejects.toThrow('Legacy financial execution is retired');
});
test('unchecked role and backend options fail closed before service resolution', async () => {
const container = createDiContainer<ServiceCradle>();
for (const options of [
@ -82,70 +84,45 @@ describe('research runtime composition admission', () => {
).rejects.toThrow('role' in options ? 'Unsupported runtime role' : 'must be a boolean');
}
});
test('standalone_legacy_research_allowed without automatic paper initialization', async () => {
const runtime = await compose({
role: 'research-only',
useRustEngine: false,
allowSyntheticData: true,
syntheticSeed: 42,
});
expect(runtime.BacktestEngine).toBeInstanceOf(BacktestEngine);
expect(runtime.ModeManager!.getConfig()).toBeNull();
await runtime.ModeManager!.initializeMode(config);
const result = await runtime.BacktestEngine!.runBacktest(config);
expect(result.status).toBe('completed');
expect(result.trades.length).toBeGreaterThan(0);
expect(runtime.ModeManager!.getConfig()).toEqual(config);
});
test('research_only_paper_activation_denied through every exposed initializer', async () => {
const runtime = await compose({ role: 'research-only', useRustEngine: false });
const mode = runtime.ModeManager!;
const execution = runtime.ExecutionService!;
await mode.initializeMode(config);
const engine = mode.getTradingEngine();
const account = await execution.getAccount();
const paper = { mode: 'paper' as const, startingCapital: 123 };
let shutdowns = 0;
mode.on('shutdown', () => shutdowns++);
await expect(mode.initializeMode(paper)).rejects.toThrow('only permits backtest');
await expect(mode.transitionMode('backtest', 'paper', paper)).rejects.toThrow(
'only permits backtest'
test.each([{}, { role: 'research-only' as const }])(
'default and explicit research compose one canonical engine without any account/feed/mode gateway',
async options => {
const { services, container } = await compose(options);
expect(services.custom!.BacktestEngine).toBeInstanceOf(RustBacktestAdapter);
for (const key of [
'ModeManager',
'ExecutionService',
'MarketDataService',
'StrategyManager',
'PaperTradingManager',
'CanonicalPaperRuntime',
]) {
expect(services.custom).not.toHaveProperty(key);
expect(container.hasRegistration(key)).toBe(false);
}
const app = createRoutes(services);
expect(await (await app.request('/health')).json()).toMatchObject({
mode: 'research-only',
execution: 'canonical-research',
});
expect((await app.request('/api/recovery')).status).toBe(503);
for (const path of ['/api/orders', '/api/positions']) {
expect((await app.request(path, { method: 'POST' })).status).toBe(409);
}
expect(await (await app.request('/api/paper/readiness')).json()).toMatchObject({
configured: false,
active: false,
ready: false,
operatorHalted: true,
accountId: null,
});
}
);
test('cannot overlay the canonical graph on a legacy account runtime', async () => {
const container = createDiContainer<ServiceCradle>();
container.register({ serviceContainer: asValue({ logger, custom: { ExecutionService: {} } }) });
await expect(registerOrchestratorServices(container)).rejects.toThrow(
'fresh runtime composition'
);
await expect(execution.initialize(paper, engine)).rejects.toThrow('only permits backtest');
const live = {
mode: 'live' as const,
broker: 'ib',
accountId: 'not-a-real-account',
accountType: 'cash' as const,
riskLimits: { ...defaultRiskLimits },
};
await expect(mode.initializeMode(live)).rejects.toThrow('Live trading is disabled');
await expect(execution.initialize(live, engine)).rejects.toThrow('Live trading is disabled');
expect(shutdowns).toBe(0);
expect(mode.getTradingEngine()).toBe(engine);
expect(mode.getConfig()).toEqual(config);
expect(await execution.getAccount()).toEqual(account);
});
test('paper composition defaults to native and cannot be switched to a legacy shared mode', async () => {
const runtime = await compose({ initializeMode: false });
expect(runtime.BacktestEngine).toBeInstanceOf(RustBacktestAdapter);
await expect(runtime.ModeManager!.initializeMode(config)).rejects.toThrow('only permits paper');
await expect(
runtime.ExecutionService!.initialize(config, makeExecution().engine)
).rejects.toThrow('only permits paper');
expect(runtime.ModeManager!.getConfig()).toBeNull();
});
test('research-only native composition also forbids paper startup and activation', async () => {
const runtime = await compose({ role: 'research-only' });
expect(runtime.BacktestEngine).toBeInstanceOf(RustBacktestAdapter);
expect(runtime.ModeManager!.getConfig()).toBeNull();
await expect(
runtime.ModeManager!.initializeMode({ mode: 'paper', startingCapital: 10000 })
).rejects.toThrow('only permits backtest');
});
});

View file

@ -23,9 +23,35 @@ import {
import { buildExperimentPreview } from '../../apps/stock/web-api/src/services/experiment-input';
import { prepareChronologicalValidation } from '../../apps/stock/web-api/src/services/validation-preview';
import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
import { parseWalkForwardDetail } from '../../apps/stock/web-app/src/features/experiments/services/walkForwardApi';
import { nativeReplayFixture } from '../fixtures/native-replay';
import { walkForwardDataset } from '../fixtures/walk-forward';
test('saved walk-forward report preserves agent authorship across nested validation evidence', () => {
const value = document('reported');
if (!value.report) {
throw new Error('Reported fixture needs its immutable report');
}
const actor = 'agent:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
value.report.principal = actor;
for (const window of value.windows) {
if (!window.validation?.selection || !window.validation.report) {
throw new Error('Reported window needs its selection and report');
}
window.validation.selection.principal = actor;
window.validation.report.principal = actor;
}
const parsed = parseWalkForwardDetail(value);
expect(parsed.report?.principal).toBe(actor);
expect(parsed.windows.map(window => window.validation?.report?.principal)).toEqual([
actor,
actor,
]);
expect(() =>
parseWalkForwardDetail({ ...value, report: { ...value.report, principal: 'agent:operator' } })
).toThrow();
});
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
const keys = ['window', 'document', 'Event', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT'] as const;
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));

View file

@ -16,6 +16,7 @@ import {
} 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';
import { seedHistoricalRun } from '../fixtures/historical-run';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('catalog-draft-test');
@ -329,7 +330,10 @@ describe.skipIf(!url)('saved catalog backtest drafts on PostgreSQL', () => {
{ autoStart: false }
);
const receipt = { principal: 'operator' as const, key: 'legacy' };
const run = await f.api.createRun({ backtestId: legacy.id }, receipt);
await expect(f.api.createRun({ backtestId: legacy.id }, receipt)).rejects.toThrow(
'Legacy backtest execution is retired'
);
const run = await seedHistoricalRun(f.pool, f.api, { 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' });

View file

@ -12,6 +12,7 @@ import {
type BacktestRequest,
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { DatasetCatalogService } from '../../apps/stock/web-api/src/services/dataset-catalog.service';
import { seedHistoricalRun } from '../fixtures/historical-run';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('dataset-catalog-test');
@ -200,7 +201,7 @@ describe.skipIf(!url)('dataset catalog and selected-run submission on real Postg
}
});
test('missing, inconsistent, malformed and unsupported selected snapshots reject before any run/outbox is inserted', async () => {
test('legacy admission refuses missing, inconsistent, malformed and unsupported snapshots before any run/outbox is inserted', async () => {
const f = await fixture();
const saved = await f.api.createBacktest(
{ ...request(), config: { fastPeriod: 2, slowPeriod: 3 } },
@ -230,7 +231,9 @@ describe.skipIf(!url)('dataset catalog and selected-run submission on real Postg
saved.id,
{ ...request().config, datasetHash: 'e'.repeat(64) },
]);
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow('not found');
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow(
'Legacy backtest execution is retired'
);
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0);
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
0
@ -288,23 +291,20 @@ describe.skipIf(!url)('dataset catalog and selected-run submission on real Postg
const retained = await f.api.getBacktest(saved.id);
expect(retained!.endDate.toISOString()).toBe(manifest().endDate);
expect(retained!.config.datasetHash).toBe(hash);
expect((await f.api.createRun({ backtestId: saved.id })).dataset.requestedHash).toBe(hash);
expect(
(await seedHistoricalRun(f.pool, f.api, { backtestId: saved.id })).dataset.requestedHash
).toBe(hash);
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow(
'Legacy backtest execution is retired'
);
});
test('selected run snapshots commit atomically and same-key retry returns its original receipt before mutable definition validation', async () => {
test('historical selected snapshots and original receipts survive retired admission and later definition edits', async () => {
const f = await fixture();
await f.insert(hash, { manifest: manifest(), bars: [{}] });
const saved = await f.api.createBacktest(request(), { autoStart: false });
await f.pool.query(
`CREATE FUNCTION reject_dataset_outbox() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected outbox failure'; END $$; CREATE TRIGGER reject_dataset_outbox BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_dataset_outbox()`
);
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow(
'injected outbox failure'
);
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0);
await f.pool.query('DROP TRIGGER reject_dataset_outbox ON backtest_dispatch');
const submission = { principal: 'operator' as const, key: 'dataset-retry' };
const first = await f.api.createRun({ backtestId: saved.id }, submission);
const first = await seedHistoricalRun(f.pool, f.api, { backtestId: saved.id }, submission);
expect(first.dataset).toEqual({
requestedHash: hash,
pinnedHash: null,
@ -334,7 +334,7 @@ describe.skipIf(!url)('dataset catalog and selected-run submission on real Postg
{ ...request(), config: { dataSource: 'eod' } },
{ autoStart: false }
);
const run = await f.api.createRun({ backtestId: saved.id });
const run = await seedHistoricalRun(f.pool, f.api, { backtestId: saved.id });
expect(run.dataset).toEqual({
requestedHash: null,
pinnedHash: null,

View file

@ -10,10 +10,12 @@ import { HandlerRegistry } from '@stock-bot/handler-registry';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { Queue } from '@stock-bot/queue';
import { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest';
import {
backtestRequestFromDefinition,
parseBacktestRequest,
} from '@stock-bot/stock-config/backtest';
canonicalRunRequestSchema,
type CanonicalRunRequest,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
@ -28,6 +30,8 @@ import {
RunSubmissionConflictError,
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
import { canonicalSettings } from '../fixtures/canonical-research';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('durable-backtest-test');
@ -35,19 +39,23 @@ const url = process.env.PIPELINE_TEST_DATABASE_URL;
const redisUrl = process.env.BACKTEST_TEST_REDIS_URL;
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) await close();
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
async function until(check: () => Promise<boolean>, timeoutMs = 3_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (await check()) return;
if (await check()) {
return;
}
await sleep(20);
}
throw new Error('Timed out waiting for durable workflow');
}
async function fixture() {
async function fixture(historical = false) {
if (
!url ||
!new URL(url).pathname.startsWith('/stock_bot_safety') ||
@ -59,7 +67,11 @@ async function fixture() {
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` });
const pool = new Pool({
connectionString: url,
application_name: schema,
options: `-c search_path=${schema}`,
});
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
@ -96,7 +108,7 @@ async function fixture() {
);
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
@ -124,20 +136,23 @@ async function fixture() {
const api = new BacktestServiceV2({ postgres, logger }, async () => {
throw new Error('No HTTP execution dispatch allowed');
});
const definition = await api.createBacktest(
{
name: 'Durable fixture',
strategy: 'sma-crossover',
symbols: ['FIXTURE.TEST'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-03-15T00:00:00.000Z',
initialCapital: 100000,
config: { fastPeriod: 3, slowPeriod: 7, commission: 0, slippage: 0 },
},
{ autoStart: false }
);
// A response DTO includes nullable catalog markers; legacy input deliberately omits them.
const definitionInput = {
const legacyDefinition = historical
? await api.createBacktest(
{
name: 'Durable fixture',
strategy: 'sma-crossover',
symbols: ['FIXTURE.TEST'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-03-15T00:00:00.000Z',
initialCapital: 100000,
config: { fastPeriod: 3, slowPeriod: 7, commission: 0, slippage: 0 },
},
{ autoStart: false }
)
: undefined;
const canonical = historical ? undefined : await canonicalAdmissionFixture(pool, postgres, false);
const definition = canonical?.draft ?? legacyDefinition!;
const definitionInput = canonical?.definition ?? {
name: definition.name,
strategy: definition.strategy,
symbols: definition.symbols,
@ -146,6 +161,25 @@ async function fixture() {
initialCapital: definition.initialCapital,
config: definition.config,
};
// This raw insertion represents already accepted pre-cutover history. It is
// deliberately not exposed through a service or production admission switch.
const historicalRun = async (_request: { backtestId: string }) => {
if (!historical) {
throw new Error('Historical fixture only');
}
const runId = randomUUID();
const snapshot = backtestRequestFromDefinition(definitionInput, {
runId,
backtestId: definition.id,
});
await pool.query(
`INSERT INTO runs(id,backtest_id,run_number,request_snapshot)
SELECT $1,$2,COALESCE(MAX(run_number),0)+1,$3 FROM runs WHERE backtest_id=$2`,
[runId, definition.id, snapshot]
);
await pool.query('INSERT INTO backtest_dispatch(run_id) VALUES($1)', [runId]);
return { id: runId };
};
const repository = new PostgresBacktestRunRepository(postgres, 2_000);
const history = { reads: 0, unavailable: false };
const storage = {
@ -200,10 +234,27 @@ async function fixture() {
return worker;
};
const snapshot = async (runId: string) =>
BacktestConfigSchema.parse(
canonicalRunRequestSchema.parse(
(await pool.query('SELECT request_snapshot FROM runs WHERE id = $1', [runId])).rows[0]
.request_snapshot
);
const legacySnapshot = async (runId: string) =>
BacktestConfigSchema.parse(
(await pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0]
.request_snapshot
);
const report = async (request: CanonicalRunRequest): Promise<CanonicalRunResult> => ({
kind: 'canonical-result/v1',
runId: request.runId,
backtestId: request.backtestId,
status: 'completed',
completedAt: new Date().toISOString(),
executionTime: 1,
financialEngine: 'rust',
strategyExecution: 'typescript-retained-builtin/v1',
request,
...(await engine.runCanonical(request, async () => canonical!.dataset)),
});
const expire = async (runId: string) => {
await pool.query(
"UPDATE runs SET lease_expires_at = NOW() - INTERVAL '1 second' WHERE id = $1",
@ -224,6 +275,10 @@ async function fixture() {
dispatcher,
enqueueWorker,
snapshot,
legacySnapshot,
historicalRun,
report,
canonical,
expire,
history,
storage,
@ -246,7 +301,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
const original = await f.snapshot(runs[0]!.id);
await f.api.updateBacktest(f.definition.id, {
initialCapital: 12345,
config: { fastPeriod: 4, slowPeriod: 9 },
strategyParameters: { fastPeriod: 3, slowPeriod: 4 },
});
expect((await f.api.createRun({ backtestId: f.definition.id }, submission)).id).toBe(
runs[0]!.id
@ -282,17 +337,27 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
[f.definition.id, second.id].map(backtestId => f.api.createRun({ backtestId }, submission))
);
try {
// Both parent-row locks are held, neither run exists yet, and both transactions
// are inside their INSERT. Releasing shared waiters forces the unique-index race.
// Both requests passed their initial receipt lookup and hold distinct parent
// locks. One waits inside INSERT; the other waits on the shared strategy
// family lock. The stale second receipt lookup must still conflict after
// the first transaction commits, rather than returning its unrelated run.
await until(
async () =>
(
await f.pool.query(
"SELECT count(*)::int AS count FROM pg_locks WHERE locktype = 'advisory' AND classid = 40303 AND objid = $1 AND NOT granted",
[barrierKey]
"SELECT count(*)::int AS count FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'",
[f.schema]
)
).rows[0].count === 2
);
expect(
(
await f.pool.query(
"SELECT count(*)::int AS count FROM pg_locks WHERE locktype='advisory' AND classid=40303 AND objid=$1 AND NOT granted",
[barrierKey]
)
).rows[0].count
).toBe(1);
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
} finally {
await barrier.query('SELECT pg_advisory_unlock(40303, $1)', [barrierKey]);
@ -313,7 +378,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
);
});
test('different principals can reuse keys; concurrent distinct and legacy submissions preserve run numbering', async () => {
test('different principals can reuse keys; concurrent distinct and unkeyed submissions preserve run numbering', async () => {
const f = await fixture();
const runs = await Promise.all([
f.api.createRun({ backtestId: f.definition.id }, { principal: 'operator', key: 'shared' }),
@ -354,7 +419,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
});
test('save_only route honors autoStart; authenticated keyed submissions return202/Location or409', async () => {
test('save_only catalog route requires explicit false; authenticated keyed submissions return202/Location or409', async () => {
const f = await fixture();
const app = new Hono();
createHttpSecurity({ disabled: true, environment: 'test' }).mount(app);
@ -387,11 +452,14 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
expect(response.headers.get('Location')).toBe(`/api/v2/runs/${run.id}`);
expect((await (await post({ speedMultiplier: null })).json()).id).toBe(run.id);
expect((await post({ speedMultiplier: 2 })).status).toBe(409);
const legacy = await app.request('/api/v2/backtests', {
const saveOnly = await app.request('/api/v2/backtests', {
method: 'POST',
body: JSON.stringify({ ...body, autoStart: undefined }),
});
expect(await f.api.listRuns((await legacy.json()).id)).toHaveLength(1);
expect(saveOnly.status).toBe(400);
expect((await f.pool.query('SELECT count(*)::int AS count FROM backtests')).rows[0].count).toBe(
2
);
});
test('cookie renewal and admin bearer replay the same operator submission while service keys are separate', async () => {
@ -442,9 +510,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
});
test('a lease expiring during snapshot insertion cannot pin or leave an orphan snapshot', async () => {
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const config = await f.snapshot(run.id);
const f = await fixture(true);
const run = await f.historicalRun({ backtestId: f.definition.id });
const config = await f.legacySnapshot(run.id);
const dataset = await loadDataset(f.storage, config);
await f.pool
.query(`CREATE FUNCTION delay_snapshot() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
@ -461,51 +529,40 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
.dataset_hash
).toBeNull();
});
test('prepared snapshots survive owner loss and replay through JSONB without provider reads', async () => {
test('retained canonical inputs survive owner loss and replay without provider reads', async () => {
const f = await fixture();
const parameters = {
...f.definition.config,
dataFrequency: '1d',
dataPolicy: { adjustment: 'raw', timestamp: 'utc-session-date' },
};
await f.api.updateBacktest(f.definition.id, { config: parameters });
const first = await f.runner.runQueued(
(await f.api.createRun({ backtestId: f.definition.id })).id
);
const baseline = (await f.api.getRunResults(first.runId))!;
expect(baseline.config.parameters).toEqual(parameters);
const first = await f.api.createRun({ backtestId: f.definition.id });
await f.runner.runQueued(first.id);
const baseline = await f.api.getRunResults(first.id);
const run = await f.api.createRun({ backtestId: f.definition.id });
const old = await f.repository.start(await f.snapshot(run.id));
const frozen = await f.repository.loadDataset(
const old = await f.repository.startCanonical(await f.snapshot(run.id));
const frozen = await f.repository.loadCanonicalDataset(
run.id,
old.attemptId,
baseline.config.dataset!.hash
f.canonical!.dataset.manifest.hash
);
expect(frozen?.bars).toHaveLength(70);
await f.expire(run.id);
await expect(f.repository.loadDataset(run.id, old.attemptId)).rejects.toBeInstanceOf(
BacktestLeaseLostError
);
await expect(f.repository.freezeDataset(run.id, old.attemptId, frozen!)).rejects.toBeInstanceOf(
BacktestLeaseLostError
);
const reads = f.history.reads;
await expect(
f.repository.loadCanonicalDataset(run.id, old.attemptId, frozen.manifest.hash)
).rejects.toBeInstanceOf(BacktestLeaseLostError);
f.history.unavailable = true;
await f.dispatcher.tick();
await f.runner.runQueued(run.id);
const replay = (await f.api.getRunResults(run.id))!;
expect(f.history.reads).toBe(reads);
expect(replay.config.dataset).toEqual(baseline.config.dataset);
expect(replay.config.parameters).toEqual(parameters);
expect(replay.trades).toEqual(baseline.trades);
expect(replay.metrics).toEqual(baseline.metrics);
const replay = await f.api.getRunResults(run.id);
if (!baseline || !replay || !('financial' in baseline) || !('financial' in replay)) {
throw new Error('Canonical results required');
}
expect(f.history.reads).toBe(0);
expect(replay.financial.projection.valuation).toEqual(baseline.financial.projection.valuation);
expect(replay.financial.projection.fills).toEqual(baseline.financial.projection.fills);
expect(replay.analytics).toEqual(baseline.analytics);
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(1);
});
test('snapshot insertion and the run pointer roll back together; frozen inputs cannot be replaced', async () => {
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const config = await f.snapshot(run.id);
const f = await fixture(true);
const run = await f.historicalRun({ backtestId: f.definition.id });
const config = await f.legacySnapshot(run.id);
const claim = await f.repository.start(config);
const dataset = await loadDataset(f.storage, config);
await f.pool
@ -536,9 +593,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
});
test('cancellation after snapshot insertion aborts preparation and rolls back the run pointer and payload', async () => {
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const config = await f.snapshot(run.id);
const f = await fixture(true);
const run = await f.historicalRun({ backtestId: f.definition.id });
const config = await f.legacySnapshot(run.id);
const claim = await f.repository.start(config);
const dataset = await loadDataset(f.storage, config);
const controller = new AbortController();
@ -549,10 +606,14 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
work(
new Proxy(client, {
get(target, key) {
if (key !== 'query') return Reflect.get(target, key);
if (key !== 'query') {
return Reflect.get(target, key);
}
return async (sql: string, params?: unknown[]) => {
const result = await target.query(sql, params);
if (sql.startsWith('INSERT INTO backtest_datasets')) controller.abort(reason);
if (sql.startsWith('INSERT INTO backtest_datasets')) {
controller.abort(reason);
}
return result;
};
},
@ -574,9 +635,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
});
test('restored snapshots are revalidated rather than trusted by their content-addressed key', async () => {
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const config = await f.snapshot(run.id);
const f = await fixture(true);
const run = await f.historicalRun({ backtestId: f.definition.id });
const config = await f.legacySnapshot(run.id);
const claim = await f.repository.start(config);
const dataset = await loadDataset(f.storage, config);
// Model corrupt historical storage at initial insertion; retained evidence cannot be edited.
@ -595,14 +656,15 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
await expect(f.repository.loadDataset(run.id, claim.attemptId)).rejects.toThrow('hash/content');
await f.expire(run.id);
await f.dispatcher.tick();
await expect(f.runner.runQueued(run.id)).rejects.toThrow('hash/content');
expect((await f.runner.runQueued(run.id)).status).toBe('failed');
expect((await f.api.getRun(run.id))?.error).toContain('Legacy backtest execution is retired');
expect((await f.api.getRun(run.id))?.status).toBe('failed');
expect(await f.api.getRunResults(run.id)).toBeNull();
expect(f.history.reads).toBe(reads);
});
test('a missing retained dataset fails a historical request without provider fallback', async () => {
const f = await fixture();
const f = await fixture(true);
const runId = randomUUID();
const snapshot = backtestRequestFromDefinition(
{ ...f.definitionInput, config: { ...f.definition.config, datasetHash: 'f'.repeat(64) } },
@ -615,56 +677,38 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
);
await f.pool.query('INSERT INTO backtest_dispatch(run_id) VALUES ($1)', [runId]);
f.history.unavailable = true;
await expect(f.runner.runQueued(runId)).rejects.toThrow('Frozen dataset not found');
expect((await f.runner.runQueued(runId)).status).toBe('failed');
expect((await f.api.getRun(runId))?.error).toContain('Legacy backtest execution is retired');
expect(f.history.reads).toBe(0);
expect((await f.api.getRun(runId))?.status).toBe('failed');
expect(await f.api.getRunResults(runId)).toBeNull();
});
test('an explicit dataset replay rejects a different listing or date range', async () => {
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
await f.runner.runQueued(run.id);
const result = (await f.api.getRunResults(run.id))!;
await expect(
f.runner.runBacktest({
...(await f.snapshot(run.id)),
runId: undefined,
endDate: '2024-03-16T00:00:00.000Z',
datasetHash: result.config.dataset!.hash,
})
).rejects.toThrow('does not match');
});
test('API acceptance uses the runner contract before writing a run or dispatch intent', async () => {
test('canonical admission rejects template ranges inconsistent with its retained dataset', async () => {
const f = await fixture();
await expect(
f.api.updateBacktest(f.definition.id, { config: { commission: -1 } })
).rejects.toThrow('commission');
expect((await f.api.getBacktest(f.definition.id))?.config).toEqual(f.definition.config);
// Model malformed historical configuration that bypassed today's API validator.
await f.pool.query('UPDATE backtests SET config = $2::jsonb WHERE id = $1', [
f.api.updateBacktest(f.definition.id, { endDate: '2025-01-01T00:00:00.000Z' })
).rejects.toThrow('trade bounds');
await f.pool.query('UPDATE backtests SET end_date=$2 WHERE id=$1', [
f.definition.id,
JSON.stringify({ ...f.definition.config, slippage: 0.2 }),
'2025-01-01T00:00:00.000Z',
]);
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow('slippage');
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow();
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
});
test('canonical admission rejects malformed policy and legacy pacing before run/outbox writes', async () => {
const f = await fixture();
await expect(
f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 7 })
).rejects.toThrow('maximum speed');
await f.pool.query('UPDATE backtests SET config=$2 WHERE id=$1', [
f.definition.id,
{ ...f.definition.config, canonical: { ...canonicalSettings, feeRate: '-1' } },
]);
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow();
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(0);
await f.pool.query('UPDATE backtests SET config = $2::jsonb WHERE id = $1', [
f.definition.id,
JSON.stringify(f.definition.config),
]);
const run = await f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 7 });
const snapshot = (
await f.pool.query('SELECT request_snapshot FROM runs WHERE id = $1', [run.id])
).rows[0].request_snapshot;
const expected = backtestRequestFromDefinition(f.definitionInput, {
runId: run.id,
backtestId: f.definition.id,
speedMultiplier: 7,
});
expect(parseBacktestRequest(snapshot)).toEqual(expected);
expect(snapshot.speed).toBe('5x');
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
});
test('acceptance commits run + immutable snapshot + intent atomically, with no Redis/HTTP dependency', async () => {
@ -691,8 +735,8 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
(await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id = $1', [run.id])).rows
).toHaveLength(1);
await f.api.updateBacktest(f.definition.id, {
config: { fastPeriod: 999 },
symbols: ['MUTATED.TEST'],
strategyParameters: { fastPeriod: 3, slowPeriod: 4 },
name: 'Mutated after admission',
});
// A fresh dispatcher models an API restart after SQL commit but before the first publish.
const restarted = new BacktestDispatcher(f.postgres, f.queue, logger);
@ -701,8 +745,12 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
f.enqueueWorker();
await until(async () => (await f.api.getRun(run.id))?.status === 'completed');
const result = await f.api.getRunResults(run.id);
expect(result?.config.symbols).toEqual(['FIXTURE.TEST']);
expect(result?.config.parameters.fastPeriod).toBe(3);
expect(result).toHaveProperty('kind', 'canonical-result/v1');
if (!result || !('request' in result)) {
throw new Error('Canonical result required');
}
expect(result.request.strategy.selection.instrumentId).toBe(f.definition.symbols[0]!);
expect(result.request.strategy.selection.parameters).toMatchObject({ fastPeriod: 2 });
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1);
});
@ -711,8 +759,8 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
const run = await f.api.createRun({ backtestId: f.definition.id });
const config = await f.snapshot(run.id);
const claims = await Promise.allSettled([
f.repository.start(config),
f.repository.start(config),
f.repository.startCanonical(config),
f.repository.startCanonical(config),
]);
expect(claims.filter(result => result.status === 'fulfilled')).toHaveLength(1);
expect(claims.filter(result => result.status === 'rejected')).toHaveLength(1);
@ -736,14 +784,13 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
test('expired owners cannot heartbeat, write progress/control/failure/cancellation, or commit a stale result', async () => {
const f = await fixture();
const baseline = await f.runner.runBacktest({
...(await f.snapshot((await f.api.createRun({ backtestId: f.definition.id })).id)),
});
const run = await f.api.createRun({ backtestId: f.definition.id });
const old = await f.repository.start(await f.snapshot(run.id));
const request = await f.snapshot(run.id);
const old = await f.repository.startCanonical(request);
const result = await f.report(request);
await f.expire(run.id);
await f.dispatcher.tick();
const replacement = await f.repository.start(await f.snapshot(run.id));
const replacement = await f.repository.startCanonical(await f.snapshot(run.id));
await expect(f.repository.heartbeat(run.id, old.attemptId)).rejects.toBeInstanceOf(
BacktestLeaseLostError
);
@ -757,13 +804,12 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
BacktestLeaseLostError
);
await f.repository.fail(run.id, 'stale failure', old.attemptId);
const result = { ...baseline, runId: run.id };
await expect(f.repository.complete(result, old.attemptId)).rejects.toBeInstanceOf(
await expect(f.repository.completeCanonical(result, old.attemptId)).rejects.toBeInstanceOf(
BacktestLeaseLostError
);
expect((await f.api.getRun(run.id))?.status).toBe('running');
await f.repository.loadDataset(run.id, replacement.attemptId, baseline.config.dataset!.hash);
await f.repository.complete(result, replacement.attemptId);
await f.repository.loadCanonicalDataset(run.id, replacement.attemptId, request.datasetHash);
await f.repository.completeCanonical(result, replacement.attemptId);
expect(
(await f.pool.query('SELECT * FROM backtest_results WHERE run_id = $1', [run.id])).rows
).toHaveLength(1);
@ -773,7 +819,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const shortLease = new PostgresBacktestRunRepository(f.postgres, 300);
const claim = await shortLease.start(await f.snapshot(run.id));
const claim = await shortLease.startCanonical(await f.snapshot(run.id));
await sleep(200);
await shortLease.heartbeat(run.id, claim.attemptId);
await sleep(150);
@ -792,7 +838,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const shortLease = new PostgresBacktestRunRepository(f.postgres, 300);
const claim = await shortLease.start(await f.snapshot(run.id));
const claim = await shortLease.startCanonical(await f.snapshot(run.id));
const lock = await f.pool.connect();
let renewal: Promise<unknown> | undefined;
try {
@ -813,20 +859,13 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
test('cancellation wins against late completion and expires an abandoned cancelled owner truthfully', async () => {
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 claim = await f.repository.startCanonical(await f.snapshot(run.id));
const result = await f.report(await f.snapshot(run.id));
await f.api.cancelRun(run.id);
expect((await f.repository.heartbeat(run.id, claim.attemptId)).cancelRequested).toBe(true);
await expect(
f.repository.complete(
{
runId: run.id,
backtestId: f.definition.id,
status: 'completed',
completedAt: new Date().toISOString(),
} as never,
claim.attemptId
)
).rejects.toBeInstanceOf(BacktestCancelledError);
await expect(f.repository.completeCanonical(result, claim.attemptId)).rejects.toBeInstanceOf(
BacktestCancelledError
);
await f.expire(run.id);
await f.dispatcher.tick();
expect((await f.api.getRun(run.id))?.status).toBe('cancelled');
@ -837,7 +876,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
for (let attempt = 1; attempt <= 3; attempt++) {
await f.repository.start(await f.snapshot(run.id));
await f.repository.startCanonical(await f.snapshot(run.id));
await f.expire(run.id);
await f.dispatcher.tick();
expect((await f.api.getRun(run.id))?.status).toBe(attempt === 3 ? 'failed' : 'pending');
@ -874,7 +913,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
child.once('error', reject);
child.once('exit', code => {
clearTimeout(timeout);
if (code) reject(new Error(`Crash owner exited: ${code}`));
if (code) {
reject(new Error(`Crash owner exited: ${code}`));
}
});
});
expect((await f.api.getRun(run.id))?.status).toBe('running');
@ -934,7 +975,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
});
test('invalid persisted snapshots become failed instead of remaining stranded pending', async () => {
const f = await fixture();
const f = await fixture(true);
const run = { id: randomUUID() };
// A legacy malformed snapshot is inserted as found, not fabricated by editing retained evidence.
await f.pool.query(
@ -948,15 +989,15 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
});
test('migration replay preserves leased owners, backfills legacy pending snapshots, and fails ownerless legacy runs', async () => {
const f = await fixture();
const f = await fixture(true);
const pending = { id: randomUUID() };
await f.pool.query('INSERT INTO runs(id,backtest_id,run_number) VALUES ($1,$2,1)', [
pending.id,
f.definition.id,
]);
const active = await f.api.createRun({ backtestId: f.definition.id });
const oldActive = await f.api.createRun({ backtestId: f.definition.id });
const claim = await f.repository.start(await f.snapshot(active.id));
const active = await f.historicalRun({ backtestId: f.definition.id });
const oldActive = await f.historicalRun({ backtestId: f.definition.id });
const claim = await f.repository.start(await f.legacySnapshot(active.id));
await f.pool.query("UPDATE runs SET status = 'running' WHERE id = $1", [oldActive.id]);
const migration = readFileSync(
new URL('../../database/postgres/init/10-durable-backtest-dispatch.sql', import.meta.url),
@ -964,13 +1005,16 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
);
await f.pool.query(migration);
await f.pool.query(migration);
expect((await f.snapshot(pending.id)).startDate).toBe('2024-01-01T00:00:00.000Z');
expect((await f.legacySnapshot(pending.id)).startDate).toBe('2024-01-01T00:00:00.000Z');
expect(
(await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id = $1', [pending.id])).rows
).toHaveLength(1);
expect((await f.api.getRun(oldActive.id))?.status).toBe('failed');
expect((await f.repository.heartbeat(active.id, claim.attemptId)).cancelRequested).toBe(false);
await f.runner.runQueued(pending.id);
expect((await f.api.getRun(pending.id))?.status).toBe('completed');
expect((await f.api.getRun(pending.id))?.status).toBe('failed');
expect((await f.api.getRun(pending.id))?.error).toContain(
'Legacy backtest execution is retired'
);
});
});

View file

@ -30,6 +30,7 @@ const migrations = [
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
'28-research-agents.sql',
];
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {

View file

@ -8,10 +8,8 @@ import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/
import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
import type { PaperRuntime } from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
import {
BacktestConfigSchema,
type OrchestratorServices,
} from '../../apps/stock/orchestrator/src/types';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
import { logger } from '../fixtures/execution';
import { paperConfig, paperFixture, paperFrame } from '../fixtures/paper-runtime';
@ -131,6 +129,7 @@ describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
const services: OrchestratorServices = { logger, postgres: f.postgres };
container.register({ serviceContainer: asValue(services) });
await registerOrchestratorServices(container, {
role: 'paper',
canonicalPaper: config,
nativeExecutionTimeoutMs: 10000,
});
@ -153,36 +152,15 @@ describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
}
expect((await custom.CanonicalPaperRuntime!.status()).active).toBe(false);
const before = await f.snapshot();
const research = BacktestConfigSchema.parse({
mode: 'backtest',
strategy: 'sma-crossover',
symbols: ['RESEARCH.TEST'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-01-21T00:00:00.000Z',
initialCapital: 100000,
dataFrequency: '1d',
commission: 0,
slippage: 0,
config: { fastPeriod: 2, slowPeriod: 3 },
});
custom.StorageService!.getHistoricalBars = async () =>
Array.from({ length: 20 }, (_, i) => {
const close = 100 + Math.sin(i) * 5;
return {
symbol: 'RESEARCH.TEST',
source: 'eod' as const,
timestamp: new Date(Date.parse(research.startDate) + i * 86400000),
open: close,
high: close + 1,
low: close - 1,
close,
volume: 1000000,
};
});
expect((await custom.BacktestEngine!.runBacktest(research)).status).toBe('completed');
const research = await canonicalAdmissionFixture(f.pool, f.postgres);
custom.StorageService!.getHistoricalBars = async () => {
throw new Error('Canonical execution cannot query providers');
};
const run = await research.api.createRun({ backtestId: research.draft.id });
expect((await custom.BacktestRunner!.runQueued(run.id)).status).toBe('completed');
expect(await f.snapshot()).toEqual(before);
await expect(
registerOrchestratorServices(container, { canonicalPaper: config })
registerOrchestratorServices(container, { role: 'paper', canonicalPaper: config })
).rejects.toThrow('fresh runtime composition');
await expect(registerOrchestratorServices(container)).rejects.toThrow(
'fresh runtime composition'

View file

@ -0,0 +1,959 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { afterEach, describe, expect, test } from 'bun:test';
import { Hono } from 'hono';
import { Pool } from 'pg';
import { createHttpSecurity } from '@stock-bot/di';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import type {
CanonicalRunRequest,
CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
import { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes';
import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes';
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service';
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
import { researchGrantPolicy } from '../../apps/stock/web-api/src/services/research-agent-budget';
import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
import { ResearchService } from '../../apps/stock/web-api/src/services/research.service';
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
import { WalkForwardService } from '../../apps/stock/web-api/src/services/walk-forward.service';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
import { canonicalSettings } from '../fixtures/canonical-research';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
import { walkForwardDataset } from '../fixtures/walk-forward';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('experiments');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void>)[] = [];
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function fixture(poolMax = 4, withAgents = true, dataset = canonicalSmaFixture().dataset) {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Disposable safety database required');
}
const schema = 'stock_bot_safety_agents_' + randomUUID().replaceAll('-', '');
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({
connectionString: url,
application_name: schema,
max: poolMax,
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',
'07-fix-execution-time-type.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',
'19-canonical-research.sql',
'20-research-workspace.sql',
'21-run-reproduction.sql',
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
...(withAgents ? ['28-research-agents.sql'] : []),
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
);
}
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 container = { postgres, logger };
const api = new BacktestServiceV2(container);
const experiments = new ExperimentsService(container);
const repository = new PostgresBacktestRunRepository(postgres);
const catalog = new StrategyCatalogService(container);
const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!;
const version = await catalog.seedBuiltin('Retained SMA', pkg, 'seed');
await retainResearchDataset(pool, dataset);
const definition = {
name: 'Canonical API',
strategy: 'catalog',
strategyVersionId: version.id,
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
symbols: dataset.manifest.executionSeries.map(s => s.instrumentId),
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
initialCapital: 10000,
config: {
datasetHash: dataset.manifest.hash,
dataFrequency: dataset.manifest.series[0]!.interval,
canonical: canonicalSettings,
},
};
const draft = await api.createBacktest(definition, { autoStart: false });
const approve = async () => {
await catalog.reviewVersion(
version.id,
{ decision: 'approve', reason: 'Reviewed retained builtin' },
'operator'
);
return (await catalog.getVersionReviews(version.id)).at(-1)!;
};
const execute = async (id: string) => {
const engine = new RustBacktestAdapter({
logger,
storage: {
async getHistoricalBars() {
throw new Error('Canonical execution must never load provider data');
},
},
});
const runner = new BacktestRunner({
engine,
engineName: 'native',
repository: new PostgresBacktestRunRepository(postgres),
logger,
});
try {
await runner.runQueued(id);
} finally {
await runner.shutdown();
}
};
return {
pool,
postgres,
container,
agents: new ResearchAgentsService(container),
research: new ResearchService(container),
schema,
api,
experiments,
repository,
catalog,
pkg,
version,
draft,
definition,
dataset,
approve,
execute,
app: new Hono().route('/', createExperimentRoutes(container)),
};
}
const limits = {
maxActiveTrials: 2,
maxTrialsPerExperiment: 10,
maxBarEvaluationsPerExperiment: 10000,
maxAttemptWallMs: 60000,
maxAttempts: 2,
};
function required<T>(value: T | null | undefined): T {
if (value === null || value === undefined) {
throw new Error('Required fixture value is missing');
}
return value;
}
type Fixture = Awaited<ReturnType<typeof fixture>>;
const receipt = (principal: string = 'operator', key = randomUUID()) => ({ principal, key });
async function provision(f: Fixture, overrides: Partial<typeof limits> = {}) {
await f.approve();
const project = await f.research.createProject({ title: 'Agent research' }, 'operator');
const created = await f.agents.create({
name: 'Bounded researcher',
allowedProjectIds: [project.id],
allowedBacktestIds: [f.draft.id],
limits: { ...limits, ...overrides },
});
return { ...created, project };
}
async function preparation(
f: Fixture,
name = 'Agent search',
backtestId = f.draft.id,
grid = { fastPeriod: [1, 2] }
) {
const input = { backtestId, name, grid };
const preview = await f.experiments.preview(input);
return { ...input, previewHash: preview.previewHash };
}
async function requestFor(f: Fixture, id: string): Promise<CanonicalRunRequest> {
return (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [id])).rows[0]
.request_snapshot;
}
async function totals(f: Fixture) {
return (
await f.pool.query(
'SELECT (SELECT count(*)::int FROM runs) runs,(SELECT count(*)::int FROM research_experiments) experiments,(SELECT count(*)::int FROM backtest_dispatch) dispatch'
)
).rows[0];
}
function http(f: Fixture) {
const app = new Hono();
const security = createHttpSecurity({
adminToken: 'operator-test-secret-12345678901234567890',
serviceToken: 'service-test-secret-123456789012345678901',
environment: 'test',
resolveResearchCredential: request => f.agents.authenticate(request),
});
security.mount(app);
app.route('/', createResearchAgentRoutes(f.container, security.researchEnabled));
app.route('/', createExperimentRoutes(f.container));
app.route('/', createResearchRoutes(f.container));
return (path: string, token: string, body?: unknown, key?: string) =>
app.request(path, {
method: body === undefined ? 'GET' : 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
...(key ? { 'Idempotency-Key': key } : {}),
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
}
describe.skipIf(!url)('authoritative research principals and budgets', () => {
test('operator provisioning stores only a hash; real mounted authentication, AI authorship and scoped writes', async () => {
const f = await fixture(1),
p = await provision(f);
const request = http(f);
expect(p.token.startsWith('sb-research.')).toBe(true);
const stored = (await f.pool.query('SELECT * FROM research_agents WHERE id=$1', [p.agent.id]))
.rows[0];
expect(JSON.stringify(stored)).not.toContain(p.token);
expect(stored.token_hash).toHaveLength(64);
const info = await request('/api/v2/research-agent/budget', p.token);
expect(info.status).toBe(200);
expect((await info.json()).activeTrials).toBe(0);
const submitted = await request(
`/api/v2/research-projects/${p.project.id}/hypotheses`,
p.token,
{ title: 'AI hypothesis', proposition: 'Test a bounded signal' }
);
expect(submitted.status).toBe(201);
const hypothesis = await submitted.json();
expect(JSON.stringify(hypothesis)).toContain(p.agent.id);
expect(JSON.stringify(hypothesis)).toContain('"contentOrigin":"ai"');
for (const contentOrigin of ['human', 'unknown']) {
const bad = await request(`/api/v2/research-projects/${p.project.id}/hypotheses`, p.token, {
title: 'False provenance',
proposition: 'not human',
contentOrigin,
});
expect(bad.status).toBe(403);
}
const denied = await request('/api/v2/research-projects', p.token, { title: 'unauthorized' });
expect(denied.status).toBe(403);
const foreign = await f.research.createProject({ title: 'Other project' }, 'operator');
expect(
(
await request(`/api/v2/research-projects/${foreign.id}/hypotheses`, p.token, {
title: 'Wrong',
proposition: 'Wrong project',
})
).status
).toBe(403);
expect((await request('/api/v2/research-agents', p.token)).status).toBe(403);
expect(
(
await f.pool.query('SELECT count(*)::int n FROM research_agent_audit WHERE agent_id=$1', [
p.agent.id,
])
).rows[0].n
).toBeGreaterThan(2);
const clone = await f.catalog.cloneVersion(
f.version.id,
{ name: 'Agent candidate' },
p.agent.id as `agent:${string}`,
randomUUID()
);
expect(String(clone.strategy.ownerPrincipal)).toBe(p.agent.id);
expect(clone.version.origin).toBe('candidate');
const candidate = await f.api.createBacktest(
{ ...f.definition, strategyVersionId: clone.version.id, name: 'Candidate cannot execute' },
{ autoStart: false }
);
await expect(
f.agents.update(p.agent.id, { expectedRevision: 1, allowedBacktestIds: [candidate.id] })
).rejects.toThrow('approved canonical templates');
expect((await totals(f)).runs).toBe(0);
await f.agents.update(p.agent.id, { expectedRevision: 1, enabled: false });
expect((await request('/api/v2/research-agent/budget', p.token)).status).toBe(401);
expect((await f.agents.budget(p.agent.id, true)).agent.enabled).toBe(false);
});
test('same receipt is exact after quota changes; capacity and grant errors are typed and atomic', async () => {
const f = await fixture(1),
p = await provision(f);
const submission = await preparation(f),
key = randomUUID();
const run = await f.experiments.submit(submission, receipt(p.agent.id, key));
expect(run.trials).toHaveLength(2);
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(2);
const policies = (
await f.pool.query(
'SELECT request_snapshot,research_limits,research_agent_id FROM runs ORDER BY run_number'
)
).rows;
for (const row of policies) {
expect(row.research_agent_id).toBe(p.agent.id);
expect(row.research_limits).toEqual(limits);
expect(
await f.pool
.query('SELECT research_grant_policy($1::jsonb) AS p', [row.request_snapshot])
.then(r => r.rows[0].p)
).toEqual(researchGrantPolicy(row.request_snapshot));
}
await f.agents.update(p.agent.id, {
expectedRevision: 1,
limits: { ...limits, maxActiveTrials: 1 },
allowedBacktestIds: [],
});
expect((await f.experiments.submit(submission, receipt(p.agent.id, key))).id).toBe(run.id);
const before = await totals(f);
const denied = await http(f)('/api/v2/experiments', p.token, submission, randomUUID());
expect(denied.status).toBe(403);
expect(await totals(f)).toEqual(before);
await f.agents.update(p.agent.id, { expectedRevision: 2, allowedBacktestIds: [f.draft.id] });
expect((await http(f)('/api/v2/experiments', p.token, submission, randomUUID())).status).toBe(
429
);
expect(await totals(f)).toEqual(before);
await f.agents.update(p.agent.id, { expectedRevision: 3, enabled: false });
expect((await http(f)('/api/v2/experiments', p.token, submission, key)).status).toBe(401);
await expect(f.experiments.submit(submission, receipt(p.agent.id, key))).rejects.toThrow(
'disabled'
);
});
test('concurrent different-parent grids cannot oversubscribe; failure releases durable capacity and ownership is immutable', async () => {
const f = await fixture(),
p = await provision(f);
const other = await f.api.createBacktest(
{ ...f.definition, name: 'Second template' },
{ autoStart: false }
);
await f.agents.update(p.agent.id, {
expectedRevision: 1,
allowedBacktestIds: [f.draft.id, other.id],
});
const [a, b] = await Promise.all([preparation(f), preparation(f, 'Other', other.id)]);
const race = await Promise.allSettled([
f.experiments.submit(a, receipt(p.agent.id)),
f.experiments.submit(b, receipt(p.agent.id)),
]);
expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1);
expect(race.filter(r => r.status === 'rejected')).toHaveLength(1);
const failed = race.find(r => r.status === 'rejected');
if (failed?.status !== 'rejected') {
throw new Error('Missing failure');
}
expect(failed.reason.message).toContain('research_budget:');
expect(await totals(f)).toEqual({ runs: 2, experiments: 1, dispatch: 2 });
const winner = race.find(r => r.status === 'fulfilled');
if (winner?.status !== 'fulfilled') {
throw new Error('Missing winner');
}
const first = winner.value.trials[0]!;
const claim = await f.repository.startCanonical(await requestFor(f, required(first.runId)));
expect(claim.executionDeadlineAt).toBeGreaterThan(Date.now());
await expect(
f.pool.query('UPDATE runs SET research_agent_id=NULL WHERE id=$1', [required(first.runId)])
).rejects.toThrow('immutable');
await expect(
f.pool.query(
"UPDATE runs SET research_limits=jsonb_set(research_limits,'{maxAttempts}','3') WHERE id=$1",
[required(first.runId)]
)
).rejects.toThrow('immutable');
await expect(
f.pool.query('UPDATE runs SET attempt_number=0 WHERE id=$1', [required(first.runId)])
).rejects.toThrow('cannot be reset');
await f.repository.fail(required(first.runId), 'controlled failure', claim.attemptId);
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1);
const single = await preparation(f, 'Replacement', f.draft.id, { fastPeriod: [1] });
await f.experiments.submit(single, receipt(p.agent.id));
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(2);
await f.experiments.cancel(winner.value.id);
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1);
});
test('deadline and attempts survive lease renewal/recovery and revocation; no expired completion', async () => {
const f = await fixture(),
p = await provision(f, { maxAttemptWallMs: 100, maxAttempts: 1 });
const run = await f.experiments.submit(
await preparation(f, 'Deadline', f.draft.id, { fastPeriod: [1] }),
receipt(p.agent.id)
);
const id = required(run.trials[0]!.runId);
await expect(
f.pool.query("UPDATE runs SET status='running' WHERE id=$1", [id])
).rejects.toThrow('complete bounded claim');
const claim = await f.repository.startCanonical(await requestFor(f, id));
const frozen = (await f.pool.query('SELECT research_deadline_at FROM runs WHERE id=$1', [id]))
.rows[0].research_deadline_at;
await f.pool.query(
"UPDATE runs SET lease_expires_at=clock_timestamp()+interval '1 hour' WHERE id=$1",
[id]
);
await expect(
f.pool.query(
"UPDATE runs SET research_deadline_at=clock_timestamp()+interval '1 hour' WHERE id=$1",
[id]
)
).rejects.toThrow('server-owned');
await f.agents.update(p.agent.id, { expectedRevision: 1, enabled: false });
await f.pool.query('SELECT pg_sleep(0.12)');
await expect(
f.pool.query("UPDATE runs SET status='completed',completed_at=NOW() WHERE id=$1", [id])
).rejects.toThrow('wall time');
const dispatcher = new BacktestDispatcher(
f.postgres,
{ add: async () => ({}) as never },
logger
);
await dispatcher.tick();
await dispatcher.shutdown();
const saved = (await f.pool.query('SELECT * FROM runs WHERE id=$1', [id])).rows[0];
expect(saved.status).toBe('failed');
expect(saved.error).toContain('wall time');
expect(saved.research_deadline_at).toEqual(frozen);
expect(saved.attempt_number).toBe(1);
expect((await f.agents.budget(p.agent.id, true)).activeTrials).toBe(0);
await f.agents.update(p.agent.id, { expectedRevision: 2, enabled: true });
await expect(
f.experiments.retryTrial(
run.id,
id,
{ expectedAttemptNumber: 1, expectedRetryCount: 0 },
receipt(p.agent.id)
)
).rejects.toThrow('attempt budget exhausted');
expect(
(await f.pool.query('SELECT count(*)::int n FROM experiment_trial_retries')).rows[0].n
).toBe(0);
expect(claim.executionDeadlineAt).toBeDefined();
});
test('ordinary native accounting is unchanged; first migration and reapply preserve saved economic evidence and leases', async () => {
const f = await fixture(4, false);
await f.approve();
const input = await preparation(f);
const before = await f.experiments.submit(input, receipt());
await f.execute(required(before.trials[0]!.runId));
const pending = required(before.trials[1]!.runId);
const claim = await f.repository.startCanonical(await requestFor(f, pending));
const snapshot = async () => ({
runs: (
await f.pool.query(
"SELECT to_jsonb(r)-ARRAY['research_agent_id','research_limits','research_deadline_at'] AS r FROM runs r ORDER BY id"
)
).rows,
results: (await f.pool.query('SELECT * FROM backtest_results ORDER BY run_id')).rows,
experiments: (await f.pool.query('SELECT * FROM research_experiments ORDER BY id')).rows,
dispatch: (await f.pool.query('SELECT * FROM backtest_dispatch ORDER BY run_id')).rows,
});
const original = await snapshot();
const sql = readFileSync(
new URL('../../database/postgres/init/28-research-agents.sql', import.meta.url),
'utf8'
);
await f.pool.query(sql);
expect(await snapshot()).toEqual(original);
await f.pool.query(sql);
expect(await snapshot()).toEqual(original);
expect(
(await f.pool.query('SELECT attempt_id FROM runs WHERE id=$1', [pending])).rows[0].attempt_id
).toBe(claim.attemptId);
const p = await provision(f);
const agentRun = await f.experiments.submit(
await preparation(f, 'Native agent', f.draft.id, { fastPeriod: [1] }),
receipt(p.agent.id)
);
await f.execute(required(agentRun.trials[0]!.runId));
const result = await f.api.getRunResults(required(agentRun.trials[0]!.runId));
expect(result && 'kind' in result ? result.kind : null).toBe('canonical-result/v1');
expect(result?.status).toBe('completed');
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(0);
const audit = (await f.pool.query('SELECT * FROM research_agent_audit ORDER BY id')).rows;
await f.pool.query(sql);
expect((await f.pool.query('SELECT * FROM research_agent_audit ORDER BY id')).rows).toEqual(
audit
);
await expect(f.pool.query('DELETE FROM research_agent_audit')).rejects.toThrow(
'cannot be rewritten'
);
});
test('manual retry reacquires capacity once and lifetime attempts remain bounded across recovery', async () => {
const f = await fixture(),
p = await provision(f, { maxActiveTrials: 1, maxAttempts: 2 });
const submitted = await f.experiments.submit(
await preparation(f, 'Retry', f.draft.id, { fastPeriod: [1] }),
receipt(p.agent.id)
);
const id = required(submitted.trials[0]!.runId),
request = await requestFor(f, id),
first = await f.repository.startCanonical(request);
await f.pool.query(
"UPDATE runs SET lease_expires_at=clock_timestamp()-interval '1 second' WHERE id=$1",
[id]
);
const dispatcher = new BacktestDispatcher(
f.postgres,
{ add: async () => ({}) as never },
logger
);
await dispatcher.tick();
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1);
const second = await f.repository.startCanonical(request);
expect(second.executionDeadlineAt).toBeGreaterThanOrEqual(first.executionDeadlineAt!);
await f.repository.fail(id, 'Second attempt failed', second.attemptId);
const before = await totals(f);
await expect(
f.experiments.retryTrial(
submitted.id,
id,
{ expectedAttemptNumber: 2, expectedRetryCount: 0 },
receipt(p.agent.id)
)
).rejects.toThrow('attempt budget exhausted');
expect(await totals(f)).toEqual(before);
expect(
(await f.pool.query('SELECT count(*)::int n FROM experiment_trial_retries')).rows[0].n
).toBe(0);
const next = await f.experiments.submit(
await preparation(f, 'Manual', f.draft.id, { fastPeriod: [1] }),
receipt(p.agent.id)
);
const nextId = required(next.trials[0]!.runId);
const claim = await f.repository.startCanonical(await requestFor(f, nextId));
await f.repository.fail(nextId, 'Retryable failure', claim.attemptId);
const key = randomUUID(),
intent = { expectedAttemptNumber: 1, expectedRetryCount: 0 };
await f.agents.update(p.agent.id, { expectedRevision: 1, allowedBacktestIds: [] });
await expect(
f.experiments.retryTrial(next.id, nextId, intent, receipt(p.agent.id, key))
).rejects.toThrow('Operator approval');
await f.agents.update(p.agent.id, { expectedRevision: 2, allowedBacktestIds: [f.draft.id] });
const retry = await f.experiments.retryTrial(next.id, nextId, intent, receipt(p.agent.id, key));
expect(String(retry.retry.principal)).toBe(p.agent.id);
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1);
await f.agents.update(p.agent.id, { expectedRevision: 3, allowedBacktestIds: [] });
expect(
(await f.experiments.retryTrial(next.id, nextId, intent, receipt(p.agent.id, key))).retry.id
).toBe(retry.retry.id);
await f.agents.update(p.agent.id, { expectedRevision: 4, enabled: false });
const resumed = await f.repository.startCanonical(await requestFor(f, nextId));
expect(resumed.executionDeadlineAt).toBeDefined();
await f.repository.fail(
nextId,
'Accepted bounded work still runs after token revocation',
resumed.attemptId
);
await dispatcher.shutdown();
});
test('cost scenarios and chronological/walk-forward phases retain exact baseline grants and bounded planned work', async () => {
const data = walkForwardDataset(),
f = await fixture(4, true, data.dataset),
p = await provision(f, { maxActiveTrials: 4 });
const costs = {
backtestId: f.draft.id,
name: 'Fees',
scenarios: [{ feeRate: '0.002', slippageRate: '0.001' }],
};
const preview = await f.experiments.previewCosts(costs);
const cost = await f.experiments.submitCosts(
{ ...costs, previewHash: preview.previewHash },
receipt(p.agent.id)
);
expect(cost.trials).toHaveLength(2);
await f.experiments.cancel(cost.id);
const validation = new ChronologicalValidationService(f.container),
walk = new WalkForwardService(f.container);
const input = {
backtestId: f.draft.id,
name: 'Validation',
grid: { fastPeriod: [1, 2] },
recipe: data.windows[0]!,
};
const prepared = await f.experiments.previewValidation(input);
const train = await validation.submit(
{ ...input, previewHash: prepared.previewHash },
receipt(p.agent.id)
);
await expect(
validation.select(train.id, { previewHash: prepared.previewHash }, receipt())
).rejects.toThrow('owning research principal');
for (const trial of train.phases[0].experiment!.trials) {
await f.execute(required(trial.runId));
}
await f.agents.update(p.agent.id, {
expectedRevision: 1,
limits: { ...limits, maxActiveTrials: 1 },
});
const selectKey = randomUUID();
await expect(
validation.select(
train.id,
{ previewHash: prepared.previewHash },
receipt(p.agent.id, selectKey)
)
).rejects.toThrow('research_budget:');
expect(
(
await f.pool.query('SELECT validation_selection FROM research_experiments WHERE id=$1', [
train.id,
])
).rows[0].validation_selection
).toBeNull();
expect(
(
await f.pool.query(
'SELECT count(*)::int n FROM research_experiments WHERE validation_parent_id=$1',
[train.id]
)
).rows[0].n
).toBe(0);
await f.agents.update(p.agent.id, {
expectedRevision: 2,
limits: { ...limits, maxActiveTrials: 4 },
});
const selected = await validation.select(
train.id,
{ previewHash: prepared.previewHash },
receipt(p.agent.id, selectKey)
);
expect(String(selected.receipt.principal)).toBe(p.agent.id);
for (const phase of selected.validation.phases.slice(1)) {
for (const trial of required(phase.experiment).trials) {
await f.execute(required(trial.runId));
}
}
const finalizeInput = {
previewHash: prepared.previewHash,
selectionHash: required(selected.validation.selection).selectionHash,
},
finalKey = randomUUID();
const sealed = await validation.finalize(
train.id,
finalizeInput,
receipt(p.agent.id, finalKey)
);
expect(String(required(sealed.validation.report).principal)).toBe(p.agent.id);
expect(
(await validation.finalize(train.id, finalizeInput, receipt(p.agent.id, finalKey))).receipt
).toEqual(sealed.receipt);
const walkInput = {
backtestId: f.draft.id,
name: 'Rolling',
grid: { fastPeriod: [1, 2] },
windows: data.windows,
};
const walkPreview = await walk.preview(walkInput);
await f.agents.update(p.agent.id, {
expectedRevision: 3,
limits: { ...limits, maxActiveTrials: 4, maxTrialsPerExperiment: 7 },
});
const before = await totals(f);
await expect(
walk.submit({ ...walkInput, previewHash: walkPreview.previewHash }, receipt(p.agent.id))
).rejects.toThrow('trial or observation budget');
expect(await totals(f)).toEqual(before);
await f.agents.update(p.agent.id, {
expectedRevision: 4,
limits: { ...limits, maxActiveTrials: 4 },
});
const series = await walk.submit(
{ ...walkInput, previewHash: walkPreview.previewHash },
receipt(p.agent.id)
);
expect(series.windows).toHaveLength(2);
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(4);
for (const window of series.windows) {
const member = required(window.validation);
for (const trial of required(member.phases[0].experiment).trials) {
await f.execute(required(trial.runId));
}
const selection = await validation.select(
member.id,
{ previewHash: member.previewHash },
receipt(p.agent.id)
);
for (const phase of selection.validation.phases.slice(1)) {
for (const trial of required(phase.experiment).trials) {
await f.execute(required(trial.runId));
}
}
await validation.finalize(
member.id,
{
previewHash: member.previewHash,
selectionHash: required(selection.validation.selection).selectionHash,
},
receipt(p.agent.id)
);
}
const reportKey = randomUUID(),
reportInput = { previewHash: walkPreview.previewHash };
const report = await walk.finalize(series.id, reportInput, receipt(p.agent.id, reportKey));
expect(String(required(report.walkForward.report).principal)).toBe(p.agent.id);
expect(
(await walk.finalize(series.id, reportInput, receipt(p.agent.id, reportKey))).receipt
).toEqual(report.receipt);
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(0);
}, 30000);
test('deadline is rechecked at result transaction commit after a valid native result and timely completed transition', async () => {
const f = await fixture(),
p = await provision(f, { maxAttemptWallMs: 1000 });
const run = await f.experiments.submit(
await preparation(f, 'Delayed commit', f.draft.id, { fastPeriod: [1] }),
receipt(p.agent.id)
);
const id = required(run.trials[0]!.runId),
request = await requestFor(f, id);
const engine = new RustBacktestAdapter({
logger,
storage: {
getHistoricalBars: async () => {
throw new Error('Provider forbidden');
},
},
});
let economic: Pick<CanonicalRunResult, 'financial' | 'analytics'>;
try {
economic = await engine.runCanonical(request, async () => f.dataset);
} finally {
await engine.shutdown();
}
const claim = await f.repository.startCanonical(request);
const result = {
kind: 'canonical-result/v1',
status: 'completed',
runId: id,
backtestId: request.backtestId,
request,
financialEngine: 'rust',
strategyExecution: 'typescript-retained-builtin/v1',
completedAt: new Date().toISOString(),
executionTime: 1,
...economic,
};
const client = await f.pool.connect();
try {
await client.query('BEGIN');
await client.query(
"UPDATE runs SET status='completed',progress=100,completed_at=NOW() WHERE id=$1 AND attempt_id=$2",
[id, claim.attemptId]
);
await client.query(
"INSERT INTO backtest_results(run_id,completed_at,execution_time,canonical_result,metrics,equity_curve,ohlc_data,trades,positions,analytics) VALUES($1,NOW(),1,$2::jsonb,'null','null','null','null','null','null')",
[id, result]
);
await client.query('SELECT pg_sleep(1.1)');
await expect(client.query('COMMIT')).rejects.toThrow(
'wall time exceeded before result commit'
);
} finally {
await client.query('ROLLBACK');
client.release();
}
expect((await f.pool.query('SELECT status FROM runs WHERE id=$1', [id])).rows[0].status).toBe(
'running'
);
expect(
(await f.pool.query('SELECT count(*)::int n FROM backtest_results WHERE run_id=$1', [id]))
.rows[0].n
).toBe(0);
await f.repository.fail(id, 'Budget expired while saving', claim.attemptId);
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(0);
});
test('foreign/disabled agent phase and retry receipts fail through service and direct SQL before any mutation', async () => {
const data = walkForwardDataset(),
f = await fixture(4, true, data.dataset),
a = await provision(f),
b = await provision(f);
const ordinary = await f.experiments.submit(
await preparation(f, 'Owned', f.draft.id, { fastPeriod: [1] }),
receipt(a.agent.id)
);
const runId = required(ordinary.trials[0]!.runId),
claim = await f.repository.startCanonical(await requestFor(f, runId));
await f.repository.fail(runId, 'controlled failure', claim.attemptId);
await expect(
f.experiments.retryTrial(
ordinary.id,
runId,
{ expectedAttemptNumber: 1, expectedRetryCount: 0 },
receipt(b.agent.id)
)
).rejects.toThrow(/owning.*principal/);
await expect(
f.pool.query(
`INSERT INTO experiment_trial_retries(id,experiment_id,run_id,trial_key,retry_number,previous_attempt_number,previous_attempt_id,error,progress,current_simulation_date,started_at,completed_at,paused_at,failure_updated_at,principal,review_id,submission_key,submission_hash)
SELECT $1,experiment_id,id,trial_key,1,attempt_number,attempt_id,error,progress,current_simulation_date,started_at,completed_at,paused_at,updated_at,$3,(SELECT id FROM strategy_review_events ORDER BY created_at DESC LIMIT 1),$4,$5 FROM runs WHERE id=$2`,
[randomUUID(), runId, b.agent.id, randomUUID(), 'a'.repeat(64)]
)
).rejects.toThrow(/owning.*principal/);
const validation = new ChronologicalValidationService(f.container),
input = {
backtestId: f.draft.id,
name: 'Owned phases',
grid: { fastPeriod: [1] },
recipe: data.windows[0]!,
};
const preview = await f.experiments.previewValidation(input),
train = await validation.submit(
{ ...input, previewHash: preview.previewHash },
receipt(a.agent.id)
);
await expect(
validation.select(train.id, { previewHash: preview.previewHash }, receipt(b.agent.id))
).rejects.toThrow(/owning.*principal/);
for (const principal of [b.agent.id, a.agent.id]) {
if (principal === a.agent.id) {
await f.agents.update(principal, { expectedRevision: 1, enabled: false });
}
for (const column of ['validation_selection', 'validation_report']) {
await expect(
f.pool.query(`UPDATE research_experiments SET ${column}=$2::jsonb WHERE id=$1`, [
train.id,
{ principal },
])
).rejects.toThrow(/owning.*principal/);
}
}
expect(
(await f.pool.query('SELECT count(*)::int n FROM experiment_trial_retries')).rows[0].n
).toBe(0);
expect(
(
await f.pool.query(
'SELECT validation_selection,validation_report FROM research_experiments WHERE id=$1',
[train.id]
)
).rows[0]
).toEqual({ validation_selection: null, validation_report: null });
});
test('operator retry reserves owning agent before parent so policy edits cannot deadlock admissions', async () => {
const f = await fixture(),
p = await provision(f),
run = await f.experiments.submit(
await preparation(f, 'Lock order', f.draft.id, { fastPeriod: [1] }),
receipt(p.agent.id)
);
const id = required(run.trials[0]!.runId),
claim = await f.repository.startCanonical(await requestFor(f, id));
await f.repository.fail(id, 'controlled', claim.attemptId);
const blocker = await f.pool.connect();
await blocker.query('BEGIN');
await blocker.query('SELECT id FROM research_agents WHERE id=$1 FOR UPDATE', [p.agent.id]);
const retry = f.experiments.retryTrial(
run.id,
id,
{ expectedAttemptNumber: 1, expectedRetryCount: 0 },
receipt()
);
try {
let waiting = false;
for (let i = 0; i < 100; i++) {
const rows = (
await f.pool.query(
"SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock' AND query LIKE 'SELECT id,enabled FROM research_agents%'",
[f.schema]
)
).rows;
if (rows.length) {
waiting = true;
break;
}
await blocker.query('SELECT pg_sleep(0.01)');
}
expect(waiting).toBe(true);
await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE NOWAIT', [f.draft.id]);
await blocker.query('COMMIT');
} finally {
await blocker.query('ROLLBACK');
blocker.release();
}
expect((await retry).retry.principal).toBe('operator');
expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1);
});
test('multi-template policy locks all parents before shared strategy families', async () => {
const f = await fixture(),
p = await provision(f),
other = await f.api.createBacktest(
{ ...f.definition, name: 'Shared family' },
{ autoStart: false }
);
const ids = [f.draft.id, other.id].sort(),
blocker = await f.pool.connect();
await blocker.query('BEGIN');
await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [ids[1]]);
const update = f.agents.update(p.agent.id, { expectedRevision: 1, allowedBacktestIds: ids });
try {
let waiting = false;
for (let i = 0; i < 100; i++) {
const rows = (
await f.pool.query(
"SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock' AND query LIKE 'SELECT * FROM backtests WHERE id=ANY%'",
[f.schema]
)
).rows;
if (rows.length) {
waiting = true;
break;
}
await blocker.query('SELECT pg_sleep(0.01)');
}
expect(waiting).toBe(true);
await blocker.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE NOWAIT', [
f.version.strategyId,
]);
await blocker.query('COMMIT');
} finally {
await blocker.query('ROLLBACK');
blocker.release();
}
expect((await update).grants).toHaveLength(2);
});
test('observation budgets and changed financial policy reject without partial admission', async () => {
const f = await fixture(),
p = await provision(f, { maxBarEvaluationsPerExperiment: 1 });
const input = await preparation(f),
before = await totals(f);
await expect(f.experiments.submit(input, receipt(p.agent.id))).rejects.toThrow(
'trial or observation budget'
);
expect(await totals(f)).toEqual(before);
await f.agents.update(p.agent.id, { expectedRevision: 1, limits });
await f.pool.query('UPDATE backtests SET initial_capital=20000 WHERE id=$1', [f.draft.id]);
const changed = await preparation(f);
expect(changed.previewHash).not.toBe(input.previewHash);
await expect(f.experiments.submit(changed, receipt(p.agent.id))).rejects.toThrow(
'Operator approval'
);
expect(await totals(f)).toEqual(before);
await f.agents.update(p.agent.id, { expectedRevision: 2, allowedBacktestIds: [f.draft.id] });
expect((await f.experiments.submit(changed, receipt(p.agent.id))).trials).toHaveLength(2);
});
});

View file

@ -12,6 +12,7 @@ import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-d
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
import { seedHistoricalRun } from '../fixtures/historical-run';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('research-retention-test');
@ -172,7 +173,9 @@ async function waitForBlocked(pool: Pool, schema: string) {
describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
test('retained_run_delete_restricted_postgres blocks raw cascades, mutations and truncation while preserving runless legacy deletion', async () => {
const f = await fixture();
const run = await f.api.createRun(
const run = await seedHistoricalRun(
f.pool,
f.api,
{ backtestId: f.definition.id },
{ principal: 'operator', key: 'retained' }
);
@ -217,7 +220,7 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
test('archive_preserves_replay hides discovery only and rejects new admission or edits until restored', async () => {
const f = await fixture();
const receipt = { principal: 'operator' as const, key: 'archive-retry' };
const run = await f.api.createRun({ backtestId: f.definition.id }, receipt);
const run = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id }, receipt);
const before = await f.snapshot(run.id);
const archived = await f.api.archiveBacktest(f.definition.id, true);
expect(archived?.archivedAt).toBeString();
@ -247,12 +250,15 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
expect((await f.api.updateBacktest(f.definition.id, { name: 'Restored' }))?.name).toBe(
'Restored'
);
expect((await f.api.createRun({ backtestId: f.definition.id })).runNumber).toBe(2);
await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow(
'Legacy backtest execution is retired'
);
expect(await f.api.listRuns(f.definition.id)).toHaveLength(1);
});
test('archive and admission use one parent lock, including direct repository inserts', async () => {
const f = await fixture();
const accepted = await f.api.createRun({ backtestId: f.definition.id });
const accepted = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id });
const blocker = await f.pool.connect();
await blocker.query('BEGIN');
await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [f.definition.id]);
@ -279,7 +285,7 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
test('accepted archived work retains binding, lease recovery, controls, progress and terminal result writes', async () => {
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const run = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id });
await f.api.archiveBacktest(f.definition.id, true);
const claim = await f.repository.start(await f.snapshot(run.id));
const frozen = await f.repository.freezeDataset(
@ -319,7 +325,10 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
await f.api.updateRunProgress(run.id, { progress: 90, attemptId: retry.attemptId });
await f.repository.complete(result(run.id, f.definition.id, frozen), retry.attemptId);
const saved = await f.api.getRunResults(run.id);
expect(saved?.config.dataset?.hash).toBe(frozen.manifest.hash);
if (!saved || !('config' in saved)) {
throw new Error('Expected preserved historical result');
}
expect(saved.config.dataset?.hash).toBe(frozen.manifest.hash);
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(2);
expect((await f.api.getRun(run.id))?.status).toBe('completed');
await f.pool.query(retention);
@ -329,7 +338,9 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
test('run identity and frozen inputs reject rewrites while legacy NULL snapshots can be populated once', async () => {
const f = await fixture();
const run = await f.api.createRun(
const run = await seedHistoricalRun(
f.pool,
f.api,
{ backtestId: f.definition.id },
{ principal: 'service', key: 'immutable' }
);
@ -381,7 +392,9 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
test('pending and running cancellation/failure still terminate accepted archived requests', async () => {
const f = await fixture();
const runs = await Promise.all(
Array.from({ length: 4 }, () => f.api.createRun({ backtestId: f.definition.id }))
Array.from({ length: 4 }, () =>
seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id })
)
);
await f.api.archiveBacktest(f.definition.id, true);
await f.api.cancelRun(runs[0]!.id);
@ -405,7 +418,7 @@ 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();
const run = await f.api.createRun({ backtestId: f.definition.id });
const run = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id });
const claim = await f.repository.start(await f.snapshot(run.id));
const dataset = await f.dataset(run.id);
const corrupt = structuredClone(dataset);
@ -430,7 +443,7 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
test('HTTP archive/list/delete errors are actionable and direct saved resources remain accessible', async () => {
const f = await fixture();
const run = await f.api.createRun({ backtestId: f.definition.id });
const run = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id });
const archived = await f.app.request(`/api/v2/backtests/${f.definition.id}/archive`, {
method: 'POST',
body: JSON.stringify({ archived: true }),

Some files were not shown because too many files have changed in this diff Show more