From 25b5cbf481e195810bc123ada50ee129a1f55e27 Mon Sep 17 00:00:00 2001 From: Boki Date: Sat, 24 Oct 2026 18:46:55 -0400 Subject: [PATCH] feat(research): isolate candidates and add reviewed paper promotion --- README.md | 78 ++ apps/stock/config/package.json | 12 + .../src/contracts/candidate-execution.ts | 94 ++ .../src/contracts/canonical-research.ts | 51 +- .../src/contracts/chronological-validation.ts | 10 +- .../config/src/contracts/cost-sensitivity.ts | 2 + .../stock/config/src/contracts/experiments.ts | 4 +- .../config/src/contracts/paper-deployments.ts | 215 +++++ .../config/src/contracts/research-agents.ts | 8 +- .../research-responses/comparison.ts | 115 +++ .../research-responses/experiment.ts | 349 +++++++ .../src/contracts/research-responses/index.ts | 5 + .../research-responses/validation-preview.ts | 138 +++ .../research-responses/validation.ts | 288 ++++++ .../research-responses/walk-forward.ts | 314 +++++++ apps/stock/config/src/contracts/strategy.ts | 2 + .../config/src/schemas/stock-app.schema.ts | 8 + apps/stock/engine/index.d.ts | 6 + apps/stock/engine/index.mjs | 18 +- apps/stock/orchestrator/package.json | 2 +- .../src/api/rest/paper-deployments.ts | 96 ++ apps/stock/orchestrator/src/api/rest/paper.ts | 36 +- .../src/backtest/BacktestRunner.ts | 22 +- .../src/backtest/NativeBacktestWorker.ts | 21 +- .../backtest/PostgresBacktestRunRepository.ts | 3 +- .../src/backtest/RustBacktestAdapter.ts | 12 +- .../src/backtest/candidate-host.ts | 99 ++ .../src/backtest/candidate-protocol.ts | 89 ++ .../src/backtest/candidate-sandbox.ts | 467 ++++++++++ .../src/backtest/execution-engine.ts | 3 +- .../src/backtest/native-worker-protocol.ts | 19 + .../src/backtest/native-worker.ts | 91 +- .../src/backtest/sandbox/guardian.rs | 218 +++++ apps/stock/orchestrator/src/container.ts | 76 +- .../src/contracts/paper-runtime.ts | 51 +- .../PostgresCanonicalExecutionRepository.ts | 2 + .../src/execution/canonical-paper.ts | 2 + apps/stock/orchestrator/src/index.ts | 9 +- .../src/paper/CanonicalPaperRuntime.ts | 3 + .../src/paper/PaperDeploymentHost.ts | 145 +++ .../src/paper/paper-deployment-custody.ts | 190 ++++ .../src/paper/paper-host-identity.ts | 76 ++ .../orchestrator/src/paper/paper-host.ts | 53 ++ .../orchestrator/src/paper/paper-operator.ts | 23 + .../orchestrator/src/routes/create-routes.ts | 33 +- .../orchestrator/src/simple-container.ts | 21 +- .../src/strategies/retained-program.ts | 70 ++ .../src/strategies/strategy-controller.ts | 3 +- apps/stock/orchestrator/src/types.ts | 1 + .../src/migrations/migration-runner.ts | 5 +- .../stock/web-api/src/routes/create-routes.ts | 14 +- .../web-api/src/routes/experiments.routes.ts | 20 +- .../src/routes/paper-deployments.routes.ts | 178 ++++ .../src/services/backtest-v2.service.ts | 15 +- .../services/canonical-research.service.ts | 89 +- .../chronological-validation.service.ts | 2 +- .../src/services/cost-sensitivity-input.ts | 7 +- .../web-api/src/services/experiment-input.ts | 7 +- .../src/services/experiments.service.ts | 67 +- .../src/services/paper-deployments.service.ts | 361 ++++++++ .../src/services/reproduction-comparison.ts | 3 +- .../src/services/research-agent-budget.ts | 26 +- .../src/services/research-agents.service.ts | 47 +- .../web-api/src/services/run-reproduction.ts | 29 +- .../src/services/strategy-catalog.service.ts | 6 +- .../src/services/validation-evidence.ts | 16 +- .../src/services/validation-preview.ts | 16 +- .../src/services/walk-forward.service.ts | 17 +- apps/stock/web-app/src/app/App.tsx | 5 + .../backtest/BacktestDetailPageV2.tsx | 7 + .../backtest/components/CanonicalResults.tsx | 14 +- .../backtest/components/CanonicalSetup.tsx | 5 +- .../backtest/services/backtestApiV2.ts | 14 +- .../experiments/ExperimentDetailPage.tsx | 1 + .../ChronologicalValidationPreflight.tsx | 17 +- .../components/ExperimentEditor.tsx | 97 +- .../components/ExperimentInputs.tsx | 30 +- .../components/ExperimentTrialRecovery.tsx | 16 +- .../components/WalkForwardPreflight.tsx | 13 +- .../services/chronologicalValidationApi.ts | 133 +-- .../chronologicalValidationDurableApi.ts | 279 +----- .../experiments/services/experimentApi.ts | 360 +------- .../services/experimentComparisonApi.ts | 119 +-- .../experiments/services/walkForwardApi.ts | 317 +------ .../features/paper/PaperDeploymentPage.tsx | 216 +++++ .../features/paper/PaperDeploymentsPage.tsx | 459 ++++++++++ .../stock/web-app/src/features/paper/index.ts | 2 + .../web-app/src/features/paper/paperApi.ts | 110 +++ .../features/research/ResearchAgentsPage.tsx | 26 +- .../strategies/StrategyDetailPage.tsx | 32 +- .../components/CandidatePublication.tsx | 197 ++++ .../components/StrategySelection.tsx | 2 +- .../services/candidatePublication.ts | 105 +++ apps/stock/web-app/src/lib/constants.ts | 1 + .../postgres/init/29-isolated-candidates.sql | 731 +++++++++++++++ .../postgres/init/30-paper-deployments.sql | 128 +++ .../init/31-research-agent-project-links.sql | 39 + .../architecture/decisions/007-ai-boundary.md | 4 + .../architecture/research-product.md | 13 + libs/core/types/src/strategy-version.ts | 2 + scripts/benchmark-candidate-isolation.ts | 188 ++++ scripts/build-candidate-sandbox.ts | 119 +++ scripts/examples/research-cycle.ts | 505 ++++++++++ scripts/package-candidate-strategy.ts | 88 ++ scripts/research-client.ts | 863 ++++++++++++++++++ scripts/test/architecture.test.ts | 6 + scripts/test/research-client.test.ts | 471 ++++++++++ scripts/test/research-cycle.test.ts | 230 +++++ test/e2e/fixture.ts | 10 +- test/e2e/workbench.test.ts | 259 ++++++ test/integration/candidate-contract.test.ts | 200 ++++ .../candidate-publication-ui.test.tsx | 296 ++++++ .../candidate-response-contract.test.ts | 63 ++ test/integration/candidate-sandbox.test.ts | 497 ++++++++++ test/integration/experiments-ui.test.tsx | 16 + test/integration/paper-composition.test.ts | 87 +- .../integration/paper-deployments-api.test.ts | 226 +++++ .../integration/paper-deployments-ui.test.tsx | 448 +++++++++ .../integration/paper-native-identity.test.ts | 66 ++ test/integration/research-agents-ui.test.tsx | 29 + test/postgres/ai-research-workflow.test.ts | 460 ++++++++++ test/postgres/canonical-research.test.ts | 6 +- test/postgres/isolated-candidates.test.ts | 537 +++++++++++ test/postgres/migration-runner.test.ts | 3 + test/postgres/paper-deployments.test.ts | 573 ++++++++++++ test/postgres/research-agents.test.ts | 78 ++ .../research-runtime-isolation.test.ts | 28 +- test/postgres/strategy-catalog.test.ts | 2 +- 128 files changed, 13038 insertions(+), 1388 deletions(-) create mode 100644 apps/stock/config/src/contracts/candidate-execution.ts create mode 100644 apps/stock/config/src/contracts/paper-deployments.ts create mode 100644 apps/stock/config/src/contracts/research-responses/comparison.ts create mode 100644 apps/stock/config/src/contracts/research-responses/experiment.ts create mode 100644 apps/stock/config/src/contracts/research-responses/index.ts create mode 100644 apps/stock/config/src/contracts/research-responses/validation-preview.ts create mode 100644 apps/stock/config/src/contracts/research-responses/validation.ts create mode 100644 apps/stock/config/src/contracts/research-responses/walk-forward.ts create mode 100644 apps/stock/orchestrator/src/api/rest/paper-deployments.ts create mode 100644 apps/stock/orchestrator/src/backtest/candidate-host.ts create mode 100644 apps/stock/orchestrator/src/backtest/candidate-protocol.ts create mode 100644 apps/stock/orchestrator/src/backtest/candidate-sandbox.ts create mode 100644 apps/stock/orchestrator/src/backtest/sandbox/guardian.rs create mode 100644 apps/stock/orchestrator/src/paper/PaperDeploymentHost.ts create mode 100644 apps/stock/orchestrator/src/paper/paper-deployment-custody.ts create mode 100644 apps/stock/orchestrator/src/paper/paper-host-identity.ts create mode 100644 apps/stock/orchestrator/src/paper/paper-host.ts create mode 100644 apps/stock/orchestrator/src/paper/paper-operator.ts create mode 100644 apps/stock/orchestrator/src/strategies/retained-program.ts create mode 100644 apps/stock/web-api/src/routes/paper-deployments.routes.ts create mode 100644 apps/stock/web-api/src/services/paper-deployments.service.ts create mode 100644 apps/stock/web-app/src/features/paper/PaperDeploymentPage.tsx create mode 100644 apps/stock/web-app/src/features/paper/PaperDeploymentsPage.tsx create mode 100644 apps/stock/web-app/src/features/paper/index.ts create mode 100644 apps/stock/web-app/src/features/paper/paperApi.ts create mode 100644 apps/stock/web-app/src/features/strategies/components/CandidatePublication.tsx create mode 100644 apps/stock/web-app/src/features/strategies/services/candidatePublication.ts create mode 100644 database/postgres/init/29-isolated-candidates.sql create mode 100644 database/postgres/init/30-paper-deployments.sql create mode 100644 database/postgres/init/31-research-agent-project-links.sql create mode 100644 scripts/benchmark-candidate-isolation.ts create mode 100644 scripts/build-candidate-sandbox.ts create mode 100644 scripts/examples/research-cycle.ts create mode 100644 scripts/package-candidate-strategy.ts create mode 100644 scripts/research-client.ts create mode 100644 scripts/test/research-client.test.ts create mode 100644 scripts/test/research-cycle.test.ts create mode 100644 test/integration/candidate-contract.test.ts create mode 100644 test/integration/candidate-publication-ui.test.tsx create mode 100644 test/integration/candidate-response-contract.test.ts create mode 100644 test/integration/candidate-sandbox.test.ts create mode 100644 test/integration/paper-deployments-api.test.ts create mode 100644 test/integration/paper-deployments-ui.test.tsx create mode 100644 test/integration/paper-native-identity.test.ts create mode 100644 test/postgres/ai-research-workflow.test.ts create mode 100644 test/postgres/isolated-candidates.test.ts create mode 100644 test/postgres/paper-deployments.test.ts diff --git a/README.md b/README.md index f76df39f..dada3d8e 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,84 @@ Bun/TypeScript workspaces for market-data collection, processing, APIs, and a Re with a Rust native trading engine. `apps/wcag-ada` is an independent project and is not part of the root workspace checks. +## Current research workflow + +The web workbench is the primary interface: Strategies → Backtests → Experiments → +Research findings. New runs use retained inputs and the canonical Rust financial engine. +The supported default is one asset and one execution series, long-only, with explicit +cash, fee, slippage and risk policies. Previous results and legacy execution code remain +readable; the historical architecture sections below do not enable legacy execution for +new research. Multi-asset default policy and live trading remain gated. + +Built-in reviewed strategies use the trusted TypeScript callback path. Arbitrary retained +TypeScript candidates always use the isolated path, including after ordinary catalog +approval. Both send target intents to the same Rust engine. Neither the browser nor a +strategy implements account or fill accounting. `ownerBudget` is a strategy sizing input; +the engine's portfolio constraints are the actual financial limits. + +`services.orchestrator.backtesting.maxConcurrent` selects 1, 2 or 4 independent durable +workers (default 1). It parallelizes trials, never concurrent transitions within one account. + +### Prepare an isolated candidate + +After the normal repository build, explicitly build the trusted local sandbox image: + +```sh +bun run scripts/build-candidate-sandbox.ts +bun run scripts/package-candidate-strategy.ts metadata.json strategy.ts > candidate-package.json +``` + +The sandbox currently requires Linux x86_64, local Docker with cgroup v2, memory/swap/CPU/PID +limits, seccomp and AppArmor, plus `rustc` and the pinned Bun runtime. The image is built +from installed trusted runtime files without pulling a base image. The descriptor and +image ID are frozen into each request; a missing or different installation fails closed. +Preserve the matching image and descriptor when retaining runs for reproduction. + +`metadata.json` supplies `program`, `parameterSchema`, `source`, `entryExport` and +`execution: { "kind": "isolated-candidate/v1", "warmupBars": 0 }`. Set the warmup to the +maximum required by all intended parameter combinations. Use the +[retained package contract](libs/core/types/src/strategy-version.ts) and +[strategy decision API](apps/stock/orchestrator/src/contracts/canonical-strategy.ts). +The entry export is a synchronous factory receiving the retained selection and returning +a target-mode strategy with explicit JSON state. The CLI transpiles self-contained +TypeScript inside isolation; it does not evaluate the source or install dependencies. + +Upload the package on the strategy page, validate parameters, then select its immutable +version in a saved backtest or experiment. Publication never starts a run. Candidates +receive only published observation/context prefixes, with no host filesystem, network, +credentials, broker or database access. The frozen sandbox policy limits each attempt to +512 MiB, one CPU, 64 PIDs and at most 300 seconds; a shorter agent deadline wins. Author +warmup declarations and seeded helpers do not prove that arbitrary JavaScript is free of +leakage or nondeterminism. Inspect diagnostics and reproduce the actual result. + +### Run an AI research cycle + +An operator creates a research-only agent on the Research agents page, grants the project +and saved template, explicitly allows its own candidates, and sets bounded job budgets. +Give that research token to the client, never an operator or brokerage credential. + +```sh +RESEARCH_API_ORIGIN=http://127.0.0.1:3001 RESEARCH_API_TOKEN=sb-research.… \ + bun run scripts/examples/research-cycle.ts --plan prepared-plan.json --receipts new-receipts.jsonl +``` + +[ResearchCyclePlan](scripts/examples/research-cycle.ts) defines the input. Supply prepared +packages, parameters, bounded grids, chronological windows and cost scenarios before +reading results. The example runs training first, freezes the server-selected candidate, +then evaluates holdouts and costs, retaining failed trials and exact evidence citations. +Findings remain explicitly AI-authored and unvalidated narratives. Use +[ResearchClient](scripts/research-client.ts) for individual APIs, including walk-forward. + +The receipt journal is mandatory and created exclusively. On interruption, inspect its +intents and accepted IDs, reopen durable resources, and retry only the exact idempotent +request. Do not blindly restart a cycle: hypothesis, family and finding creation do not +have replay keys. The client cannot promote or activate paper/live trading. + +Human paper promotion uses the separate `/paper` workflow and a configured, initially +halted paper host. See [paper setup and evidence requirements](docs/development/architecture/research-product.md). +Creating a deployment is distinct from binding and activating it; development tests use +disposable accounts only. + ## Build and verify Use Bun 1.2.17, Node.js 18 or newer, and a Rust toolchain with a native linker. CI uses Rust diff --git a/apps/stock/config/package.json b/apps/stock/config/package.json index 81f84894..e28b9ff4 100644 --- a/apps/stock/config/package.json +++ b/apps/stock/config/package.json @@ -52,6 +52,18 @@ "./research-agents": { "types": "./dist/contracts/research-agents.d.ts", "default": "./dist/contracts/research-agents.js" + }, + "./research-responses": { + "types": "./dist/contracts/research-responses/index.d.ts", + "default": "./dist/contracts/research-responses/index.js" + }, + "./candidate-execution": { + "types": "./dist/contracts/candidate-execution.d.ts", + "default": "./dist/contracts/candidate-execution.js" + }, + "./paper-deployments": { + "types": "./dist/contracts/paper-deployments.d.ts", + "import": "./dist/contracts/paper-deployments.js" } }, "scripts": { diff --git a/apps/stock/config/src/contracts/candidate-execution.ts b/apps/stock/config/src/contracts/candidate-execution.ts new file mode 100644 index 00000000..63dbdbaf --- /dev/null +++ b/apps/stock/config/src/contracts/candidate-execution.ts @@ -0,0 +1,94 @@ +/** Pure isolated-candidate contracts. No runtime, artifact import or financial implementation. */ +import { z } from 'zod'; +import { parseFinancialDecimal } from '@stock-bot/types'; +import type { financialDecimal } from '@stock-bot/types'; + +export type { financialDecimal }; + +const hash = z.string().regex(/^[a-f0-9]{64}$/); +const identity = z + .string() + .min(1) + .refine(value => + [...value].every(character => { + const code = character.charCodeAt(0); + return ( + code >= 32 && code !== 127 && !(character.length === 1 && code >= 0xd800 && code <= 0xdfff) + ); + }) + ); +export const candidatePackageExecutionSchema = z + .object({ + kind: z.literal('isolated-candidate/v1'), + /** Fixed author declaration for all parameter combinations, not a verified leakage claim. */ + warmupBars: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), + }) + .strict(); +export const retainedProgramSelectionSchema = z + .object({ + ownerId: identity, + strategyId: identity, + strategyVersion: identity, + seed: z.number().int().min(0).max(0xffffffff), + instrumentId: identity, + seriesId: identity, + /** Strategy sizing input. Rust portfolio constraints remain the financial authority. */ + ownerBudget: z + .string() + .transform(parseFinancialDecimal) + .refine(value => !value.startsWith('-') && value !== '0.00000000'), + parameters: z.record(z.union([z.string(), z.number().finite(), z.boolean()])), + }) + .strict(); +export type RetainedProgramSelection = z.infer; + +export const candidateSandboxLimits = { + memoryBytes: 536870912, + cpuQuota: 1, + pids: 64, + tmpBytes: 16777216, + wallMs: 300000, + frameBytes: 8388608, + stderrBytes: 65536, +} as const; +export const candidateSandboxProfileSchema = z + .object({ + version: z.literal(1), + policy: z.literal('linux-docker-guardian/v1'), + protocol: z.literal('candidate-controller/v1'), + platform: z.literal('linux'), + arch: z.literal('x64'), + hostSha256: hash, + guardianSha256: hash, + bunSha256: hash, + limits: z + .object({ + memoryBytes: z.literal(candidateSandboxLimits.memoryBytes), + cpuQuota: z.literal(candidateSandboxLimits.cpuQuota), + pids: z.literal(candidateSandboxLimits.pids), + tmpBytes: z.literal(candidateSandboxLimits.tmpBytes), + wallMs: z.literal(candidateSandboxLimits.wallMs), + frameBytes: z.literal(candidateSandboxLimits.frameBytes), + stderrBytes: z.literal(candidateSandboxLimits.stderrBytes), + }) + .strict(), + }) + .strict(); +export const candidateExecutionSchema = z + .object({ + kind: z.literal('typescript-isolated-candidate/v1'), + imageId: z.string().regex(/^sha256:[a-f0-9]{64}$/), + profile: candidateSandboxProfileSchema, + }) + .strict(); +export type CandidateExecution = z.infer; + +export const candidateOverrideSchema = z + .object({ + versionId: z + .string() + .uuid() + .transform(value => value.toLowerCase()), + parameters: retainedProgramSelectionSchema.shape.parameters, + }) + .strict(); diff --git a/apps/stock/config/src/contracts/canonical-research.ts b/apps/stock/config/src/contracts/canonical-research.ts index 44ac4bde..d644ffaa 100644 --- a/apps/stock/config/src/contracts/canonical-research.ts +++ b/apps/stock/config/src/contracts/canonical-research.ts @@ -10,6 +10,11 @@ import type { } from '@stock-bot/types'; import { parseFinancialDecimal } from '@stock-bot/types'; import { builtinStrategySelectionSchema } from './builtin-strategy'; +import { + candidateExecutionSchema, + retainedProgramSelectionSchema, + type CandidateExecution, +} from './candidate-execution'; import { parseReplayReportValue, replayConfigSchema, @@ -93,16 +98,30 @@ const admitted = z runId: z.string().uuid(), backtestId: z.string().uuid(), name: z.string().min(1), - strategy: z - .object({ - familyId: z.string().uuid(), - versionId: z.string().uuid(), - origin: z.literal('builtin'), - reviewId: z.string().uuid(), - package: z.unknown().transform(parseStrategyVersionPackage), - selection: builtinStrategySelectionSchema, - }) - .strict(), + strategy: z.discriminatedUnion('origin', [ + z + .object({ + familyId: z.string().uuid(), + versionId: z.string().uuid(), + origin: z.literal('builtin'), + reviewId: z.string().uuid(), + package: z.unknown().transform(parseStrategyVersionPackage), + selection: builtinStrategySelectionSchema, + }) + .strict(), + z + .object({ + familyId: z.string().uuid(), + versionId: z.string().uuid(), + origin: z.literal('candidate'), + baselineVersionId: z.string().uuid(), + reviewId: z.string().uuid().nullable(), + package: z.unknown().transform(parseStrategyVersionPackage), + selection: retainedProgramSelectionSchema, + execution: candidateExecutionSchema, + }) + .strict(), + ]), datasetHash: hash, policy: replayConfigSchema, analyticsPolicy: metricsPolicy, @@ -117,6 +136,9 @@ export const canonicalRunRequestSchema = admitted.superRefine((value, context) = const ledger = policy.matching.risk.ledger; const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b); const valid = + (strategy.origin === 'candidate' + ? strategy.package.execution?.kind === 'isolated-candidate/v1' + : strategy.package.execution === undefined) && strategy.package.program.strategyId === selection.strategyId && strategy.package.program.strategyVersion === selection.strategyVersion && ledger.sessionId === value.runId && @@ -146,6 +168,12 @@ export const canonicalRunRequestSchema = admitted.superRefine((value, context) = } }); export type CanonicalRunRequest = z.infer; +/** Derive execution from the strict origin branch, never from an independent client flag. */ +export function canonicalStrategyExecution(request: CanonicalRunRequest) { + return request.strategy.origin === 'candidate' + ? ('typescript-isolated-candidate/v1' as const) + : ('typescript-retained-builtin/v1' as const); +} export interface CanonicalRunResult { kind: 'canonical-result/v1'; @@ -155,7 +183,7 @@ export interface CanonicalRunResult { completedAt: string; executionTime: number; financialEngine: 'rust'; - strategyExecution: 'typescript-retained-builtin/v1'; + strategyExecution: 'typescript-retained-builtin/v1' | 'typescript-isolated-candidate/v1'; request: CanonicalRunRequest; financial: ReplayReportResult; analytics: CanonicalBacktestAnalytics; @@ -165,6 +193,7 @@ export function isCanonicalRunResult(value: ResearchRunResult): value is Canonic return 'kind' in value && value.kind === 'canonical-result/v1'; } export interface CanonicalRunCapability { + execution?: CandidateExecution; available: boolean; reason: string | null; } diff --git a/apps/stock/config/src/contracts/chronological-validation.ts b/apps/stock/config/src/contracts/chronological-validation.ts index 062b1dd0..b65c4698 100644 --- a/apps/stock/config/src/contracts/chronological-validation.ts +++ b/apps/stock/config/src/contracts/chronological-validation.ts @@ -72,6 +72,12 @@ export const chronologicalValidationPolicy = { model: 'deterministic-unfitted', readiness: 'input-checks-only', } as const; +/** Arbitrary candidate code does not prove deterministic/unfitted behavior. */ +export function chronologicalPolicyForOrigin(origin: 'builtin' | 'candidate') { + return origin === 'candidate' + ? { ...chronologicalValidationPolicy, model: 'unverified-candidate' as const } + : chronologicalValidationPolicy; +} export interface ChronologicalValidationPreview { version: 'chronological-validation-preview/v1'; execution: 'preview-only'; @@ -79,7 +85,7 @@ export interface ChronologicalValidationPreview { input: ChronologicalValidationInput; /** Source lineage lives here; dataset parentDatasetHash retains its legacy-v1 meaning. */ source: ExperimentPreview; - policy: typeof chronologicalValidationPolicy; + policy: ReturnType; partitions: [ValidationPartitionPreview, ValidationPartitionPreview, ValidationPartitionPreview]; } @@ -129,7 +135,7 @@ export interface ChronologicalValidationSelection { createdAt: string; principal: ResearchActor; /** Current original-version approval for the new holdout admissions. */ - reviewId: string; + reviewId: string | null; winner: ExperimentCandidate; /** All training candidates in ascending original candidate index. */ training: ValidationResultEvidence[]; diff --git a/apps/stock/config/src/contracts/cost-sensitivity.ts b/apps/stock/config/src/contracts/cost-sensitivity.ts index 44d88e85..8d5bf66a 100644 --- a/apps/stock/config/src/contracts/cost-sensitivity.ts +++ b/apps/stock/config/src/contracts/cost-sensitivity.ts @@ -1,6 +1,7 @@ /** Cost diagnostics reuse ordinary experiments and the authoritative Rust matcher. */ import { z } from 'zod'; import type { financialDecimal } from '@stock-bot/types'; +import { candidateOverrideSchema } from './candidate-execution'; import { canonicalResearchSettingsSchema, type CanonicalRunRequest } from './canonical-research'; import { MAX_EXPERIMENT_TRIALS, @@ -21,6 +22,7 @@ export const costSensitivityInputSchema = z .object({ backtestId: z.string().uuid(), name: z.string().trim().min(1), + candidate: candidateOverrideSchema.optional(), /** Baseline is automatic and consumes one of the existing 100 trial slots. */ scenarios: z .array(costScenarioSchema) diff --git a/apps/stock/config/src/contracts/experiments.ts b/apps/stock/config/src/contracts/experiments.ts index a45f63e6..17ffce57 100644 --- a/apps/stock/config/src/contracts/experiments.ts +++ b/apps/stock/config/src/contracts/experiments.ts @@ -6,6 +6,7 @@ import type { ResearchActor, StrategyParameterValue, } from '@stock-bot/types'; +import { candidateOverrideSchema } from './candidate-execution'; import type { CanonicalRunRequest } from './canonical-research'; /** Admission bound for atomic expansion, not a promise of concurrent execution. */ @@ -36,6 +37,7 @@ export const experimentInputSchema = z backtestId: z.string().uuid(), name: z.string().trim().min(1), grid, + candidate: candidateOverrideSchema.optional(), }) .strict(); export const experimentSubmissionSchema = experimentInputSchema.extend({ @@ -70,7 +72,7 @@ export interface ExperimentTrialRetry { recordedAt: string; principal: ResearchActor; /** Current approval at retry admission; the original run snapshot stays immutable. */ - reviewId: string; + reviewId: string | null; } export interface ExperimentRetryResult { retry: ExperimentTrialRetry; diff --git a/apps/stock/config/src/contracts/paper-deployments.ts b/apps/stock/config/src/contracts/paper-deployments.ts new file mode 100644 index 00000000..abdf13e0 --- /dev/null +++ b/apps/stock/config/src/contracts/paper-deployments.ts @@ -0,0 +1,215 @@ +/** Explicit human promotion into a trusted paper host. No live capability or code import. */ +import { z } from 'zod'; +import type { financialDecimal } from '@stock-bot/types'; +import { retainedProgramSelectionSchema } from './candidate-execution'; +import { replayConfigSchema } from './canonical-replay'; +import { researchFindingSourceSchema } from './research'; + +export type { financialDecimal }; + +const id = z + .string() + .min(1) + .refine(value => [...value].every(c => c.charCodeAt(0) >= 32 && c.charCodeAt(0) !== 127)); +const uuid = z + .string() + .uuid() + .transform(value => value.toLowerCase()); +const hash = z.string().regex(/^[a-f0-9]{64}$/); +const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); +const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER); +const riskSession = replayConfigSchema.shape.matching.shape.risk.shape.ledger.shape.riskSession; +export const paperPolicySchema = z + .object({ + version: z.literal(1), + sourceId: id, + priceBasis: z.literal('raw'), + maxFeedAgeMs: counter.refine(v => v > 0), + observations: z.array( + z + .object({ + seriesId: id, + instrumentId: id, + intervalMs: counter.refine(v => v > 0), + staleAfterMs: counter, + }) + .strict() + ), + cadence: z.array(z.object({ ownerId: id, seriesIds: z.array(id).min(1) }).strict()), + calendars: z + .array( + z + .object({ + instrumentId: id, + calendarId: id, + revision: id, + sessions: z + .array(z.object({ sessionId: id, opensAt: time, closesAt: time }).strict()) + .min(1), + }) + .strict() + ) + .min(1), + riskBoundaries: z.array(riskSession), + }) + .strict() + .transform(value => ({ + ...value, + calendars: value.calendars.map(calendar => ({ + ...calendar, + sessions: [...calendar.sessions].sort((a, b) => a.opensAt - b.opensAt), + })), + riskBoundaries: [...value.riskBoundaries].sort((a, b) => a.startsAt - b.startsAt), + })); +export const deployedPaperConfigurationSchema = z + .object({ + version: z.literal(2), + matching: replayConfigSchema.shape.matching.extend({ + series: z + .array( + replayConfigSchema.shape.matching.shape.series.element.extend({ + mode: z.literal('Quote'), + }) + ) + .length(1), + }), + strategies: z.tuple([retainedProgramSelectionSchema]), + policy: paperPolicySchema, + }) + .strict(); +export const paperHostIdentitySchema = z + .object({ + version: z.literal('paper-host/v1'), + hostSha256: hash, + engineWrapperSha256: hash, + engineBinarySha256: hash, + dependencyLockSha256: hash, + runtime: z.literal('bun'), + runtimeVersion: id, + platform: id, + arch: id, + }) + .strict(); +/** Only transport and future clocks are operator inputs. Economics come from the selected cost trial. */ +export const paperTransportSchema = z + .object({ + accountId: id, + sessionId: id, + quoteSeriesId: id, + riskSession, + policy: paperPolicySchema, + }) + .strict(); +export const paperPromotionInputSchema = z + .object({ + name: z.string().trim().min(1), + outOfSample: researchFindingSourceSchema.refine( + value => value.kind !== 'experiment/v1', + 'Select a sealed chronological or walk-forward report' + ), + testRunId: uuid, + costExperimentId: uuid, + costPreviewHash: hash, + costRunId: uuid, + transport: paperTransportSchema, + reason: z.string().trim().min(1), + acknowledgeTrustedCode: z.literal(true), + }) + .strict(); +export const paperPromotionSubmissionSchema = paperPromotionInputSchema.extend({ + previewHash: hash, +}); +export const paperMetricEvidenceSchema = z + .object({ + runId: uuid, + datasetHash: hash, + economicHash: hash, + resultHash: hash, + metrics: z.record(z.number().finite().nullable()), + fillCount: counter, + limitations: z.array(z.string()), + }) + .strict(); +export const paperPromotionPreviewSchema = z + .object({ + version: z.literal('paper-promotion-preview/v1'), + previewHash: hash, + input: paperPromotionInputSchema, + strategy: z + .object({ + familyId: uuid, + versionId: uuid, + reviewId: uuid, + origin: z.enum(['builtin', 'candidate']), + artifactSha256: hash, + dependencyLockSha256: hash, + }) + .strict(), + configuration: deployedPaperConfigurationSchema, + host: paperHostIdentitySchema, + evidence: z + .object({ test: paperMetricEvidenceSchema, costs: z.array(paperMetricEvidenceSchema).min(2) }) + .strict(), + limitations: z.array(z.string()), + }) + .strict(); +export const paperDeploymentSchema = z + .object({ + id: uuid, + version: z.literal('paper-deployment/v1'), + principal: z.literal('operator'), + createdAt: z.string().datetime(), + promotionHash: hash, + preview: paperPromotionPreviewSchema, + }) + .strict(); +export const paperDeploymentBindingSchema = z + .object({ + deploymentId: uuid, + promotionHash: hash, + strategyVersionId: uuid, + artifactSha256: hash, + dependencyLockSha256: hash, + host: paperHostIdentitySchema, + }) + .strict(); +export const paperReadinessSchema = z + .object({ + configured: z.boolean(), + accountId: z.string().nullable(), + sourceId: z.string().nullable(), + active: z.boolean(), + ready: z.boolean(), + operatorHalted: z.boolean(), + connected: z.boolean(), + reasons: z.array(z.string()), + lastReceivedAt: time.nullable(), + lastAvailableAt: time.nullable(), + requiresHistoricalRecovery: z.boolean(), + pendingInput: z.string().nullable(), + pendingBatch: z.string().nullable(), + pendingDecisionSequence: counter.nullable(), + nativeStatus: z + .union([ + z.literal('Running'), + z.literal('Complete'), + z.object({ Failed: z.object({ diagnostic: z.string() }).strict() }).strict(), + ]) + .nullable(), + risk: z.object({ dailyHalted: z.boolean(), drawdownHalted: z.boolean() }).strict().nullable(), + }) + .strict(); +export const paperDeploymentStatusSchema = z + .object({ + deploymentId: uuid, + boundDeploymentId: uuid.nullable(), + readiness: paperReadinessSchema, + }) + .strict(); +export type PaperPromotionInput = z.input; +export type PaperPromotionPreview = z.infer; +export type PaperDeployment = z.infer; +export type PaperDeploymentBinding = z.infer; +export type PaperHostIdentity = z.infer; +export type PaperDeploymentStatus = z.infer; +export type DeployedPaperConfiguration = z.infer; diff --git a/apps/stock/config/src/contracts/research-agents.ts b/apps/stock/config/src/contracts/research-agents.ts index 26b505ef..db85460e 100644 --- a/apps/stock/config/src/contracts/research-agents.ts +++ b/apps/stock/config/src/contracts/research-agents.ts @@ -27,6 +27,8 @@ export const createResearchAgentSchema = z name: z.string().trim().min(1), allowedProjectIds: ids, allowedBacktestIds: ids, + /** Explicit operator opt-in, a subset of allowed backtests. Omitted means none. */ + allowOwnCandidateBacktestIds: ids.optional(), limits: researchAgentLimitsSchema, }) .strict(); @@ -50,7 +52,11 @@ export const researchAgentRecordSchema = z allowedProjectIds: ids, grants: z.array( z - .object({ backtestId: z.string().uuid(), policyHash: z.string().regex(/^[a-f0-9]{64}$/) }) + .object({ + backtestId: z.string().uuid(), + policyHash: z.string().regex(/^[a-f0-9]{64}$/), + allowOwnCandidates: z.boolean().optional(), + }) .strict() ), limits: researchAgentLimitsSchema, diff --git a/apps/stock/config/src/contracts/research-responses/comparison.ts b/apps/stock/config/src/contracts/research-responses/comparison.ts new file mode 100644 index 00000000..5620899b --- /dev/null +++ b/apps/stock/config/src/contracts/research-responses/comparison.ts @@ -0,0 +1,115 @@ +/** Shared response verification; no IO or financial calculations. */ +import { z } from 'zod'; +import { + experimentComparisonDimensions, + experimentComparisonInputSchema, + type ExperimentComparison, + type ExperimentComparisonInput, +} from '../experiment-comparison'; +import { parseWorkbenchExperimentDetail, type WorkbenchExperimentDetailView } from './experiment'; + +export type ExperimentComparisonView = Omit & { + experiments: [WorkbenchExperimentDetailView, WorkbenchExperimentDetailView]; +}; +const hash = z.string().regex(/^[a-f0-9]{64}$/), + uuid = z.string().uuid(); +const schema = z.object({ + version: z.literal('experiment-comparison/v1'), + policy: z.literal('retained-input-compatibility/v1'), + selection: z.object({ leftId: uuid, rightId: uuid, referenceTrialKey: hash }).strict(), + reference: z.object({ + experimentId: uuid, + trialKey: hash, + index: z.number().int().nonnegative(), + runId: uuid.nullable(), + summaryAvailable: z.boolean(), + diagnostic: z.string().nullable(), + }), + experiments: z.tuple([z.unknown(), z.unknown()]), + rows: z + .array( + z.object({ + experimentId: uuid, + trialKey: hash, + inputCompatibility: z.enum(['match', 'mismatch']), + differences: z.array(z.enum(experimentComparisonDimensions)), + summaryAvailable: z.boolean(), + ready: z.boolean(), + }) + ) + .min(2) + .max(200), + limitations: z.array(z.string().min(1)).min(1), +}); +const invalid = () => + new Error('The experiment comparison could not be verified. Refresh the same selection.'); +export function parseComparisonQuery(params: URLSearchParams): ExperimentComparisonInput { + const allowed = ['leftId', 'rightId', 'referenceTrialKey']; + for (const key of params.keys()) { + if (!allowed.includes(key) || params.getAll(key).length !== 1) { + throw new Error( + 'Comparison URL requires two different experiment IDs and at most one reference trial key. Unknown or repeated query fields are not supported.' + ); + } + } + const result = experimentComparisonInputSchema.safeParse(Object.fromEntries(params)); + if (!result.success) { + throw new Error( + 'Select two different saved experiments to compare. The URL must contain valid leftId and rightId values and, when supplied, a valid referenceTrialKey.' + ); + } + return result.data; +} +export function parseExperimentComparison( + raw: unknown, + input: ExperimentComparisonInput +): ExperimentComparisonView { + const value = schema.parse(raw), + experiments = value.experiments.map( + parseWorkbenchExperimentDetail + ) as ExperimentComparisonView['experiments']; + const [left, right] = experiments; + const expectedKey = input.referenceTrialKey ?? left.trials[0]?.trialKey; + const reference = left.trials.find(trial => trial.trialKey === expectedKey); + if ( + !reference || + left.id !== input.leftId || + right.id !== input.rightId || + value.selection.leftId !== input.leftId || + value.selection.rightId !== input.rightId || + value.selection.referenceTrialKey !== expectedKey || + value.reference.experimentId !== left.id || + value.reference.trialKey !== reference.trialKey || + value.reference.index !== reference.index || + value.reference.runId !== reference.runId || + value.reference.summaryAvailable !== reference.comparable || + value.reference.diagnostic !== reference.diagnostic + ) { + throw invalid(); + } + const expectedRows = experiments.flatMap(experiment => + experiment.trials.map(trial => ({ experimentId: experiment.id, trial })) + ); + if (value.rows.length !== expectedRows.length) { + throw invalid(); + } + value.rows.forEach((row, index) => { + const expected = expectedRows[index], + order = row.differences.map(key => experimentComparisonDimensions.indexOf(key)); + if ( + !expected || + row.experimentId !== expected.experimentId || + row.trialKey !== expected.trial.trialKey || + order.some((position, i) => i > 0 && position <= (order[i - 1] ?? -1)) || + (row.inputCompatibility === 'match') !== (row.differences.length === 0) || + row.summaryAvailable !== expected.trial.comparable || + row.ready !== + (row.inputCompatibility === 'match' && row.summaryAvailable && reference.comparable) + ) { + throw invalid(); + } + }); + return { ...value, experiments }; +} + +export { invalid as invalidExperimentComparison }; diff --git a/apps/stock/config/src/contracts/research-responses/experiment.ts b/apps/stock/config/src/contracts/research-responses/experiment.ts new file mode 100644 index 00000000..4deb45ba --- /dev/null +++ b/apps/stock/config/src/contracts/research-responses/experiment.ts @@ -0,0 +1,349 @@ +/** Shared response verification for browser and authorized research clients; no IO or accounting. */ +import { z } from 'zod'; +import { canonicalRunRequestSchema } from '../canonical-research'; +import { + costScenarioSchema, + costSensitivityInputSchema, + type CostSensitivityDetail, + type CostSensitivityPreview, +} from '../cost-sensitivity'; +import { + experimentInputSchema, + MAX_EXPERIMENT_TRIALS, + type ExperimentDetail, + type ExperimentPreview, + type ExperimentSummary, +} from '../experiments'; +import { researchActorSchema } from '../research'; +import { canonicalStrategyJson, validateStrategyParameters } from '../strategy'; + +export class ExperimentApiError extends Error { + constructor( + message: string, + public readonly status: number | null + ) { + super(message); + } + get ambiguous() { + return this.status === null || this.status >= 500; + } +} +const hash = z.string().regex(/^[a-f0-9]{64}$/); +const count = z.number().int().nonnegative().max(MAX_EXPERIMENT_TRIALS); +const counter = z.number().int().nonnegative().max(2147483647); +const scalar = z.union([z.string(), z.number().finite(), z.boolean()]); +const candidate = z + .object({ + index: count, + trialKey: hash, + parameters: z.record(scalar), + }) + .strict(); +const statuses = ['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'] as const; +const counts = z.object({ + pending: count, + running: count, + paused: count, + completed: count, + failed: count, + cancelled: count, +}); +const summary = z.object({ + kind: z.enum(['parameters', 'cost-sensitivity']).optional(), + id: z.string().uuid(), + name: z.string().min(1), + backtestId: z.string().uuid(), + createdAt: z.string().min(1), + cancelRequested: z.boolean(), + trialCount: count.min(1), + counts, + datasetHash: hash, + strategyVersionId: z.string().uuid(), + previewHash: hash, +}); +const timestamp = z.number().int().min(-8640000000000000).max(8640000000000000); +const dataset = z + .object({ + version: z.literal(2), + hash, + bounds: z.object({ + warmupStart: timestamp, + tradeStart: timestamp, + tradeEnd: timestamp, + }), + series: z.array( + z.object({ id: z.string(), instrumentId: z.string(), interval: z.string() }).passthrough() + ), + }) + .passthrough(); +/** Only the manifest fields consumed by this UI are structurally decoded here. */ +export type ExperimentPreviewView = Omit & { + dataset: z.infer; +}; +export type ExperimentDetailView = Omit & { + preview: ExperimentPreviewView; +}; +export type CostSensitivityPreviewView = Omit & { + dataset: ExperimentPreviewView['dataset']; + source: ExperimentPreviewView; +}; +export type WorkbenchExperimentPreviewView = ExperimentPreviewView | CostSensitivityPreviewView; +export type CostSensitivityDetailView = Omit & { + preview: CostSensitivityPreviewView; +}; +export type WorkbenchExperimentDetailView = ExperimentDetailView | CostSensitivityDetailView; +const preview = z + .object({ + version: z.literal('research-experiment-preview/v1'), + previewHash: hash, + input: experimentInputSchema, + request: canonicalRunRequestSchema, + dataset, + candidates: z.array(candidate).min(1).max(MAX_EXPERIMENT_TRIALS), + }) + .strict(); +const metric = z.number().finite().nullable(); +export const experimentMetricsSchema = z.object({ + totalReturn: metric, + cagr: metric, + maxDrawdown: metric, + exposureTime: metric, + volatility: metric, + downsideDeviation: metric, + sharpeRatio: metric, + sortinoRatio: metric, + var95: metric, + cvar95: metric, + var99: metric, + alpha: z.null(), + beta: z.null(), + informationRatio: z.null(), + roundTripCount: z.null(), + winRate: z.null(), + profitFactor: z.null(), + avgWin: z.null(), + avgLoss: z.null(), +}); +const trial = candidate.extend({ + runId: z.string().uuid().nullable(), + attemptNumber: counter, + retryCount: counter, + status: z.enum([...statuses, 'missing']), + progress: z.number().finite().min(0).max(100), + cancelRequested: z.boolean(), + error: z.string().nullable(), + comparable: z.boolean(), + diagnostic: z.string().nullable(), + metrics: experimentMetricsSchema.nullable(), + unavailable: z.record(z.string()).nullable(), + limitations: z.array(z.string()), +}); +const detail = summary.extend({ + standalone: z.boolean().optional(), + preview, + trials: z.array(trial).max(MAX_EXPERIMENT_TRIALS), +}); +const retryReceipt = z.object({ + id: z.string().uuid(), + experimentId: z.string().uuid(), + runId: z.string().uuid(), + trialKey: hash, + retryNumber: counter.min(1), + previousAttemptNumber: counter, + previousAttemptId: z.string().uuid().nullable(), + error: z.string().nullable(), + progress: z.number().finite().min(0).max(100), + currentDate: z.string().nullable(), + startedAt: z.string().nullable(), + completedAt: z.string().nullable(), + pausedAt: z.string().nullable(), + failureUpdatedAt: z.string().min(1), + recordedAt: z.string().min(1), + principal: researchActorSchema, + reviewId: z.string().uuid().nullable(), +}); +/** Immutable source identity captured when the operator reviews a failed trial. */ +export interface ExperimentRetryTarget { + experimentId: string; + backtestId: string; + previewHash: string; + runId: string; + trialKey: string; +} +const same = (left: unknown, right: unknown) => + canonicalStrategyJson(left) === canonicalStrategyJson(right); +const invalid = () => + new ExperimentApiError( + 'The experiment response could not be verified. Refresh or retry the same submission.', + null + ); + +function parseSummary(value: unknown): ExperimentSummary { + const parsed = summary.parse(value); + if (Object.values(parsed.counts).reduce((sum, value) => sum + value, 0) > parsed.trialCount) { + throw invalid(); + } + return parsed; +} +export function parseExperimentPreview(value: unknown): ExperimentPreviewView { + const parsed = preview.parse(value); + if ( + parsed.input.backtestId !== parsed.request.backtestId || + (parsed.input.candidate && + (parsed.request.strategy.origin !== 'candidate' || + parsed.input.candidate.versionId !== parsed.request.strategy.versionId || + !same( + validateStrategyParameters( + parsed.request.strategy.package, + parsed.input.candidate.parameters + ), + parsed.request.strategy.selection.parameters + ))) || + parsed.dataset.hash !== parsed.request.datasetHash || + parsed.dataset.bounds.warmupStart > parsed.dataset.bounds.tradeStart || + parsed.dataset.bounds.tradeStart >= parsed.dataset.bounds.tradeEnd || + !parsed.dataset.series.some( + series => + series.id === parsed.request.strategy.selection.seriesId && + series.instrumentId === parsed.request.strategy.selection.instrumentId + ) || + parsed.candidates.some((item, index) => item.index !== index) || + new Set(parsed.candidates.map(item => item.trialKey)).size !== parsed.candidates.length + ) { + throw invalid(); + } + // The server retains and verifies the complete manifest; the browser only renders its identity/window. + return parsed; +} +const costCandidate = candidate.extend({ costs: costScenarioSchema }); +const costPreview = preview + .omit({ version: true, input: true, candidates: true }) + .extend({ + version: z.literal('cost-sensitivity-preview/v1'), + input: costSensitivityInputSchema, + source: z.unknown(), + candidates: z.array(costCandidate).min(2).max(MAX_EXPERIMENT_TRIALS), + }) + .strict(); +const costDetail = summary.extend({ + kind: z.literal('cost-sensitivity'), + standalone: z.boolean().optional(), + preview: z.unknown(), + trials: z.array(trial.extend({ costs: costScenarioSchema })).max(MAX_EXPERIMENT_TRIALS), +}); +export function parseCostSensitivityPreview(raw: unknown): CostSensitivityPreviewView { + const parsed = costPreview.parse(raw), + source = parseExperimentPreview(parsed.source); + const costs = [ + { + feeRate: source.request.policy.matching.risk.feeRate, + slippageRate: source.request.policy.matching.slippageRate, + }, + ...parsed.input.scenarios, + ]; + if ( + !same(source.input, { + backtestId: parsed.input.backtestId, + name: parsed.input.name, + grid: {}, + ...(parsed.input.candidate ? { candidate: parsed.input.candidate } : {}), + }) || + source.candidates.length !== 1 || + !same(source.candidates[0]?.parameters, source.request.strategy.selection.parameters) || + !same(parsed.request, source.request) || + !same(parsed.dataset, source.dataset) || + parsed.candidates.length !== costs.length || + new Set(costs.map(canonicalStrategyJson)).size !== costs.length || + new Set(parsed.candidates.map(item => item.trialKey)).size !== costs.length || + parsed.candidates.some( + (item, index) => + item.index !== index || + !same(item.parameters, source.request.strategy.selection.parameters) || + !same(item.costs, costs[index]) + ) + ) { + throw invalid(); + } + return { ...parsed, source } as CostSensitivityPreviewView; +} +function checkDetail( + parsed: z.infer | z.infer, + retained: WorkbenchExperimentPreviewView +) { + parseSummary(parsed); + if ( + parsed.backtestId !== retained.input.backtestId || + parsed.name !== retained.input.name || + parsed.previewHash !== retained.previewHash || + parsed.datasetHash !== retained.request.datasetHash || + parsed.strategyVersionId !== retained.request.strategy.versionId || + parsed.trialCount !== retained.candidates.length || + parsed.trials.length !== parsed.trialCount + ) { + throw invalid(); + } + const costKind = retained.version === 'cost-sensitivity-preview/v1'; + if ( + (costKind && parsed.kind !== 'cost-sensitivity') || + (!costKind && parsed.kind === 'cost-sensitivity') + ) { + throw invalid(); + } + const runIds = new Set(); + for (const [index, item] of parsed.trials.entries()) { + const expected = retained.candidates[index]; + if ( + !expected || + item.index !== expected.index || + item.trialKey !== expected.trialKey || + !same(item.parameters, expected.parameters) || + (costKind && + (!('costs' in item) || !('costs' in expected) || !same(item.costs, expected.costs))) || + (item.status === 'missing') !== (item.runId === null) || + (item.status === 'missing' && (item.attemptNumber !== 0 || item.retryCount !== 0)) || + (item.comparable && (item.status !== 'completed' || !item.metrics || !item.unavailable)) || + (item.runId !== null && runIds.has(item.runId)) + ) { + throw invalid(); + } + if (item.runId) { + runIds.add(item.runId); + } + } + if ( + statuses.some( + status => + parsed.counts[status] !== parsed.trials.filter(item => item.status === status).length + ) + ) { + throw invalid(); + } + + return { ...parsed, preview: retained }; +} +export function parseExperimentDetail(value: unknown): ExperimentDetailView { + const parsed = detail.parse(value); + return checkDetail(parsed, parseExperimentPreview(parsed.preview)) as ExperimentDetailView; +} +export function parseWorkbenchExperimentDetail(value: unknown): WorkbenchExperimentDetailView { + const version = z.object({ preview: z.object({ version: z.string() }) }).parse(value) + .preview.version; + if (version === 'research-experiment-preview/v1') { + return parseExperimentDetail(value); + } + if (version !== 'cost-sensitivity-preview/v1') { + throw invalid(); + } + const parsed = costDetail.parse(value); + return checkDetail( + parsed, + parseCostSensitivityPreview(parsed.preview) + ) as CostSensitivityDetailView; +} + +export { + retryReceipt as experimentRetryReceiptSchema, + invalid as invalidExperimentResponse, + parseSummary as parseExperimentSummary, + same as sameExperimentInput, +}; diff --git a/apps/stock/config/src/contracts/research-responses/index.ts b/apps/stock/config/src/contracts/research-responses/index.ts new file mode 100644 index 00000000..6cbf50f8 --- /dev/null +++ b/apps/stock/config/src/contracts/research-responses/index.ts @@ -0,0 +1,5 @@ +export * from './experiment'; +export * from './validation'; +export * from './validation-preview'; +export * from './walk-forward'; +export * from './comparison'; diff --git a/apps/stock/config/src/contracts/research-responses/validation-preview.ts b/apps/stock/config/src/contracts/research-responses/validation-preview.ts new file mode 100644 index 00000000..99e37cb5 --- /dev/null +++ b/apps/stock/config/src/contracts/research-responses/validation-preview.ts @@ -0,0 +1,138 @@ +/** Shared response verification for browser and authorized research clients; no IO or accounting. */ +import { z } from 'zod'; +import { + chronologicalPolicyForOrigin, + chronologicalValidationInputSchema, + type ChronologicalValidationInput, + type ChronologicalValidationPreview, + type ValidationPartitionPreview, +} from '../chronological-validation'; +import { canonicalStrategyJson } from '../strategy'; +import { parseExperimentPreview, type ExperimentPreviewView } from './experiment'; + +export type ValidationPartitionView = Omit & { + dataset: ExperimentPreviewView['dataset']; +}; +export type ChronologicalValidationPreviewView = Omit< + ChronologicalValidationPreview, + 'source' | 'partitions' +> & { + source: ExperimentPreviewView; + partitions: [ValidationPartitionView, ValidationPartitionView, ValidationPartitionView]; +}; +const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); +const counts = z.object({ + totalBars: counter, + availableWarmup: counter, + admittedWarmup: counter, + ignoredLateWarmup: counter, + availableEvaluation: counter, + terminalAtEnd: counter, + unavailableAtEnd: counter, +}); +const partition = z.object({ + phase: z.enum(['train', 'validation', 'test']), + dataset: z.unknown(), + request: z.unknown(), + counts, + requiredWarmup: counter, + warnings: z.array(z.string()), +}); +const prepared = z.object({ + version: z.literal('chronological-validation-preview/v1'), + execution: z.literal('preview-only'), + previewHash: z.string().regex(/^[a-f0-9]{64}$/), + input: chronologicalValidationInputSchema, + source: z.unknown(), + policy: z.unknown(), + partitions: z.tuple([partition, partition, partition]), +}); +const same = (left: unknown, right: unknown) => + canonicalStrategyJson(left) === canonicalStrategyJson(right); +const invalid = () => + new Error( + 'The chronological validation preview could not be verified. Preview the current inputs again.' + ); + +export function parseChronologicalValidationPreview( + body: unknown, + input: ChronologicalValidationInput +): ChronologicalValidationPreviewView { + const value = prepared.parse(z.object({ preview: z.unknown() }).parse(body).preview); + const source = parseExperimentPreview(value.source); + const { recipe: _recipe, ...sourceInput } = input; + if ( + !same(value.input, input) || + !same(source.input, sourceInput) || + !same(value.policy, chronologicalPolicyForOrigin(source.request.strategy.origin)) + ) { + throw invalid(); + } + const phases = ['train', 'validation', 'test'] as const; + const partitions = value.partitions.map((part, index): ValidationPartitionView => { + const phase = phases[index]; + if (!phase || part.phase !== phase) { + throw invalid(); + } + const decoded = parseExperimentPreview({ + ...source, + dataset: part.dataset, + request: part.request, + }); + const { request, dataset } = decoded; + const expected = { + ...source.request, + datasetHash: dataset.hash, + policy: { + ...source.request.policy, + risk_boundaries: request.policy.risk_boundaries, + matching: { + ...source.request.policy.matching, + risk: { + ...source.request.policy.matching.risk, + ledger: { + ...source.request.policy.matching.risk.ledger, + riskSession: request.policy.matching.risk.ledger.riskSession, + }, + }, + }, + }, + }; + const measured = part.counts; + const metadata = (manifest: ExperimentPreviewView['dataset']) => { + const { hash: _hash, bounds: _bounds, barCount: _barCount, ...retained } = manifest; + return retained; + }; + if ( + !same(request, expected) || + !same(dataset.bounds, input.recipe[phase]) || + !same(metadata(dataset), metadata(source.dataset)) || + measured.totalBars !== dataset.barCount || + dataset.bounds.warmupStart < source.dataset.bounds.warmupStart || + dataset.bounds.tradeStart < source.dataset.bounds.tradeStart || + dataset.bounds.tradeEnd > source.dataset.bounds.tradeEnd || + measured.totalBars !== + measured.availableWarmup + + measured.availableEvaluation + + measured.terminalAtEnd + + measured.unavailableAtEnd || + measured.availableWarmup !== measured.admittedWarmup + measured.ignoredLateWarmup || + measured.admittedWarmup < part.requiredWarmup || + (source.request.strategy.origin === 'candidate' + ? part.requiredWarmup !== source.request.strategy.package.execution?.warmupBars + : part.requiredWarmup < 1) || + measured.availableEvaluation === 0 + ) { + throw invalid(); + } + return { ...part, phase, request, dataset }; + }) as [ValidationPartitionView, ValidationPartitionView, ValidationPartitionView]; + return { + ...value, + source, + policy: chronologicalPolicyForOrigin(source.request.strategy.origin), + partitions, + }; +} + +export { invalid as invalidValidationPreview }; diff --git a/apps/stock/config/src/contracts/research-responses/validation.ts b/apps/stock/config/src/contracts/research-responses/validation.ts new file mode 100644 index 00000000..dd2eada1 --- /dev/null +++ b/apps/stock/config/src/contracts/research-responses/validation.ts @@ -0,0 +1,288 @@ +/** Shared response verification for browser and authorized research clients; no IO or accounting. */ +import { z } from 'zod'; +import { + chronologicalValidationInputSchema, + type ChronologicalValidationDetail, +} from '../chronological-validation'; +import { researchActorSchema } from '../research'; +import { canonicalStrategyJson } from '../strategy'; +import { + experimentMetricsSchema, + parseExperimentDetail, + type ExperimentDetailView, +} from './experiment'; +import { + parseChronologicalValidationPreview, + type ChronologicalValidationPreviewView, +} from './validation-preview'; + +export type ValidationDetailView = Omit & { + preview: ChronologicalValidationPreviewView; + phases: Array<{ + phase: 'train' | 'validation' | 'test'; + status: 'not-admitted' | 'admitted' | 'missing'; + experimentId: string | null; + experiment: ExperimentDetailView | null; + }>; +}; +export class ValidationApiError extends Error { + constructor( + message: string, + public readonly status: number | null + ) { + super(message); + } + get ambiguous() { + return this.status === null || this.status >= 500; + } +} +const hash = z.string().regex(/^[a-f0-9]{64}$/), + uuid = z.string().uuid(), + count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); +const candidate = z.object({ + index: count, + trialKey: hash, + parameters: z.record(z.union([z.string(), z.number().finite(), z.boolean()])), +}); +const actor = researchActorSchema; +const summary = z.object({ + id: uuid, + name: z.string().min(1), + backtestId: uuid, + createdAt: z.string().min(1), + cancelRequested: z.boolean(), + previewHash: hash, + trainingCandidateCount: count.min(1).max(100), + stage: z.enum(['training', 'holdouts', 'reported']), +}); +export const validationEvidenceSchema = z.object({ + phase: z.enum(['train', 'validation', 'test']), + experimentId: uuid, + runId: uuid, + sourceCandidateIndex: count, + trialKey: hash, + parameters: candidate.shape.parameters, + datasetHash: hash, + requestHash: hash, + economicHash: hash, + metrics: experimentMetricsSchema, + unavailable: z.record(z.string()), + completePeriodCount: count, + periodicSampleCount: count, + fillCount: count, + limitations: z.array(z.string()), +}); +const selection = z.object({ + version: z.literal('chronological-validation-selection/v1'), + id: uuid, + validationId: uuid, + previewHash: hash, + selectionHash: hash, + createdAt: z.string().min(1), + principal: actor, + reviewId: uuid.nullable(), + winner: candidate, + training: z.array(validationEvidenceSchema).min(1).max(100), + holdoutExperimentIds: z.object({ validation: uuid, test: uuid }), +}); +const report = z.object({ + version: z.literal('chronological-validation-report/v1'), + id: uuid, + validationId: uuid, + previewHash: hash, + selectionHash: hash, + reportHash: hash, + createdAt: z.string().min(1), + principal: actor, + reset: z.literal('initial-capital-empty-positions'), + training: z.array(validationEvidenceSchema).min(1).max(100), + validation: validationEvidenceSchema, + test: validationEvidenceSchema, + limitations: z.array(z.string()), +}); +const capability = z.object({ available: z.boolean(), reason: z.string().nullable() }); +const phase = z.object({ + phase: z.enum(['train', 'validation', 'test']), + status: z.enum(['not-admitted', 'admitted', 'missing']), + experimentId: uuid.nullable(), + experiment: z.unknown(), +}); +const detail = summary.extend({ + preview: z.unknown(), + phases: z.tuple([phase, phase, phase]), + selection: selection.nullable(), + report: report.nullable(), + actions: z.object({ select: capability, finalize: capability }), +}); +const receipt = z.object({ + id: uuid, + validationId: uuid, + operation: z.enum(['select-and-admit-holdouts', 'finalize-report']), + previewHash: hash, + selectionHash: hash, + createdAt: z.string().min(1), + principal: actor, +}); +const same = (a: unknown, b: unknown) => canonicalStrategyJson(a) === canonicalStrategyJson(b); +const invalid = () => + new ValidationApiError( + 'The saved validation response could not be verified. Refresh or retry the same request.', + null + ); +export function parseValidationDetail(raw: unknown): ValidationDetailView { + const value = detail.parse(raw); + const rawPreview = z.object({ input: chronologicalValidationInputSchema }).parse(value.preview); + const preview = parseChronologicalValidationPreview({ preview: value.preview }, rawPreview.input); + if ( + value.backtestId !== preview.input.backtestId || + value.name !== preview.input.name || + value.previewHash !== preview.previewHash || + value.trainingCandidateCount !== preview.source.candidates.length || + (value.selection?.reviewId === null && + preview.source.request.strategy.origin !== 'candidate') || + (value.stage === 'training') !== (value.selection === null) || + (value.stage === 'reported') !== (value.report !== null) + ) { + throw invalid(); + } + const phases = value.phases.map((item, index) => { + const name = (['train', 'validation', 'test'] as const)[index]; + if (item.phase !== name || (item.status === 'admitted') !== (item.experiment !== null)) { + throw invalid(); + } + const expectedId = + name === 'train' + ? value.id + : (value.selection?.holdoutExperimentIds[name ?? 'validation'] ?? null); + if ( + item.experimentId !== expectedId || + (item.status === 'not-admitted') !== (expectedId === null) + ) { + throw invalid(); + } + const experiment = item.experiment === null ? null : parseExperimentDetail(item.experiment); + if (experiment) { + const prototype = preview.partitions[index]; + const parameters = + name === 'train' + ? prototype?.request.strategy.selection.parameters + : value.selection?.winner.parameters; + if (!prototype || !parameters) { + throw invalid(); + } + const expectedRequest = { + ...prototype.request, + strategy: { + ...prototype.request.strategy, + reviewId: + name === 'train' ? prototype.request.strategy.reviewId : value.selection?.reviewId, + selection: { ...prototype.request.strategy.selection, parameters }, + }, + }; + const expectedCandidates = + name === 'train' ? preview.source.candidates : [{ ...value.selection?.winner, index: 0 }]; + if ( + experiment.id !== expectedId || + experiment.backtestId !== value.backtestId || + !same(experiment.preview.request, expectedRequest) || + !same(experiment.preview.dataset, prototype.dataset) || + !same(experiment.preview.candidates, expectedCandidates) || + !same( + experiment.preview.input.candidate ?? null, + preview.input.candidate + ? { + ...preview.input.candidate, + parameters: + name === 'train' + ? preview.input.candidate.parameters + : value.selection?.winner.parameters, + } + : null + ) || + !same(experiment.preview.input.grid, name === 'train' ? preview.input.grid : {}) + ) { + throw invalid(); + } + } + return { ...item, experiment }; + }); + const validateEvidence = ( + item: z.infer, + expectedPhase: 'train' | 'validation' | 'test' + ) => { + const index = ['train', 'validation', 'test'].indexOf(expectedPhase); + const candidateValue = preview.source.candidates[item.sourceCandidateIndex]; + const phaseValue = phases[index]; + const trial = phaseValue?.experiment?.trials.find( + trial => trial.runId === item.runId && trial.trialKey === item.trialKey + ); + if ( + !candidateValue || + !phaseValue || + item.phase !== expectedPhase || + item.experimentId !== phaseValue.experimentId || + item.trialKey !== candidateValue.trialKey || + !same(item.parameters, candidateValue.parameters) || + item.datasetHash !== preview.partitions[index]?.dataset.hash || + (expectedPhase !== 'train' && item.sourceCandidateIndex !== value.selection?.winner.index) || + (phaseValue.experiment && + (!trial || + trial.status !== 'completed' || + !trial.comparable || + !same(trial.metrics, item.metrics) || + !same(trial.unavailable, item.unavailable) || + !same(trial.limitations, item.limitations))) + ) { + throw invalid(); + } + }; + if (value.selection) { + const chosen = value.selection; + if ( + chosen.validationId !== value.id || + chosen.previewHash !== value.previewHash || + !same(chosen.winner, preview.source.candidates[chosen.winner.index]) || + chosen.training.length !== value.trainingCandidateCount || + chosen.training.some((item, index) => item.sourceCandidateIndex !== index) || + new Set([value.id, chosen.holdoutExperimentIds.validation, chosen.holdoutExperimentIds.test]) + .size !== 3 + ) { + throw invalid(); + } + for (const item of chosen.training) { + validateEvidence(item, 'train'); + if (item.metrics.totalReturn === null) { + throw invalid(); + } + } + } + if (value.report) { + const saved = value.report; + if ( + !value.selection || + saved.validationId !== value.id || + saved.previewHash !== value.previewHash || + saved.selectionHash !== value.selection.selectionHash || + !same(saved.training, value.selection.training) + ) { + throw invalid(); + } + validateEvidence(saved.validation, 'validation'); + validateEvidence(saved.test, 'test'); + } + if ( + (value.actions.select.available && (value.selection || value.cancelRequested)) || + (value.actions.finalize.available && + (!value.selection || value.report || value.cancelRequested)) + ) { + throw invalid(); + } + return { ...value, preview, phases } as ValidationDetailView; +} + +export { + invalid as invalidValidationResponse, + same as sameValidationInput, + receipt as validationReceiptSchema, + summary as validationSummarySchema, +}; diff --git a/apps/stock/config/src/contracts/research-responses/walk-forward.ts b/apps/stock/config/src/contracts/research-responses/walk-forward.ts new file mode 100644 index 00000000..8401be83 --- /dev/null +++ b/apps/stock/config/src/contracts/research-responses/walk-forward.ts @@ -0,0 +1,314 @@ +/** Shared response verification for browser and authorized research clients; no IO or accounting. */ +import { z } from 'zod'; +import { researchActorSchema } from '../research'; +import { canonicalStrategyJson } from '../strategy'; +import { + MAX_WALK_FORWARD_RUNS, + MAX_WALK_FORWARD_WINDOWS, + walkForwardInputSchema, + walkForwardPolicy, + type WalkForwardDetail, + type WalkForwardInput, +} from '../walk-forward'; +import { parseExperimentPreview, type ExperimentPreviewView } from './experiment'; +import { + parseValidationDetail, + validationEvidenceSchema, + type ValidationDetailView, +} from './validation'; +import { + parseChronologicalValidationPreview, + type ChronologicalValidationPreviewView, +} from './validation-preview'; + +export type WalkForwardPreviewView = { + version: 'walk-forward-preview/v1'; + execution: 'preview-only'; + previewHash: string; + input: WalkForwardInput; + source: ExperimentPreviewView; + policy: typeof walkForwardPolicy; + windows: { index: number; preview: ChronologicalValidationPreviewView }[]; + counts: { + windows: number; + trainingRuns: number; + holdoutRuns: number; + totalRuns: number; + maxRuns: number; + }; +}; +export type WalkForwardDetailView = Omit & { + preview: WalkForwardPreviewView; + windows: { + index: number; + validationId: string; + status: 'admitted' | 'missing'; + validation: ValidationDetailView | null; + }[]; +}; +export class WalkForwardApiError extends Error { + constructor( + message: string, + public readonly status: number | null + ) { + super(message); + } + get ambiguous() { + return this.status === null || this.status >= 500; + } +} +const hash = z.string().regex(/^[a-f0-9]{64}$/), + uuid = z.string().uuid(), + count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); +const same = (left: unknown, right: unknown) => + canonicalStrategyJson(left) === canonicalStrategyJson(right); +const invalid = () => + new WalkForwardApiError( + 'The walk-forward response could not be verified. Refresh or retry the same request.', + null + ); +const prepared = z.object({ + version: z.literal('walk-forward-preview/v1'), + execution: z.literal('preview-only'), + previewHash: hash, + input: walkForwardInputSchema, + source: z.unknown(), + policy: z.unknown(), + windows: z + .array(z.object({ index: count, preview: z.unknown() })) + .min(2) + .max(MAX_WALK_FORWARD_WINDOWS), + counts: z.object({ + windows: count, + trainingRuns: count, + holdoutRuns: count, + totalRuns: count, + maxRuns: count, + }), +}); +export function parseWalkForwardPreview( + raw: unknown, + expected?: WalkForwardInput +): WalkForwardPreviewView { + const value = prepared.parse(raw), + source = parseExperimentPreview(value.source); + const { windows: recipes, ...sourceInput } = value.input; + const size = recipes.length, + candidates = source.candidates.length; + if ( + (expected && !same(value.input, expected)) || + !same(source.input, sourceInput) || + !same(value.policy, walkForwardPolicy) || + value.windows.length !== size || + !same(value.counts, { + windows: size, + trainingRuns: size * candidates, + holdoutRuns: size * 2, + totalRuns: size * (candidates + 2), + maxRuns: MAX_WALK_FORWARD_RUNS, + }) || + value.counts.totalRuns > MAX_WALK_FORWARD_RUNS + ) { + throw invalid(); + } + const windows = value.windows.map((item, index) => { + const recipe = recipes[index], + previous = recipes[index - 1]; + if ( + !recipe || + item.index !== index || + (previous && + (recipe.train.tradeStart < previous.train.tradeStart || + recipe.train.tradeEnd <= previous.train.tradeEnd || + recipe.validation.tradeStart < previous.test.tradeEnd)) + ) { + throw invalid(); + } + const name = `${value.input.name} · window ${index + 1}`; + const preview = parseChronologicalValidationPreview( + { preview: item.preview }, + { ...sourceInput, name, recipe } + ); + const { previewHash: _windowHash, ...childSource } = preview.source; + const { previewHash: _sourceHash, ...originalSource } = source; + if (!same(childSource, { ...originalSource, input: { ...sourceInput, name } })) { + throw invalid(); + } + return { index, preview }; + }); + return { ...value, source, windows, policy: walkForwardPolicy }; +} +const summary = z + .object({ + id: uuid, + backtestId: uuid, + name: z.string().min(1), + previewHash: hash, + createdAt: z.string().min(1), + cancelRequested: z.boolean(), + windowCount: count.min(2).max(MAX_WALK_FORWARD_WINDOWS), + reportedWindowCount: count, + trainingRunCount: count, + plannedRunCount: count.max(MAX_WALK_FORWARD_RUNS), + stage: z.enum(['windows', 'reported']), + }) + .superRefine((item, context) => { + if ( + item.reportedWindowCount > item.windowCount || + item.trainingRunCount < item.windowCount || + item.plannedRunCount !== item.trainingRunCount + 2 * item.windowCount + ) { + context.addIssue({ + code: z.ZodIssueCode.custom, + message: 'Inconsistent walk-forward counts', + }); + } + }); +const report = z.object({ + version: z.literal('walk-forward-report/v1'), + id: uuid, + walkForwardId: uuid, + previewHash: hash, + reportHash: hash, + createdAt: z.string().min(1), + principal: researchActorSchema, + reset: z.literal('initial-capital-empty-positions'), + segments: z + .array( + z.object({ + index: count, + validationId: uuid, + previewHash: hash, + selectionHash: hash, + reportId: uuid, + reportHash: hash, + validation: validationEvidenceSchema, + test: validationEvidenceSchema, + }) + ) + .min(2) + .max(MAX_WALK_FORWARD_WINDOWS), + limitations: z.array(z.string()), +}); +const detail = z.object({ + preview: z.unknown(), + windows: z.array( + z.object({ + index: count, + validationId: uuid, + status: z.enum(['admitted', 'missing']), + validation: z.unknown(), + }) + ), + report: report.nullable(), + actions: z.object({ + finalize: z.object({ available: z.boolean(), reason: z.string().nullable() }), + }), +}); +export function parseWalkForwardDetail(raw: unknown): WalkForwardDetailView { + const base = summary.parse(raw), + value = detail.parse(raw), + preview = parseWalkForwardPreview(value.preview); + if ( + base.backtestId !== preview.input.backtestId || + base.name !== preview.input.name || + base.previewHash !== preview.previewHash || + base.windowCount !== preview.counts.windows || + base.trainingRunCount !== preview.counts.trainingRuns || + base.plannedRunCount !== preview.counts.totalRuns || + value.windows.length !== base.windowCount || + new Set(value.windows.map(item => item.validationId)).size !== base.windowCount || + (base.stage === 'reported') !== (value.report !== null) + ) { + throw invalid(); + } + const windows = value.windows.map((item, index) => { + if (item.index !== index || (item.status === 'missing') !== (item.validation === null)) { + throw invalid(); + } + const validation = item.validation === null ? null : parseValidationDetail(item.validation); + if ( + validation && + (validation.id !== item.validationId || + validation.backtestId !== base.backtestId || + !same(validation.preview, preview.windows[index]?.preview)) + ) { + throw invalid(); + } + return { ...item, validation }; + }); + if ( + base.reportedWindowCount !== windows.filter(item => item.validation?.report).length || + (value.actions.finalize.available && + (base.cancelRequested || + value.report || + windows.some( + item => + !item.validation?.report || + item.validation.cancelRequested || + item.validation.phases.some( + phase => + phase.status !== 'admitted' || + !phase.experiment || + phase.experiment.cancelRequested || + phase.experiment.trials.some( + trial => + trial.status !== 'completed' || !trial.comparable || trial.cancelRequested + ) + ) + ))) + ) { + throw invalid(); + } + if (value.report) { + const saved = value.report; + if ( + saved.walkForwardId !== base.id || + saved.previewHash !== base.previewHash || + saved.segments.length !== base.windowCount + ) { + throw invalid(); + } + for (const [index, segment] of saved.segments.entries()) { + const member = windows[index], + frozen = preview.windows[index]?.preview, + child = member?.validation?.report; + const candidate = frozen?.source.candidates[segment.validation.sourceCandidateIndex]; + if ( + !member || + !frozen || + !candidate || + segment.index !== index || + segment.validationId !== member.validationId || + segment.previewHash !== frozen.previewHash || + segment.validation.phase !== 'validation' || + segment.test.phase !== 'test' || + segment.validation.sourceCandidateIndex !== segment.test.sourceCandidateIndex || + segment.validation.datasetHash !== frozen.partitions[1].dataset.hash || + segment.test.datasetHash !== frozen.partitions[2].dataset.hash || + [segment.validation, segment.test].some( + item => + item.trialKey !== candidate.trialKey || !same(item.parameters, candidate.parameters) + ) || + (member.validation && + (!child || + segment.reportId !== child.id || + segment.reportHash !== child.reportHash || + segment.selectionHash !== child.selectionHash || + !same(segment.validation, child.validation) || + !same(segment.test, child.test))) + ) { + throw invalid(); + } + } + } + return { ...base, ...value, preview, windows }; +} + +export { + invalid as invalidWalkForwardResponse, + same as sameWalkForwardInput, + hash as walkForwardHashSchema, + uuid as walkForwardIdSchema, + summary as walkForwardSummarySchema, +}; diff --git a/apps/stock/config/src/contracts/strategy.ts b/apps/stock/config/src/contracts/strategy.ts index dad75bbb..05a5dd81 100644 --- a/apps/stock/config/src/contracts/strategy.ts +++ b/apps/stock/config/src/contracts/strategy.ts @@ -10,6 +10,7 @@ import { meanReversionStrategySelectionSchema, smaStrategySelectionSchema, } from './builtin-strategy'; +import { candidatePackageExecutionSchema } from './candidate-execution'; import { maxStrategyPeriod } from './strategy-names'; export * from './builtin-strategy'; @@ -70,6 +71,7 @@ const text = z.string().min(1); const packageSchema = z .object({ version: z.literal(1), + execution: candidatePackageExecutionSchema.optional(), program: z .object({ strategyId: text, diff --git a/apps/stock/config/src/schemas/stock-app.schema.ts b/apps/stock/config/src/schemas/stock-app.schema.ts index 1a9d4594..98c14814 100644 --- a/apps/stock/config/src/schemas/stock-app.schema.ts +++ b/apps/stock/config/src/schemas/stock-app.schema.ts @@ -89,6 +89,14 @@ export const stockAppSchema = baseAppSchema.extend({ paperTradingCapital: z.number().default(100000), // Validated by the orchestrator's canonical contract before opening resources. canonicalPaper: z.record(z.unknown()).optional(), + // Explicitly creates an unbound/halted host. A supplied ID binds without activation. + paperDeploymentHost: z + .object({ + enabled: z.literal(true), + deploymentId: z.string().uuid().optional(), + }) + .strict() + .optional(), enableWebSocket: z.boolean().default(true), backtesting: z .object({ diff --git a/apps/stock/engine/index.d.ts b/apps/stock/engine/index.d.ts index 963a5065..327dc02a 100644 --- a/apps/stock/engine/index.d.ts +++ b/apps/stock/engine/index.d.ts @@ -7,3 +7,9 @@ export { declare const nativeBinding: typeof import('./dist/index'); export default nativeBinding; + +/** Exact wrapper/native bytes captured when this module first loaded. Artifact updates require restart. */ +export declare const loadedNativeIdentity: Readonly<{ + engineWrapperSha256: string; + engineBinarySha256: string; +}>; diff --git a/apps/stock/engine/index.mjs b/apps/stock/engine/index.mjs index de6e3052..53cecaaf 100644 --- a/apps/stock/engine/index.mjs +++ b/apps/stock/engine/index.mjs @@ -1,5 +1,7 @@ // ESM wrapper for the native module import { createRequire } from 'module'; +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; import { dirname, join } from 'path'; import { fileURLToPath } from 'url'; @@ -7,7 +9,21 @@ const require = createRequire(import.meta.url); const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); -const nativeBinding = require(join(__dirname, 'dist', 'engine.node')); +// Loaded executable identity is captured before native loading, not inferred later from disk. +// Build artifacts must remain immutable while the process runs; updates require a restart. +const nativePath = join(__dirname, 'dist', 'engine.node'); +const fileHash = path => createHash('sha256').update(readFileSync(path)).digest('hex'); +export const loadedNativeIdentity = Object.freeze({ + engineWrapperSha256: fileHash(__filename), + engineBinarySha256: fileHash(nativePath), +}); +const nativeBinding = require(nativePath); +if ( + loadedNativeIdentity.engineWrapperSha256 !== fileHash(__filename) || + loadedNativeIdentity.engineBinarySha256 !== fileHash(nativePath) +) { + throw new Error('Native artifacts changed while loading; restart with immutable build artifacts'); +} export const { TradingEngine, diff --git a/apps/stock/orchestrator/package.json b/apps/stock/orchestrator/package.json index 75edaf9d..0e4e657b 100644 --- a/apps/stock/orchestrator/package.json +++ b/apps/stock/orchestrator/package.json @@ -6,7 +6,7 @@ "main": "dist/index.js", "scripts": { "dev": "bun --watch src/index.ts", - "build": "bun build src/index.ts src/backtest/native-worker.ts --outdir dist --entry-naming '[name].[ext]' --target node --external @stock-bot/engine --external @tensorflow/tfjs-node --external chromium-bidi --external electron --external playwright --external playwright-core", + "build": "bun build src/index.ts src/backtest/native-worker.ts src/paper/paper-host.ts --outdir dist --entry-naming '[name].[ext]' --target node --external @stock-bot/engine --external @tensorflow/tfjs-node --external chromium-bidi --external electron --external playwright --external playwright-core", "start": "bun dist/index.js", "test": "bun test", "test:indicators": "bun test tests/indicators.test.ts", diff --git a/apps/stock/orchestrator/src/api/rest/paper-deployments.ts b/apps/stock/orchestrator/src/api/rest/paper-deployments.ts new file mode 100644 index 00000000..ce198687 --- /dev/null +++ b/apps/stock/orchestrator/src/api/rest/paper-deployments.ts @@ -0,0 +1,96 @@ +import { Hono } from 'hono'; +import { z } from 'zod'; +import { + paperActivationSchema, + paperHaltSchema, + PaperRuntimeError, +} from '../../contracts/paper-runtime'; +import { ExecutionConflictError } from '../../execution/repository'; +import { PaperDeploymentError } from '../../paper/paper-deployment-custody'; +import { paperAllowedOrigins, requirePaperOperator } from '../../paper/paper-operator'; +import type { PaperDeploymentHost } from '../../paper/PaperDeploymentHost'; + +export function createPaperDeploymentHostRoutes( + host?: PaperDeploymentHost, + origins: readonly string[] = paperAllowedOrigins() +) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.header('Cache-Control', 'no-store'); + requirePaperOperator(c.req.raw, origins); + await next(); + }); + app.onError((error, c) => { + if (error instanceof PaperDeploymentError) { + return c.json({ error: error.message }, error.status); + } + if (error instanceof z.ZodError || error instanceof SyntaxError) { + return c.json({ error: 'Invalid paper command' }, 400); + } + if (error instanceof PaperRuntimeError || error instanceof ExecutionConflictError) { + return c.json({ error: error.message }, 409); + } + return c.json({ error: 'Paper deployment host unavailable' }, 503); + }); + const configured = () => { + if (!host) { + throw new PaperDeploymentError( + 503, + 'Paper deployment host is explicitly disabled or unconfigured' + ); + } + return host; + }; + app.get('/:id/readiness', async c => + c.json( + await configured().status( + z + .string() + .uuid() + .transform(value => value.toLowerCase()) + .parse(c.req.param('id')) + ) + ) + ); + app.post('/:id/bind', async c => { + z.object({}) + .strict() + .parse(await c.req.json()); + return c.json( + await configured().bind( + z + .string() + .uuid() + .transform(value => value.toLowerCase()) + .parse(c.req.param('id')) + ) + ); + }); + app.post('/:id/activate', async c => { + const input = paperActivationSchema.parse(await c.req.json()); + return c.json( + await configured().activate( + z + .string() + .uuid() + .transform(value => value.toLowerCase()) + .parse(c.req.param('id')), + input.recoverPending + ) + ); + }); + app.post('/:id/halt', async c => { + const input = paperHaltSchema.parse(await c.req.json()); + return c.json( + await configured().halt( + z + .string() + .uuid() + .transform(value => value.toLowerCase()) + .parse(c.req.param('id')), + input.reason + ) + ); + }); + return app; +} diff --git a/apps/stock/orchestrator/src/api/rest/paper.ts b/apps/stock/orchestrator/src/api/rest/paper.ts index 7ff6d8bb..8a31ce82 100644 --- a/apps/stock/orchestrator/src/api/rest/paper.ts +++ b/apps/stock/orchestrator/src/api/rest/paper.ts @@ -1,6 +1,6 @@ import { Hono } from 'hono'; import { z } from 'zod'; -import { getVerifiedHttpPrincipal } from '@stock-bot/di'; +import { getCredentialHttpPrincipal } from '@stock-bot/di'; import { paperActivationSchema, paperConnectionSchema, @@ -10,12 +10,20 @@ import { type PaperReadiness, } from '../../contracts/paper-runtime'; import { ExecutionConflictError } from '../../execution/repository'; +import { PaperDeploymentError } from '../../paper/paper-deployment-custody'; +import { paperAllowedOrigins, requirePaperOperator } from '../../paper/paper-operator'; +import type { PaperDeploymentHost } from '../../paper/PaperDeploymentHost'; import type { OrchestratorServices } from '../../types'; -export function createPaperRoutes(services: OrchestratorServices): Hono { +export function createPaperRoutes( + services: OrchestratorServices, + options: { deploymentHost?: PaperDeploymentHost; origins?: readonly string[] } = {} +): Hono { const app = new Hono(); const runtime = () => { - const value = services.custom?.CanonicalPaperRuntime; + const value = options.deploymentHost + ? options.deploymentHost.runtime() + : services.custom?.CanonicalPaperRuntime; if (!value) { throw new PaperRuntimeError('not-ready', 'Canonical paper execution is not configured'); } @@ -24,8 +32,11 @@ export function createPaperRoutes(services: OrchestratorServices): Hono { app.use('*', async (c, next) => { c.header('Cache-Control', 'no-store'); if (c.req.method !== 'GET') { - const principal = getVerifiedHttpPrincipal(c.req.raw); + const principal = getCredentialHttpPrincipal(c.req.raw); const feed = c.req.path.includes('/feed/'); + if (!feed) { + requirePaperOperator(c.req.raw, options.origins ?? paperAllowedOrigins()); + } if (principal !== 'operator' && !(feed && principal === 'service')) { return c.json( { error: feed ? 'Verified feed producer required' : 'Human operator required' }, @@ -37,6 +48,9 @@ export function createPaperRoutes(services: OrchestratorServices): Hono { return undefined; }); app.onError((error, c) => { + if (error instanceof PaperDeploymentError) { + return c.json({ error: error.message }, error.status); + } if (error instanceof z.ZodError || error instanceof SyntaxError) { return c.json({ error: 'Invalid paper request' }, 400); } @@ -53,7 +67,10 @@ export function createPaperRoutes(services: OrchestratorServices): Hono { return c.json({ error: 'Canonical paper runtime unavailable' }, 503); }); app.get('/readiness', async c => { - if (!services.custom?.CanonicalPaperRuntime) { + if (options.deploymentHost) { + return c.json(await options.deploymentHost.readiness()); + } + if (!services.custom?.CanonicalPaperRuntime && !options.deploymentHost) { const unavailable: PaperReadiness = { configured: false, accountId: null, @@ -76,9 +93,12 @@ export function createPaperRoutes(services: OrchestratorServices): Hono { } return c.json(await runtime().status()); }); - app.post('/activate', async c => - c.json(await runtime().activate(paperActivationSchema.parse(await c.req.json()))) - ); + app.post('/activate', async c => { + if (options.deploymentHost) { + throw new PaperDeploymentError(409, 'Use the deployment-bound activation endpoint'); + } + return c.json(await runtime().activate(paperActivationSchema.parse(await c.req.json()))); + }); app.post('/halt', async c => c.json(await runtime().halt(paperHaltSchema.parse(await c.req.json()).reason)) ); diff --git a/apps/stock/orchestrator/src/backtest/BacktestRunner.ts b/apps/stock/orchestrator/src/backtest/BacktestRunner.ts index 5558fd9d..2a66bccd 100644 --- a/apps/stock/orchestrator/src/backtest/BacktestRunner.ts +++ b/apps/stock/orchestrator/src/backtest/BacktestRunner.ts @@ -3,6 +3,7 @@ import type { Logger } from '@stock-bot/services'; import { parseBacktestRequest } from '@stock-bot/stock-config/backtest'; import { canonicalRunRequestSchema, + canonicalStrategyExecution, type CanonicalRunRequest, type CanonicalRunResult, } from '@stock-bot/stock-config/canonical-research'; @@ -260,14 +261,17 @@ export class BacktestRunner extends EventEmitter { throw new Error('Canonical execution capabilities are unavailable'); } const claim = this.active; - const report = await engine.runCanonical(executionConfig, signal => - loadCanonicalDataset.call( - repository, - claim.runId, - claim.attemptId, - executionConfig.datasetHash, - signal - ) + const report = await engine.runCanonical( + executionConfig, + signal => + loadCanonicalDataset.call( + repository, + claim.runId, + claim.attemptId, + executionConfig.datasetHash, + signal + ), + { executionDeadlineAt: claim.executionDeadlineAt } ); if (this.cancelled) { throw new BacktestCancelledError(); @@ -280,7 +284,7 @@ export class BacktestRunner extends EventEmitter { completedAt: new Date().toISOString(), executionTime: performance.now() - started, financialEngine: 'rust', - strategyExecution: 'typescript-retained-builtin/v1', + strategyExecution: canonicalStrategyExecution(executionConfig), request: executionConfig, ...report, }; diff --git a/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts b/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts index 8428fbae..13fc3448 100644 --- a/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts +++ b/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts @@ -1,4 +1,5 @@ import { fork, type ChildProcess } from 'node:child_process'; +import { randomUUID } from 'node:crypto'; import { realpathSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { @@ -13,6 +14,7 @@ import { parseStrategyReplayResult, strategyReplayRequestSchema, } from '../contracts/strategy-replay'; +import { removeCandidateContainer } from './candidate-sandbox'; import { canonicalWorkerUrl } from './canonical-build'; import { nativeWorkerMessageSchema, @@ -49,6 +51,16 @@ export class NativeBacktestWorker { request.type === 'runStrategyReplay' ? structuredClone(strategyReplayRequestSchema.parse(request)) : undefined; + const candidateContainerName = + retainedRequest?.request.strategy.origin === 'candidate' + ? `stock-bot-candidate-${randomUUID()}` + : undefined; + if (retainedRequest) { + delete retainedRequest.candidateContainerName; + if (candidateContainerName) { + retainedRequest.candidateContainerName = candidateContainerName; + } + } const submitted = retainedRequest ?? strategyRequest ?? request; if ( retainedRequest && @@ -155,7 +167,7 @@ export class NativeBacktestWorker { } } }; - const finish = (code: number | null, exitSignal: NodeJS.Signals | null) => { + const finish = async (code: number | null, exitSignal: NodeJS.Signals | null) => { if (settled) { return; } @@ -163,6 +175,13 @@ export class NativeBacktestWorker { signal.removeEventListener('abort', onAbort); child.off('message', onMessage); child.stderr?.off('data', onStderr); + if (candidateContainerName) { + try { + await removeCandidateContainer(candidateContainerName); + } catch (error) { + failure ??= error instanceof Error ? error : new Error(String(error)); + } + } this.active = undefined; if (failure) { reject(failure); diff --git a/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts b/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts index d524e459..35a856aa 100644 --- a/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts +++ b/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts @@ -8,6 +8,7 @@ import { } from '@stock-bot/stock-config/backtest'; import { canonicalRunRequestSchema, + canonicalStrategyExecution, parseCanonicalFinancialResult, type CanonicalRunRequest, type CanonicalRunResult, @@ -414,7 +415,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository { result.runId !== request.runId || result.backtestId !== request.backtestId || result.financialEngine !== 'rust' || - result.strategyExecution !== 'typescript-retained-builtin/v1' + result.strategyExecution !== canonicalStrategyExecution(request) ) { throw new BacktestConflictError('Canonical result identity mismatch'); } diff --git a/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts b/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts index 7948b2d7..9c92ffc8 100644 --- a/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts +++ b/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts @@ -58,7 +58,8 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti async runCanonical( input: CanonicalRunRequest, - resolveDataset: (signal: AbortSignal) => Promise + resolveDataset: (signal: AbortSignal) => Promise, + controls: { executionDeadlineAt?: number } = {} ): Promise> { const request = canonicalRunRequestSchema.parse(input); return this.runOwned( @@ -67,7 +68,14 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti const dataset = await Promise.race([resolveDataset(signal), aborted]); signal.throwIfAborted(); const raw = await this.worker.execute( - { type: 'runRetainedStrategy', request, dataset }, + { + type: 'runRetainedStrategy', + request, + dataset, + ...(controls.executionDeadlineAt === undefined + ? {} + : { executionDeadlineAt: controls.executionDeadlineAt }), + }, signal, progress => { this.progress = progress.progress; diff --git a/apps/stock/orchestrator/src/backtest/candidate-host.ts b/apps/stock/orchestrator/src/backtest/candidate-host.ts new file mode 100644 index 00000000..0b4342cb --- /dev/null +++ b/apps/stock/orchestrator/src/backtest/candidate-host.ts @@ -0,0 +1,99 @@ +/** This entrypoint runs ONLY inside the restricted image; never the API/native supervisor. */ +import { sameIdentity } from '../contracts/native-replay'; +import { importRetainedProgram } from '../strategies/retained-program'; +import { StrategyController } from '../strategies/strategy-controller'; +import { freeze } from '../strategies/strategy-decision'; +import { + candidateRequestSchema, + readCandidateFrames, + writeCandidateFrame, +} from './candidate-protocol'; + +// Ordinary logs are diagnostics, not protocol. Deliberate raw stdout forgery remains untrusted. +// eslint-disable-next-line no-console -- stdout belongs exclusively to the framed protocol. +console.log = console.info = console.debug = (...values: unknown[]) => console.error(...values); +let controller: StrategyController | undefined; +let identity: ConstructorParameters[0] | undefined; +let sequence = 0; +try { + for await (const raw of readCandidateFrames(process.stdin)) { + const request = candidateRequestSchema.parse(raw); + if (request.sequence !== sequence) { + throw new Error('Candidate protocol sequence mismatch'); + } + const response = { version: 1, sequence }; + if (request.type === 'transpile') { + if (sequence !== 0 || controller) { + throw new Error('Packaging must be the first and only host operation'); + } + const compiler = new Bun.Transpiler({ loader: 'ts', target: 'browser' }); + if ( + compiler.scanImports(request.source).length || + /\b(?:import|require)\s*\(/.test(request.source) + ) { + throw new Error( + 'Candidate packaging accepts self-contained TypeScript without import/require edges' + ); + } + // Transformation only: top-level statements are data and are never imported or evaluated. + const content = compiler.transformSync(request.source); + if (compiler.scanImports(content).length) { + throw new Error('Packaged candidate retained an import edge'); + } + await writeCandidateFrame(process.stdout, { + ...response, + type: 'transpiled', + content, + runtimeVersion: Bun.version, + }); + process.exit(0); + } else if (request.type === 'init') { + if (controller || sequence !== 0) { + throw new Error('Candidate host already initialized'); + } + identity = freeze(request.identity); + const program = await importRetainedProgram( + request.package as Parameters[0], + request.selection + ); + controller = new StrategyController(identity, [program], { + matching: { owners: [{ ownerId: request.selection.ownerId, mode: 'Target' }] }, + }); + await writeCandidateFrame(process.stdout, { ...response, type: 'ready' }); + } else { + if (!controller || !identity) { + throw new Error('Candidate host is not initialized'); + } + if (request.type === 'stage') { + sameIdentity(request.published.identity, identity); + if (request.published.step.type !== 'decisionBatch') { + throw new Error('Candidate requires a decision barrier'); + } + freeze(request.published); + const decisions = controller.stage(request.published.step, request.published.observations); + await writeCandidateFrame(process.stdout, { ...response, type: 'decisions', decisions }); + } else if (request.type === 'committed') { + sameIdentity(request.admitted.identity, identity); + freeze(request.admitted.outcome); + controller.committed(request.admitted.outcome); + await writeCandidateFrame(process.stdout, { ...response, type: 'ack' }); + } else { + await writeCandidateFrame(process.stdout, { ...response, type: 'finished' }); + process.exit(0); + } + } + sequence++; + } + throw new Error('Candidate supervisor disconnected before finish'); +} catch (error) { + try { + await writeCandidateFrame(process.stdout, { + version: 1, + sequence, + type: 'error', + message: String(error).slice(0, 4096), + }); + } finally { + process.exit(1); + } +} diff --git a/apps/stock/orchestrator/src/backtest/candidate-protocol.ts b/apps/stock/orchestrator/src/backtest/candidate-protocol.ts new file mode 100644 index 00000000..ed7203f5 --- /dev/null +++ b/apps/stock/orchestrator/src/backtest/candidate-protocol.ts @@ -0,0 +1,89 @@ +/** Bounded transport, shared by the restricted host and its untrusted-output supervisor. */ +import { Readable, Writable } from 'node:stream'; +import { z } from 'zod'; +import { + candidateSandboxLimits, + retainedProgramSelectionSchema, +} from '@stock-bot/stock-config/candidate-execution'; +import { parseFinancialStrategyDecision } from '@stock-bot/types'; +import { replayIdentitySchema, stepSchema, submissionSchema } from '../contracts/native-replay'; + +const base = { + version: z.literal(1), + sequence: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), +}; +export const candidateRequestSchema = z.discriminatedUnion('type', [ + z.object({ ...base, type: z.literal('transpile'), source: z.string().min(1) }).strict(), + z + .object({ + ...base, + type: z.literal('init'), + identity: replayIdentitySchema, + package: z.unknown(), + selection: retainedProgramSelectionSchema, + }) + .strict(), + z.object({ ...base, type: z.literal('stage'), published: stepSchema }).strict(), + z.object({ ...base, type: z.literal('committed'), admitted: submissionSchema }).strict(), + z.object({ ...base, type: z.literal('finish') }).strict(), +]); +export const candidateResponseSchema = z.discriminatedUnion('type', [ + z.object({ ...base, type: z.literal('ready') }).strict(), + z + .object({ + ...base, + type: z.literal('transpiled'), + content: z.string(), + runtimeVersion: z.string().min(1), + }) + .strict(), + z + .object({ + ...base, + type: z.literal('decisions'), + decisions: z.array(z.unknown().transform(parseFinancialStrategyDecision)).length(1), + }) + .strict(), + z.object({ ...base, type: z.literal('ack') }).strict(), + z.object({ ...base, type: z.literal('finished') }).strict(), + z.object({ ...base, type: z.literal('error'), message: z.string().max(4096) }).strict(), +]); +export type CandidateResponse = z.infer; + +export async function writeCandidateFrame(stream: Writable, value: unknown): Promise { + const body = Buffer.from(JSON.stringify(value)); + if (body.length > candidateSandboxLimits.frameBytes) { + throw new Error('Candidate protocol frame exceeds its retained resource limit'); + } + const header = Buffer.alloc(4); + header.writeUInt32BE(body.length); + await new Promise((resolve, reject) => + stream.write(Buffer.concat([header, body]), error => (error ? reject(error) : resolve())) + ); +} +export async function* readCandidateFrames(stream: Readable): AsyncGenerator { + let buffer = Buffer.alloc(0); + for await (const raw of stream) { + const chunk = Buffer.isBuffer(raw) ? raw : Buffer.from(raw as string); + // Readable chunks are bounded by stream buffering; reject oversized buffered input before parsing. + if (buffer.length + chunk.length > candidateSandboxLimits.frameBytes + 4) { + throw new Error('Candidate protocol buffer exceeds its retained resource limit'); + } + buffer = Buffer.concat([buffer, chunk]); + while (buffer.length >= 4) { + const length = buffer.readUInt32BE(0); + if (length === 0 || length > candidateSandboxLimits.frameBytes) { + throw new Error('Invalid or oversized candidate protocol frame'); + } + if (buffer.length < length + 4) { + break; + } + const content = buffer.subarray(4, length + 4); + buffer = buffer.subarray(length + 4); + yield JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(content)); + } + } + if (buffer.length) { + throw new Error('Truncated candidate protocol frame'); + } +} diff --git a/apps/stock/orchestrator/src/backtest/candidate-sandbox.ts b/apps/stock/orchestrator/src/backtest/candidate-sandbox.ts new file mode 100644 index 00000000..93ae193d --- /dev/null +++ b/apps/stock/orchestrator/src/backtest/candidate-sandbox.ts @@ -0,0 +1,467 @@ +/** Trusted launcher. Candidate code is never imported in this process. */ +import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { mkdtemp, readFile, realpath, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; +import { + candidateExecutionSchema, + candidateSandboxLimits, + type CandidateExecution, +} from '@stock-bot/stock-config/candidate-execution'; +import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research'; +import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; +import { parseFinancialStrategyDecision } from '@stock-bot/types'; +import type { ReplaySubmissionOutcome } from '../contracts/native-replay'; +import { + candidateResponseSchema, + readCandidateFrames, + writeCandidateFrame, + type CandidateResponse, +} from './candidate-protocol'; +import type { + AsyncReplayController, + DecisionContext, + PublishedObservation, + ReplayIdentity, +} from './native-replay'; + +const runFile = promisify(execFile); +const docker = '/usr/bin/docker'; +const daemon = ['--host', 'unix:///var/run/docker.sock']; +const environment = (config: string) => ({ PATH: '/usr/bin:/bin', DOCKER_CONFIG: config }); +const root = resolve(dirname(fileURLToPath(import.meta.resolve('@stock-bot/engine'))), '../../..'); +export const candidateDescriptorPath = resolve( + root, + 'apps/stock/orchestrator/dist/candidate-sandbox.json' +); +export class CandidateSandboxUnavailable extends Error { + readonly code = 'candidate_sandbox_unavailable'; +} + +async function dockerRead(args: string[]) { + const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-')); + try { + return ( + await runFile(docker, [...daemon, ...args], { + env: environment(config), + timeout: 10000, + maxBuffer: 65536, + }) + ).stdout.trim(); + } finally { + await rm(config, { recursive: true, force: true }); + } +} +export async function readCandidateExecution(): Promise { + try { + if (process.platform !== 'linux' || process.arch !== 'x64') { + throw new Error('Unsupported candidate platform'); + } + const execution = candidateExecutionSchema.parse( + JSON.parse(await readFile(candidateDescriptorPath, 'utf8')) + ); + const files = [ + resolve(root, 'apps/stock/orchestrator/dist/candidate-host.js'), + resolve(root, 'apps/stock/orchestrator/dist/candidate-guardian'), + await realpath(process.execPath), + ]; + const hashes = await Promise.all( + files.map(async path => + createHash('sha256') + .update(await readFile(path)) + .digest('hex') + ) + ); + if ( + hashes[0] !== execution.profile.hostSha256 || + hashes[1] !== execution.profile.guardianSha256 || + hashes[2] !== execution.profile.bunSha256 + ) { + throw new Error('Candidate installed host/runtime bytes differ'); + } + const info = JSON.parse(await dockerRead(['info', '--format', '{{json .}}'])) as Record< + string, + unknown + >; + if ( + info.OSType !== 'linux' || + info.CgroupVersion !== '2' || + info.MemoryLimit !== true || + info.SwapLimit !== true || + info.CpuCfsQuota !== true || + info.PidsLimit !== true || + !Array.isArray(info.SecurityOptions) || + !info.SecurityOptions.some(v => String(v).startsWith('name=seccomp')) || + !info.SecurityOptions.some(v => String(v).startsWith('name=apparmor')) + ) { + throw new Error('Candidate cgroup/seccomp/AppArmor isolation is unavailable'); + } + if ( + (await dockerRead(['image', 'inspect', execution.imageId, '--format', '{{.Id}}'])) !== + execution.imageId + ) { + throw new Error('Candidate exact image is unavailable'); + } + return execution; + } catch (cause) { + throw new CandidateSandboxUnavailable('The exact isolated candidate runtime is unavailable', { + cause, + }); + } +} +export async function verifyCandidateExecution(expected: CandidateExecution): Promise { + if ( + canonicalStrategyJson(await readCandidateExecution()) !== + canonicalStrategyJson(candidateExecutionSchema.parse(expected)) + ) { + throw new CandidateSandboxUnavailable( + 'The retained isolated candidate runtime is not installed' + ); + } +} +export function validateCandidateContainerName(value: string): string { + if (!/^stock-bot-candidate-[0-9a-f-]{36}$/.test(value)) { + throw new Error('Invalid owned candidate container name'); + } + return value; +} +/** Removal is exact-name only; never touches other research or operator containers. */ +export async function removeCandidateContainer(name: string): Promise { + validateCandidateContainerName(name); + try { + await dockerRead(['rm', '--force', name]); + } catch (cause) { + // A successful --rm exit races explicit cancellation cleanup. Confirm absence. + if ((await dockerRead(['ps', '--all', '--quiet', '--filter', `name=^/${name}$`])) !== '') { + throw cause; + } + } +} + +export class IsolatedCandidateController implements AsyncReplayController { + private readonly child: ChildProcessWithoutNullStreams; + private readonly closed: Promise<{ code: number | null; signal: NodeJS.Signals | null }>; + private failure: Error | undefined; + private pending: + | { + sequence: number; + type: CandidateResponse['type']; + resolve(value: CandidateResponse): void; + reject(error: Error): void; + } + | undefined; + private sequence = 0; + private decisionSequence = 0; + private stderr = Buffer.alloc(0); + private readonly timer: ReturnType; + private disposed = false; + private expectedExit = false; + private hasClosed = false; + private readonly identity: ReplayIdentity | undefined; + private constructor( + private readonly request: CandidateRequest | null, + private readonly name: string, + deadlineAt: number, + private readonly dockerConfig: string, + execution: CandidateExecution + ) { + this.identity = request + ? { version: 1, sessionId: request.runId, datasetHash: request.datasetHash } + : undefined; + const limits = candidateSandboxLimits; + this.child = spawn( + docker, + [ + ...daemon, + 'run', + '--rm', + '--interactive', + '--pull=never', + '--name', + name, + '--network', + 'none', + '--ipc', + 'none', + '--read-only', + '--tmpfs', + `/tmp:rw,nosuid,nodev,noexec,size=${limits.tmpBytes}`, + '--memory', + String(limits.memoryBytes), + '--memory-swap', + String(limits.memoryBytes), + '--cpus', + String(limits.cpuQuota), + '--pids-limit', + String(limits.pids), + '--cap-drop', + 'ALL', + '--cap-add', + 'SETUID', + '--cap-add', + 'SETGID', + '--cap-add', + 'KILL', + '--security-opt', + 'no-new-privileges=true', + '--log-driver', + 'none', + execution.imageId, + String(deadlineAt), + ], + { env: environment(dockerConfig), stdio: ['pipe', 'pipe', 'pipe'] } + ); + this.child.stdin.on('error', cause => this.fail(cause)); + this.child.stderr.on('data', (chunk: Buffer) => { + this.stderr = Buffer.concat([this.stderr, chunk]).subarray(-limits.stderrBytes); + }); + this.closed = new Promise(resolveClosed => { + this.child.once('error', cause => this.fail(cause)); + this.child.once('close', (code, signal) => { + this.hasClosed = true; + if (!this.disposed && (!this.expectedExit || this.pending)) { + this.fail( + new Error(`Candidate host exited before completion (code ${code}, signal ${signal})`) + ); + } + resolveClosed({ code, signal }); + }); + }); + this.timer = setTimeout( + () => this.fail(new Error('Candidate host exceeded its wall deadline')), + Math.max(1, deadlineAt - Date.now()) + ); + void this.readResponses(); + } + static async start( + request: CanonicalRunRequest, + name: string, + suppliedDeadline?: number + ): Promise { + if (request.strategy.origin !== 'candidate') { + throw new Error('Only candidates may use the isolated controller'); + } + validateCandidateContainerName(name); + await verifyCandidateExecution(request.strategy.execution); + const deadlineAt = Math.min( + Date.now() + candidateSandboxLimits.wallMs, + suppliedDeadline ?? Infinity + ); + if (!Number.isSafeInteger(deadlineAt) || deadlineAt <= Date.now()) { + throw new Error('Candidate execution deadline is expired or invalid'); + } + const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-')); + const controller = new IsolatedCandidateController( + request as CandidateRequest, + name, + deadlineAt, + config, + request.strategy.execution + ); + try { + await controller.exchange('ready', { + type: 'init', + identity: controller.identity, + package: request.strategy.package, + selection: request.strategy.selection, + }); + return controller; + } catch (cause) { + try { + await controller.dispose(); + } catch (cleanup) { + throw new AggregateError([cause, cleanup], 'Candidate initialization and cleanup failed'); + } + throw cause; + } + } + static async transpile( + source: string, + name: string + ): Promise<{ content: string; runtimeVersion: string; execution: CandidateExecution }> { + validateCandidateContainerName(name); + const execution = await readCandidateExecution(); + const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-')); + const controller = new IsolatedCandidateController( + null, + name, + Date.now() + candidateSandboxLimits.wallMs, + config, + execution + ); + try { + const response = await controller.exchange('transpiled', { type: 'transpile', source }); + const status = await controller.closed; + if (response.type !== 'transpiled' || controller.failure || status.code !== 0) { + throw controller.failure ?? new Error('Candidate packaging failed'); + } + return { content: response.content, runtimeVersion: response.runtimeVersion, execution }; + } finally { + await controller.dispose(); + } + } + private fail(error: Error) { + this.failure ??= error; + const pending = this.pending; + this.pending = undefined; + pending?.reject(this.failure); + this.child.stdin.destroy(); + } + private async readResponses() { + try { + for await (const raw of readCandidateFrames(this.child.stdout)) { + const response = candidateResponseSchema.parse(raw); + const pending = this.pending; + if ( + !pending || + response.sequence !== pending.sequence || + (response.type !== pending.type && response.type !== 'error') + ) { + throw new Error('Unsolicited or mismatched candidate response'); + } + if (response.type === 'error') { + throw new Error(`Candidate strategy failed: ${response.message}`); + } + if (response.type === 'finished' || response.type === 'transpiled') { + this.expectedExit = true; + } + this.pending = undefined; + pending.resolve(response); + } + if (!this.disposed && !this.expectedExit) { + this.fail(new Error('Candidate protocol closed before completion')); + } + } catch (cause) { + this.fail(cause instanceof Error ? cause : new Error(String(cause))); + } + } + private async exchange( + type: CandidateResponse['type'], + message: Record + ): Promise { + if (this.failure) { + throw this.failure; + } + if (this.pending || this.disposed || this.hasClosed || this.expectedExit) { + throw new Error('Candidate controller is unavailable or busy'); + } + const sequence = this.sequence++; + const response = new Promise((resolveResponse, reject) => { + this.pending = { sequence, type, resolve: resolveResponse, reject }; + }); + void response.catch(() => undefined); + try { + await writeCandidateFrame(this.child.stdin, { version: 1, sequence, ...message }); + } catch (cause) { + this.fail(cause instanceof Error ? cause : new Error(String(cause))); + } + return response; + } + async stage(context: DecisionContext, observations: readonly PublishedObservation[]) { + const response = await this.exchange('decisions', { + type: 'stage', + published: { identity: this.identity, step: context, observations }, + }); + if (response.type !== 'decisions') { + throw new Error('Expected candidate decisions'); + } + const decision = parseFinancialStrategyDecision(response.decisions[0]); + if (!this.request || !this.identity) { + throw new Error('Packaging host cannot make decisions'); + } + const selected = this.request.strategy.selection; + const expectedId = JSON.stringify([ + 'strategy', + selected.ownerId, + selected.strategyId, + selected.strategyVersion, + this.decisionSequence, + ]); + if ( + context.barrier.owner_ids.length !== 1 || + context.barrier.owner_ids[0] !== selected.ownerId || + decision.sessionId !== this.identity.sessionId || + decision.barrierId !== context.barrier.barrier_id || + decision.revision !== context.barrier.revision || + decision.decision.ownerId !== selected.ownerId || + decision.decision.sequence !== this.decisionSequence || + decision.decision.decisionId !== expectedId || + decision.intent.mode !== 'target' + ) { + throw new Error('Candidate returned a forged decision identity or mode'); + } + return [decision]; + } + async committed(outcome: ReplaySubmissionOutcome): Promise { + if (!this.identity) { + throw new Error('Packaging host cannot accept financial acknowledgements'); + } + await this.exchange('ack', { + type: 'committed', + admitted: { identity: this.identity, outcome }, + }); + this.decisionSequence++; + } + async finish(): Promise { + await this.exchange('finished', { type: 'finish' }); + const status = await this.closed; + if (this.failure || status.code !== 0) { + throw this.failure ?? new Error(`Candidate host did not exit successfully: ${this.stderr}`); + } + } + async dispose(): Promise { + if (this.disposed) { + return; + } + this.disposed = true; + if (this.pending) { + this.fail(new Error('Candidate controller disposed before acknowledgement')); + } + clearTimeout(this.timer); + this.child.stdin.destroy(); + const errors: unknown[] = []; + // Always attempt every cleanup stage, including when the daemon is unavailable. + // The independent guardian still enforces its frozen wall deadline in that case. + try { + await removeCandidateContainer(this.name); + } catch (error) { + errors.push(error); + } + if (!this.hasClosed) { + this.child.kill('SIGKILL'); + } + let timer: ReturnType | undefined; + try { + await Promise.race([ + this.closed, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error('Candidate Docker client did not close during cleanup')), + 10000 + ); + }), + ]); + } catch (error) { + errors.push(error); + } finally { + clearTimeout(timer); + } + try { + await rm(this.dockerConfig, { recursive: true, force: true }); + } catch (error) { + errors.push(error); + } + if (errors.length) { + throw new AggregateError( + this.failure ? [this.failure, ...errors] : errors, + 'Candidate cleanup failed' + ); + } + } +} +type CandidateRequest = CanonicalRunRequest & { + strategy: Extract; +}; diff --git a/apps/stock/orchestrator/src/backtest/execution-engine.ts b/apps/stock/orchestrator/src/backtest/execution-engine.ts index e9fa8e2e..636da88a 100644 --- a/apps/stock/orchestrator/src/backtest/execution-engine.ts +++ b/apps/stock/orchestrator/src/backtest/execution-engine.ts @@ -17,7 +17,8 @@ export interface BacktestExecutionEngine extends Pick; runCanonical?( request: CanonicalRunRequest, - resolveDataset: (signal: AbortSignal) => Promise + resolveDataset: (signal: AbortSignal) => Promise, + controls?: { executionDeadlineAt?: number } ): Promise>; stopBacktest(): Promise; pauseBacktest(): Promise; diff --git a/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts b/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts index d6d7ff19..c6f4db49 100644 --- a/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts +++ b/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts @@ -1,4 +1,8 @@ import { z } from 'zod'; +import { + candidateExecutionSchema, + type CandidateExecution, +} from '@stock-bot/stock-config/candidate-execution'; import { canonicalBuildIdentitySchema, canonicalRunRequestSchema, @@ -19,6 +23,11 @@ export const retainedStrategyRequestSchema = z type: z.literal('runRetainedStrategy'), request: canonicalRunRequestSchema, dataset: z.unknown(), + executionDeadlineAt: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(), + candidateContainerName: z + .string() + .regex(/^stock-bot-candidate-[0-9a-f-]{36}$/) + .optional(), }) .strict(); @@ -33,6 +42,7 @@ export interface RetainedStrategyResult { version: 1; build: CanonicalBuildIdentity; artifactHash: string; + execution?: CandidateExecution; financial: ReplayReportResult; analytics: CanonicalBacktestAnalytics; } @@ -43,6 +53,7 @@ const retainedStrategyResultSchema = z version: z.literal(1), build: canonicalBuildIdentitySchema, artifactHash: z.string().regex(/^[a-f0-9]{64}$/), + execution: candidateExecutionSchema.optional(), financial: z.unknown(), analytics: z.unknown(), }) @@ -60,6 +71,14 @@ export function parseRetainedStrategyResult( ) { throw new Error('Retained strategy result build/artifact identity mismatch'); } + if ( + request.strategy.origin === 'candidate' + ? canonicalStrategyJson(envelope.execution) !== + canonicalStrategyJson(request.strategy.execution) + : envelope.execution !== undefined + ) { + throw new Error('Retained strategy result execution identity mismatch'); + } const financial = parseCanonicalFinancialResult(envelope.financial, request); const analytics = buildCanonicalBacktestReport(financial, request.analyticsPolicy).analytics; if (canonicalStrategyJson(envelope.analytics) !== canonicalStrategyJson(analytics)) { diff --git a/apps/stock/orchestrator/src/backtest/native-worker.ts b/apps/stock/orchestrator/src/backtest/native-worker.ts index bfb1c00a..21c4376b 100644 --- a/apps/stock/orchestrator/src/backtest/native-worker.ts +++ b/apps/stock/orchestrator/src/backtest/native-worker.ts @@ -1,14 +1,21 @@ -import { createHash } from 'node:crypto'; -import type { StrategyProgram } from '../contracts/canonical-strategy'; import type { StrategyReplayResult } from '../contracts/strategy-replay'; import { createBuiltinStrategy, validateBuiltinStrategyBindings, } from '../strategies/canonical-builtins'; -import { freeze } from '../strategies/strategy-decision'; +import { + importRetainedProgram, + verifyRetainedProgramPackage, +} from '../strategies/retained-program'; +import { IsolatedCandidateController } from './candidate-sandbox'; import { verifyCanonicalWorkerBuild } from './canonical-build'; import { buildCanonicalBacktestReport } from './canonical-result'; -import { executeReplayTrace, prepareReplayLoad } from './native-replay'; +import { + executeReplayTrace, + NativeReplaySession, + prepareReplayLoad, + runReplaySessionAsync, +} from './native-replay'; import { nativeWorkerRequestSchema, type NativeWorkerMessage, @@ -34,17 +41,7 @@ process.once('message', async (input: unknown) => { const admitted = request.request; // Identity checks precede bundle import, including any top-level module side effects. const build = await verifyCanonicalWorkerBuild(admitted.build, import.meta.url); - const pkg = admitted.strategy.package; - const hash = (content: string) => createHash('sha256').update(content, 'utf8').digest('hex'); - if ( - hash(pkg.artifact.content) !== pkg.artifact.sha256 || - hash(pkg.dependencyLock.content) !== pkg.dependencyLock.sha256 - ) { - throw new Error('Retained strategy artifact or dependency lock hash mismatch'); - } - if (pkg.program.apiVersion !== 'canonical-ts/v1') { - throw new Error('Unsupported retained strategy API version'); - } + const pkg = verifyRetainedProgramPackage(admitted.strategy.package); const load = prepareReplayLoad(request.dataset, admitted.policy); if ( load.identity.datasetHash !== admitted.datasetHash || @@ -53,50 +50,48 @@ process.once('message', async (input: unknown) => { ) { throw new Error('Retained strategy requires its exact eligible single-series dataset'); } - const selection = admitted.strategy.selection; - validateBuiltinStrategyBindings([selection], load); - // Only server-admitted built-ins reach this trusted worker path. Candidate - // execution requires separate isolation; import is never performed by an API. - // Bun's data-URL loader rejects real bundle-sized specifiers. A Blob keeps - // these exact UTF-8 bytes in memory without temporary files surviving SIGKILL. - const moduleUrl = URL.createObjectURL( - new Blob([pkg.artifact.content], { type: 'text/javascript' }) - ); - let module: Record; - try { - module = await import(moduleUrl); - } finally { - URL.revokeObjectURL(moduleUrl); - } - const factory = module[pkg.artifact.entryExport]; - if (typeof factory !== 'function') { - throw new Error('Retained strategy factory export is missing'); - } - const program = factory(freeze(structuredClone(selection))) as StrategyProgram; - if ( - !program || - typeof program !== 'object' || - program.ownerId !== selection.ownerId || - program.strategyId !== selection.strategyId || - program.strategyVersion !== selection.strategyVersion || - program.seed !== selection.seed || - program.mode !== 'target' || - typeof program.decide !== 'function' - ) { - throw new Error('Retained strategy factory identity or API mismatch'); - } await send({ type: 'progress', progress: 0, message: 'Retained canonical strategy replay started', }); - const { result } = runStrategyReplay(load, [program], { resultFormat: 'report' }); + let result; + if (admitted.strategy.origin === 'candidate') { + if (!request.candidateContainerName) { + throw new Error('Isolated candidate lacks its owned container identity'); + } + const controller = await IsolatedCandidateController.start( + admitted, + request.candidateContainerName, + request.executionDeadlineAt + ); + try { + result = ( + await runReplaySessionAsync(new NativeReplaySession(load), controller, { + resultFormat: 'report', + }) + ).result; + await controller.finish(); + } finally { + await controller.dispose(); + } + } else { + validateBuiltinStrategyBindings([admitted.strategy.selection], load); + const program = await importRetainedProgram(pkg, admitted.strategy.selection); + result = runStrategyReplay(load, [program], { resultFormat: 'report' }).result; + } + if (!('format' in result) || result.format !== 'report') { + throw new Error('Retained replay requires the canonical report format'); + } const report = buildCanonicalBacktestReport(result, admitted.analyticsPolicy); const envelope: RetainedStrategyResult = { type: 'retainedStrategyResult', version: 1, build, artifactHash: pkg.artifact.sha256, + ...(admitted.strategy.origin === 'candidate' + ? { execution: admitted.strategy.execution } + : {}), financial: report.financial, analytics: report.analytics, }; diff --git a/apps/stock/orchestrator/src/backtest/sandbox/guardian.rs b/apps/stock/orchestrator/src/backtest/sandbox/guardian.rs new file mode 100644 index 00000000..f1746696 --- /dev/null +++ b/apps/stock/orchestrator/src/backtest/sandbox/guardian.rs @@ -0,0 +1,218 @@ +//! Minimal Linux x86_64 PID1. This executable contains no strategy/data logic. +use std::{ + os::{fd::FromRawFd, unix::process::CommandExt}, + process::{Command, Stdio}, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, +}; +#[repr(C)] +struct Filter { + code: u16, + jt: u8, + jf: u8, + k: u32, +} +#[repr(C)] +struct Program { + len: u16, + filter: *const Filter, +} +#[repr(C)] +struct PollFd { + fd: i32, + events: i16, + revents: i16, +} +#[repr(C)] +struct Limit { + current: u64, + maximum: u64, +} +unsafe extern "C" { + fn prctl(option: i32, ...) -> i32; + fn setgid(gid: u32) -> i32; + fn setuid(uid: u32) -> i32; + fn setgroups(size: usize, list: *const u32) -> i32; + fn setrlimit(resource: i32, limit: *const Limit) -> i32; + fn poll(fds: *mut PollFd, nfds: usize, timeout: i32) -> i32; + fn kill(pid: i32, signal: i32) -> i32; +} +fn stmt(code: u16, k: u32) -> Filter { + Filter { + code, + jt: 0, + jf: 0, + k, + } +} +fn equal(k: u32, jt: u8, jf: u8) -> Filter { + Filter { + code: 0x15, + jt, + jf, + k, + } +} +fn error() -> std::io::Error { + std::io::Error::last_os_error() +} +fn main() { + if !cfg!(all(target_os = "linux", target_arch = "x86_64")) { + std::process::exit(126); + } + let deadline: u128 = std::env::args() + .nth(1) + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock") + .as_millis(); + if deadline <= now || deadline - now > 300_000 { + std::process::exit(124); + } + let remaining = Duration::from_millis((deadline - now) as u64); + let clock = Instant::now(); + let mut command = Command::new("/usr/bin/bun"); + command + .arg("/app/candidate-host.js") + .current_dir("/tmp") + .env_clear() + .stdin(Stdio::inherit()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()); + unsafe { + command.pre_exec(|| { + if setgroups(0, std::ptr::null()) != 0 || setgid(65534) != 0 || setuid(65534) != 0 { + return Err(error()); + } + if setrlimit( + 0, + &Limit { + current: 300, + maximum: 300, + }, + ) != 0 + || setrlimit( + 4, + &Limit { + current: 0, + maximum: 0, + }, + ) != 0 + { + return Err(error()); + } + if prctl(38, 1, 0, 0, 0) != 0 { + return Err(error()); + } + // Check architecture and reject x32 syscall-number aliases before any allow rule. + let mut filter = vec![ + stmt(0x20, 4), + equal(0xc000003e, 1, 0), + stmt(0x06, 0x80000000), + stmt(0x20, 0), + Filter { + code: 0x35, + jt: 0, + jf: 1, + k: 0x40000000, + }, + stmt(0x06, 0x00050001), + ]; + // fork, vfork, socket, ptrace, mount, umount2, unshare, setns, bpf, perf_event_open. + for nr in [57, 58, 41, 101, 165, 166, 272, 308, 321, 298] { + filter.push(equal(nr, 0, 1)); + filter.push(stmt(0x06, 0x00050001)); + } + // clone3 cannot inspect the pointed-to flags; make libc use checked clone instead. + filter.push(equal(435, 0, 1)); + filter.push(stmt(0x06, 0x00050026)); + filter.push(equal(56, 0, 4)); + filter.push(stmt(0x20, 16)); + filter.push(Filter { + code: 0x45, + jt: 0, + jf: 1, + k: 0x00010000, + }); + filter.push(stmt(0x06, 0x7fff0000)); + filter.push(stmt(0x06, 0x00050001)); + filter.push(stmt(0x06, 0x7fff0000)); + let program = Program { + len: filter.len() as u16, + filter: filter.as_ptr(), + }; + if prctl(22, 2, &program as *const Program) != 0 { + return Err(error()); + } + Ok(()) + }); + } + let mut child = command + .spawn() + .expect("restricted host initialization failed"); + let mut output = child.stdout.take().expect("restricted host stdout missing"); + let output_closed = Arc::new(AtomicBool::new(false)); + let relay_closed = Arc::clone(&output_closed); + // A bounded std::io::copy buffer relays bytes only. A separate watchdog remains + // responsive even if the child floods stdout or the consumer stops reading. + // Direct File writes avoid line-buffering the binary protocol. + std::thread::spawn(move || { + let mut destination = unsafe { std::fs::File::from_raw_fd(1) }; + let _ = std::io::copy(&mut output, &mut destination); + relay_closed.store(true, Ordering::Release); + }); + let mut exit_status = None; + let mut stdout_closed_at = None; + loop { + if exit_status.is_none() { + if let Some(status) = child.try_wait().expect("restricted host wait failed") { + exit_status = Some(status.code().unwrap_or(125)); + } + } + if output_closed.load(Ordering::Acquire) { + if let Some(code) = exit_status { + // Drain the complete final frame before ending a normal finish/transpile. + std::process::exit(code); + } + stdout_closed_at.get_or_insert_with(Instant::now); + } + // EOF can precede the child's normal exit by a few scheduler turns. + let protocol_closed = + stdout_closed_at.is_some_and(|at| at.elapsed() >= Duration::from_millis(100)); + let mut input = PollFd { + fd: 0, + events: 0, + revents: 0, + }; + let ready = unsafe { poll(&mut input, 1, 0) }; + let disconnected = ready < 0 || input.revents & (0x10 | 0x08 | 0x20) != 0; + if disconnected || protocol_closed || clock.elapsed() >= remaining { + unsafe { + kill(child.id() as i32, 9); + } + let _ = child.wait(); + eprintln!( + "Candidate host {}", + if disconnected { + "supervisor disconnected" + } else if protocol_closed { + "protocol stdout closed" + } else { + "wall deadline exceeded" + } + ); + // Exiting namespace PID1 kills remaining threads/processes independently of JS. + std::process::exit(if disconnected || protocol_closed { + 125 + } else { + 124 + }); + } + std::thread::sleep(Duration::from_millis(10)); + } +} diff --git a/apps/stock/orchestrator/src/container.ts b/apps/stock/orchestrator/src/container.ts index 034ac73e..a851cc34 100644 --- a/apps/stock/orchestrator/src/container.ts +++ b/apps/stock/orchestrator/src/container.ts @@ -1,4 +1,5 @@ import { asValue, type AwilixContainer } from 'awilix'; +import { z } from 'zod'; import type { ServiceCradle as ServiceDefinitions } from '@stock-bot/di'; import { BacktestRunner } from './backtest/BacktestRunner'; import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRepository'; @@ -10,6 +11,7 @@ import { PostgresCanonicalExecutionRepository } from './execution/PostgresCanoni import { BacktestHandler } from './handlers/backtest/backtest.handler'; import { CanonicalPaperRuntime } from './paper/CanonicalPaperRuntime'; import { validatePaperConfiguration } from './paper/feed'; +import { PaperDeploymentHost } from './paper/PaperDeploymentHost'; import { AnalyticsService } from './services/AnalyticsService'; import { StorageService } from './services/StorageService'; import { createBuiltinStrategy } from './strategies/canonical-builtins'; @@ -29,6 +31,45 @@ export function assertSupportedComposition(role: OrchestratorRole, useRustEngine } } +/** Validate before opening resources as well as before registering runtime services. */ +export function resolvePaperComposition( + role: OrchestratorRole, + canonicalInput?: PaperConfigurationInput, + deploymentInput?: unknown +) { + if ((canonicalInput !== undefined || deploymentInput !== undefined) && role !== 'paper') { + throw new Error('Canonical paper configuration requires a paper composition'); + } + if (canonicalInput !== undefined && deploymentInput !== undefined) { + throw new Error('Choose canonicalPaper or paperDeploymentHost, never two account owners'); + } + const canonicalPaper = + canonicalInput === undefined ? undefined : validatePaperConfiguration(canonicalInput); + if (canonicalPaper && canonicalPaper.version !== 1) { + throw new Error('Promoted paper strategies require an explicitly reviewed deployment host'); + } + const paperDeploymentHost = + deploymentInput === undefined + ? undefined + : z + .object({ + enabled: z.literal(true), + deploymentId: z + .string() + .uuid() + .transform(id => id.toLowerCase()) + .optional(), + }) + .strict() + .parse(deploymentInput); + if (role === 'paper' && !canonicalPaper && !paperDeploymentHost) { + throw new Error( + 'Paper composition requires explicit canonicalPaper or paperDeploymentHost configuration; accounts are never migrated automatically' + ); + } + return { canonicalPaper, paperDeploymentHost }; +} + /** * Register orchestrator-specific services in the DI container */ @@ -43,6 +84,7 @@ export async function registerOrchestratorServices( nativeExecutionTimeoutMs?: number; maxConcurrent?: number; canonicalPaper?: PaperConfigurationInput; + paperDeploymentHost?: { enabled: true; deploymentId?: string }; } = {} ): Promise { const role = options.role === undefined ? 'research-only' : options.role; @@ -50,18 +92,11 @@ export async function registerOrchestratorServices( assertSupportedComposition(role, useRustEngine); const maxConcurrent = options.maxConcurrent === undefined ? 1 : options.maxConcurrent; assertResearchConcurrency(maxConcurrent); - if (options.canonicalPaper !== undefined && role !== 'paper') { - throw new Error('Canonical paper configuration requires a paper composition'); - } - const canonicalPaper = - options.canonicalPaper === undefined - ? undefined - : validatePaperConfiguration(options.canonicalPaper); - if (role === 'paper' && !canonicalPaper) { - throw new Error( - 'Paper composition requires explicit canonicalPaper configuration; accounts are never migrated automatically' - ); - } + const { canonicalPaper, paperDeploymentHost } = resolvePaperComposition( + role, + options.canonicalPaper, + options.paperDeploymentHost + ); // Create a service adapter that provides the expected interface const services = container.resolve('serviceContainer') as IServiceContainer; @@ -72,6 +107,7 @@ export async function registerOrchestratorServices( if ( [ 'CanonicalPaperRuntime', + 'PaperDeploymentHost', 'ModeManager', 'ExecutionService', 'MarketDataService', @@ -93,7 +129,7 @@ export async function registerOrchestratorServices( options ); - if (canonicalPaper && !services.postgres) { + if ((canonicalPaper || paperDeploymentHost) && !services.postgres) { throw new Error('Canonical paper requires durable PostgreSQL custody'); } const paper = @@ -103,6 +139,13 @@ export async function registerOrchestratorServices( programs: canonicalPaper.strategies.map(createBuiltinStrategy), }) : undefined; + const deploymentHost = + paperDeploymentHost && services.postgres + ? new PaperDeploymentHost({ + database: services.postgres, + repository: new PostgresCanonicalExecutionRepository(services.postgres), + }) + : undefined; const runner = new ResearchBacktestPool({ runners: Array.from( { length: maxConcurrent }, @@ -129,12 +172,14 @@ export async function registerOrchestratorServices( AnalyticsService: analytics, BacktestRunner: runner, ...(paper ? { CanonicalPaperRuntime: paper } : {}), + ...(deploymentHost ? { PaperDeploymentHost: deploymentHost } : {}), }); const canonicalContainer = container as AwilixContainer< ServiceDefinitions & { StorageService: StorageService; AnalyticsService: AnalyticsService; CanonicalPaperRuntime: PaperRuntime; + PaperDeploymentHost: PaperDeploymentHost; BacktestRunner: ResearchBacktestPool; orchestratorServices: IServiceContainer; } @@ -145,6 +190,7 @@ export async function registerOrchestratorServices( BacktestRunner: asValue(runner), orchestratorServices: asValue(services), ...(paper ? { CanonicalPaperRuntime: asValue(paper) } : {}), + ...(deploymentHost ? { PaperDeploymentHost: asValue(deploymentHost) } : {}), }); container .resolve('handlerScanner') @@ -153,10 +199,14 @@ export async function registerOrchestratorServices( if (paper && canonicalPaper && options.initializeMode !== false) { await paper.initialize(canonicalPaper); } + if (deploymentHost && paperDeploymentHost?.deploymentId && options.initializeMode !== false) { + await deploymentHost.bind(paperDeploymentHost.deploymentId); + } services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: maxConcurrent }); } catch (error) { await runner.shutdown().catch(() => {}); await paper?.shutdown().catch(() => {}); + await deploymentHost?.shutdown().catch(() => {}); throw error; } } diff --git a/apps/stock/orchestrator/src/contracts/paper-runtime.ts b/apps/stock/orchestrator/src/contracts/paper-runtime.ts index ff3a36f7..62adab89 100644 --- a/apps/stock/orchestrator/src/contracts/paper-runtime.ts +++ b/apps/stock/orchestrator/src/contracts/paper-runtime.ts @@ -1,54 +1,22 @@ /** Explicit trusted producer boundary. No legacy timestamp repair or broker capabilities. */ import { z } from 'zod'; +import { + deployedPaperConfigurationSchema, + paperPolicySchema, +} from '@stock-bot/stock-config/paper-deployments'; import { parseFinancialDecimal } from '@stock-bot/types'; import { builtinStrategySelectionSchema } from './builtin-strategy'; import { canonicalMatchingConfigSchema, matchingCommandSchema } from './canonical-execution'; -import { replayConfigSchema, stepSchema } from './native-replay'; +import { stepSchema } from './native-replay'; const id = matchingCommandSchema.shape.key.shape.instrumentId; const time = matchingCommandSchema.shape.key.shape.at; const counter = matchingCommandSchema.shape.key.shape.sourceSequence; -const duration = counter.refine(value => value > 0, 'Duration must be positive'); const decimal = z.string().transform(value => parseFinancialDecimal(value)); -export const paperPolicySchema = z - .object({ - version: z.literal(1), - sourceId: id, - priceBasis: z.literal('raw'), - maxFeedAgeMs: duration, - observations: z.array( - z - .object({ - seriesId: id, - instrumentId: id, - intervalMs: duration, - staleAfterMs: counter, - }) - .strict() - ), - cadence: z.array(z.object({ ownerId: id, seriesIds: z.array(id).min(1) }).strict()), - calendars: z - .array( - z - .object({ - instrumentId: id, - calendarId: id, - revision: id, - sessions: z - .array(z.object({ sessionId: id, opensAt: time, closesAt: time }).strict()) - .min(1), - }) - .strict() - ) - .min(1), - riskBoundaries: z.array( - replayConfigSchema.shape.matching.shape.risk.shape.ledger.shape.riskSession - ), - }) - .strict(); +export { paperPolicySchema } from '@stock-bot/stock-config/paper-deployments'; -export const paperConfigurationSchema = z +const legacyPaperConfigurationSchema = z .object({ version: z.literal(1), matching: canonicalMatchingConfigSchema, @@ -57,6 +25,11 @@ export const paperConfigurationSchema = z }) .strict(); +export const paperConfigurationSchema = z.union([ + legacyPaperConfigurationSchema, + deployedPaperConfigurationSchema, +]); + /** availableAt is the producer's atomic release time for the whole quote frame. * Quotes retain their original physical timestamp and source sequence. The * supplied completed bars were available by this release; quotes never synthesize bars. */ diff --git a/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts b/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts index b639cd00..50d6ab79 100644 --- a/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts +++ b/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts @@ -98,12 +98,14 @@ export class PostgresCanonicalExecutionRepository implements CanonicalExecutionR config: account.checkpoint.config, definitions: account.definitions, hostConfiguration: account.host?.configuration ?? null, + deployment: account.host?.deployment ?? null, }) !== canonicalJson({ identity: expected.identity, config: expected.checkpoint.config, definitions: expected.definitions, hostConfiguration: expected.host?.configuration ?? null, + deployment: expected.host?.deployment ?? null, }) ) { throw new ExecutionConflictError( diff --git a/apps/stock/orchestrator/src/execution/canonical-paper.ts b/apps/stock/orchestrator/src/execution/canonical-paper.ts index d095bf1c..ebd5e541 100644 --- a/apps/stock/orchestrator/src/execution/canonical-paper.ts +++ b/apps/stock/orchestrator/src/execution/canonical-paper.ts @@ -1,6 +1,7 @@ /** Durable custody contracts. Financial values and transitions belong to Rust. */ import { z } from 'zod'; import type { PostgresClient } from '@stock-bot/services'; +import { paperDeploymentBindingSchema } from '@stock-bot/stock-config/paper-deployments'; import { canonicalExecutionCheckpointSchema, financialTransactionResultSchema, @@ -29,6 +30,7 @@ export const canonicalPaperHostSchema = z .object({ version: z.literal(1), configuration: paperConfigurationSchema, + deployment: paperDeploymentBindingSchema.optional(), generation: z.string().min(1), active: z.boolean(), operatorHalted: z.boolean(), diff --git a/apps/stock/orchestrator/src/index.ts b/apps/stock/orchestrator/src/index.ts index ecc2619d..f056509b 100644 --- a/apps/stock/orchestrator/src/index.ts +++ b/apps/stock/orchestrator/src/index.ts @@ -13,7 +13,11 @@ import { createContainer } from './simple-container'; // Initialize configuration with service-specific overrides const config = initializeStockConfig('orchestrator'); -const security = createHttpSecurity({ ...httpSecurityOptions(), environment: config.environment }); +const security = createHttpSecurity({ + ...httpSecurityOptions(), + environment: config.environment, + browserSessions: true, +}); const logger = getLogger('orchestrator'); // Get service-specific config @@ -71,7 +75,7 @@ async function main() { }); // Create and mount routes (without Socket.IO for now) - const routes = createRoutes(services); + const routes = createRoutes(services, undefined, security.allowedOrigins); app.route('/', routes); // Start Bun server @@ -153,6 +157,7 @@ async function main() { try { const failures: unknown[] = []; for (const close of [ + () => services.custom?.PaperDeploymentHost?.shutdown(), () => services.custom?.CanonicalPaperRuntime?.shutdown(), () => services.custom?.BacktestRunner?.shutdown(), () => services.queueManager?.shutdown(), diff --git a/apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts b/apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts index 1df6ce2e..0348f223 100644 --- a/apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts +++ b/apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts @@ -1,4 +1,5 @@ import { createHash, randomUUID } from 'node:crypto'; +import type { PaperDeploymentBinding } from '@stock-bot/stock-config/paper-deployments'; import type { StrategyProgram } from '../contracts/canonical-strategy'; import { paperActivationSchema, @@ -43,6 +44,7 @@ export class CanonicalPaperRuntime implements PaperRuntime { constructor( private readonly options: { repository: CanonicalExecutionRepository; + deployment?: PaperDeploymentBinding; programs: readonly StrategyProgram[]; now?: () => number; publish?: (entries: readonly CanonicalJournalEntry[]) => void | Promise; @@ -84,6 +86,7 @@ export class CanonicalPaperRuntime implements PaperRuntime { const host: CanonicalPaperHost = { version: 1, configuration, + ...(this.options.deployment ? { deployment: structuredClone(this.options.deployment) } : {}), generation: this.generation, active: false, operatorHalted: true, diff --git a/apps/stock/orchestrator/src/paper/PaperDeploymentHost.ts b/apps/stock/orchestrator/src/paper/PaperDeploymentHost.ts new file mode 100644 index 00000000..4e4680fd --- /dev/null +++ b/apps/stock/orchestrator/src/paper/PaperDeploymentHost.ts @@ -0,0 +1,145 @@ +import { z } from 'zod'; +import type { PaperDeploymentStatus } from '@stock-bot/stock-config/paper-deployments'; +import type { PaperReadiness, PaperRuntime } from '../contracts/paper-runtime'; +import type { CanonicalExecutionRepository, CanonicalPostgres } from '../execution/canonical-paper'; +import { + authorizedPaperPackage, + PaperDeploymentError, + paperHash, + readPaperDeployment, + verifyPaperEvidenceCustody, +} from './paper-deployment-custody'; +import type { createPromotedPaperRuntime } from './paper-host'; +import { paperHostUrl, readPaperHostIdentity } from './paper-host-identity'; + +export const unboundPaperReadiness = (reason = 'deployment-not-bound'): PaperReadiness => ({ + configured: false, + accountId: null, + sourceId: null, + active: false, + ready: false, + operatorHalted: true, + connected: false, + reasons: [reason], + lastReceivedAt: null, + lastAvailableAt: null, + requiresHistoricalRecovery: false, + pendingInput: null, + pendingBatch: null, + pendingDecisionSequence: null, + nativeStatus: null, + risk: null, +}); + +/** One explicit paper host. No default account, scheduler, automatic activation or strategy hot swap. */ +export class PaperDeploymentHost { + private bound?: { id: string; runtime: PaperRuntime }; + private tail: Promise = Promise.resolve(); + private readonly startupIdentity = readPaperHostIdentity().catch(() => null); + constructor( + private readonly options: { + database: CanonicalPostgres; + repository: CanonicalExecutionRepository; + now?: () => number; + } + ) {} + private serial(work: () => Promise): Promise { + const next = this.tail.then(work, work); + this.tail = next.catch(() => undefined); + return next; + } + private async authorized(id: string) { + return this.options.database.transaction(async tx => { + const deployment = await readPaperDeployment(tx, id); + const { pkg } = await authorizedPaperPackage(tx, deployment, true); + await verifyPaperEvidenceCustody(tx, deployment); + const startup = await this.startupIdentity; + if ( + !startup || + paperHash(startup) !== paperHash(deployment.preview.host) || + paperHash(await readPaperHostIdentity()) !== paperHash(deployment.preview.host) + ) { + throw new PaperDeploymentError( + 409, + 'Installed paper host/native/runtime differs from the reviewed promotion' + ); + } + return { deployment, pkg }; + }); + } + async bind(id: string): Promise { + id = z.string().uuid().parse(id).toLowerCase(); + return this.serial(async () => { + if (this.bound) { + if (this.bound.id !== id) { + throw new PaperDeploymentError( + 409, + 'This paper host is already bound; restart with the explicit deployment configuration to change it' + ); + } + return this.status(id); + } + const { deployment, pkg } = await this.authorized(id); + const url = new URL(paperHostUrl); + url.searchParams.set('sha256', deployment.preview.host.hostSha256); + const module = (await import(url.href)) as { + createPromotedPaperRuntime: typeof createPromotedPaperRuntime; + }; + const runtime = await module.createPromotedPaperRuntime({ + deployment, + pkg, + repository: this.options.repository, + now: this.options.now, + }); + this.bound = { id, runtime }; + return this.status(id); + }); + } + async activate(id: string, recoverPending = false): Promise { + id = z.string().uuid().parse(id).toLowerCase(); + return this.serial(async () => { + await this.authorized(id); + const runtime = this.runtime(id); + await runtime.activate({ recoverPending }); + return this.status(id); + }); + } + async halt(id: string, reason: string): Promise { + id = z.string().uuid().parse(id).toLowerCase(); + // Emergency halt remains available even if evidence/build/review later becomes unavailable. + return this.serial(async () => { + await this.runtime(id).halt(reason); + return this.status(id); + }); + } + async readiness(): Promise { + return this.bound ? this.bound.runtime.status() : unboundPaperReadiness(); + } + + async status(id: string): Promise { + id = z.string().uuid().parse(id).toLowerCase(); + await this.options.database.transaction(tx => readPaperDeployment(tx, id)); + return { + deploymentId: id, + boundDeploymentId: this.bound?.id ?? null, + readiness: + this.bound?.id === id + ? await this.bound.runtime.status() + : unboundPaperReadiness( + this.bound ? 'host-bound-to-another-deployment' : 'deployment-not-bound' + ), + }; + } + runtime(id?: string): PaperRuntime { + if (!this.bound || (id !== undefined && this.bound.id !== id)) { + throw new PaperDeploymentError(409, 'Deployment is not bound to this paper host'); + } + return this.bound.runtime; + } + async shutdown() { + return this.serial(async () => { + await this.bound?.runtime.shutdown(); + this.bound = undefined; + }); + } +} diff --git a/apps/stock/orchestrator/src/paper/paper-deployment-custody.ts b/apps/stock/orchestrator/src/paper/paper-deployment-custody.ts new file mode 100644 index 00000000..e9bb6657 --- /dev/null +++ b/apps/stock/orchestrator/src/paper/paper-deployment-custody.ts @@ -0,0 +1,190 @@ +/** Read-only promotion custody. This module cannot import or execute strategy code. */ +import { createHash } from 'node:crypto'; +import type { QueryResultRow } from 'pg'; +import { + paperDeploymentSchema, + type PaperDeployment, + type PaperPromotionPreview, +} from '@stock-bot/stock-config/paper-deployments'; +import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; +import { verifyRetainedProgramPackage } from '../strategies/retained-program'; + +export interface PaperDeploymentDatabase { + query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }>; +} +export class PaperDeploymentError extends Error { + constructor( + readonly status: 400 | 403 | 404 | 409 | 422 | 503, + message: string + ) { + super(message); + } +} +export const paperHash = (value: unknown) => + createHash('sha256').update(canonicalStrategyJson(value)).digest('hex'); +export function paperPreviewHash( + preview: Omit | PaperPromotionPreview +) { + const { previewHash: _ignored, ...body } = preview as PaperPromotionPreview; + return paperHash(body); +} +export function retainedPaperDeployment(raw: unknown): PaperDeployment { + const value = paperDeploymentSchema.parse(raw); + const { promotionHash, ...body } = value; + if ( + paperHash(body) !== promotionHash || + paperPreviewHash(value.preview) !== value.preview.previewHash + ) { + throw new Error('Retained paper promotion identity mismatch'); + } + return value; +} +export async function readPaperDeployment( + database: PaperDeploymentDatabase, + id: string +): Promise { + const row = (await database.query('SELECT * FROM paper_deployments WHERE id=$1', [id])).rows[0]; + if (!row) { + throw new PaperDeploymentError(404, 'Paper deployment not found'); + } + const value = retainedPaperDeployment(row.document); + if ( + value.id !== row.id || + value.preview.configuration.matching.risk.ledger.accountId !== row.account_id || + value.preview.strategy.versionId !== row.strategy_version_id || + value.promotionHash !== row.promotion_hash + ) { + throw new Error('Retained paper deployment row identity mismatch'); + } + return value; +} +/** Admission and activation require a current operator approval. Historical GET stays available. */ +export async function authorizedPaperPackage( + database: PaperDeploymentDatabase, + deployment: PaperDeployment | Pick, + lock = false +) { + const preview = 'preview' in deployment ? deployment.preview : deployment; + const version = ( + await database.query( + `SELECT v.envelope,v.origin,s.archived_at FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id WHERE v.id=$1 AND s.id=$2${lock ? ' FOR UPDATE OF s' : ''}`, + [preview.strategy.versionId, preview.strategy.familyId] + ) + ).rows[0]; + const review = ( + await database.query( + 'SELECT id,decision FROM strategy_review_events WHERE version_id=$1 ORDER BY ordinal DESC LIMIT 1', + [preview.strategy.versionId] + ) + ).rows[0]; + if (!version || version.archived_at !== null || review?.decision !== 'approve') { + throw new PaperDeploymentError( + 409, + 'Paper deployment requires an active family and current operator approval' + ); + } + const pkg = verifyRetainedProgramPackage(version.envelope); + if ( + version.origin !== preview.strategy.origin || + pkg.artifact.sha256 !== preview.strategy.artifactSha256 || + pkg.dependencyLock.sha256 !== preview.strategy.dependencyLockSha256 + ) { + throw new Error('Paper promotion artifact no longer matches retained bytes'); + } + return { pkg, reviewId: String(review.id) }; +} + +/** Host-side retained identity check, independent of the web API's full financial source reader. */ +export async function verifyPaperEvidenceCustody( + database: PaperDeploymentDatabase, + deployment: PaperDeployment +) { + const { input, evidence } = deployment.preview, + source = input.outOfSample; + let report: Record | undefined; + if (source.kind === 'chronological-report/v1') { + const row = ( + await database.query('SELECT validation_report FROM research_experiments WHERE id=$1', [ + source.validationId, + ]) + ).rows[0]; + report = row?.validation_report; + if ((report?.test as { runId?: string } | undefined)?.runId !== input.testRunId) { + throw new Error('Paper test membership changed'); + } + } else if (source.kind === 'walk-forward-report/v1') { + const row = ( + await database.query('SELECT report FROM research_walk_forwards WHERE id=$1', [ + source.walkForwardId, + ]) + ).rows[0]; + report = row?.report; + if ( + !(report?.segments as Array<{ test: { runId: string } }> | undefined)?.some( + segment => segment.test.runId === input.testRunId + ) + ) { + throw new Error('Paper walk-forward test membership changed'); + } + } else { + throw new Error('Paper promotion requires sealed out-of-sample evidence'); + } + if (!report) { + throw new Error('Paper source report is missing'); + } + const { _receipt, reportHash, ...body } = report; + if ( + !_receipt || + paperHash(body) !== reportHash || + reportHash !== source.reportHash || + report.id !== source.reportId || + report.previewHash !== source.previewHash + ) { + throw new Error('Paper source report changed'); + } + const cost = ( + await database.query( + 'SELECT preview,preview_hash,validation_phase FROM research_experiments WHERE id=$1', + [input.costExperimentId] + ) + ).rows[0]; + if ( + !cost || + cost.validation_phase !== null || + cost.preview?.version !== 'cost-sensitivity-preview/v1' || + cost.preview_hash !== input.costPreviewHash || + cost.preview?.previewHash !== input.costPreviewHash || + cost.preview.candidates.length !== evidence.costs.length + ) { + throw new Error('Paper cost source changed'); + } + const rows = ( + await database.query('SELECT id FROM runs WHERE experiment_id=$1 ORDER BY trial_index', [ + input.costExperimentId, + ]) + ).rows; + if ( + canonicalStrategyJson(rows.map(row => row.id)) !== + canonicalStrategyJson(evidence.costs.map(item => item.runId)) + ) { + throw new Error('Paper cost membership changed'); + } + for (const item of [evidence.test, ...evidence.costs]) { + const row = ( + await database.query( + 'SELECT r.status,r.request_snapshot,r.dataset_hash,br.canonical_result FROM runs r JOIN backtest_results br ON br.run_id=r.id WHERE r.id=$1', + [item.runId] + ) + ).rows[0]; + if ( + !row || + row.status !== 'completed' || + row.dataset_hash !== item.datasetHash || + paperHash(row.canonical_result) !== item.resultHash || + canonicalStrategyJson(row.canonical_result.request) !== + canonicalStrategyJson(row.request_snapshot) + ) { + throw new Error('Paper retained result identity changed'); + } + } +} diff --git a/apps/stock/orchestrator/src/paper/paper-host-identity.ts b/apps/stock/orchestrator/src/paper/paper-host-identity.ts new file mode 100644 index 00000000..665d7368 --- /dev/null +++ b/apps/stock/orchestrator/src/paper/paper-host-identity.ts @@ -0,0 +1,76 @@ +/** Read-only build identity. This module never imports the native addon or strategy code. */ +import { createHash } from 'node:crypto'; +import { realpathSync } from 'node:fs'; +import { readFile } from 'node:fs/promises'; +import { dirname, isAbsolute, relative, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { + paperHostIdentitySchema, + type PaperHostIdentity, +} from '@stock-bot/stock-config/paper-deployments'; +import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; + +const engineWrapper = realpathSync(fileURLToPath(import.meta.resolve('@stock-bot/engine'))); +const repositoryRoot = resolve(dirname(engineWrapper), '../../..'); +const ownPath = relative(repositoryRoot, realpathSync(fileURLToPath(import.meta.url))); +if (isAbsolute(ownPath) || ownPath === '..' || ownPath.startsWith('../')) { + throw new Error('Paper engine resolves outside this checkout'); +} +if (engineWrapper !== resolve(repositoryRoot, 'apps/stock/engine/index.mjs')) { + throw new Error('Unsupported canonical engine wrapper location'); +} + +export const paperHostUrl = pathToFileURL( + resolve(repositoryRoot, 'apps/stock/orchestrator/dist/paper-host.js') +); + +async function hashLocalFile(path: string): Promise { + if (realpathSync(path) !== path) { + throw new Error('Paper build artifacts must belong to this checkout'); + } + return createHash('sha256') + .update(await readFile(path)) + .digest('hex'); +} + +/** Capture all executable worker/native bytes and the runtime that interprets them. */ +export async function readPaperHostIdentity(): Promise { + if (typeof Bun === 'undefined') { + throw new Error('Paper deployment requires the Bun runtime'); + } + const [hostSha256, engineWrapperSha256, engineBinarySha256, dependencyLockSha256] = + await Promise.all([ + hashLocalFile(fileURLToPath(paperHostUrl)), + hashLocalFile(engineWrapper), + hashLocalFile(resolve(repositoryRoot, 'apps/stock/engine/dist/engine.node')), + hashLocalFile(resolve(repositoryRoot, 'bun.lock')), + ]); + return paperHostIdentitySchema.parse({ + version: 'paper-host/v1', + hostSha256, + engineWrapperSha256, + engineBinarySha256, + dependencyLockSha256, + runtime: 'bun', + runtimeVersion: Bun.version, + platform: process.platform, + arch: process.arch, + }); +} + +/** The running child supplies its own module URL, never a URL from the request. */ +export async function verifyPaperHostBuild( + expected: PaperHostIdentity, + actualHostUrl: string +): Promise { + if (realpathSync(fileURLToPath(actualHostUrl)) !== realpathSync(fileURLToPath(paperHostUrl))) { + throw new Error('Paper deployment requires the bundled paper host from this checkout'); + } + const actual = await readPaperHostIdentity(); + if ( + canonicalStrategyJson(actual) !== canonicalStrategyJson(paperHostIdentitySchema.parse(expected)) + ) { + throw new Error('Paper host/native/runtime build identity mismatch'); + } + return actual; +} diff --git a/apps/stock/orchestrator/src/paper/paper-host.ts b/apps/stock/orchestrator/src/paper/paper-host.ts new file mode 100644 index 00000000..fd6b2918 --- /dev/null +++ b/apps/stock/orchestrator/src/paper/paper-host.ts @@ -0,0 +1,53 @@ +/** Dedicated bundled entry point. Importing it does not start a host or import a strategy. */ +import { loadedNativeIdentity } from '@stock-bot/engine'; +import type { PaperDeployment } from '@stock-bot/stock-config/paper-deployments'; +import type { StrategyVersionPackage } from '@stock-bot/types'; +import type { CanonicalExecutionRepository } from '../execution/canonical-paper'; +import { importRetainedProgram } from '../strategies/retained-program'; +import { CanonicalPaperRuntime } from './CanonicalPaperRuntime'; +import { retainedPaperDeployment } from './paper-deployment-custody'; +import { verifyPaperHostBuild } from './paper-host-identity'; + +/** Caller must have verified the immutable operator promotion and current permission before calling. */ +export async function createPromotedPaperRuntime(options: { + deployment: PaperDeployment; + pkg: StrategyVersionPackage; + repository: CanonicalExecutionRepository; + now?: () => number; +}) { + const deployment = retainedPaperDeployment(options.deployment); + await verifyPaperHostBuild(deployment.preview.host, import.meta.url); + if ( + loadedNativeIdentity.engineWrapperSha256 !== deployment.preview.host.engineWrapperSha256 || + loadedNativeIdentity.engineBinarySha256 !== deployment.preview.host.engineBinarySha256 + ) { + throw new Error( + 'Loaded native identity differs from paper promotion; restart with immutable build artifacts' + ); + } + if ( + options.pkg.artifact.sha256 !== deployment.preview.strategy.artifactSha256 || + options.pkg.dependencyLock.sha256 !== deployment.preview.strategy.dependencyLockSha256 + ) { + throw new Error('Paper host artifact does not match the operator promotion'); + } + const program = await importRetainedProgram( + options.pkg, + deployment.preview.configuration.strategies[0] + ); + const runtime = new CanonicalPaperRuntime({ + repository: options.repository, + programs: [program], + now: options.now, + deployment: { + deploymentId: deployment.id, + promotionHash: deployment.promotionHash, + strategyVersionId: deployment.preview.strategy.versionId, + artifactSha256: deployment.preview.strategy.artifactSha256, + dependencyLockSha256: deployment.preview.strategy.dependencyLockSha256, + host: deployment.preview.host, + }, + }); + await runtime.initialize(deployment.preview.configuration); + return runtime; +} diff --git a/apps/stock/orchestrator/src/paper/paper-operator.ts b/apps/stock/orchestrator/src/paper/paper-operator.ts new file mode 100644 index 00000000..4ea511d1 --- /dev/null +++ b/apps/stock/orchestrator/src/paper/paper-operator.ts @@ -0,0 +1,23 @@ +import { getCredentialHttpPrincipal } from '@stock-bot/di'; +import { PaperDeploymentError } from './paper-deployment-custody'; + +/** Defense in depth for both public services, including bearer requests carrying browser Origin. */ +export function requirePaperOperator(request: Request, origins: readonly string[]) { + if (getCredentialHttpPrincipal(request) !== 'operator') { + throw new PaperDeploymentError( + 403, + 'Credential-backed human operator required for paper commands' + ); + } + const origin = request.headers.get('origin'); + if (origin && (!origins.length || !origins.includes(origin))) { + throw new PaperDeploymentError( + 403, + 'Paper commands require an explicitly configured trusted Origin' + ); + } +} +export const paperAllowedOrigins = () => + process.env.STOCK_BOT_ALLOWED_ORIGINS?.split(',') + .map(v => v.trim()) + .filter(Boolean) ?? []; diff --git a/apps/stock/orchestrator/src/routes/create-routes.ts b/apps/stock/orchestrator/src/routes/create-routes.ts index bfc82070..dded6309 100644 --- a/apps/stock/orchestrator/src/routes/create-routes.ts +++ b/apps/stock/orchestrator/src/routes/create-routes.ts @@ -3,12 +3,17 @@ import type { Server as SocketIOServer } from 'socket.io'; import { createAnalyticsRoutes } from '../api/rest/analytics'; import { createBacktestRoutes } from '../api/rest/backtest'; import { createPaperRoutes } from '../api/rest/paper'; +import { createPaperDeploymentHostRoutes } from '../api/rest/paper-deployments'; 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, + origins?: readonly string[] +): Hono { const app = new Hono(); services.logger.info('Creating orchestrator routes'); @@ -17,8 +22,15 @@ export function createRoutes(services: IServiceContainer, _io?: SocketIOServer): return c.json({ status: 'healthy', service: 'orchestrator', - mode: services.custom?.CanonicalPaperRuntime ? 'paper' : 'research-only', - execution: services.custom?.CanonicalPaperRuntime ? 'canonical-paper' : 'canonical-research', + mode: + services.custom?.CanonicalPaperRuntime || services.custom?.PaperDeploymentHost + ? 'paper' + : 'research-only', + execution: services.custom?.PaperDeploymentHost + ? 'reviewed-paper-deployment' + : services.custom?.CanonicalPaperRuntime + ? 'canonical-paper' + : 'canonical-research', timestamp: new Date().toISOString(), }); }); @@ -32,13 +44,26 @@ export function createRoutes(services: IServiceContainer, _io?: SocketIOServer): ...(await services.custom.CanonicalPaperRuntime.status()), }); } + if (services.custom?.PaperDeploymentHost) { + return c.json({ + engine: 'reviewed-paper-deployment', + ...(await services.custom.PaperDeploymentHost.readiness()), + }); + } 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)); + app.route( + '/api/paper/deployments', + createPaperDeploymentHostRoutes(services.custom?.PaperDeploymentHost, origins) + ); + app.route( + '/api/paper', + createPaperRoutes(services, { deploymentHost: services.custom?.PaperDeploymentHost, origins }) + ); // Retired gateways remain explicit diagnostics, never a fallback simulator. const unavailable = new Hono().all('*', c => c.json( diff --git a/apps/stock/orchestrator/src/simple-container.ts b/apps/stock/orchestrator/src/simple-container.ts index 735499b6..4e691f80 100644 --- a/apps/stock/orchestrator/src/simple-container.ts +++ b/apps/stock/orchestrator/src/simple-container.ts @@ -2,10 +2,10 @@ import { ServiceContainerBuilder } from '@stock-bot/di'; import type { StockAppConfig } from '@stock-bot/stock-config'; import { assertResearchConcurrency } from './backtest/ResearchBacktestPool'; import { paperConfigurationSchema } from './contracts/paper-runtime'; -import { validatePaperConfiguration } from './paper/feed'; import { assertSupportedComposition, registerOrchestratorServices, + resolvePaperComposition, type OrchestratorRole, } from './container'; import type { OrchestratorServices } from './types'; @@ -32,21 +32,17 @@ export async function createContainer( const maxConcurrent = settings?.backtesting?.maxConcurrent === undefined ? 1 : settings.backtesting.maxConcurrent; assertResearchConcurrency(maxConcurrent); - if (settings?.canonicalPaper !== undefined && role !== 'paper') { - throw new Error('Canonical paper configuration requires a paper composition'); - } - const canonicalPaper = + const { canonicalPaper, paperDeploymentHost } = resolvePaperComposition( + role, 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) { + : paperConfigurationSchema.parse(settings.canonicalPaper), + settings?.paperDeploymentHost + ); + if ((canonicalPaper || paperDeploymentHost) && !config.database?.postgres?.enabled) { throw new Error('Canonical paper requires durable PostgreSQL custody'); } + const container = await new ServiceContainerBuilder() .withConfig(config) .withOptions({ @@ -67,6 +63,7 @@ export async function createContainer( syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42, nativeExecutionTimeoutMs: config.services?.orchestrator?.backtesting?.executionTimeoutMs, canonicalPaper, + paperDeploymentHost, }); return container.resolve('serviceContainer') as OrchestratorServices; } diff --git a/apps/stock/orchestrator/src/strategies/retained-program.ts b/apps/stock/orchestrator/src/strategies/retained-program.ts new file mode 100644 index 00000000..7a509343 --- /dev/null +++ b/apps/stock/orchestrator/src/strategies/retained-program.ts @@ -0,0 +1,70 @@ +/** Executable loader: call only in an OS-isolated candidate host or after a server-owned + * trusted builtin/paper-promotion authorization. Metadata never grants that authority. */ +import { createHash } from 'node:crypto'; +import { + retainedProgramSelectionSchema, + type RetainedProgramSelection, +} from '@stock-bot/stock-config/candidate-execution'; +import { parseStrategyVersionPackage } from '@stock-bot/stock-config/strategy'; +import type { StrategyVersionPackage } from '@stock-bot/types'; +import type { StrategyProgram } from '../contracts/canonical-strategy'; +import { freeze } from './strategy-decision'; + +export type { RetainedProgramSelection } from '@stock-bot/stock-config/candidate-execution'; + +/** Validates bytes and metadata only; never imports, compiles or calls candidate code. */ +export function verifyRetainedProgramPackage(input: unknown): StrategyVersionPackage { + const pkg = parseStrategyVersionPackage(input); + const hash = (content: string) => createHash('sha256').update(content, 'utf8').digest('hex'); + if ( + hash(pkg.artifact.content) !== pkg.artifact.sha256 || + hash(pkg.dependencyLock.content) !== pkg.dependencyLock.sha256 + ) { + throw new Error('Retained strategy artifact or dependency lock hash mismatch'); + } + if (pkg.program.apiVersion !== 'canonical-ts/v1') { + throw new Error('Unsupported retained strategy API version'); + } + return pkg; +} + +export async function importRetainedProgram( + input: StrategyVersionPackage, + rawSelection: RetainedProgramSelection +): Promise { + const pkg = verifyRetainedProgramPackage(input); + const selection = retainedProgramSelectionSchema.parse(rawSelection); + if ( + pkg.program.strategyId !== selection.strategyId || + pkg.program.strategyVersion !== selection.strategyVersion + ) { + throw new Error('Retained strategy selection identity mismatch'); + } + const moduleUrl = URL.createObjectURL( + new Blob([pkg.artifact.content], { type: 'text/javascript' }) + ); + let module: Record; + try { + module = await import(moduleUrl); + } finally { + URL.revokeObjectURL(moduleUrl); + } + const factory = module[pkg.artifact.entryExport]; + if (typeof factory !== 'function') { + throw new Error('Retained strategy factory export is missing'); + } + const program = factory(freeze(structuredClone(selection))) as StrategyProgram; + if ( + !program || + typeof program !== 'object' || + program.ownerId !== selection.ownerId || + program.strategyId !== selection.strategyId || + program.strategyVersion !== selection.strategyVersion || + program.seed !== selection.seed || + program.mode !== 'target' || + typeof program.decide !== 'function' + ) { + throw new Error('Retained strategy factory identity or API mismatch'); + } + return program; +} diff --git a/apps/stock/orchestrator/src/strategies/strategy-controller.ts b/apps/stock/orchestrator/src/strategies/strategy-controller.ts index 69fa35bf..7c4ea7e6 100644 --- a/apps/stock/orchestrator/src/strategies/strategy-controller.ts +++ b/apps/stock/orchestrator/src/strategies/strategy-controller.ts @@ -12,7 +12,6 @@ import { nativeAdmissionOrders, type DecisionContext, type PublishedObservation, - type replayConfigSchema, type ReplayIdentity, type ReplaySubmissionOutcome, } from '../contracts/native-replay'; @@ -48,7 +47,7 @@ export class StrategyController { constructor( private readonly identity: ReplayIdentity, programs: readonly StrategyProgram[], - config: ReturnType + config: { matching: { owners: { ownerId: string; mode: 'Target' | 'Orders' }[] } } ) { this.slots = new Map( programs.map(program => { diff --git a/apps/stock/orchestrator/src/types.ts b/apps/stock/orchestrator/src/types.ts index 572ce13f..fd5fe860 100644 --- a/apps/stock/orchestrator/src/types.ts +++ b/apps/stock/orchestrator/src/types.ts @@ -56,6 +56,7 @@ export type OrchestratorServices = import('@stock-bot/services').IServiceContain PaperTradingManager: import('./paper/PaperTradingManager').PaperTradingManager; ModeManager: import('./core/ModeManager').ModeManager; CanonicalPaperRuntime: import('./contracts/paper-runtime').PaperRuntime; + PaperDeploymentHost: import('./paper/PaperDeploymentHost').PaperDeploymentHost; }>; }; export type { BacktestResult } from './backtest/RustBacktestAdapter'; diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index 99a183df..30279ea1 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -68,7 +68,10 @@ export async function runMigrations(container: IServiceContainer): Promise f === '25-walk-forward.sql' || f === '26-cost-sensitivity.sql' || f === '27-research-evidence-sources.sql' || - f === '28-research-agents.sql') + f === '28-research-agents.sql' || + f === '29-isolated-candidates.sql' || + f === '30-paper-deployments.sql' || + f === '31-research-agent-project-links.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 25482c67..fd52ae50 100644 --- a/apps/stock/web-api/src/routes/create-routes.ts +++ b/apps/stock/web-api/src/routes/create-routes.ts @@ -15,6 +15,7 @@ import { createExchangeRoutes } from './exchange.routes'; import { createExperimentRoutes } from './experiments.routes'; import { createHealthRoutes } from './health.routes'; import { createMonitoringRoutes } from './monitoring.routes'; +import { createPaperDeploymentRoutes } from './paper-deployments.routes'; import { createPipelineRoutes } from './pipeline.routes'; import { createResearchAgentRoutes } from './research-agents.routes'; import { createResearchRoutes } from './research.routes'; @@ -24,7 +25,11 @@ 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, suppliedSecurity?: HttpSecurity): Hono { +export function createRoutes( + container: IServiceContainer, + suppliedSecurity?: HttpSecurity, + integrations?: { paperOrchestratorOrigin?: string } +): Hono { const agents = new ResearchAgentsService(container); const security = suppliedSecurity ?? @@ -67,6 +72,13 @@ export function createRoutes(container: IServiceContainer, suppliedSecurity?: Ht app.route('/', createResearchRoutes(container)); app.route('/', createResearchAgentRoutes(container, security.researchEnabled)); app.route('/', createExperimentRoutes(container)); + app.route( + '/', + createPaperDeploymentRoutes(container, { + origin: integrations ? integrations.paperOrchestratorOrigin : process.env.ORCHESTRATOR_URL, + origins: security.allowedOrigins, + }) + ); 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 6b8dcaf7..29005802 100644 --- a/apps/stock/web-api/src/routes/experiments.routes.ts +++ b/apps/stock/web-api/src/routes/experiments.routes.ts @@ -75,7 +75,10 @@ export function createExperimentRoutes(container: IServiceContainer) { }; app.post('/api/v2/experiments/cost-sensitivity/preview', async c => c.json({ - preview: await service.previewCosts(parseCostSensitivityInput(await body(c.req.raw))), + preview: await service.previewCosts( + parseCostSensitivityInput(await body(c.req.raw)), + getResearchHttpPrincipal(c.req.raw) ?? '' + ), }) ); app.post('/api/v2/experiments/cost-sensitivity', async c => { @@ -91,7 +94,12 @@ export function createExperimentRoutes(container: IServiceContainer) { return c.json({ experiment }, 202); }); app.post('/api/v2/experiments/walk-forward/preview', async c => - c.json({ preview: await walkForwards.preview(parseWalkForwardInput(await body(c.req.raw))) }) + c.json({ + preview: await walkForwards.preview( + parseWalkForwardInput(await body(c.req.raw)), + getResearchHttpPrincipal(c.req.raw) ?? '' + ), + }) ); app.post('/api/v2/experiments/walk-forward', async c => { const input = parseWalkForwardSubmission(await body(c.req.raw)); @@ -140,7 +148,9 @@ export function createExperimentRoutes(container: IServiceContainer) { }); app.post('/api/v2/experiments/validation/preview', async c => { const input = parseChronologicalValidation(await body(c.req.raw)); - return c.json({ preview: await service.previewValidation(input) }); + return c.json({ + preview: await service.previewValidation(input, getResearchHttpPrincipal(c.req.raw) ?? ''), + }); }); app.post('/api/v2/experiments/validation', async c => { const input = parseValidationSubmission(await body(c.req.raw)); @@ -204,7 +214,9 @@ export function createExperimentRoutes(container: IServiceContainer) { }); app.post('/api/v2/experiments/preview', async c => { const input = parseExperimentInput(await body(c.req.raw)); - return c.json({ preview: await service.preview(input) }); + return c.json({ + preview: await service.preview(input, getResearchHttpPrincipal(c.req.raw) ?? ''), + }); }); app.post('/api/v2/experiments', async c => { const input = parseExperimentSubmission(await body(c.req.raw)); diff --git a/apps/stock/web-api/src/routes/paper-deployments.routes.ts b/apps/stock/web-api/src/routes/paper-deployments.routes.ts new file mode 100644 index 00000000..0108a135 --- /dev/null +++ b/apps/stock/web-api/src/routes/paper-deployments.routes.ts @@ -0,0 +1,178 @@ +import { Hono } from 'hono'; +import { z } from 'zod'; +import type { IServiceContainer } from '@stock-bot/services'; +import { paperDeploymentStatusSchema } from '@stock-bot/stock-config/paper-deployments'; +import { + paperActivationSchema, + paperHaltSchema, + PaperRuntimeError, +} from '../../../orchestrator/src/contracts/paper-runtime'; +import { PaperDeploymentError } from '../../../orchestrator/src/paper/paper-deployment-custody'; +import { + paperAllowedOrigins, + requirePaperOperator, +} from '../../../orchestrator/src/paper/paper-operator'; +import { PaperDeploymentsService } from '../services/paper-deployments.service'; +import { ResearchError } from '../services/research-errors'; + +/** Forwards the original human credential; never substitutes a service token. */ +export async function forwardPaperCommand( + request: Request, + id: string, + operation: 'bind' | 'activate' | 'halt' | 'readiness', + body: unknown, + options: { + origin?: string; + request?: (url: string | URL | Request, init?: RequestInit) => Promise; + } +) { + if (!options.origin) { + throw new PaperDeploymentError(503, 'Paper orchestrator origin is not configured'); + } + let base: URL; + try { + base = new URL(options.origin); + } catch { + throw new PaperDeploymentError(503, 'Paper orchestrator origin is invalid'); + } + if ( + !['http:', 'https:'].includes(base.protocol) || + base.username || + base.password || + base.pathname !== '/' || + base.search || + base.hash + ) { + throw new PaperDeploymentError(503, 'Paper orchestrator requires a fixed HTTP origin'); + } + const headers = new Headers({ 'Content-Type': 'application/json' }); + for (const name of ['authorization', 'cookie', 'origin']) { + const value = request.headers.get(name); + if (value) { + headers.set(name, value); + } + } + let response: Response; + try { + response = await (options.request ?? fetch)( + new URL(`/api/paper/deployments/${id}/${operation}`, base), + { + method: operation === 'readiness' ? 'GET' : 'POST', + headers, + ...(operation === 'readiness' ? {} : { body: JSON.stringify(body) }), + redirect: 'error', + signal: AbortSignal.timeout(15000), + } + ); + } catch { + throw new PaperDeploymentError( + 503, + 'Paper orchestrator could not confirm the command; check readiness before retrying' + ); + } + const value: unknown = await response.json().catch(() => null); + if (!response.ok) { + const status = [400, 403, 404, 409, 422, 503].includes(response.status) ? response.status : 503; + const message = + value && typeof value === 'object' && 'error' in value && typeof value.error === 'string' + ? value.error + : 'Paper orchestrator rejected the request'; + throw new PaperDeploymentError(status as 400 | 403 | 404 | 409 | 422 | 503, message); + } + const status = paperDeploymentStatusSchema.parse(value); + if (status.deploymentId !== id) { + throw new Error('Paper orchestrator returned another deployment'); + } + return status; +} +export function createPaperDeploymentRoutes( + container: IServiceContainer, + options: { + origin?: string; + origins?: readonly string[]; + request?: (url: string | URL | Request, init?: RequestInit) => Promise; + service?: PaperDeploymentsService; + } = {} +) { + const app = new Hono(), + service = options.service ?? new PaperDeploymentsService(container), + origins = options.origins ?? paperAllowedOrigins(); + app.use('*', async (c, next) => { + c.header('Cache-Control', 'no-store'); + if (c.req.method !== 'GET' || c.req.path.endsWith('/readiness')) { + requirePaperOperator(c.req.raw, origins); + } + await next(); + }); + app.onError((error, c) => { + if (error instanceof PaperDeploymentError || error instanceof ResearchError) { + return c.json({ error: error.message }, error.status); + } + if ( + error instanceof z.ZodError || + error instanceof SyntaxError || + error instanceof PaperRuntimeError + ) { + return c.json( + { + error: + error instanceof PaperRuntimeError ? error.message : 'Invalid paper promotion request', + }, + 400 + ); + } + container.logger.error('Paper deployment operation failed', { error }); + return c.json({ error: 'Paper deployment evidence or storage unavailable' }, 500); + }); + app.get('/api/v2/paper-deployments', async c => c.json({ deployments: await service.list() })); + app.post('/api/v2/paper-deployments/preview', async c => + c.json(await service.preview(await c.req.json())) + ); + app.post('/api/v2/paper-deployments', async c => + c.json(await service.create(await c.req.json(), c.req.header('Idempotency-Key') ?? ''), 201) + ); + app.get('/api/v2/paper-deployments/:id', async c => + c.json( + await service.get( + z + .string() + .uuid() + .transform(value => value.toLowerCase()) + .parse(c.req.param('id')) + ) + ) + ); + for (const operation of ['bind', 'activate', 'halt', 'readiness'] as const) { + const path = `/api/v2/paper-deployments/:id/${operation}`; + app.on(operation === 'readiness' ? 'GET' : 'POST', path, async c => { + const id = z + .string() + .uuid() + .transform(value => value.toLowerCase()) + .parse(c.req.param('id')); + const body = + operation === 'readiness' + ? undefined + : operation === 'activate' + ? paperActivationSchema.parse(await c.req.json()) + : operation === 'halt' + ? paperHaltSchema.parse(await c.req.json()) + : z + .object({}) + .strict() + .parse(await c.req.json()); + if (operation === 'bind' || operation === 'activate') { + await service.authorizeCommand(id); + } else { + await service.get(id); + } + return c.json( + await forwardPaperCommand(c.req.raw, id, operation, body, { + origin: options.origin ?? process.env.ORCHESTRATOR_URL, + request: options.request, + }) + ); + }); + } + return app; +} 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 8112ad81..5842b67b 100644 --- a/apps/stock/web-api/src/services/backtest-v2.service.ts +++ b/apps/stock/web-api/src/services/backtest-v2.service.ts @@ -15,6 +15,7 @@ import { } from '@stock-bot/stock-config/backtest'; import { canonicalRunRequestSchema, + canonicalStrategyExecution, parseCanonicalFinancialResult, type CanonicalReproductionComparison, type CanonicalReproductionPreview, @@ -862,7 +863,7 @@ export class BacktestServiceV2 { saved.backtestId !== row.backtest_id || saved.status !== 'completed' || saved.financialEngine !== 'rust' || - saved.strategyExecution !== 'typescript-retained-builtin/v1' || + saved.strategyExecution !== canonicalStrategyExecution(request) || !Number.isFinite(Date.parse(saved.completedAt)) || !Number.isFinite(saved.executionTime) || saved.executionTime < 0 || @@ -884,15 +885,21 @@ export class BacktestServiceV2 { async canonicalCapability(id: string): Promise { try { - await this.container.postgres.transaction(async client => { + const execution = await this.container.postgres.transaction(async client => { const row = (await client.query('SELECT * FROM backtests WHERE id=$1 FOR UPDATE', [id])) .rows[0]; if (!row || row.archived_at !== null) { throw new Error('Backtest is missing or archived'); } - await admitCanonicalRequest(client, this.container, this.mapBacktest(row), id); + const request = await admitCanonicalRequest( + client, + this.container, + this.mapBacktest(row), + id + ); + return request.strategy.origin === 'candidate' ? request.strategy.execution : undefined; }); - return { available: true, reason: null }; + return { available: true, reason: null, ...(execution ? { execution } : {}) }; } catch (error) { return { available: false, diff --git a/apps/stock/web-api/src/services/canonical-research.service.ts b/apps/stock/web-api/src/services/canonical-research.service.ts index b2a5eef0..d55059d9 100644 --- a/apps/stock/web-api/src/services/canonical-research.service.ts +++ b/apps/stock/web-api/src/services/canonical-research.service.ts @@ -1,19 +1,27 @@ import { randomUUID } from 'node:crypto'; import type { PoolClient } from 'pg'; import type { IServiceContainer } from '@stock-bot/services'; +import { + retainedProgramSelectionSchema, + type CandidateExecution, +} from '@stock-bot/stock-config/candidate-execution'; import { canonicalResearchSettingsSchema, canonicalRunRequestSchema, type CanonicalDatasetCatalogEntry, type CanonicalRunRequest, } from '@stock-bot/stock-config/canonical-research'; -import { builtinStrategySelectionSchema } from '@stock-bot/stock-config/strategy'; +import { + builtinStrategySelectionSchema, + validateStrategyParameters, +} from '@stock-bot/stock-config/strategy'; import { HistoricalDataRequestError, parseFinancialDecimal, type HistoricalDatasetV2, type StrategyParameterValue, } from '@stock-bot/types'; +import { readCandidateExecution } from '../../../orchestrator/src/backtest/candidate-sandbox'; import { readCanonicalBuildIdentity } from '../../../orchestrator/src/backtest/canonical-build'; import { validateDatasetV2 } from '../../../orchestrator/src/data/historical-dataset-v2'; import { canonicalRiskSessionClock } from './canonical-risk-clock'; @@ -155,8 +163,34 @@ export async function admitCanonicalRequest( container: IServiceContainer, template: CanonicalTemplate, backtestId: string, - runId = randomUUID() + runId = randomUUID(), + override?: { versionId: string; parameters: Record }, + baselineVersionId = template.strategyVersionId ): Promise { + if (override) { + await client.query( + 'SELECT s.id FROM strategies s WHERE s.id IN (SELECT strategy_id FROM strategy_versions WHERE id=ANY($1::uuid[])) ORDER BY s.id FOR UPDATE', + [[template.strategyVersionId, override.versionId].filter(Boolean)] + ); + await admitCanonicalRequest(client, container, template, backtestId, runId); + const candidate = await admitCanonicalRequest( + client, + container, + { + ...template, + strategyVersionId: override.versionId, + strategyParameters: override.parameters, + }, + backtestId, + runId, + undefined, + template.strategyVersionId + ); + if (candidate.strategy.origin !== 'candidate') { + return invalid('Candidate override requires an immutable candidate version'); + } + return candidate; + } if (!template.strategyVersionId || !template.strategyParameters) { return invalid('Select an immutable strategy version and validated parameters'); } @@ -167,10 +201,12 @@ export async function admitCanonicalRequest( [template.strategyVersionId] ) ).rows[0]; - if (!selected || selected.archived_at !== null || selected.origin !== 'builtin') { - return invalid( - 'Only active, server-seeded built-in versions can execute; candidates require isolation' - ); + if ( + !selected || + selected.archived_at !== null || + !['builtin', 'candidate'].includes(selected.origin) + ) { + return invalid('Select an active retained strategy version'); } const review = ( await client.query( @@ -178,17 +214,45 @@ export async function admitCanonicalRequest( [template.strategyVersionId] ) ).rows[0]; - if (review?.decision !== 'approve') { - return invalid('An operator must approve this built-in version before execution'); + if ( + selected.origin === 'builtin' ? review?.decision !== 'approve' : review?.decision === 'revoke' + ) { + return invalid( + selected.origin === 'builtin' + ? 'An operator must approve this built-in version before execution' + : 'The candidate version is revoked' + ); } const pkg = await new StrategyCatalogService(container).getVersionArtifact( template.strategyVersionId, client ); + let candidateExecution: CandidateExecution | undefined; + if (selected.origin === 'candidate') { + if ( + pkg.execution?.kind !== 'isolated-candidate/v1' || + pkg.program.apiVersion !== 'canonical-ts/v1' + ) { + return invalid( + 'Candidate requires a retained isolated execution declaration and supported API' + ); + } + try { + candidateExecution = await readCandidateExecution(); + } catch (error) { + return invalid(error instanceof Error ? error.message : 'Candidate isolation unavailable'); + } + } else if (pkg.execution !== undefined) { + return invalid('Built-in origin cannot select a candidate execution profile'); + } const { settings, dataset, execution, initial } = await validateCanonicalSetup(client, template); const clock = canonicalRiskSessionClock(dataset); const ownerId = `strategy:${template.strategyVersionId}`; - const selection = builtinStrategySelectionSchema.parse({ + const selection = ( + selected.origin === 'candidate' + ? retainedProgramSelectionSchema + : builtinStrategySelectionSchema + ).parse({ strategyId: pkg.program.strategyId, strategyVersion: pkg.program.strategyVersion, ownerId, @@ -196,7 +260,7 @@ export async function admitCanonicalRequest( instrumentId: execution.instrumentId, seriesId: execution.seriesId, ownerBudget: settings.ownerBudget, - parameters: template.strategyParameters, + parameters: validateStrategyParameters(pkg, template.strategyParameters), // API/checkpoint identities are retained in the package, not selection fields. }); return canonicalRunRequestSchema.parse({ @@ -207,8 +271,9 @@ export async function admitCanonicalRequest( strategy: { familyId: selected.strategy_id, versionId: template.strategyVersionId, - origin: 'builtin', - reviewId: review.id, + origin: selected.origin, + reviewId: review?.id ?? null, + ...(candidateExecution ? { execution: candidateExecution, baselineVersionId } : {}), package: pkg, selection, }, 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 29b329ed..0d90d270 100644 --- a/apps/stock/web-api/src/services/chronological-validation.service.ts +++ b/apps/stock/web-api/src/services/chronological-validation.service.ts @@ -120,7 +120,7 @@ export class ChronologicalValidationService { return concurrent; } const { recipe: _recipe, ...sourceInput } = input; - const source = await this.experiments.lockedPreview(client, sourceInput); + const source = await this.experiments.lockedPreview(client, sourceInput, identity.principal); const sourceDataset = await readCanonicalDataset(client, source.request.datasetHash); const prepared = prepareChronologicalValidation(input, source, sourceDataset); if (prepared.preview.previewHash !== previewHash) { diff --git a/apps/stock/web-api/src/services/cost-sensitivity-input.ts b/apps/stock/web-api/src/services/cost-sensitivity-input.ts index 40aef8dd..ccdb3d55 100644 --- a/apps/stock/web-api/src/services/cost-sensitivity-input.ts +++ b/apps/stock/web-api/src/services/cost-sensitivity-input.ts @@ -40,7 +40,12 @@ export function buildCostSensitivityPreview( const input = parseCostSensitivityInput(raw), source = retainedExperimentPreview(baseline); if ( - !equal(source.input, { backtestId: input.backtestId, name: input.name, grid: {} }) || + !equal(source.input, { + backtestId: input.backtestId, + name: input.name, + grid: {}, + ...(input.candidate ? { candidate: input.candidate } : {}), + }) || source.candidates.length !== 1 ) { throw new Error('Cost sensitivity requires the unchanged empty-grid source'); diff --git a/apps/stock/web-api/src/services/experiment-input.ts b/apps/stock/web-api/src/services/experiment-input.ts index a919e3db..f8d4e38d 100644 --- a/apps/stock/web-api/src/services/experiment-input.ts +++ b/apps/stock/web-api/src/services/experiment-input.ts @@ -1,5 +1,6 @@ import { createHash } from 'node:crypto'; import { z } from 'zod'; +import { retainedProgramSelectionSchema } from '@stock-bot/stock-config/candidate-execution'; import { canonicalRunRequestSchema, type CanonicalRunRequest, @@ -108,7 +109,11 @@ export function experimentCandidates( return combinations.map((parameters, index) => { try { const validated = validateStrategyParameters(request.strategy.package, parameters); - const selection = builtinStrategySelectionSchema.parse({ + const selection = ( + request.strategy.origin === 'candidate' + ? retainedProgramSelectionSchema + : builtinStrategySelectionSchema + ).parse({ ...request.strategy.selection, parameters: validated, }); diff --git a/apps/stock/web-api/src/services/experiments.service.ts b/apps/stock/web-api/src/services/experiments.service.ts index 48acdcf8..c6153350 100644 --- a/apps/stock/web-api/src/services/experiments.service.ts +++ b/apps/stock/web-api/src/services/experiments.service.ts @@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto'; import type { PoolClient, QueryResultRow } from 'pg'; import { z } from 'zod'; import { requireServices, type IServiceContainer } from '@stock-bot/services'; +import { canonicalStrategyExecution } from '@stock-bot/stock-config/canonical-research'; import type { CostSensitivityInput, WorkbenchExperimentDetail, @@ -39,7 +40,11 @@ import { PREVIEW_RUN_ID, } from './experiment-input'; import { mapExperimentRetry, parseExperimentRetry, retryColumns } from './experiment-retry'; -import { lockExperimentResearchAgent, lockResearchAgent } from './research-agent-budget'; +import { + lockExperimentResearchAgent, + lockResearchAgent, + verifyCandidateGrant, +} from './research-agent-budget'; import { RunReproductionError, verifyReproductionInputs } from './run-reproduction'; import { StrategyCatalogError } from './strategy-catalog.service'; import { parseChronologicalValidation, prepareChronologicalValidation } from './validation-preview'; @@ -118,32 +123,52 @@ export class ExperimentsService { constructor(private readonly container: IServiceContainer) { this.database = requireServices(container, 'postgres').postgres; } - async preview(raw: unknown): Promise { + async preview(raw: unknown, principal = 'operator'): Promise { const input = parseExperimentInput(raw); - return this.database.transaction(client => this.lockedPreview(client, input)); - } - async previewCosts(raw: unknown) { - const input = parseCostSensitivityInput(raw); - return this.database.transaction(client => this.lockedCostPreview(client, input)); - } - private async lockedCostPreview(client: PoolClient, input: CostSensitivityInput) { - const source = await this.lockedPreview(client, { - backtestId: input.backtestId, - name: input.name, - grid: {}, + return this.database.transaction(async client => { + await lockResearchAgent(client, principal); + return this.lockedPreview(client, input, principal); }); + } + async previewCosts(raw: unknown, principal = 'operator') { + const input = parseCostSensitivityInput(raw); + return this.database.transaction(async client => { + await lockResearchAgent(client, principal); + return this.lockedCostPreview(client, input, principal); + }); + } + private async lockedCostPreview( + client: PoolClient, + input: CostSensitivityInput, + principal = 'operator' + ) { + const source = await this.lockedPreview( + client, + { + backtestId: input.backtestId, + name: input.name, + grid: {}, + ...(input.candidate ? { candidate: input.candidate } : {}), + }, + principal + ); return buildCostSensitivityPreview(input, source); } - async previewValidation(raw: unknown) { + async previewValidation(raw: unknown, principal = 'operator') { const input = parseChronologicalValidation(raw); const { recipe: _recipe, ...sourceInput } = input; return this.database.transaction(async client => { - const source = await this.lockedPreview(client, sourceInput); + await lockResearchAgent(client, principal); + const source = await this.lockedPreview(client, sourceInput, principal); const dataset = await readCanonicalDataset(client, source.request.datasetHash); return prepareChronologicalValidation(input, source, dataset).preview; }); } - async lockedPreview(client: PoolClient, input: ExperimentInput): Promise { + async lockedPreview( + client: PoolClient, + input: ExperimentInput, + principal = 'operator' + ): Promise { const parent = ( await client.query('SELECT * FROM backtests WHERE id=$1 FOR UPDATE', [input.backtestId]) ).rows[0]; @@ -172,7 +197,8 @@ export class ExperimentsService { config: parent.config, }, input.backtestId, - PREVIEW_RUN_ID + PREVIEW_RUN_ID, + input.candidate ); } catch (cause) { if ( @@ -192,6 +218,7 @@ export class ExperimentsService { } throw cause; } + await verifyCandidateGrant(client, request, principal); return buildExperimentPreview( input, request, @@ -251,8 +278,8 @@ export class ExperimentsService { } const preview: WorkbenchExperimentPreview = 'scenarios' in input - ? await this.lockedCostPreview(client, input) - : await this.lockedPreview(client, input); + ? await this.lockedCostPreview(client, input, receipt.principal) + : await this.lockedPreview(client, input, receipt.principal); if (preview.previewHash !== previewHash) { throw new ExperimentError( 409, @@ -648,7 +675,7 @@ export class ExperimentsService { run.result_run_id !== run.id || run.result_backtest_id !== expected.backtestId || run.financial_engine !== 'rust' || - run.strategy_execution !== 'typescript-retained-builtin/v1' || + run.strategy_execution !== canonicalStrategyExecution(expected) || !equal(run.result_request, expected) || run.analytics_version !== 1 || !equal(run.analytics_policy, expectedPolicy) || diff --git a/apps/stock/web-api/src/services/paper-deployments.service.ts b/apps/stock/web-api/src/services/paper-deployments.service.ts new file mode 100644 index 00000000..a532269f --- /dev/null +++ b/apps/stock/web-api/src/services/paper-deployments.service.ts @@ -0,0 +1,361 @@ +import { randomUUID } from 'node:crypto'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; +import type { + CanonicalRunRequest, + CanonicalRunResult, +} from '@stock-bot/stock-config/canonical-research'; +import { + paperPromotionInputSchema, + paperPromotionPreviewSchema, + paperPromotionSubmissionSchema, + type PaperDeployment, + type PaperPromotionInput, + type PaperPromotionPreview, +} from '@stock-bot/stock-config/paper-deployments'; +import { assertStrategyJsonText, canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; +import type { ResearchEvidenceReference } from '@stock-bot/types'; +import { validatePaperConfiguration } from '../../../orchestrator/src/paper/feed'; +import { + authorizedPaperPackage, + PaperDeploymentError, + paperHash, + paperPreviewHash, + readPaperDeployment, + retainedPaperDeployment, +} from '../../../orchestrator/src/paper/paper-deployment-custody'; +import { readPaperHostIdentity } from '../../../orchestrator/src/paper/paper-host-identity'; +import { BacktestServiceV2, type BacktestResultQuery } from './backtest-v2.service'; +import { retainedCostSensitivityPreview } from './cost-sensitivity-input'; +import { canonicalReproductionHash } from './reproduction-comparison'; +import { verifyResearchSource } from './research-source-evidence'; + +const equal = (a: unknown, b: unknown) => canonicalStrategyJson(a) === canonicalStrategyJson(b); +const reference = (runId: string): ResearchEvidenceReference => ({ + runId, + metricsVersion: 'canonical-analytics/v1', + metricPath: 'analytics.metrics.totalReturn', +}); +const inputError = (message: string): never => { + throw new PaperDeploymentError(422, message); +}; +/** Explicit economic comparison: only run identity, dates, and the two studied cost rates may vary. */ +export function paperEconomicProfile(request: CanonicalRunRequest) { + const { ledger, feeRate: _fee, ...risk } = request.policy.matching.risk; + const { sessionId: _session, accountId: _account, riskSession: _clock, ...capital } = ledger; + const { risk: _risk, slippageRate: _slippage, ...execution } = request.policy.matching; + const { matching: _matching, risk_boundaries: _boundaries, ...policy } = request.policy; + const { reviewId: _review, ...strategy } = request.strategy; + return { + strategy, + capital, + risk, + execution, + policy, + analyticsPolicy: request.analyticsPolicy, + build: request.build, + modelArtifacts: request.modelArtifacts, + }; +} +function evidence(result: CanonicalRunResult) { + return { + runId: result.runId, + datasetHash: result.request.datasetHash, + economicHash: canonicalReproductionHash(result), + resultHash: paperHash(result), + metrics: { ...result.analytics.metrics }, + fillCount: result.analytics.fillCount, + limitations: [...result.financial.limitations, ...result.financial.modelLimitations], + }; +} + +export class PaperDeploymentsService { + private readonly database; + private readonly results; + constructor( + private readonly container: IServiceContainer, + private readonly identity = readPaperHostIdentity + ) { + this.database = requireServices(container, 'postgres').postgres; + this.results = new BacktestServiceV2(container); + } + private async prepare( + input: PaperPromotionInput, + db: BacktestResultQuery, + lock = false + ): Promise { + const selected = paperPromotionInputSchema.parse(input), + source = selected.outOfSample; + const results = await verifyResearchSource( + source, + [reference(selected.testRunId)], + db, + (id, tx) => this.results.getRunResults(id, tx) + ); + const test = results.get(selected.testRunId); + if (!test) { + return inputError('Selected test evidence is unavailable'); + } + let sourceHash: string | undefined; + if (source.kind === 'chronological-report/v1') { + const row = ( + await db.query( + 'SELECT validation_report,validation_manifest FROM research_experiments WHERE id=$1', + [source.validationId] + ) + ).rows[0]; + if (row?.validation_report?.test?.runId !== test.runId) { + return inputError('Select the sealed test run, not training or validation'); + } + sourceHash = row.validation_manifest?.source?.request?.datasetHash; + } else { + const row = ( + await db.query('SELECT report,preview FROM research_walk_forwards WHERE id=$1', [ + source.walkForwardId, + ]) + ).rows[0]; + if ( + !row?.report?.segments?.some( + (segment: { test?: { runId: string } }) => segment.test?.runId === test.runId + ) + ) { + return inputError('Select a sealed walk-forward test run'); + } + sourceHash = row.preview?.source?.request?.datasetHash; + } + const costRow = ( + await db.query('SELECT * FROM research_experiments WHERE id=$1', [selected.costExperimentId]) + ).rows[0]; + if ( + !costRow || + costRow.validation_phase !== null || + costRow.preview?.version !== 'cost-sensitivity-preview/v1' + ) { + return inputError('Select a standalone cost-sensitivity study'); + } + const costs = retainedCostSensitivityPreview(costRow.preview); + if ( + costs.previewHash !== selected.costPreviewHash || + costRow.preview_hash !== costs.previewHash || + costs.source.request.datasetHash !== sourceHash + ) { + return inputError('Cost evidence must use the exact common source dataset and preview'); + } + const rows = ( + await db.query( + 'SELECT id,status,trial_index FROM runs WHERE experiment_id=$1 ORDER BY trial_index', + [selected.costExperimentId] + ) + ).rows; + if ( + rows.length !== costs.candidates.length || + rows.some((r, i) => r.status !== 'completed' || r.trial_index !== i) + ) { + return inputError('Every cost scenario must have a completed retained result'); + } + const costResults = await verifyResearchSource( + { kind: 'experiment/v1', experimentId: costRow.id, previewHash: costs.previewHash }, + rows.map(r => reference(r.id)), + db, + (id, tx) => this.results.getRunResults(id, tx) + ); + const cost = costResults.get(selected.costRunId); + if (!cost) { + return inputError('Selected cost scenario is not a completed member'); + } + for (const item of costResults.values()) { + if (!equal(paperEconomicProfile(test.request), paperEconomicProfile(item.request))) { + return inputError( + 'Test and cost evidence must share the exact version, parameters, seed, capital, risk, execution and research build' + ); + } + } + const selection = structuredClone(cost.request.strategy.selection), + matching = structuredClone(cost.request.policy.matching); + const { transport } = selected; + matching.risk.ledger.accountId = transport.accountId; + matching.risk.ledger.sessionId = transport.sessionId; + matching.risk.ledger.riskSession = transport.riskSession; + const configuration = validatePaperConfiguration({ + version: 2, + matching: { + ...matching, + series: [ + { + instrumentId: selection.instrumentId, + seriesId: transport.quoteSeriesId, + mode: 'Quote', + }, + ], + }, + strategies: [selection], + policy: transport.policy, + }); + if (configuration.version !== 2) { + throw new Error('Promotion requires deployment configuration'); + } + const interval = costs.dataset.series.find(s => s.id === selection.seriesId)?.interval; + if (interval === '1d') { + return inputError( + 'Paper promotion currently requires an explicit intraday observation interval' + ); + } + const retainedInterval = interval + ? { '1m': 60000, '5m': 300000, '15m': 900000, '1h': 3600000, '1d': 86400000 }[interval] + : undefined; + if ( + configuration.policy.observations.length !== 1 || + configuration.policy.observations[0]?.intervalMs !== retainedInterval + ) { + return inputError('Paper observation interval must equal the retained research series'); + } + const strategy = { + familyId: test.request.strategy.familyId, + versionId: test.request.strategy.versionId, + origin: test.request.strategy.origin, + reviewId: test.request.strategy.reviewId as string, + artifactSha256: test.request.strategy.package.artifact.sha256, + dependencyLockSha256: test.request.strategy.package.dependencyLock.sha256, + }; + const host = await this.identity(); + const sharedBuildFields = [ + 'engineWrapperSha256', + 'engineBinarySha256', + 'dependencyLockSha256', + 'runtime', + 'runtimeVersion', + 'platform', + 'arch', + ] as const; + if (sharedBuildFields.some(field => host[field] !== test.request.build[field])) { + throw new PaperDeploymentError( + 409, + 'Paper and research require the same native, dependency and runtime build; rerun evidence on the installed build' + ); + } + const draft = { + version: 'paper-promotion-preview/v1' as const, + input: selected, + strategy, + configuration, + host, + evidence: { + test: evidence(test), + costs: rows.map(r => { + const result = costResults.get(r.id); + if (!result) { + throw new Error('Missing verified cost result'); + } + return evidence(result); + }), + }, + limitations: [ + 'Human promotion authorizes these exact strategy bytes to execute as trusted paper-host code; research isolation does not carry over.', + 'Paper uses explicit quotes and displayed sizes instead of historical Open prices and volume participation; fills may differ.', + 'Future feed timing, sessions, corporate-action handling and liquidity are operator-supplied. No live broker is connected.', + 'Paper starts with the factory initial strategy state and empty positions; historical strategy checkpoints are not copied.', + 'Sealed reset-account holdouts and cost studies are evidence, not a guarantee of future performance.', + ], + }; + const authorization = await authorizedPaperPackage(db, draft, lock); + draft.strategy.reviewId = authorization.reviewId; + return paperPromotionPreviewSchema.parse({ ...draft, previewHash: paperPreviewHash(draft) }); + } + async preview(raw: unknown) { + assertStrategyJsonText(raw); + const input = paperPromotionInputSchema.parse(raw); + return this.database.transaction(async tx => { + await tx.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); + return this.prepare(input, tx); + }); + } + async create(raw: unknown, key: string): Promise { + if (!/^[!-~]{1,200}$/.test(key)) { + throw new PaperDeploymentError(400, 'A printable Idempotency-Key is required'); + } + assertStrategyJsonText(raw); + const input = paperPromotionSubmissionSchema.parse(raw), + requestHash = paperHash(input); + return this.database.transaction(async tx => { + await tx.query("SELECT pg_advisory_xact_lock(hashtextextended('paper-promotion:'||$1,0))", [ + key, + ]); + const old = ( + await tx.query( + 'SELECT document,request_hash FROM paper_deployments WHERE idempotency_key=$1', + [key] + ) + ).rows[0]; + if (old) { + if (old.request_hash !== requestHash) { + throw new PaperDeploymentError(409, 'Paper promotion key already names another request'); + } + return retainedPaperDeployment(old.document); + } + const { previewHash, ...rawInput } = input; + const preview = await this.prepare(rawInput, tx, true); + if (preview.previewHash !== previewHash) { + throw new PaperDeploymentError( + 409, + 'Paper preview changed; review the evidence and host identity again' + ); + } + const body = { + id: randomUUID(), + version: 'paper-deployment/v1' as const, + principal: 'operator' as const, + createdAt: new Date().toISOString(), + preview, + }; + const document = { ...body, promotionHash: paperHash(body) }; + try { + await tx.query( + 'INSERT INTO paper_deployments(id,account_id,strategy_version_id,promotion_hash,idempotency_key,request_hash,document) VALUES($1,$2,$3,$4,$5,$6,$7::jsonb)', + [ + document.id, + preview.configuration.matching.risk.ledger.accountId, + preview.strategy.versionId, + document.promotionHash, + key, + requestHash, + JSON.stringify(document), + ] + ); + } catch (error) { + if ((error as { code?: string }).code === '23505') { + throw new PaperDeploymentError(409, 'Paper account already has an immutable deployment'); + } + throw error; + } + return document; + }); + } + async list(): Promise { + return ( + await this.database.query( + 'SELECT document FROM paper_deployments ORDER BY created_at DESC,id' + ) + ).rows.map(r => retainedPaperDeployment(r.document)); + } + async get(id: string) { + return readPaperDeployment(this.database, id); + } + /** Recheck full retained financial evidence before forwarding a human bind or activation. */ + async authorizeCommand(id: string) { + return this.database.transaction(async tx => { + await tx.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); + const saved = await readPaperDeployment(tx, id); + const current = await this.prepare(saved.preview.input, tx); + const oldBody = { + ...saved.preview, + strategy: { ...saved.preview.strategy, reviewId: current.strategy.reviewId }, + }; + if (paperPreviewHash(oldBody) !== current.previewHash) { + throw new PaperDeploymentError( + 409, + 'Retained deployment evidence or installed paper host changed' + ); + } + return saved; + }); + } +} diff --git a/apps/stock/web-api/src/services/reproduction-comparison.ts b/apps/stock/web-api/src/services/reproduction-comparison.ts index e82f1235..56c387aa 100644 --- a/apps/stock/web-api/src/services/reproduction-comparison.ts +++ b/apps/stock/web-api/src/services/reproduction-comparison.ts @@ -1,6 +1,7 @@ import { createHash } from 'node:crypto'; import { canonicalRunRequestSchema, + canonicalStrategyExecution, parseCanonicalFinancialResult, type CanonicalRunResult, } from '@stock-bot/stock-config/canonical-research'; @@ -16,7 +17,7 @@ export function canonicalReproductionHash(result: CanonicalRunResult): string { result.kind !== 'canonical-result/v1' || result.status !== 'completed' || result.financialEngine !== 'rust' || - result.strategyExecution !== 'typescript-retained-builtin/v1' || + result.strategyExecution !== canonicalStrategyExecution(request) || result.runId !== request.runId || result.backtestId !== request.backtestId ) { diff --git a/apps/stock/web-api/src/services/research-agent-budget.ts b/apps/stock/web-api/src/services/research-agent-budget.ts index 82422a50..83713b94 100644 --- a/apps/stock/web-api/src/services/research-agent-budget.ts +++ b/apps/stock/web-api/src/services/research-agent-budget.ts @@ -20,9 +20,18 @@ 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'; + if (request.strategy.origin === 'candidate') { + const ownerId = `strategy:${request.strategy.baselineVersionId}`; + policy.matching.risk.ledger.ownerIds = [ownerId]; + policy.matching.owners = [{ ownerId, mode: 'Target' }]; + policy.cadence = [{ owner_id: ownerId, series_ids: [request.strategy.selection.seriesId] }]; + } return { datasetHash: request.datasetHash, - versionId: request.strategy.versionId, + versionId: + request.strategy.origin === 'candidate' + ? request.strategy.baselineVersionId + : request.strategy.versionId, ownerBudget: request.strategy.selection.ownerBudget, seed: request.strategy.selection.seed, policy, @@ -92,3 +101,18 @@ export async function lockExperimentResearchAgent( await lockResearchAgent(database, owner); } } + +/** SQL remains authoritative; this preflight never executes candidate code or changes grants. */ +export async function verifyCandidateGrant( + database: AgentQuery, + request: CanonicalRunRequest, + principal: string +): Promise { + if (!isResearchAgent(principal) || request.strategy.origin !== 'candidate') { + return; + } + await database.query( + 'SELECT assert_research_agent_grant(a,$2,$3::jsonb) FROM research_agents a WHERE id=$1', + [principal, request.backtestId, request] + ); +} diff --git a/apps/stock/web-api/src/services/research-agents.service.ts b/apps/stock/web-api/src/services/research-agents.service.ts index d1a8a901..4e23c1c8 100644 --- a/apps/stock/web-api/src/services/research-agents.service.ts +++ b/apps/stock/web-api/src/services/research-agents.service.ts @@ -27,10 +27,13 @@ function record(row: QueryResultRow): ResearchAgentRecord { 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, - })), + grants: row.policy.grants.map( + (grant: { backtestId: string; policyHash: string; allowOwnCandidates?: boolean }) => ({ + backtestId: grant.backtestId, + policyHash: grant.policyHash, + ...(grant.allowOwnCandidates ? { allowOwnCandidates: true } : {}), + }) + ), limits: row.policy.limits, createdAt: new Date(row.created_at).toISOString(), updatedAt: new Date(row.updated_at).toISOString(), @@ -78,9 +81,13 @@ export class ResearchAgentsService { input: { allowedProjectIds: string[]; allowedBacktestIds: string[]; + allowOwnCandidateBacktestIds?: string[]; limits: ResearchAgentRecord['limits']; } ) { + if (input.allowOwnCandidateBacktestIds?.some(id => !input.allowedBacktestIds.includes(id))) { + throw new ResearchAgentError(400, 'Candidate opt-ins must be a subset of granted backtests'); + } for (const id of input.allowedProjectIds) { if ( !( @@ -148,7 +155,12 @@ export class ResearchAgentsService { ); } const policy = researchGrantPolicy(request); - grants.push({ backtestId: id, policyHash: researchGrantHash(policy), policy }); + grants.push({ + backtestId: id, + policyHash: researchGrantHash(policy), + policy, + ...(input.allowOwnCandidateBacktestIds?.includes(id) ? { allowOwnCandidates: true } : {}), + }); } return { version: 1, allowedProjectIds: input.allowedProjectIds, grants, limits: input.limits }; } @@ -200,8 +212,33 @@ export class ResearchAgentsService { : await this.policy(client, { allowedProjectIds: input.allowedProjectIds ?? old.policy.allowedProjectIds, allowedBacktestIds: input.allowedBacktestIds, + allowOwnCandidateBacktestIds: input.allowOwnCandidateBacktestIds ?? [], limits: input.limits ?? old.policy.limits, }); + if ( + input.allowedBacktestIds === undefined && + input.allowOwnCandidateBacktestIds !== undefined + ) { + const allowed = new Set( + policy.grants.map((grant: { backtestId: string }) => grant.backtestId) + ); + if (input.allowOwnCandidateBacktestIds.some(id => !allowed.has(id))) { + throw new ResearchAgentError( + 400, + 'Candidate opt-ins must be a subset of granted backtests' + ); + } + const candidateOptIns = input.allowOwnCandidateBacktestIds; + policy.grants = policy.grants.map( + (grant: { backtestId: string; allowOwnCandidates?: boolean }) => { + const { allowOwnCandidates: _old, ...frozen } = grant; + return { + ...frozen, + ...(candidateOptIns.includes(grant.backtestId) ? { allowOwnCandidates: true } : {}), + }; + } + ); + } if (input.allowedProjectIds) { for (const projectId of input.allowedProjectIds) { if ( diff --git a/apps/stock/web-api/src/services/run-reproduction.ts b/apps/stock/web-api/src/services/run-reproduction.ts index 24eeed96..35da8e39 100644 --- a/apps/stock/web-api/src/services/run-reproduction.ts +++ b/apps/stock/web-api/src/services/run-reproduction.ts @@ -3,6 +3,7 @@ import type { IServiceContainer } from '@stock-bot/services'; import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research'; import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; import { HistoricalDataRequestError } from '@stock-bot/types'; +import { verifyCandidateExecution } from '../../../orchestrator/src/backtest/candidate-sandbox'; import { readCanonicalBuildIdentity } from '../../../orchestrator/src/backtest/canonical-build'; import { readCanonicalDataset } from './canonical-research.service'; import { StrategyCatalogError, StrategyCatalogService } from './strategy-catalog.service'; @@ -22,7 +23,7 @@ export async function verifyReproductionInputs( client: PoolClient, container: IServiceContainer, request: CanonicalRunRequest -): Promise { +): Promise { const selected = ( await client.query( `SELECT v.strategy_id,v.origin,s.archived_at FROM strategy_versions v @@ -33,9 +34,9 @@ export async function verifyReproductionInputs( if ( !selected || selected.strategy_id !== request.strategy.familyId || - selected.origin !== 'builtin' + selected.origin !== request.strategy.origin ) { - throw new RunReproductionError(409, 'The original retained built-in version is unavailable'); + throw new RunReproductionError(409, 'The original retained strategy version is unavailable'); } if (selected.archived_at !== null) { throw new RunReproductionError(409, 'The original strategy family is archived'); @@ -46,10 +47,16 @@ export async function verifyReproductionInputs( [request.strategy.versionId] ) ).rows[0]; - if (review?.decision !== 'approve') { + if ( + request.strategy.origin === 'builtin' + ? review?.decision !== 'approve' + : review?.decision === 'revoke' + ) { throw new RunReproductionError( 409, - 'The original strategy version requires current operator approval' + request.strategy.origin === 'builtin' + ? 'The original strategy version requires current operator approval' + : 'The original candidate version is explicitly revoked' ); } try { @@ -100,5 +107,15 @@ export async function verifyReproductionInputs( 'The original worker/native/runtime build is not installed; historical build execution is unavailable' ); } - return review.id; + if (request.strategy.origin === 'candidate') { + try { + await verifyCandidateExecution(request.strategy.execution); + } catch { + throw new RunReproductionError( + 409, + 'The retained isolated candidate runtime is not installed' + ); + } + } + return review?.id ?? null; } 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 28f84312..ebc4b7b5 100644 --- a/apps/stock/web-api/src/services/strategy-catalog.service.ts +++ b/apps/stock/web-api/src/services/strategy-catalog.service.ts @@ -111,7 +111,11 @@ const version = (row: QueryResultRow): StrategyVersionSummary => ({ ? row.review_status === 'approved' ? 'Configure a supported canonical dataset and explicit financial policy before execution.' : 'An operator must approve this built-in version before configuring execution.' - : 'Candidate execution requires isolation (A02); publication and approval do not execute code.', + : row.review_status === 'revoked' + ? 'Candidate is revoked; new research admissions are unavailable.' + : row.package.execution?.kind === 'isolated-candidate/v1' + ? 'Candidate runs only in the isolated research host. Configure retained data and financial policy; approval never selects trusted execution.' + : 'Publish a new immutable version with an isolated execution declaration and author-declared warmup before execution.', }); class ReceiptRace extends Error {} diff --git a/apps/stock/web-api/src/services/validation-evidence.ts b/apps/stock/web-api/src/services/validation-evidence.ts index 339ba990..48817c9c 100644 --- a/apps/stock/web-api/src/services/validation-evidence.ts +++ b/apps/stock/web-api/src/services/validation-evidence.ts @@ -76,7 +76,7 @@ export function validationPhasePreview( preview: ChronologicalValidationPreview, phase: ValidationPhase, winner?: ExperimentCandidate, - reviewId?: string + reviewId?: string | null ) { const partition = preview.partitions.find(p => p.phase === phase); if (!partition) { @@ -84,7 +84,11 @@ export function validationPhasePreview( } const request = structuredClone(partition.request); if (phase !== 'train') { - if (!winner || !reviewId) { + if ( + !winner || + reviewId === undefined || + (request.strategy.origin === 'builtin' && reviewId === null) + ) { throw new Error('Holdout admission requires a frozen winner and current approval'); } request.strategy.selection.parameters = structuredClone( @@ -97,6 +101,14 @@ export function validationPhasePreview( backtestId: preview.input.backtestId, name: `${preview.input.name} · ${phase}`, grid: phase === 'train' ? preview.input.grid : {}, + ...(preview.input.candidate + ? { + candidate: { + ...preview.input.candidate, + parameters: structuredClone(request.strategy.selection.parameters), + }, + } + : {}), }, canonicalRunRequestSchema.parse(request), partition.dataset diff --git a/apps/stock/web-api/src/services/validation-preview.ts b/apps/stock/web-api/src/services/validation-preview.ts index 4de91a08..55af2591 100644 --- a/apps/stock/web-api/src/services/validation-preview.ts +++ b/apps/stock/web-api/src/services/validation-preview.ts @@ -1,7 +1,7 @@ import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research'; import { + chronologicalPolicyForOrigin, chronologicalValidationInputSchema, - chronologicalValidationPolicy, type ChronologicalValidationInput, type ChronologicalValidationPreview, type ValidationPartitionPreview, @@ -33,6 +33,13 @@ export function parseChronologicalValidation(input: unknown): ChronologicalValid } } function requiredHistory(source: ExperimentPreview): number { + if (source.request.strategy.origin === 'candidate') { + const execution = source.request.strategy.package.execution; + if (!execution) { + throw new ExperimentError(409, 'Candidate is missing its author-declared warmup'); + } + return execution.warmupBars; + } return Math.max( ...source.candidates.map(candidate => { const selection = builtinStrategySelectionSchema.parse({ @@ -136,6 +143,11 @@ export function prepareChronologicalValidation( ); } const warnings: string[] = []; + if (source.request.strategy.origin === 'candidate') { + warnings.push( + 'Candidate warmup is author-declared; input checks do not establish absence of leakage, model fitting validity, or reproducible strategy decisions' + ); + } if (counts.unavailableAtEnd) { warnings.push( `${counts.unavailableAtEnd} completed-bar observations arrive after the evaluation end and cannot inform decisions or terminal marks` @@ -170,7 +182,7 @@ export function prepareChronologicalValidation( execution: 'preview-only' as const, input, source, - policy: chronologicalValidationPolicy, + policy: chronologicalPolicyForOrigin(source.request.strategy.origin), partitions, }; return { preview: { ...manifest, previewHash: experimentHash(manifest) }, datasets }; 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 751307ac..f9522941 100644 --- a/apps/stock/web-api/src/services/walk-forward.service.ts +++ b/apps/stock/web-api/src/services/walk-forward.service.ts @@ -78,13 +78,20 @@ export class WalkForwardService { this.experiments = new ExperimentsService(container); this.validations = new ChronologicalValidationService(container); } - async preview(raw: unknown) { + async preview(raw: unknown, principal = 'operator') { const input = parseWalkForwardInput(raw); - return this.database.transaction(async client => (await this.prepare(client, input)).preview); + return this.database.transaction(async client => { + await lockResearchAgent(client, principal); + return (await this.prepare(client, input, principal)).preview; + }); } - private async prepare(client: PoolClient, input: ReturnType) { + private async prepare( + client: PoolClient, + input: ReturnType, + principal = 'operator' + ) { const { windows: _windows, ...sourceInput } = input; - const source = await this.experiments.lockedPreview(client, sourceInput); + const source = await this.experiments.lockedPreview(client, sourceInput, principal); const dataset = await readCanonicalDataset(client, source.request.datasetHash); return prepareWalkForward(input, source, dataset); } @@ -122,7 +129,7 @@ export class WalkForwardService { if (concurrent) { return concurrent; } - const prepared = await this.prepare(client, input); + const prepared = await this.prepare(client, input, identity.principal); if (prepared.preview.previewHash !== previewHash) { throw new ExperimentError( 409, diff --git a/apps/stock/web-app/src/app/App.tsx b/apps/stock/web-app/src/app/App.tsx index 688decfa..7e59f2ed 100644 --- a/apps/stock/web-app/src/app/App.tsx +++ b/apps/stock/web-app/src/app/App.tsx @@ -11,6 +11,7 @@ import { WalkForwardDetailPage, } from '@/features/experiments'; import { MonitoringPage } from '@/features/monitoring'; +import { PaperDeploymentPage, PaperDeploymentsPage } from '@/features/paper'; import { PipelinePage } from '@/features/pipeline'; import { ResearchAgentsPage, ResearchListPage, ResearchProjectPage } from '@/features/research'; import { StrategyDetailPage, StrategyListPage, StrategyVersionPage } from '@/features/strategies'; @@ -51,6 +52,10 @@ 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 d15703c3..5f8ba785 100644 --- a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx +++ b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx @@ -550,6 +550,13 @@ export function BacktestDetailPageV2() { > Retry execution eligibility + {canonicalCapability?.execution && !isCapabilityLoading && ( + + Isolated candidate sandbox: {canonicalCapability.execution.imageId}. Limit{' '} + {canonicalCapability.execution.profile.limits.wallMs / 1000}s per container; agent + attempt deadlines may be shorter. + + )} {backtest?.strategyVersionId && ( <> {' '} diff --git a/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx b/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx index fd6150d7..35d42716 100644 --- a/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx +++ b/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx @@ -68,9 +68,19 @@ export function CanonicalResults({ >

