diff --git a/apps/stock/config/config/default.json b/apps/stock/config/config/default.json index 86cbb208..34659cf3 100644 --- a/apps/stock/config/config/default.json +++ b/apps/stock/config/config/default.json @@ -216,7 +216,7 @@ }, "orchestrator": { "port": 2004, - "defaultMode": "paper", + "defaultMode": "backtest", "paperTradingCapital": 100000, "enableWebSocket": true, "backtesting": { diff --git a/apps/stock/config/package.json b/apps/stock/config/package.json index 67559e49..81f84894 100644 --- a/apps/stock/config/package.json +++ b/apps/stock/config/package.json @@ -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": { diff --git a/apps/stock/config/src/contracts/chronological-validation.ts b/apps/stock/config/src/contracts/chronological-validation.ts index cd245772..062b1dd0 100644 --- a/apps/stock/config/src/contracts/chronological-validation.ts +++ b/apps/stock/config/src/contracts/chronological-validation.ts @@ -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; diff --git a/apps/stock/config/src/contracts/experiments.ts b/apps/stock/config/src/contracts/experiments.ts index 6b27a5ba..a45f63e6 100644 --- a/apps/stock/config/src/contracts/experiments.ts +++ b/apps/stock/config/src/contracts/experiments.ts @@ -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; } diff --git a/apps/stock/config/src/contracts/research-agents.ts b/apps/stock/config/src/contracts/research-agents.ts new file mode 100644 index 00000000..26b505ef --- /dev/null +++ b/apps/stock/config/src/contracts/research-agents.ts @@ -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; +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; +export const researchAgentBudgetSchema = z + .object({ + agent: researchAgentRecordSchema, + activeTrials: z.number().int().nonnegative(), + remainingActiveTrials: z.number().int().nonnegative(), + }) + .strict(); +export type ResearchAgentBudget = z.infer; +export interface ResearchAgentAuditEvent { + id: string; + agentId: string; + operation: string; + entityId: string; + createdAt: string; +} diff --git a/apps/stock/config/src/contracts/research.ts b/apps/stock/config/src/contracts/research.ts index 3dd6867b..bb7bfa9f 100644 --- a/apps/stock/config/src/contracts/research.ts +++ b/apps/stock/config/src/contracts/research.ts @@ -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( + 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); diff --git a/apps/stock/config/src/contracts/walk-forward.ts b/apps/stock/config/src/contracts/walk-forward.ts index 38b1d91c..46d893f8 100644 --- a/apps/stock/config/src/contracts/walk-forward.ts +++ b/apps/stock/config/src/contracts/walk-forward.ts @@ -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; diff --git a/apps/stock/config/src/schemas/stock-app.schema.ts b/apps/stock/config/src/schemas/stock-app.schema.ts index 274522fa..56749867 100644 --- a/apps/stock/config/src/schemas/stock-app.schema.ts +++ b/apps/stock/config/src/schemas/stock-app.schema.ts @@ -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(), diff --git a/apps/stock/engine/src/api/backtest.rs b/apps/stock/engine/src/api/backtest.rs index 9bd5cf9f..4d37577a 100644 --- a/apps/stock/engine/src/api/backtest.rs +++ b/apps/stock/engine/src/api/backtest.rs @@ -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, diff --git a/apps/stock/orchestrator/examples/example-runtime.ts b/apps/stock/orchestrator/examples/example-runtime.ts index 4fcbc916..a346f19e 100644 --- a/apps/stock/orchestrator/examples/example-runtime.ts +++ b/apps/stock/orchestrator/examples/example-runtime.ts @@ -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, }; } diff --git a/apps/stock/orchestrator/examples/multi-strategy-backtest.ts b/apps/stock/orchestrator/examples/multi-strategy-backtest.ts index f9f3f36d..b4aa860d 100644 --- a/apps/stock/orchestrator/examples/multi-strategy-backtest.ts +++ b/apps/stock/orchestrator/examples/multi-strategy-backtest.ts @@ -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, + runner: Pick, range: Pick ) { const request = BacktestConfigSchema.parse({ diff --git a/apps/stock/orchestrator/src/api/rest/backtest.ts b/apps/stock/orchestrator/src/api/rest/backtest.ts index 0ddc87e4..103058ac 100644 --- a/apps/stock/orchestrator/src/api/rest/backtest.ts +++ b/apps/stock/orchestrator/src/api/rest/backtest.ts @@ -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; } diff --git a/apps/stock/orchestrator/src/backtest/BacktestRunner.ts b/apps/stock/orchestrator/src/backtest/BacktestRunner.ts index 13d86a6f..5558fd9d 100644 --- a/apps/stock/orchestrator/src/backtest/BacktestRunner.ts +++ b/apps/stock/orchestrator/src/backtest/BacktestRunner.ts @@ -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 = Promise.resolve(); private closing = false; private phase: 'preparing' | 'executing' | 'persisting' = 'preparing'; - private execution: Promise | undefined; + private execution: Promise | undefined; constructor( private readonly dependencies: { @@ -51,20 +50,18 @@ export class BacktestRunner extends EventEmitter { logger: Pick; heartbeatMs?: number; heartbeatTimeoutMs?: number; - prepare?: (config: BacktestConfig) => Promise; } ) { super(); } + /** Retained only to diagnose obsolete callers; canonical work requires durable admission. */ async runBacktest(input: unknown): Promise { - return this.begin(parseBacktestRequest(input)); + parseBacktestRequest(input); + throw new BacktestConflictError(LEGACY_EXECUTION_RETIRED); } - private begin(config: BacktestConfig): Promise; - private begin(config: CanonicalRunRequest): Promise; - private begin(config: DurableRequest): Promise; - private begin(config: DurableRequest): Promise { + private begin(config: CanonicalRunRequest): Promise { 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 { + private async execute(config: CanonicalRunRequest): Promise { const started = performance.now(); this.progressWrites = Promise.resolve(); let heartbeatTimer: ReturnType | undefined; let heartbeatWork: Promise | undefined; + let executionDeadline: ReturnType | undefined; + let deadlineFailure: Error | undefined; + let deadlineStop: Promise | 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); } diff --git a/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts b/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts index c7f877ad..8428fbae 100644 --- a/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts +++ b/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts @@ -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 { signal.throwIfAborted(); + request = nativeWorkerRequestSchema.parse(request); if (this.active) { throw new BacktestConflictError('A native backtest worker is already running'); } diff --git a/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts b/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts index 9f83746c..d524e459 100644 --- a/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts +++ b/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts @@ -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() } + : {}), }; }); } diff --git a/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts b/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts index 94ad5200..7948b2d7 100644 --- a/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts +++ b/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts @@ -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 { - 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( initialTime: number, work: (signal: AbortSignal, aborted: Promise) => Promise @@ -147,25 +133,6 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti } } - private async loadData( - config: BacktestConfig, - signal: AbortSignal, - resolver?: DatasetResolver - ): Promise['data']> { - signal.throwIfAborted(); - const dataset = await resolveDataset(this.dependencies.storage, config, resolver, signal); - signal.throwIfAborted(); - const data: Extract['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); diff --git a/apps/stock/orchestrator/src/backtest/execution-engine.ts b/apps/stock/orchestrator/src/backtest/execution-engine.ts index f6ed88ae..e9fa8e2e 100644 --- a/apps/stock/orchestrator/src/backtest/execution-engine.ts +++ b/apps/stock/orchestrator/src/backtest/execution-engine.ts @@ -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.'; diff --git a/apps/stock/orchestrator/src/backtest/native-replay.ts b/apps/stock/orchestrator/src/backtest/native-replay.ts index 8a99f198..596e5ef7 100644 --- a/apps/stock/orchestrator/src/backtest/native-replay.ts +++ b/apps/stock/orchestrator/src/backtest/native-replay.ts @@ -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; + committed?(outcome: ReplaySubmissionOutcome): Promise; +} /* 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; } } diff --git a/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts b/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts index eec75783..d6d7ff19 100644 --- a/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts +++ b/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts @@ -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, diff --git a/apps/stock/orchestrator/src/backtest/native-worker.ts b/apps/stock/orchestrator/src/backtest/native-worker.ts index e36a1a21..bfb1c00a 100644 --- a/apps/stock/orchestrator/src/backtest/native-worker.ts +++ b/apps/stock/orchestrator/src/backtest/native-worker.ts @@ -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; diff --git a/apps/stock/orchestrator/src/backtest/run-repository.ts b/apps/stock/orchestrator/src/backtest/run-repository.ts index 7b8b962a..56e2dcc5 100644 --- a/apps/stock/orchestrator/src/backtest/run-repository.ts +++ b/apps/stock/orchestrator/src/backtest/run-repository.ts @@ -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; } diff --git a/apps/stock/orchestrator/src/backtest/strategy-runtime.ts b/apps/stock/orchestrator/src/backtest/strategy-runtime.ts index 8684cfbe..6a0dc38c 100644 --- a/apps/stock/orchestrator/src/backtest/strategy-runtime.ts +++ b/apps/stock/orchestrator/src/backtest/strategy-runtime.ts @@ -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; - pendingObservations: PublishedObservation[]; -} -class StrategyController implements ReplayController { - private slots: Map; - 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 - ) { - 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 { - 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 = { - 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, diff --git a/apps/stock/orchestrator/src/container.ts b/apps/stock/orchestrator/src/container.ts index 9937774a..9cf68b0a 100644 --- a/apps/stock/orchestrator/src/container.ts +++ b/apps/stock/orchestrator/src/container.ts @@ -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 { - 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.' diff --git a/apps/stock/orchestrator/src/handlers/backtest/backtest.handler.ts b/apps/stock/orchestrator/src/handlers/backtest/backtest.handler.ts index 93fec4fd..467578b7 100644 --- a/apps/stock/orchestrator/src/handlers/backtest/backtest.handler.ts +++ b/apps/stock/orchestrator/src/handlers/backtest/backtest.handler.ts @@ -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 { 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') diff --git a/apps/stock/orchestrator/src/index.ts b/apps/stock/orchestrator/src/index.ts index fefb8a72..ecc2619d 100644 --- a/apps/stock/orchestrator/src/index.ts +++ b/apps/stock/orchestrator/src/index.ts @@ -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, }; diff --git a/apps/stock/orchestrator/src/routes/create-routes.ts b/apps/stock/orchestrator/src/routes/create-routes.ts index 6f8229f4..bfc82070 100644 --- a/apps/stock/orchestrator/src/routes/create-routes.ts +++ b/apps/stock/orchestrator/src/routes/create-routes.ts @@ -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(); diff --git a/apps/stock/orchestrator/src/simple-container.ts b/apps/stock/orchestrator/src/simple-container.ts index 3bd81e49..bc612c3d 100644 --- a/apps/stock/orchestrator/src/simple-container.ts +++ b/apps/stock/orchestrator/src/simple-container.ts @@ -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; } diff --git a/apps/stock/orchestrator/src/strategies/strategy-controller.ts b/apps/stock/orchestrator/src/strategies/strategy-controller.ts new file mode 100644 index 00000000..69fa35bf --- /dev/null +++ b/apps/stock/orchestrator/src/strategies/strategy-controller.ts @@ -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; + pendingObservations: PublishedObservation[]; +} +export class StrategyController { + private slots: Map; + 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 + ) { + 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 { + 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 = { + 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; + } +} diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index b8926e67..99a183df 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -67,7 +67,8 @@ export async function runMigrations(container: IServiceContainer): Promise 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(); diff --git a/apps/stock/web-api/src/routes/create-routes.ts b/apps/stock/web-api/src/routes/create-routes.ts index 6e107bb4..25482c67 100644 --- a/apps/stock/web-api/src/routes/create-routes.ts +++ b/apps/stock/web-api/src/routes/create-routes.ts @@ -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; diff --git a/apps/stock/web-api/src/routes/experiments.routes.ts b/apps/stock/web-api/src/routes/experiments.routes.ts index e8f4a5ff..6b8dcaf7 100644 --- a/apps/stock/web-api/src/routes/experiments.routes.ts +++ b/apps/stock/web-api/src/routes/experiments.routes.ts @@ -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); diff --git a/apps/stock/web-api/src/routes/research-agents.routes.ts b/apps/stock/web-api/src/routes/research-agents.routes.ts new file mode 100644 index 00000000..7f025cd4 --- /dev/null +++ b/apps/stock/web-api/src/routes/research-agents.routes.ts @@ -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; +} diff --git a/apps/stock/web-api/src/routes/research.routes.ts b/apps/stock/web-api/src/routes/research.routes.ts index 026cb206..0ab1748d 100644 --- a/apps/stock/web-api/src/routes/research.routes.ts +++ b/apps/stock/web-api/src/routes/research.routes.ts @@ -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'); } diff --git a/apps/stock/web-api/src/routes/strategies.routes.ts b/apps/stock/web-api/src/routes/strategies.routes.ts index 869cfb6d..7b7a1af9 100644 --- a/apps/stock/web-api/src/routes/strategies.routes.ts +++ b/apps/stock/web-api/src/routes/strategies.routes.ts @@ -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'); } diff --git a/apps/stock/web-api/src/services/BacktestDispatcher.ts b/apps/stock/web-api/src/services/BacktestDispatcher.ts index ade955a9..1e799792 100644 --- a/apps/stock/web-api/src/services/BacktestDispatcher.ts +++ b/apps/stock/web-api/src/services/BacktestDispatcher.ts @@ -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] ); }); diff --git a/apps/stock/web-api/src/services/backtest-v2.service.ts b/apps/stock/web-api/src/services/backtest-v2.service.ts index 68765862..8112ad81 100644 --- a/apps/stock/web-api/src/services/backtest-v2.service.ts +++ b/apps/stock/web-api/src/services/backtest-v2.service.ts @@ -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'); } diff --git a/apps/stock/web-api/src/services/chronological-validation.service.ts b/apps/stock/web-api/src/services/chronological-validation.service.ts index 4307347a..29b329ed 100644 --- a/apps/stock/web-api/src/services/chronological-validation.service.ts +++ b/apps/stock/web-api/src/services/chronological-validation.service.ts @@ -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, 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(); diff --git a/apps/stock/web-api/src/services/experiment-input.ts b/apps/stock/web-api/src/services/experiment-input.ts index 0a16ae42..a919e3db 100644 --- a/apps/stock/web-api/src/services/experiment-input.ts +++ b/apps/stock/web-api/src/services/experiment-input.ts @@ -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() diff --git a/apps/stock/web-api/src/services/experiments.service.ts b/apps/stock/web-api/src/services/experiments.service.ts index b666aa78..48acdcf8 100644 --- a/apps/stock/web-api/src/services/experiments.service.ts +++ b/apps/stock/web-api/src/services/experiments.service.ts @@ -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 => { 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( diff --git a/apps/stock/web-api/src/services/research-agent-budget.ts b/apps/stock/web-api/src/services/research-agent-budget.ts new file mode 100644 index 00000000..82422a50 --- /dev/null +++ b/apps/stock/web-api/src/services/research-agent-budget.ts @@ -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) => + 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 { + 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 { + 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); + } +} diff --git a/apps/stock/web-api/src/services/research-agents.service.ts b/apps/stock/web-api/src/services/research-agents.service.ts new file mode 100644 index 00000000..d1a8a901 --- /dev/null +++ b/apps/stock/web-api/src/services/research-agents.service.ts @@ -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 { + return ( + await this.database.query('SELECT * FROM research_agents ORDER BY created_at,id') + ).rows.map(record); + } + async update(id: string, raw: unknown): Promise { + 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 { + 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 }; + } +} diff --git a/apps/stock/web-api/src/services/research-source-evidence.ts b/apps/stock/web-api/src/services/research-source-evidence.ts index 16fada46..3f390e7c 100644 --- a/apps/stock/web-api/src/services/research-source-evidence.ts +++ b/apps/stock/web-api/src/services/research-source-evidence.ts @@ -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, 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' && diff --git a/apps/stock/web-api/src/services/research.service.ts b/apps/stock/web-api/src/services/research.service.ts index 379e9686..81fa82b6 100644 --- a/apps/stock/web-api/src/services/research.service.ts +++ b/apps/stock/web-api/src/services/research.service.ts @@ -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( ( diff --git a/apps/stock/web-api/src/services/strategy-catalog.service.ts b/apps/stock/web-api/src/services/strategy-catalog.service.ts index be588c4b..28f84312 100644 --- a/apps/stock/web-api/src/services/strategy-catalog.service.ts +++ b/apps/stock/web-api/src/services/strategy-catalog.service.ts @@ -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]; diff --git a/apps/stock/web-api/src/services/walk-forward.service.ts b/apps/stock/web-api/src/services/walk-forward.service.ts index 2e4ce98d..751307ac 100644 --- a/apps/stock/web-api/src/services/walk-forward.service.ts +++ b/apps/stock/web-api/src/services/walk-forward.service.ts @@ -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( diff --git a/apps/stock/web-app/src/app/App.tsx b/apps/stock/web-app/src/app/App.tsx index 23f01319..688decfa 100644 --- a/apps/stock/web-app/src/app/App.tsx +++ b/apps/stock/web-app/src/app/App.tsx @@ -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() { } /> + } /> } /> diff --git a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx index f92803eb..d15703c3 100644 --- a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx +++ b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx @@ -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 && (

- 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.

)} {archived && ( diff --git a/apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx b/apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx index 740495ed..90dca9ef 100644 --- a/apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx +++ b/apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx @@ -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}`); }} /> )} diff --git a/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx b/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx index 3147de32..1c13f01a 100644 --- a/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx +++ b/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx @@ -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(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(null); - const saved = useRef(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({
{ e.preventDefault(); - void handleSubmit(saved.current !== null); + void handleSubmit(); }} className="space-y-6" onChange={() => setEdited(true)} > -
+
- - {catalogMode ? ( - - ) : ( - setFormData(previous => ({ ...previous, strategy }))} - /> - )} +

+ Select an immutable strategy version. After saving, configure a retained dataset and + financial policies before running a canonical backtest. +

+ setFormData(previous => ({ ...previous, ...selection }))} onValidityChange={setHistoricalValid} - disabled={isSubmitting || saved.current !== null} + disabled={isSubmitting} />
@@ -295,32 +245,19 @@ export function CreateBacktestDialog({ + - {!saved.current && ( - - )}
diff --git a/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts b/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts index ac2261a1..673b2126 100644 --- a/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts +++ b/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts @@ -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; diff --git a/apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts b/apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts index 3093e88e..e1c26c1d 100644 --- a/apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts +++ b/apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts @@ -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), diff --git a/apps/stock/web-app/src/features/experiments/services/experimentApi.ts b/apps/stock/web-app/src/features/experiments/services/experimentApi.ts index 2ed9fb45..f87e85ce 100644 --- a/apps/stock/web-app/src/features/experiments/services/experimentApi.ts +++ b/apps/stock/web-app/src/features/experiments/services/experimentApi.ts @@ -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. */ diff --git a/apps/stock/web-app/src/features/experiments/services/walkForwardApi.ts b/apps/stock/web-app/src/features/experiments/services/walkForwardApi.ts index b3c7ed25..7dcbfe3d 100644 --- a/apps/stock/web-app/src/features/experiments/services/walkForwardApi.ts +++ b/apps/stock/web-app/src/features/experiments/services/walkForwardApi.ts @@ -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')), diff --git a/apps/stock/web-app/src/features/research/ResearchAgentsPage.tsx b/apps/stock/web-app/src/features/research/ResearchAgentsPage.tsx new file mode 100644 index 00000000..6720be26 --- /dev/null +++ b/apps/stock/web-app/src/features/research/ResearchAgentsPage.tsx @@ -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([]); + const [budgets, setBudgets] = useState>({}); + const [name, setName] = useState(''); + const [projects, setProjects] = useState(search.get('projectId') ?? ''); + const [backtests, setBacktests] = useState(''); + const [limits, setLimits] = useState>(() => + 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(null); + const alive = useRef(false); + const writing = useRef(false); + const generation = useRef(0); + const budgetRequests = useRef(new Map()); + 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 ( +
+ + Back to research + +

Research agent access

+

+ 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. +

+ {writeError &&

{writeError}

} + {token && ( +
+

+ This credential is shown once. Store it in the authorized research client before + dismissing. +

+