Canonical research result

- Rust financial simulation · retained TypeScript built-in. Completion does not establish - strategy profitability or authorize trading. + Rust financial simulation ·{' '} + {request.strategy.origin === 'candidate' + ? 'isolated TypeScript candidate' + : 'retained TypeScript built-in'} + . Completion does not establish strategy profitability or authorize trading.

+ {request.strategy.origin === 'candidate' && ( +

+ Sandbox {request.strategy.execution.imageId} · Author-declared warmup{' '} + {request.strategy.package.execution?.warmupBars} bars. Candidate code is unverified; + retained seeds and inputs support an actual reproduction comparison. +

+ )}
Run
diff --git a/apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx b/apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx index bd55a58a..67ccd9b8 100644 --- a/apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx +++ b/apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx @@ -32,9 +32,10 @@ const policyFields: { { key: 'ownerBudget', label: 'Owner budget', - group: 'Capital allocation', + group: 'Strategy sizing', kind: 'decimal', - description: 'USD allocated to this strategy; it cannot exceed initial capital.', + description: + 'USD sizing input supplied to the strategy. Rust enforces the separate position, exposure and cash constraints. This input cannot exceed initial capital.', }, { key: 'feeRate', diff --git a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts index 84bccb17..23141efd 100644 --- a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts +++ b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts @@ -1,4 +1,5 @@ import { z } from 'zod'; +import { candidateExecutionSchema } from '@stock-bot/stock-config/candidate-execution'; import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research'; import type { CanonicalDatasetCatalogEntry, @@ -562,7 +563,18 @@ export const backtestApiV2 = { if (!response.ok) { throw await requestError(response, 'Could not check canonical execution eligibility'); } - return response.json(); + const capability = z + .object({ + available: z.boolean(), + reason: z.string().nullable(), + execution: candidateExecutionSchema.optional(), + }) + .strict() + .parse(await response.json()); + if (capability.execution && !capability.available) { + throw new Error('Unavailable execution cannot advertise an admitted sandbox profile'); + } + return capability; }, async listCanonicalDatasets(signal?: AbortSignal): Promise { const response = await fetch(`${API_BASE_URL}/api/v2/datasets/canonical?limit=50&offset=0`, { diff --git a/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx b/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx index 8c808f5e..07724154 100644 --- a/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx +++ b/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx @@ -348,6 +348,7 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) { experimentId={experiment.id} backtestId={experiment.backtestId} previewHash={experiment.previewHash} + strategyOrigin={experiment.preview.request.strategy.origin} experimentCancelled={experiment.cancelRequested} trial={trial} disabled={mutating || loading} diff --git a/apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx b/apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx index 597e37ff..26e9a526 100644 --- a/apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx +++ b/apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx @@ -35,6 +35,7 @@ export function ChronologicalValidationPreflight({ backtestId, name, grid, + candidate, disabled, eligible, onDirty, @@ -44,6 +45,7 @@ export function ChronologicalValidationPreflight({ backtestId: string; name: string; grid: string; + candidate?: ChronologicalValidationSubmission['candidate']; disabled: boolean; eligible: boolean; onDirty: (dirty: boolean) => void; @@ -72,7 +74,15 @@ export function ChronologicalValidationPreflight({ const request = useRef(null); const pending = useRef(false); const alive = useRef(false); - const identity = JSON.stringify({ backtestId, name, grid, windows, disabled, eligible }); + const identity = JSON.stringify({ + backtestId, + name, + grid, + candidate, + windows, + disabled, + eligible, + }); const currentIdentity = useRef(identity); currentIdentity.current = identity; const preview = @@ -123,6 +133,7 @@ export function ChronologicalValidationPreflight({ backtestId, name, grid: JSON.parse(grid), + ...(candidate ? { candidate } : {}), recipe: parseValidationWindows(windows), }); const value = await chronologicalValidationApi.preview(input, controller.signal); @@ -325,7 +336,9 @@ export function ChronologicalValidationPreflight({

Input checks only. Warmup sufficiency is not evidence of profitability or statistical - adequacy. Only deterministic, unfitted strategies with zero label horizon are supported. + adequacy. Built-in strategies use the declared unfitted model. Candidate warmup is + author-declared and candidate behavior is unverified; fitting and nonzero label horizons + have no supported validation contract.

{preview.partitions.map(part => ( diff --git a/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx b/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx index 92fd36dc..cf312ea4 100644 --- a/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx +++ b/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx @@ -13,6 +13,10 @@ import { } from '@stock-bot/stock-config/experiments'; import { Button } from '@/components/ui/Button'; import { backtestApiV2, type Backtest } from '@/features/backtest/services/backtestApiV2'; +import { + StrategySelection, + type CatalogSelection, +} from '@/features/strategies/components/StrategySelection'; import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning'; import { experimentApi, @@ -94,6 +98,19 @@ export function ExperimentEditor({ const [backtestId, setBacktestId] = useState(initialBacktestId); const [name, setName] = useState(''); const [grid, setGrid] = useState('{}'); + const [useCandidate, setUseCandidate] = useState(false); + const [candidateSelection, setCandidateSelection] = useState({}); + const [candidateValid, setCandidateValid] = useState(false); + const candidateRevision = useRef(0); + const candidateValidity = useRef(false); + const renderedCandidateRevision = candidateRevision.current; + const candidate = + useCandidate && candidateSelection.strategyVersionId + ? { + versionId: candidateSelection.strategyVersionId, + parameters: candidateSelection.strategyParameters ?? {}, + } + : undefined; const [backtests, setBacktests] = useState([]); const [templateLoading, setTemplateLoading] = useState(true); const [templateError, setTemplateError] = useState(''); @@ -113,6 +130,7 @@ export function ExperimentEditor({ walkForwardDirty || Boolean( name || + useCandidate || grid !== '{}' || backtestId !== initialBacktestId || mode !== 'parameters' || @@ -179,7 +197,12 @@ export function ExperimentEditor({ change(); }; const prepare = async () => { - if (submissionOwner.current || previewLoading) { + if ( + submissionOwner.current || + previewLoading || + candidateRevision.current !== renderedCandidateRevision || + (useCandidate && !candidateValid) + ) { return; } const current = ++generation.current; @@ -194,11 +217,21 @@ export function ExperimentEditor({ const value = modeRef.current === 'cost-sensitivity' ? await experimentApi.costPreview( - costSensitivityInputSchema.parse({ backtestId, name, scenarios }), + costSensitivityInputSchema.parse({ + backtestId, + name, + scenarios, + ...(candidate ? { candidate } : {}), + }), controller.signal ) : await experimentApi.preview( - experimentInputSchema.parse({ backtestId, name, grid: JSON.parse(grid) }), + experimentInputSchema.parse({ + backtestId, + name, + grid: JSON.parse(grid), + ...(candidate ? { candidate } : {}), + }), controller.signal ); if (alive.current && current === generation.current) { @@ -356,6 +389,49 @@ export function ExperimentEditor({ Load more backtests )} + + {useCandidate && ( +
+

+ Select an immutable candidate and validate its base parameters. The saved backtest + supplies the dataset, capital and financial policy. Preview checks candidate + eligibility. +

+ { + if (submissionOwner.current) { + return; + } + candidateRevision.current++; + invalidate(() => setCandidateSelection(value)); + }} + onValidityChange={valid => { + if (submissionOwner.current || valid === candidateValidity.current) { + return; + } + candidateValidity.current = valid; + candidateRevision.current++; + invalidate(() => setCandidateValid(valid)); + }} + disabled={Boolean(lockedBy)} + /> +
+ )} + + + ) : ( +

Readiness has not been confirmed. Activation is unavailable.

+ )} + + +

+ Startup is inactive. A trusted feed producer must connect and provide fresh quotes + before an operator can activate. Existing capital and checkpoints are retained. + Activation rechecks current approval and build. Revoking catalog approval blocks new + activation; use Halt paper to stop an already active account. +

+ + + )} + {pending &&

Confirming paper command…

} + + ); +} diff --git a/apps/stock/web-app/src/features/paper/PaperDeploymentsPage.tsx b/apps/stock/web-app/src/features/paper/PaperDeploymentsPage.tsx new file mode 100644 index 00000000..6c8c2ef2 --- /dev/null +++ b/apps/stock/web-app/src/features/paper/PaperDeploymentsPage.tsx @@ -0,0 +1,459 @@ +import { useEffect, useRef, useState } from 'react'; +import { Link, useNavigate } from 'react-router-dom'; +import type { + PaperDeployment, + PaperPromotionInput, + PaperPromotionPreview, +} from '@stock-bot/stock-config/paper-deployments'; +import { paperPromotionInputSchema } from '@stock-bot/stock-config/paper-deployments'; +import { chronologicalValidationDurableApi } from '../experiments/services/chronologicalValidationDurableApi'; +import { experimentApi } from '../experiments/services/experimentApi'; +import { walkForwardApi } from '../experiments/services/walkForwardApi'; +import { actionClass, fieldClass } from '../strategies/components/StrategyParameterForm'; +import { useUnsavedWarning } from '../strategies/components/useUnsavedWarning'; +import { paperApi, PaperApiError } from './paperApi'; + +const message = (cause: unknown) => + cause instanceof Error ? cause.message : 'Paper request failed'; +const initialTransport = JSON.stringify( + { + accountId: '', + sessionId: '', + quoteSeriesId: '', + riskSession: { calendarId: '', calendarRevision: '', sessionId: '', startsAt: 0 }, + policy: { + version: 1, + sourceId: '', + priceBasis: 'raw', + maxFeedAgeMs: 60000, + observations: [], + cadence: [], + calendars: [], + riskBoundaries: [], + }, + }, + null, + 2 +); +type Source = { + source: PaperPromotionInput['outOfSample']; + tests: Array<{ runId: string; label: string }>; +}; +export function PaperDeploymentsPage() { + const navigate = useNavigate(), + alive = useRef(true), + busy = useRef(false), + generation = useRef(0), + frozen = useRef(false), + dirty = useRef(false), + receipt = useRef<{ preview: PaperPromotionPreview; key: string } | null>(null); + const [rows, setRows] = useState([]), + [loading, setLoading] = useState(true), + [error, setError] = useState(''), + [pending, setPending] = useState(false), + [uncertain, setUncertain] = useState(false); + const [name, setName] = useState(''), + [kind, setKind] = useState<'chronological' | 'walk-forward'>('chronological'), + [sourceId, setSourceId] = useState(''), + [costId, setCostId] = useState(''); + const [source, setSource] = useState(null), + [cost, setCost] = useState<{ + id: string; + previewHash: string; + trials: Array<{ runId: string; label: string }>; + } | null>(null), + [testRunId, setTestRunId] = useState(''), + [costRunId, setCostRunId] = useState(''); + const [transport, setTransport] = useState(initialTransport), + [reason, setReason] = useState(''), + [ack, setAck] = useState(false), + [preview, setPreview] = useState(null); + useUnsavedWarning(dirty.current || pending || uncertain); + useEffect(() => { + alive.current = true; + const abort = new AbortController(); + void paperApi + .list(abort.signal) + .then(value => { + if (alive.current) { + setRows(value.deployments); + } + }) + .catch(cause => { + if (alive.current) { + setError(message(cause)); + } + }) + .finally(() => { + if (alive.current) { + setLoading(false); + } + }); + return () => { + alive.current = false; + generation.current++; + abort.abort(); + }; + }, []); + const change = (action: () => void) => { + if (busy.current || frozen.current) { + return; + } + dirty.current = true; + generation.current++; + receipt.current = null; + setPreview(null); + setError(''); + action(); + }; + const run = async (work: () => Promise, retryReceipt = false) => { + if (busy.current || (frozen.current && !retryReceipt)) { + return; + } + busy.current = true; + setPending(true); + setError(''); + try { + await work(); + } catch (cause) { + if (alive.current) { + setError(message(cause)); + } + } finally { + busy.current = false; + if (alive.current) { + setPending(false); + } + } + }; + const loadEvidence = () => + run(async () => { + const captured = generation.current; + const sourcePromise = + kind === 'chronological' + ? chronologicalValidationDurableApi.get(sourceId).then(value => { + if (!value.report) { + throw new Error('Chronological report is not sealed'); + } + return { + source: { + kind: 'chronological-report/v1' as const, + validationId: value.id, + reportId: value.report.id, + reportHash: value.report.reportHash, + previewHash: value.report.previewHash, + }, + tests: [{ runId: value.report.test.runId, label: 'Sealed chronological test' }], + }; + }) + : walkForwardApi.get(sourceId).then(value => { + if (!value.report) { + throw new Error('Walk-forward report is not sealed'); + } + return { + source: { + kind: 'walk-forward-report/v1' as const, + walkForwardId: value.id, + reportId: value.report.id, + reportHash: value.report.reportHash, + previewHash: value.report.previewHash, + }, + tests: value.report.segments.map(segment => ({ + runId: segment.test.runId, + label: `Window ${segment.index + 1} test`, + })), + }; + }); + const [nextSource, nextCost] = await Promise.all([sourcePromise, experimentApi.get(costId)]); + if ( + nextCost.preview.version !== 'cost-sensitivity-preview/v1' || + nextCost.trials.some(t => t.status !== 'completed' || !t.runId) + ) { + throw new Error('Select a fully completed cost-sensitivity study'); + } + if (!alive.current || captured !== generation.current) { + return; + } + const trials = nextCost.trials.map((trial, index) => { + const scenario = + nextCost.preview.version === 'cost-sensitivity-preview/v1' + ? nextCost.preview.candidates[index]?.costs + : null; + return { + runId: trial.runId ?? '', + label: `${index === 0 ? 'Baseline' : `Scenario ${index}`} · fee ${scenario?.feeRate}, slippage ${scenario?.slippageRate}`, + }; + }); + setSource(nextSource); + setCost({ id: nextCost.id, previewHash: nextCost.previewHash, trials }); + setTestRunId(nextSource.tests[0]?.runId ?? ''); + setCostRunId(trials[0]?.runId ?? ''); + }); + const review = () => + run(async () => { + if (!source || !cost) { + throw new Error('Load sealed test and completed cost evidence first'); + } + const input = paperPromotionInputSchema.parse({ + name, + outOfSample: source.source, + testRunId, + costExperimentId: cost.id, + costPreviewHash: cost.previewHash, + costRunId, + transport: JSON.parse(transport), + reason, + acknowledgeTrustedCode: ack, + }); + const captured = generation.current, + next = await paperApi.preview(input); + if (alive.current && captured === generation.current) { + setPreview(next); + receipt.current = { preview: next, key: crypto.randomUUID() }; + } + }); + const create = () => + run(async () => { + const captured = receipt.current; + if (!preview || !captured || captured.preview !== preview) { + throw new Error('Review a current preview first'); + } + try { + const saved = await paperApi.create( + captured.preview.input, + captured.preview.previewHash, + captured.key + ); + if (alive.current) { + frozen.current = false; + dirty.current = false; + setUncertain(false); + navigate(`/paper/${saved.id}`); + } + } catch (cause) { + if (alive.current && (!(cause instanceof PaperApiError) || cause.uncertain)) { + frozen.current = true; + setUncertain(true); + } + throw cause; + } + }, true); + const disabled = pending || uncertain; + return ( +
{ + const link = (event.target as HTMLElement).closest('a'); + if ( + link && + (!link.target || link.target === '_self') && + !link.hasAttribute('download') && + event.button === 0 && + !event.ctrlKey && + !event.metaKey && + !event.shiftKey && + !event.altKey && + (dirty.current || busy.current || frozen.current) && + !window.confirm( + 'Leave this paper promotion draft or unconfirmed submission? Its exact retry inputs and key will be discarded. You can inspect saved records in another tab.' + ) + ) { + event.preventDefault(); + event.stopPropagation(); + } + }} + > +

Paper deployments

+

+ Promote reviewed research into a halted paper account. Live trading is unavailable. Creating + a deployment does not connect a feed or activate trading. +

+ {loading ? ( +

Loading deployments…

+ ) : rows.length ? ( +
    + {rows.map(row => ( +
  • + {row.preview.input.name} ·{' '} + {row.preview.configuration.matching.risk.ledger.accountId} +
  • + ))} +
+ ) : ( +

No paper deployments yet.

+ )} + {error &&

{error}

} +
+

Review a new promotion

+

+ Use a sealed report and completed cost study from{' '} + experiments. Future sessions and feed metadata must be + supplied explicitly; no calendar is inferred. +

+
+ + + + + + {source && ( + + )} + {cost && ( + + )} +