The clone retains exact artifact bytes and parent lineage. It is a new
- candidate awaiting review; cloning does not enable execution.
+ candidate. Research eligibility requires a declared isolated execution
+ contract and an available sandbox.
Clone name
@@ -517,7 +537,7 @@ function VersionIdentity({ version }: { version: StrategyVersionSummary }) {
{version.origin === 'candidate'
- ? 'Candidate execution is unavailable until isolated execution is supported.'
+ ? 'Candidate research uses the isolated runtime. Eligibility is checked against the retained package, dataset and financial policy.'
: 'Canonical execution requires approval, a matching executable build, a supported dataset and an explicit simulation policy.'}
diff --git a/apps/stock/web-app/src/features/strategies/components/CandidatePublication.tsx b/apps/stock/web-app/src/features/strategies/components/CandidatePublication.tsx
new file mode 100644
index 00000000..0813d594
--- /dev/null
+++ b/apps/stock/web-app/src/features/strategies/components/CandidatePublication.tsx
@@ -0,0 +1,197 @@
+import { useEffect, useRef, useState } from 'react';
+import type { StrategyVersionPackage } from '@stock-bot/types';
+import {
+ CandidatePublicationError,
+ publishCandidate,
+ readCandidatePackage,
+ type PublishedCandidate,
+} from '../services/candidatePublication';
+import { actionClass, fieldClass } from './StrategyParameterForm';
+
+/** Key by family/parent identity. A lost write keeps exactly one package and receipt. */
+export function CandidatePublication({
+ strategyId,
+ parentVersionId,
+ disabled,
+ onDirtyChange,
+ onPublished,
+}: {
+ strategyId: string;
+ parentVersionId: string | null;
+ disabled: boolean;
+ onDirtyChange: (dirty: boolean) => void;
+ onPublished: (version: PublishedCandidate) => void;
+}) {
+ const [pkg, setPackage] = useState(null);
+ const [filename, setFilename] = useState('');
+ const [loading, setLoading] = useState(false);
+ const [pending, setPending] = useState(false);
+ const [uncertain, setUncertain] = useState(false);
+ const [error, setError] = useState('');
+ const active = useRef(false);
+ const generation = useRef(0);
+ const writing = useRef(false);
+ const fileInput = useRef(null);
+ const intent = useRef<{ pkg: StrategyVersionPackage; key: string } | null>(null);
+ const dirtyCallback = useRef(onDirtyChange);
+ dirtyCallback.current = onDirtyChange;
+ useEffect(() => {
+ active.current = true;
+ return () => {
+ active.current = false;
+ generation.current++;
+ dirtyCallback.current(false);
+ };
+ }, []);
+ useEffect(() => {
+ onDirtyChange(Boolean(filename || pkg || uncertain));
+ }, [filename, pkg, uncertain, onDirtyChange]);
+ const select = async (file: File | undefined) => {
+ if (writing.current || intent.current) {
+ return;
+ }
+ const current = ++generation.current;
+ setPackage(null);
+ setError('');
+ setFilename(file?.name ?? '');
+ intent.current = null;
+ if (!file) {
+ setLoading(false);
+ return;
+ }
+ setLoading(true);
+ try {
+ const parsed = await readCandidatePackage(await file.text());
+ if (active.current && current === generation.current) {
+ setPackage(parsed);
+ }
+ } catch (cause) {
+ if (active.current && current === generation.current) {
+ setError(cause instanceof Error ? cause.message : 'Package could not be read');
+ }
+ } finally {
+ if (active.current && current === generation.current) {
+ setLoading(false);
+ }
+ }
+ };
+ const publish = async () => {
+ if (writing.current || (!intent.current && (disabled || loading || !pkg))) {
+ return;
+ }
+ if (!intent.current && pkg) {
+ intent.current = { pkg, key: crypto.randomUUID() };
+ }
+ const captured = intent.current;
+ if (!captured) {
+ return;
+ }
+ writing.current = true;
+ setPending(true);
+ setError('');
+ try {
+ const saved = await publishCandidate(strategyId, captured.pkg, parentVersionId, captured.key);
+ if (active.current) {
+ intent.current = null;
+ setUncertain(false);
+ setPackage(null);
+ setFilename('');
+ if (fileInput.current) {
+ fileInput.current.value = '';
+ }
+ onDirtyChange(false);
+ onPublished(saved);
+ }
+ } catch (cause) {
+ if (active.current) {
+ setError(cause instanceof Error ? cause.message : 'Publication failed');
+ const lost = !(cause instanceof CandidatePublicationError) || cause.uncertain;
+ setUncertain(lost);
+ if (!lost) {
+ intent.current = null;
+ }
+ }
+ } finally {
+ writing.current = false;
+ if (active.current) {
+ setPending(false);
+ }
+ }
+ };
+ return (
+
+ Publish candidate version
+
+ Upload a self-contained strategy package. Research evaluates candidate code in the isolated
+ runtime with Rust financial constraints. Warmup is an author declaration; paper promotion
+ requires a separate operator review.
+
+
+ Candidate package (JSON)
+ void select(event.target.files?.[0])}
+ />
+
+ {loading && Checking retained package...
}
+ {error && {error}
}
+ {pkg && (
+
+ Program
+
+ {pkg.program.strategyId} / {pkg.program.strategyVersion}
+
+ Artifact SHA256
+ {pkg.artifact.sha256}
+ Dependency lock SHA256
+ {pkg.dependencyLock.sha256}
+ Author-declared warmup bars
+ {pkg.execution?.warmupBars}
+ Parent version
+ {parentVersionId ?? 'First version in this family'}
+
+ )}
+ void publish()}
+ >
+ {pending
+ ? 'Publishing...'
+ : uncertain
+ ? 'Retry same publication'
+ : 'Publish immutable candidate'}
+
+ {
+ if (writing.current || intent.current) {
+ return;
+ }
+ generation.current++;
+ setLoading(false);
+ setPackage(null);
+ setFilename('');
+ setError('');
+ intent.current = null;
+ if (fileInput.current) {
+ fileInput.current.value = '';
+ }
+ }}
+ >
+ Clear package
+
+
+ );
+}
diff --git a/apps/stock/web-app/src/features/strategies/components/StrategySelection.tsx b/apps/stock/web-app/src/features/strategies/components/StrategySelection.tsx
index 4378d8c6..656fabb6 100644
--- a/apps/stock/web-app/src/features/strategies/components/StrategySelection.tsx
+++ b/apps/stock/web-app/src/features/strategies/components/StrategySelection.tsx
@@ -222,7 +222,7 @@ export function StrategySelection({
{selected.origin === 'candidate'
- ? 'Candidate execution is unavailable until isolated execution is supported.'
+ ? 'Candidate research requires an isolated execution declaration and an available sandbox. Eligibility is checked when preparing the run.'
: 'Reviewed built-in versions require a supported dataset, explicit policy and matching executable build before execution.'}
{family?.archived && (
diff --git a/apps/stock/web-app/src/features/strategies/services/candidatePublication.ts b/apps/stock/web-app/src/features/strategies/services/candidatePublication.ts
new file mode 100644
index 00000000..25f23349
--- /dev/null
+++ b/apps/stock/web-app/src/features/strategies/services/candidatePublication.ts
@@ -0,0 +1,105 @@
+import { z } from 'zod';
+import { parseStrategyVersionPackage } from '@stock-bot/stock-config/strategy';
+import type { StrategyVersionPackage } from '@stock-bot/types';
+import { API_BASE_URL, apiFetch } from '@/lib/api';
+
+export class CandidatePublicationError extends Error {
+ constructor(
+ message: string,
+ public readonly status: number | null
+ ) {
+ super(message);
+ }
+ get uncertain() {
+ return this.status === null || this.status >= 500;
+ }
+}
+export interface PublishedCandidate {
+ id: string;
+ strategyId: string;
+ ordinal: number;
+}
+const hash = async (value: string) =>
+ [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value)))]
+ .map(byte => byte.toString(16).padStart(2, '0'))
+ .join('');
+
+/** Parse and hash inert bytes. Generated code is never imported or compiled in the browser. */
+export async function readCandidatePackage(text: string): Promise {
+ const pkg = parseStrategyVersionPackage(JSON.parse(text));
+ if (pkg.execution?.kind !== 'isolated-candidate/v1') {
+ throw new Error('Package must declare isolated-candidate/v1 execution and its warmup bars');
+ }
+ const [artifact, lock] = await Promise.all([
+ hash(pkg.artifact.content),
+ hash(pkg.dependencyLock.content),
+ ]);
+ if (artifact !== pkg.artifact.sha256 || lock !== pkg.dependencyLock.sha256) {
+ throw new Error('Package artifact or dependency-lock hash does not match its retained bytes');
+ }
+ return pkg;
+}
+export async function publishCandidate(
+ strategyId: string,
+ pkg: StrategyVersionPackage,
+ parentVersionId: string | null,
+ key: string
+): Promise {
+ strategyId = z.string().uuid().parse(strategyId).toLowerCase();
+ parentVersionId = z.string().uuid().nullable().parse(parentVersionId)?.toLowerCase() ?? null;
+ const body = JSON.stringify({ package: pkg, parentVersionId });
+ let response: Response;
+ try {
+ response = await apiFetch(
+ `${API_BASE_URL}/api/v2/strategies/${encodeURIComponent(strategyId)}/versions`,
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
+ body,
+ }
+ );
+ } catch {
+ throw new CandidatePublicationError(
+ 'Publication response was lost. Retry the same publication to recover its receipt.',
+ null
+ );
+ }
+ const raw: unknown = await response.json().catch(() => null);
+ if (!response.ok) {
+ const parsed = z.object({ error: z.string() }).safeParse(raw);
+ throw new CandidatePublicationError(
+ parsed.success ? parsed.data.error : `Publication failed (${response.status})`,
+ response.status
+ );
+ }
+ const parsed = z
+ .object({
+ version: z.object({
+ id: z.string().uuid(),
+ strategyId: z.string().uuid(),
+ ordinal: z.number().int().positive(),
+ origin: z.literal('candidate'),
+ parentVersionId: z.string().uuid().nullable(),
+ package: z.object({
+ artifact: z.object({ sha256: z.string() }),
+ dependencyLock: z.object({ sha256: z.string() }),
+ }),
+ }),
+ })
+ .safeParse(raw);
+ if (
+ !parsed.success ||
+ response.status !== 201 ||
+ parsed.data.version.strategyId !== strategyId ||
+ parsed.data.version.parentVersionId !== parentVersionId ||
+ parsed.data.version.package.artifact.sha256 !== pkg.artifact.sha256 ||
+ parsed.data.version.package.dependencyLock.sha256 !== pkg.dependencyLock.sha256
+ ) {
+ throw new CandidatePublicationError(
+ 'Publication response could not be verified. Retry the same publication.',
+ null
+ );
+ }
+ const { id, ordinal } = parsed.data.version;
+ return { id, strategyId, ordinal };
+}
diff --git a/apps/stock/web-app/src/lib/constants.ts b/apps/stock/web-app/src/lib/constants.ts
index 457407f7..0e45e716 100644
--- a/apps/stock/web-app/src/lib/constants.ts
+++ b/apps/stock/web-app/src/lib/constants.ts
@@ -35,6 +35,7 @@ export const navigation: NavigationItem[] = [
{ name: 'Backtests', href: '/backtests', icon: BeakerIcon },
{ name: 'Research', href: '/research', icon: BeakerIcon },
{ name: 'Experiments', href: '/experiments', icon: BeakerIcon },
+ { name: 'Paper deployments', href: '/paper', icon: DocumentTextIcon },
{
name: 'System',
icon: ServerStackIcon,
diff --git a/database/postgres/init/29-isolated-candidates.sql b/database/postgres/init/29-isolated-candidates.sql
new file mode 100644
index 00000000..88714df9
--- /dev/null
+++ b/database/postgres/init/29-isolated-candidates.sql
@@ -0,0 +1,731 @@
+-- Isolated candidate execution is additive; all existing financial request/result kinds remain v1.
+-- No existing request, receipt, grant or result is rewritten by this migration.
+ALTER TABLE experiment_trial_retries ALTER COLUMN review_id DROP NOT NULL;
+
+CREATE OR REPLACE FUNCTION retained_strategy_authorized(request JSONB, current_review JSONB DEFAULT NULL) RETURNS BOOLEAN LANGUAGE plpgsql AS $$
+DECLARE selected RECORD; approval RECORD; execution JSONB:=request#>'{strategy,execution}'; profile JSONB:=execution->'profile';
+BEGIN
+ SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id WHERE v.id::text=request#>>'{strategy,versionId}' FOR UPDATE OF s;
+ SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1;
+ IF (selected.id IS NOT NULL AND selected.family_archived IS NULL
+ AND selected.origin=request#>>'{strategy,origin}' AND selected.strategy_id::text=request#>>'{strategy,familyId}'
+ AND selected.envelope=request#>'{strategy,package}' AND request#>'{strategy}' ? 'reviewId'
+ AND COALESCE(current_review,request#>'{strategy,reviewId}')=COALESCE(to_jsonb(approval.id::text),'null'::jsonb)
+ AND request#>>'{strategy,selection,ownerId}'='strategy:'||selected.id::text
+ AND request#>>'{strategy,selection,strategyId}'=selected.envelope#>>'{program,strategyId}'
+ AND request#>>'{strategy,selection,strategyVersion}'=selected.envelope#>>'{program,strategyVersion}'
+ AND request#>'{policy,matching,risk,ledger,ownerIds}'=jsonb_build_array('strategy:'||selected.id::text)
+ AND request#>'{policy,matching,owners}'=jsonb_build_array(jsonb_build_object('ownerId','strategy:'||selected.id::text,'mode','Target'))
+ AND request#>'{policy,cadence}'=jsonb_build_array(jsonb_build_object('owner_id','strategy:'||selected.id::text,'series_ids',jsonb_build_array(request#>>'{strategy,selection,seriesId}')))) IS NOT TRUE THEN RETURN FALSE; END IF;
+ IF selected.origin='builtin' THEN RETURN approval.decision='approve' AND NOT request#>'{strategy}' ? 'execution' AND NOT selected.envelope ? 'execution'; END IF;
+ RETURN (selected.origin='candidate' AND approval.decision IS DISTINCT FROM 'revoke'
+ AND request#>>'{strategy,baselineVersionId}' ~ '^[0-9a-f-]{36}$'
+ AND selected.envelope#>>'{program,apiVersion}'='canonical-ts/v1'
+ AND selected.envelope#>>'{execution,kind}'='isolated-candidate/v1'
+ AND (selected.envelope->'execution')-ARRAY['kind','warmupBars']='{}'::jsonb
+ AND jsonb_typeof(selected.envelope#>'{execution,warmupBars}')='number'
+ AND (selected.envelope#>>'{execution,warmupBars}')::numeric BETWEEN 0 AND 9007199254740991
+ AND trunc((selected.envelope#>>'{execution,warmupBars}')::numeric)=(selected.envelope#>>'{execution,warmupBars}')::numeric
+ AND (request#>'{strategy}')-ARRAY['familyId','versionId','baselineVersionId','origin','reviewId','package','selection','execution']='{}'::jsonb
+ AND execution->>'kind'='typescript-isolated-candidate/v1' AND execution->>'imageId' ~ '^sha256:[a-f0-9]{64}$'
+ AND execution-ARRAY['kind','imageId','profile']='{}'::jsonb
+ AND profile->>'version'='1' AND profile->>'policy'='linux-docker-guardian/v1' AND profile->>'protocol'='candidate-controller/v1'
+ AND profile->>'platform'='linux' AND profile->>'arch'='x64'
+ AND profile->>'hostSha256' ~ '^[a-f0-9]{64}$' AND profile->>'guardianSha256' ~ '^[a-f0-9]{64}$' AND profile->>'bunSha256' ~ '^[a-f0-9]{64}$'
+ AND profile-ARRAY['version','policy','protocol','platform','arch','hostSha256','guardianSha256','bunSha256','limits']='{}'::jsonb
+ AND profile->'limits'='{"memoryBytes":536870912,"cpuQuota":1,"pids":64,"tmpBytes":16777216,"wallMs":300000,"frameBytes":8388608,"stderrBytes":65536}'::jsonb) IS TRUE;
+END $$;
+
+-- Exact existing grant shape; only candidate owner/version identities map to the retained baseline.
+CREATE OR REPLACE FUNCTION research_grant_policy(request JSONB) RETURNS JSONB LANGUAGE plpgsql IMMUTABLE AS $$
+DECLARE policy JSONB:=request->'policy'; version_id JSONB:=request#>'{strategy,versionId}'; owner_id TEXT;
+BEGIN
+ policy:=jsonb_set(jsonb_set(policy,'{matching,risk,ledger,sessionId}','"agent-grant-run"'),'{matching,risk,ledger,accountId}','"agent-grant-account"');
+ IF request#>>'{strategy,origin}'='candidate' THEN
+ version_id:=request#>'{strategy,baselineVersionId}'; owner_id:='strategy:'||(version_id#>>'{}');
+ policy:=jsonb_set(policy,'{matching,risk,ledger,ownerIds}',jsonb_build_array(owner_id));
+ policy:=jsonb_set(policy,'{matching,owners}',jsonb_build_array(jsonb_build_object('ownerId',owner_id,'mode','Target')));
+ policy:=jsonb_set(policy,'{cadence}',jsonb_build_array(jsonb_build_object('owner_id',owner_id,'series_ids',jsonb_build_array(request#>>'{strategy,selection,seriesId}'))));
+ END IF;
+ RETURN jsonb_build_object('datasetHash',request->'datasetHash','versionId',version_id,'ownerBudget',request#>'{strategy,selection,ownerBudget}','seed',request#>'{strategy,selection,seed}','policy',policy,'analyticsPolicy',request->'analyticsPolicy','build',request->'build','modelArtifacts',request->'modelArtifacts');
+END $$;
+CREATE OR REPLACE FUNCTION assert_research_agent_grant(agent research_agents, backtest_id UUID, request JSONB) RETURNS void LANGUAGE plpgsql AS $$
+DECLARE candidate BOOLEAN:=request#>>'{strategy,origin}'='candidate';
+BEGIN
+ IF agent.enabled IS DISTINCT FROM TRUE OR NOT EXISTS(SELECT 1 FROM jsonb_array_elements(agent.policy->'grants') g WHERE g->>'backtestId'=backtest_id::text AND g->'policy'=research_grant_policy(request) AND (NOT candidate OR g->'allowOwnCandidates'='true'::jsonb)) THEN
+ RAISE EXCEPTION 'research_access:Operator approval of this exact baseline, dataset, financial policy and candidate permission is required';
+ END IF;
+ IF candidate AND NOT EXISTS(SELECT 1 FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id WHERE v.id::text=request#>>'{strategy,versionId}' AND v.origin='candidate' AND v.created_by=agent.id AND s.owner_principal=agent.id AND s.archived_at IS NULL) THEN
+ RAISE EXCEPTION 'research_access:Candidate must belong to the submitting research principal';
+ END IF;
+END $$;
+CREATE OR REPLACE FUNCTION validate_research_agent_policy() RETURNS trigger LANGUAGE plpgsql AS $$
+DECLARE key TEXT; value JSONB; item JSONB;
+BEGIN
+ IF TG_OP='UPDATE' AND (NEW.id IS DISTINCT FROM OLD.id OR NEW.token_hash IS DISTINCT FROM OLD.token_hash OR NEW.created_at IS DISTINCT FROM OLD.created_at OR NEW.revision<>OLD.revision+1) THEN
+ RAISE EXCEPTION 'Research principal identity is immutable and policy updates require the next revision' USING ERRCODE='23514';
+ END IF;
+ IF (jsonb_typeof(NEW.policy)='object' AND NEW.policy->>'version'='1' AND jsonb_typeof(NEW.policy->'allowedProjectIds')='array' AND jsonb_typeof(NEW.policy->'grants')='array' AND jsonb_typeof(NEW.policy->'limits')='object'
+ AND NEW.policy-ARRAY['version','allowedProjectIds','grants','limits']='{}'::jsonb
+ AND (NEW.policy->'limits')-ARRAY['maxActiveTrials','maxTrialsPerExperiment','maxBarEvaluationsPerExperiment','maxAttemptWallMs','maxAttempts']='{}'::jsonb) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Invalid research principal policy' USING ERRCODE='23514';
+ END IF;
+ FOREACH key IN ARRAY ARRAY['maxActiveTrials','maxTrialsPerExperiment','maxBarEvaluationsPerExperiment','maxAttemptWallMs','maxAttempts'] LOOP
+ value:=NEW.policy->'limits'->key;
+ IF jsonb_typeof(value) IS DISTINCT FROM 'number' THEN RAISE EXCEPTION 'Invalid research resource limit' USING ERRCODE='23514'; END IF;
+ IF (value::text)::numeric<1 OR (value::text)::numeric>9007199254740991 OR trunc((value::text)::numeric)<>(value::text)::numeric THEN RAISE EXCEPTION 'Invalid research resource limit' USING ERRCODE='23514'; END IF;
+ END LOOP;
+ IF (NEW.policy#>>'{limits,maxAttempts}')::numeric>3 OR (NEW.policy#>>'{limits,maxAttemptWallMs}')::numeric>2147483647 THEN RAISE EXCEPTION 'Invalid research attempt budget' USING ERRCODE='23514'; END IF;
+ FOR item IN SELECT jsonb_array_elements(NEW.policy->'grants') LOOP
+ IF (jsonb_typeof(item)='object' AND item-ARRAY['backtestId','policyHash','policy','allowOwnCandidates']='{}'::jsonb AND item->>'backtestId' ~ '^[0-9a-f-]{36}$' AND item->>'policyHash' ~ '^[a-f0-9]{64}$' AND jsonb_typeof(item->'policy')='object' AND (NOT item ? 'allowOwnCandidates' OR jsonb_typeof(item->'allowOwnCandidates')='boolean')) IS NOT TRUE THEN RAISE EXCEPTION 'Invalid research template grant' USING ERRCODE='23514'; END IF;
+ END LOOP;
+ RETURN NEW;
+END $$;
+
+CREATE OR REPLACE FUNCTION validate_experiment_manifest(candidate_row research_experiments) RETURNS void LANGUAGE plpgsql AS $$
+DECLARE parent RECORD; selected RECORD; approval RECORD; retained JSONB; request JSONB; candidate JSONB; candidate_index INTEGER := 0;
+BEGIN
+ SELECT * INTO parent FROM backtests WHERE id=candidate_row.backtest_id FOR UPDATE;
+ request := candidate_row.preview->'request';
+ IF candidate_row.preview->'input' ? 'candidate' THEN
+ PERFORM s.id FROM strategies s WHERE s.id IN (SELECT v.strategy_id FROM strategy_versions v WHERE v.id::text IN (parent.strategy_version_id::text,request#>>'{strategy,versionId}')) ORDER BY s.id FOR UPDATE;
+ END IF;
+ IF (parent.id IS NOT NULL AND parent.archived_at IS NULL AND NOT candidate_row.cancel_requested
+ AND jsonb_typeof(candidate_row.preview)='object' AND candidate_row.preview->>'version'='research-experiment-preview/v1'
+ AND candidate_row.preview->>'previewHash'=candidate_row.preview_hash AND candidate_row.preview#>>'{input,name}'=candidate_row.name
+ AND candidate_row.preview#>>'{input,backtestId}'=candidate_row.backtest_id::text
+ AND jsonb_typeof(candidate_row.preview#>'{input,grid}')='object'
+ AND jsonb_typeof(candidate_row.preview->'candidates')='array'
+ AND jsonb_array_length(candidate_row.preview->'candidates') BETWEEN 1 AND 100
+ AND request->>'kind'='canonical-research/v1' AND request->>'backtestId'=candidate_row.backtest_id::text
+ AND request->>'runId'='00000000-0000-4000-8000-000000000001'
+ AND request->>'name'=parent.name
+ AND request#>>'{strategy,versionId}'=COALESCE(candidate_row.preview#>>'{input,candidate,versionId}',parent.strategy_version_id::text)
+ AND request#>'{strategy,selection,parameters}'=COALESCE(candidate_row.preview#>'{input,candidate,parameters}',parent.strategy_parameters)
+ AND (request#>>'{strategy,origin}'<>'candidate' OR request#>>'{strategy,baselineVersionId}'=parent.strategy_version_id::text)
+ AND (NOT candidate_row.preview->'input' ? 'candidate' OR (request#>>'{strategy,origin}'='candidate' AND (candidate_row.preview#>'{input,candidate}')-ARRAY['versionId','parameters']='{}'::jsonb))
+ AND request->>'datasetHash'=parent.config->>'datasetHash'
+ AND request#>>'{policy,matching,risk,ledger,sessionId}'=request->>'runId'
+ AND request#>>'{policy,matching,risk,ledger,accountId}'='research:'||(request->>'runId')
+ AND request#>>'{policy,matching,risk,ledger,baseCurrency}'='USD'
+ AND request#>>'{policy,matching,risk,ledger,reserveOwnerId}'='reserve'
+ AND (request#>>'{policy,matching,risk,ledger,initialCapital}')::numeric=parent.initial_capital
+ AND request#>>'{strategy,selection,ownerBudget}'=parent.config#>>'{canonical,ownerBudget}'
+ AND request#>'{strategy,selection,seed}'=parent.config#>'{canonical,seed}'
+ AND request#>>'{policy,allow_exploratory}'='false'
+ AND jsonb_typeof(request->'build')='object'
+ AND request#>>'{build,version}'='1' AND request#>>'{build,runtime}'='bun'
+ AND request#>>'{build,workerSha256}' ~ '^[a-f0-9]{64}$'
+ AND request#>>'{build,engineWrapperSha256}' ~ '^[a-f0-9]{64}$'
+ AND request#>>'{build,engineBinarySha256}' ~ '^[a-f0-9]{64}$'
+ AND request#>>'{build,dependencyLockSha256}' ~ '^[a-f0-9]{64}$'
+ AND length(request#>>'{build,runtimeVersion}')>0 AND length(request#>>'{build,platform}')>0 AND length(request#>>'{build,arch}')>0
+ AND request->'modelArtifacts'='[]'::jsonb) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Experiment manifest requires an active canonical template and complete frozen identity' USING ERRCODE='23514';
+ END IF;
+ IF EXISTS (SELECT 1 FROM jsonb_each(parent.config->'canonical') settings
+ WHERE CASE settings.key
+ WHEN 'version' THEN request#>'{analyticsPolicy,version}'
+ WHEN 'ownerBudget' THEN request#>'{strategy,selection,ownerBudget}'
+ WHEN 'seed' THEN request#>'{strategy,selection,seed}'
+ WHEN 'halfSpreadRate' THEN request#>'{policy,matching,halfSpreadRate}'
+ WHEN 'slippageRate' THEN request#>'{policy,matching,slippageRate}'
+ WHEN 'latencyMs' THEN request#>'{policy,matching,latencyMs}'
+ WHEN 'participationRate' THEN request#>'{policy,participation_rate}'
+ WHEN 'periodsPerYear' THEN request#>'{analyticsPolicy,periodsPerYear}'
+ WHEN 'annualRiskFreeRate' THEN request#>'{analyticsPolicy,annualRiskFreeRate}'
+ ELSE request#>ARRAY['policy','matching','risk',settings.key] END IS DISTINCT FROM settings.value) THEN
+ RAISE EXCEPTION 'Experiment financial and analysis settings must match its saved template' USING ERRCODE='23514';
+ END IF;
+ IF candidate_row.preview->'input' ? 'candidate' AND NOT EXISTS (
+ SELECT 1 FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id WHERE v.id=parent.strategy_version_id AND s.archived_at IS NULL
+ AND CASE WHEN v.origin='builtin' THEN (SELECT decision='approve' FROM strategy_review_events WHERE version_id=v.id ORDER BY ordinal DESC LIMIT 1)
+ ELSE COALESCE((SELECT decision<>'revoke' FROM strategy_review_events WHERE version_id=v.id ORDER BY ordinal DESC LIMIT 1),TRUE) END
+ ) THEN RAISE EXCEPTION 'Candidate override requires its currently available saved baseline version' USING ERRCODE='23514'; END IF;
+ SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id
+ WHERE v.id::text=request#>>'{strategy,versionId}' FOR UPDATE OF s;
+ SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1;
+ IF (retained_strategy_authorized(request) AND selected.family_archived IS NULL
+ AND request#>>'{strategy,familyId}'=selected.strategy_id::text
+ AND request#>'{strategy,reviewId}' IS NOT DISTINCT FROM COALESCE(to_jsonb(approval.id::text),'null'::jsonb) AND request#>'{strategy,package}'=selected.envelope
+ AND request#>>'{strategy,selection,ownerId}'='strategy:'||selected.id::text
+ AND request#>'{policy,matching,risk,ledger,ownerIds}'=jsonb_build_array('strategy:'||selected.id::text)
+ AND request#>'{policy,matching,owners}'=jsonb_build_array(jsonb_build_object('ownerId','strategy:'||selected.id::text,'mode','Target'))
+ AND request#>>'{strategy,selection,strategyId}'=selected.envelope#>>'{program,strategyId}'
+ AND request#>>'{strategy,selection,strategyVersion}'=selected.envelope#>>'{program,strategyVersion}') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Experiment requires the exact current approved built-in version' USING ERRCODE='23514';
+ END IF;
+ SELECT payload INTO retained FROM backtest_datasets WHERE hash=request->>'datasetHash';
+ IF (retained#>>'{manifest,version}'='2' AND retained#>>'{manifest,eligibility}'='eligible'
+ AND retained->'manifest'=candidate_row.preview->'dataset' AND retained#>>'{manifest,hash}'=request->>'datasetHash'
+ AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1 AND jsonb_array_length(retained#>'{manifest,series}')=1
+ AND jsonb_array_length(retained#>'{manifest,universe,instrumentIds}')=1
+ AND request#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
+ AND request#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}'
+ AND request#>'{policy,matching,series}'=jsonb_build_array(jsonb_build_object('instrumentId',request#>>'{strategy,selection,instrumentId}','seriesId',request#>>'{strategy,selection,seriesId}','mode','Open'))
+ AND request#>'{policy,cadence}'=jsonb_build_array(jsonb_build_object('owner_id','strategy:'||selected.id::text,'series_ids',jsonb_build_array(request#>>'{strategy,selection,seriesId}')))) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Experiment requires the exact eligible retained single-asset dataset' USING ERRCODE='23514';
+ END IF;
+ FOR candidate IN SELECT value FROM jsonb_array_elements(candidate_row.preview->'candidates') LOOP
+ IF (jsonb_typeof(candidate)='object' AND candidate->>'index'=candidate_index::text
+ AND candidate->>'trialKey' ~ '^[a-f0-9]{64}$' AND jsonb_typeof(candidate->'parameters')='object'
+ AND (selected.origin='candidate' OR candidate->'parameters' <> '{}'::jsonb)
+ AND NOT EXISTS (SELECT 1 FROM jsonb_object_keys(candidate->'parameters') p(key)
+ WHERE p.key IN ('__proto__','constructor','prototype') OR NOT selected.envelope#>'{parameterSchema,properties}' ? p.key)
+ AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements_text(selected.envelope#>'{parameterSchema,required}') required(key)
+ WHERE NOT candidate->'parameters' ? required.key)
+ AND NOT EXISTS (SELECT 1 FROM jsonb_each(candidate->'parameters') p WHERE jsonb_typeof(p.value) NOT IN ('string','number','boolean'))) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Experiment candidates require contiguous indexes, keys and complete scalar parameters' USING ERRCODE='23514';
+ END IF;
+ candidate_index := candidate_index+1;
+ END LOOP;
+ IF (SELECT count(DISTINCT value->>'trialKey') FROM jsonb_array_elements(candidate_row.preview->'candidates'))<>candidate_index
+ OR (SELECT count(DISTINCT value->'parameters') FROM jsonb_array_elements(candidate_row.preview->'candidates'))<>candidate_index THEN
+ RAISE EXCEPTION 'Experiment candidates must be unique' USING ERRCODE='23514';
+ END IF;
+ RETURN;
+END $$;
+
+CREATE OR REPLACE FUNCTION require_experiment_manifest() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
+ IF NEW.preview->>'version'='cost-sensitivity-preview/v1' THEN
+ PERFORM validate_cost_manifest(NEW);
+ ELSE
+ IF (NEW.preview-ARRAY['version','previewHash','input','request','dataset','candidates']='{}'::jsonb
+ AND (NEW.preview->'input')-ARRAY['backtestId','name','grid','candidate']='{}'::jsonb
+ AND NOT EXISTS(SELECT 1 FROM jsonb_array_elements(NEW.preview->'candidates') c WHERE c-ARRAY['index','trialKey','parameters']<>'{}'::jsonb)) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Parameter experiments cannot contain cost-scenario fields' USING ERRCODE='23514';
+ END IF;
+ PERFORM validate_experiment_manifest(NEW);
+ END IF;
+ RETURN NEW;
+END $$;
+
+CREATE OR REPLACE FUNCTION validate_cost_manifest(candidate_row research_experiments) RETURNS void LANGUAGE plpgsql AS $$
+DECLARE source_row research_experiments; manifest JSONB:=candidate_row.preview; source JSONB:=manifest->'source'; candidate JSONB; costs JSONB; idx INTEGER:=0; size INTEGER;
+BEGIN
+ IF (manifest->>'version'='cost-sensitivity-preview/v1' AND manifest->>'previewHash'=candidate_row.preview_hash
+ AND manifest-ARRAY['version','previewHash','input','source','request','dataset','candidates']='{}'::jsonb
+ AND manifest#>>'{input,name}'=candidate_row.name AND manifest#>>'{input,backtestId}'=candidate_row.backtest_id::text
+ AND (manifest->'input')-ARRAY['name','backtestId','scenarios','candidate']='{}'::jsonb
+ AND manifest->'request'=source->'request' AND manifest->'dataset'=source->'dataset'
+ AND source->'input'=jsonb_build_object('name',candidate_row.name,'backtestId',candidate_row.backtest_id::text,'grid','{}'::jsonb)||CASE WHEN manifest->'input' ? 'candidate' THEN jsonb_build_object('candidate',manifest#>'{input,candidate}') ELSE '{}'::jsonb END
+ AND source->>'version'='research-experiment-preview/v1' AND source->>'previewHash' ~ '^[a-f0-9]{64}$'
+ AND jsonb_typeof(source->'candidates')='array' AND jsonb_array_length(source->'candidates')=1
+ AND source#>'{candidates,0,parameters}'=source#>'{request,strategy,selection,parameters}'
+ AND (source#>'{candidates,0}')-ARRAY['index','trialKey','parameters']='{}'::jsonb
+ AND jsonb_typeof(manifest#>'{input,scenarios}')='array' AND jsonb_array_length(manifest#>'{input,scenarios}') BETWEEN 1 AND 99
+ AND jsonb_typeof(manifest->'candidates')='array') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Cost experiment requires an exact fixed-parameter empty-grid source and explicit ordered scenarios' USING ERRCODE='23514';
+ END IF;
+ source_row:=candidate_row; source_row.preview:=source; source_row.preview_hash:=source->>'previewHash';
+ PERFORM validate_experiment_manifest(source_row);
+ size:=jsonb_array_length(manifest->'candidates');
+ IF size<>jsonb_array_length(manifest#>'{input,scenarios}')+1 THEN
+ RAISE EXCEPTION 'Every cost scenario and the automatic baseline require one candidate' USING ERRCODE='23514';
+ END IF;
+ FOR candidate IN SELECT value FROM jsonb_array_elements(manifest->'candidates') LOOP
+ costs:=CASE WHEN idx=0 THEN jsonb_build_object('feeRate',source#>'{request,policy,matching,risk,feeRate}','slippageRate',source#>'{request,policy,matching,slippageRate}') ELSE manifest#>ARRAY['input','scenarios',(idx-1)::text] END;
+ PERFORM assert_cost_scenario(costs);
+ IF (candidate-ARRAY['index','trialKey','parameters','costs']='{}'::jsonb AND candidate->>'index'=idx::text
+ AND candidate->>'trialKey' ~ '^[a-f0-9]{64}$' AND candidate->'parameters'=source#>'{request,strategy,selection,parameters}'
+ AND candidate->'costs'=costs) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Cost candidates must preserve fixed parameters, exact ordered costs and contiguous identities' USING ERRCODE='23514';
+ END IF;
+ idx:=idx+1;
+ END LOOP;
+ IF (SELECT count(DISTINCT value->'costs') FROM jsonb_array_elements(manifest->'candidates'))<>size
+ OR (SELECT count(DISTINCT value->>'trialKey') FROM jsonb_array_elements(manifest->'candidates'))<>size THEN
+ RAISE EXCEPTION 'Normalized cost pairs and trial identities must be distinct, including baseline' USING ERRCODE='23514';
+ END IF;
+END $$;
+
+CREATE OR REPLACE FUNCTION require_active_backtest_for_new_run() RETURNS trigger
+LANGUAGE plpgsql AS $$
+DECLARE parent RECORD; selected RECORD; approval RECORD; retained JSONB; snapshot JSONB; original RECORD; expected JSONB; experiment RECORD; candidate JSONB;
+BEGIN
+ SELECT * INTO parent FROM backtests WHERE id=NEW.backtest_id FOR UPDATE;
+ IF NOT FOUND THEN RETURN NEW; END IF;
+ IF parent.archived_at IS NOT NULL THEN
+ RAISE EXCEPTION 'Backtest is archived; restore it before submitting a new run' USING ERRCODE='23514';
+ END IF;
+ snapshot := NEW.request_snapshot;
+ IF NEW.experiment_id IS NOT NULL THEN
+ SELECT * INTO experiment FROM research_experiments WHERE id=NEW.experiment_id FOR UPDATE;
+ candidate := experiment.preview->'candidates'->NEW.trial_index;
+ IF (experiment.id IS NOT NULL AND experiment.backtest_id=NEW.backtest_id AND NOT experiment.cancel_requested
+ AND NEW.trial_index>=0 AND candidate->>'index'=NEW.trial_index::text
+ AND candidate->>'trialKey'=NEW.trial_key
+ AND NEW.original_run_id IS NULL AND NEW.submission_principal IS NULL
+ AND NEW.submission_key IS NULL AND NEW.submission_hash IS NULL
+ AND NEW.status='pending' AND NEW.speed_multiplier IS NULL
+ AND NEW.dataset_hash=experiment.preview#>>'{request,datasetHash}') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Experiment trial requires its uncancelled manifest, exact candidate and no individual receipt or lineage' USING ERRCODE='23514';
+ END IF;
+ SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id
+ WHERE v.id::text=experiment.preview#>>'{request,strategy,versionId}' FOR UPDATE OF s;
+ SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1;
+ IF (retained_strategy_authorized(experiment.preview->'request') AND selected.family_archived IS NULL
+ AND experiment.preview#>>'{request,strategy,familyId}'=selected.strategy_id::text
+ AND experiment.preview#>'{request,strategy,package}'=selected.envelope) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Experiment requires its current approved original retained built-in version' USING ERRCODE='23514';
+ END IF;
+ expected := experiment_trial_request(experiment.preview,NEW.trial_index,NEW.id);
+ IF snapshot IS DISTINCT FROM expected THEN
+ RAISE EXCEPTION 'Experiment trial must preserve its exact frozen request and candidate parameters' USING ERRCODE='23514';
+ END IF;
+ SELECT payload INTO retained FROM backtest_datasets WHERE hash=NEW.dataset_hash;
+ IF (retained#>>'{manifest,version}'='2' AND retained#>>'{manifest,eligibility}'='eligible'
+ AND retained->'manifest'=experiment.preview->'dataset'
+ AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1
+ AND jsonb_array_length(retained#>'{manifest,series}')=1
+ AND snapshot#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
+ AND snapshot#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Experiment requires the same eligible retained single-asset dataset' USING ERRCODE='23514';
+ END IF;
+ RETURN NEW;
+ END IF;
+ IF NEW.original_run_id IS NOT NULL THEN
+ SELECT r.*,br.canonical_result INTO original FROM runs r
+ LEFT JOIN backtest_results br ON br.run_id=r.id WHERE r.id=NEW.original_run_id;
+ IF (original.id IS NOT NULL AND original.id<>NEW.id
+ AND original.backtest_id=NEW.backtest_id AND original.status='completed'
+ AND original.request_snapshot->>'kind'='canonical-research/v1'
+ AND original.request_snapshot->>'runId'=original.id::text
+ AND original.request_snapshot->>'backtestId'=NEW.backtest_id::text
+ AND original.request_snapshot->>'datasetHash'=original.dataset_hash
+ AND original.canonical_result->>'kind'='canonical-result/v1'
+ AND original.canonical_result->>'status'='completed'
+ AND original.canonical_result->>'runId'=original.id::text
+ AND original.canonical_result->>'backtestId'=NEW.backtest_id::text
+ AND original.canonical_result->'request'=original.request_snapshot
+ AND original.canonical_result->>'financialEngine'='rust'
+ AND original.canonical_result->>'strategyExecution'=CASE WHEN original.request_snapshot#>>'{strategy,origin}'='candidate' THEN 'typescript-isolated-candidate/v1' ELSE 'typescript-retained-builtin/v1' END
+ AND NEW.dataset_hash=original.dataset_hash
+ AND NEW.status='pending' AND NEW.speed_multiplier IS NULL
+ AND is_research_actor(NEW.submission_principal)
+ AND NEW.submission_key ~ '^[!-~]{1,200}$'
+ AND NEW.submission_hash ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Reproduction requires a completed canonical source in the same backtest and a submission receipt' USING ERRCODE='23514';
+ END IF;
+ SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v
+ JOIN strategies s ON s.id=v.strategy_id
+ WHERE v.id::text=original.request_snapshot#>>'{strategy,versionId}' FOR UPDATE OF s;
+ SELECT id,decision INTO approval FROM strategy_review_events
+ WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1;
+ IF (retained_strategy_authorized(original.request_snapshot,COALESCE(to_jsonb(approval.id::text),'null'::jsonb)) AND selected.family_archived IS NULL
+ AND original.request_snapshot#>>'{strategy,familyId}'=selected.strategy_id::text
+ AND original.request_snapshot#>'{strategy,package}'=selected.envelope) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Reproduction requires the currently approved original retained built-in version' USING ERRCODE='23514';
+ END IF;
+ expected := jsonb_set(original.request_snapshot, '{runId}', to_jsonb(NEW.id::text));
+ expected := jsonb_set(expected, '{policy,matching,risk,ledger,sessionId}', to_jsonb(NEW.id::text));
+ expected := jsonb_set(expected, '{policy,matching,risk,ledger,accountId}', to_jsonb('research:'||NEW.id::text));
+ expected := jsonb_set(expected, '{strategy,reviewId}', COALESCE(to_jsonb(approval.id::text),'null'::jsonb));
+ IF snapshot IS DISTINCT FROM expected THEN
+ RAISE EXCEPTION 'Reproduction must preserve the original frozen request except run identities and current approval' USING ERRCODE='23514';
+ END IF;
+ SELECT payload INTO retained FROM backtest_datasets WHERE hash=NEW.dataset_hash;
+ IF (retained#>>'{manifest,version}'='2'
+ AND retained#>>'{manifest,eligibility}'='eligible'
+ AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1
+ AND jsonb_array_length(retained#>'{manifest,series}')=1
+ AND jsonb_array_length(snapshot#>'{policy,matching,series}')=1
+ AND jsonb_array_length(snapshot#>'{policy,matching,owners}')=1
+ AND jsonb_array_length(snapshot#>'{policy,matching,risk,ledger,ownerIds}')=1
+ AND snapshot#>>'{policy,allow_exploratory}'='false'
+ AND snapshot#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
+ AND snapshot#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Reproduction requires the original eligible retained single-asset dataset' USING ERRCODE='23514';
+ END IF;
+ RETURN NEW;
+ END IF;
+ IF parent.strategy_version_id IS NULL AND parent.strategy <> 'catalog' THEN
+ IF snapshot->>'kind'='canonical-research/v1' THEN
+ RAISE EXCEPTION 'Canonical research requires a catalog template' USING ERRCODE='23514';
+ END IF;
+ RETURN NEW;
+ END IF;
+ IF (snapshot->>'kind'='canonical-research/v1'
+ AND snapshot->>'runId'=NEW.id::text
+ AND snapshot->>'backtestId'=NEW.backtest_id::text
+ AND snapshot#>>'{strategy,versionId}'=parent.strategy_version_id::text
+ AND snapshot->>'datasetHash'=NEW.dataset_hash
+ AND NEW.status='pending' AND NEW.speed_multiplier IS NULL) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Catalog strategy execution requires an admitted canonical request' USING ERRCODE='23514';
+ END IF;
+ -- This is the same family lock used by operator review and archive. Later
+ -- review changes affect new admissions, never rewrite accepted snapshots.
+ SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v
+ JOIN strategies s ON s.id=v.strategy_id WHERE v.id=parent.strategy_version_id FOR UPDATE OF s;
+ SELECT id,decision INTO approval FROM strategy_review_events
+ WHERE version_id=parent.strategy_version_id ORDER BY ordinal DESC LIMIT 1;
+ IF (retained_strategy_authorized(snapshot) AND selected.family_archived IS NULL
+ AND snapshot#>>'{strategy,familyId}'=selected.strategy_id::text
+ AND snapshot#>'{strategy,reviewId}' IS NOT DISTINCT FROM COALESCE(to_jsonb(approval.id::text),'null'::jsonb)
+ AND snapshot#>'{strategy,package}'=selected.envelope
+ AND snapshot#>'{strategy,selection,parameters}'=parent.strategy_parameters
+ AND (snapshot#>>'{strategy,origin}'<>'candidate' OR snapshot#>>'{strategy,baselineVersionId}'=parent.strategy_version_id::text)
+ AND snapshot#>>'{strategy,selection,ownerId}'='strategy:'||selected.id::text) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Canonical research requires the exact approved retained built-in version' USING ERRCODE='23514';
+ END IF;
+ SELECT payload INTO retained FROM backtest_datasets WHERE hash=NEW.dataset_hash;
+ IF (retained#>>'{manifest,version}'='2'
+ AND retained#>>'{manifest,eligibility}'='eligible'
+ AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1
+ AND jsonb_array_length(retained#>'{manifest,series}')=1
+ AND jsonb_array_length(snapshot#>'{policy,matching,series}')=1
+ AND jsonb_array_length(snapshot#>'{policy,matching,owners}')=1
+ AND jsonb_array_length(snapshot#>'{policy,matching,risk,ledger,ownerIds}')=1
+ AND snapshot#>>'{policy,allow_exploratory}'='false'
+ AND snapshot#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
+ AND snapshot#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}'
+ AND snapshot#>>'{policy,matching,series,0,instrumentId}'=snapshot#>>'{strategy,selection,instrumentId}'
+ AND snapshot#>>'{policy,matching,series,0,seriesId}'=snapshot#>>'{strategy,selection,seriesId}') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Canonical research requires one eligible retained v2 execution asset' USING ERRCODE='23514';
+ END IF;
+ RETURN NEW;
+END $$;
+
+CREATE OR REPLACE FUNCTION require_experiment_retry_failure() RETURNS trigger LANGUAGE plpgsql AS $$
+DECLARE parent RECORD; experiment RECORD; original RECORD; selected RECORD; approval RECORD; expected JSONB; candidate JSONB; retained JSONB;
+BEGIN
+ -- Match the API lock order; worker-owned updates only need the run lock.
+ SELECT * INTO parent FROM backtests WHERE id=(SELECT backtest_id FROM research_experiments WHERE id=NEW.experiment_id) FOR UPDATE;
+ SELECT * INTO experiment FROM research_experiments WHERE id=NEW.experiment_id FOR UPDATE;
+ SELECT * INTO original FROM runs WHERE id=NEW.run_id AND experiment_id=NEW.experiment_id FOR UPDATE;
+ IF (parent.id IS NOT NULL AND parent.archived_at IS NULL AND experiment.id IS NOT NULL AND NOT experiment.cancel_requested
+ AND original.id IS NOT NULL AND original.backtest_id=parent.id AND original.status='failed' AND NOT original.cancel_requested
+ AND NEW.recorded_at=NOW() AND original.trial_key=NEW.trial_key AND original.manual_retry_count<2147483647 AND original.attempt_number<2147483647
+ AND NEW.retry_number=original.manual_retry_count+1 AND NEW.previous_attempt_number=original.attempt_number
+ AND NEW.previous_attempt_id IS NOT DISTINCT FROM original.attempt_id
+ AND NEW.error IS NOT DISTINCT FROM original.error AND NEW.progress IS NOT DISTINCT FROM original.progress
+ AND NEW.current_simulation_date IS NOT DISTINCT FROM original.current_simulation_date
+ AND NEW.started_at IS NOT DISTINCT FROM original.started_at AND NEW.completed_at IS NOT DISTINCT FROM original.completed_at
+ AND NEW.paused_at IS NOT DISTINCT FROM original.paused_at AND NEW.failure_updated_at=original.updated_at
+ AND NOT EXISTS (SELECT 1 FROM backtest_results WHERE run_id=original.id)) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Retry requires the exact current failed experiment trial without cancellation or retained result' USING ERRCODE='23514';
+ END IF;
+ candidate := experiment.preview->'candidates'->original.trial_index;
+ expected := experiment_trial_request(experiment.preview,original.trial_index,original.id);
+ IF (candidate->>'index'=original.trial_index::text AND candidate->>'trialKey'=original.trial_key
+ AND expected=original.request_snapshot AND expected->>'kind'='canonical-research/v1'
+ AND expected->>'backtestId'=original.backtest_id::text AND expected->>'datasetHash'=original.dataset_hash
+ AND original.original_run_id IS NULL AND original.speed_multiplier IS NULL) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Retry must preserve its exact immutable experiment request and candidate' USING ERRCODE='23514';
+ END IF;
+ SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id
+ WHERE v.id::text=expected#>>'{strategy,versionId}' FOR UPDATE OF s;
+ SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1;
+ IF (retained_strategy_authorized(expected,COALESCE(to_jsonb(NEW.review_id::text),'null'::jsonb)) AND selected.family_archived IS NULL
+ AND NEW.review_id IS NOT DISTINCT FROM approval.id
+ AND expected#>>'{strategy,familyId}'=selected.strategy_id::text
+ AND expected#>'{strategy,package}'=selected.envelope) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Retry requires current approval of the original retained built-in version' USING ERRCODE='23514';
+ END IF;
+ SELECT payload INTO retained FROM backtest_datasets WHERE hash=original.dataset_hash;
+ IF (retained#>>'{manifest,version}'='2' AND retained#>>'{manifest,eligibility}'='eligible'
+ AND retained->'manifest'=experiment.preview->'dataset'
+ AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1
+ AND jsonb_array_length(retained#>'{manifest,series}')=1
+ AND expected#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
+ AND expected#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Retry requires its retained eligible original dataset' USING ERRCODE='23514';
+ END IF;
+ RETURN NEW;
+END $$;
+
+CREATE OR REPLACE FUNCTION assert_validation_phase_preview(value JSONB, manifest JSONB, phase TEXT, winner JSONB DEFAULT NULL, review_id TEXT DEFAULT NULL)
+RETURNS void LANGUAGE plpgsql AS $$
+DECLARE partition JSONB; request JSONB; candidates JSONB; expected JSONB;
+BEGIN
+ partition := manifest->'partitions'->CASE phase WHEN 'train' THEN 0 WHEN 'validation' THEN 1 WHEN 'test' THEN 2 ELSE -1 END;
+ request := partition->'request';
+ IF phase='train' THEN candidates := manifest#>'{source,candidates}';
+ ELSE
+ IF winner IS NULL OR (review_id IS NULL AND request#>>'{strategy,origin}'='builtin') THEN RAISE EXCEPTION 'Holdout requires frozen winner and approval' USING ERRCODE='23514'; END IF;
+ request := jsonb_set(request,'{strategy,selection,parameters}',winner->'parameters');
+ request := jsonb_set(request,'{strategy,reviewId}',COALESCE(to_jsonb(review_id),'null'::jsonb));
+ candidates := jsonb_build_array(jsonb_set(winner,'{index}','0'::jsonb));
+ END IF;
+ expected := jsonb_build_object('version','research-experiment-preview/v1','input',jsonb_build_object(
+ 'backtestId',manifest#>'{input,backtestId}','name',(manifest#>>'{input,name}')||' · '||phase,
+ 'grid',CASE WHEN phase='train' THEN manifest#>'{input,grid}' ELSE '{}'::jsonb END)||CASE WHEN manifest->'input' ? 'candidate' THEN jsonb_build_object('candidate',jsonb_set(manifest#>'{input,candidate}','{parameters}',request#>'{strategy,selection,parameters}')) ELSE '{}'::jsonb END,
+ 'request',request,'dataset',partition->'dataset','candidates',candidates);
+ IF ((value-'previewHash')=expected AND value->>'previewHash' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Validation phase must preserve its exact frozen request, data and candidate' USING ERRCODE='23514';
+ END IF;
+END $$;
+
+CREATE OR REPLACE FUNCTION assert_validation_preparation(manifest JSONB) RETURNS void LANGUAGE plpgsql AS $$
+DECLARE source JSONB; retained JSONB; slice JSONB; partition JSONB; bounds JSONB; bar JSONB; calendar JSONB;
+ phase TEXT; idx INTEGER := 0; candidate JSONB; required_history BIGINT := 0; n BIGINT;
+ warmup BIGINT; start_at BIGINT; end_at BIGINT; prior_end BIGINT := NULL;
+ total INTEGER; available_warmup INTEGER; admitted INTEGER; evaluation INTEGER; terminal INTEGER; delayed INTEGER;
+ previous_event BIGINT; previous_sequence BIGINT; event_at BIGINT; sequence BIGINT; arrival BIGINT;
+ expected_bars JSONB; expected_manifest JSONB; expected_request JSONB; initial_session JSONB; boundaries JSONB; counts JSONB;
+BEGIN
+ source := manifest->'source';
+ IF (manifest->>'version'='chronological-validation-preview/v1' AND manifest->>'execution'='preview-only'
+ AND manifest->>'previewHash' ~ '^[a-f0-9]{64}$'
+ AND ((manifest->'input')-'recipe')=source->'input'
+ AND manifest#>'{input,recipe,version}'='1'::jsonb AND manifest#>'{input,recipe,labelHorizonMs}'='0'::jsonb
+ AND jsonb_typeof(manifest->'partitions')='array' AND jsonb_array_length(manifest->'partitions')=3
+ AND jsonb_set(manifest->'policy','{model}','"deterministic-unfitted"')='{"selection":{"phase":"train","metric":"totalReturn","direction":"maximize","tieBreak":"candidate-index","requireAllCandidates":true},"validationRole":"diagnostic-only","testRole":"holdout-only","reset":"initial-capital-empty-positions","model":"deterministic-unfitted","readiness":"input-checks-only"}'::jsonb) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Validation requires the fixed complete chronological preparation policy' USING ERRCODE='23514';
+ END IF;
+ IF manifest#>>'{policy,model}' IS DISTINCT FROM (CASE WHEN source#>>'{request,strategy,origin}'='candidate' THEN 'unverified-candidate' ELSE 'deterministic-unfitted' END) THEN RAISE EXCEPTION 'Validation model declaration differs from strategy origin' USING ERRCODE='23514'; END IF;
+ SELECT payload INTO retained FROM backtest_datasets WHERE hash=source#>>'{request,datasetHash}';
+ IF (retained->'manifest'=source->'dataset' AND retained#>>'{manifest,eligibility}'='eligible') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Validation source must equal its retained eligible manifest' USING ERRCODE='23514';
+ END IF;
+ FOR candidate IN SELECT value FROM jsonb_array_elements(source->'candidates') LOOP
+ IF source#>>'{request,strategy,origin}'='candidate' THEN
+ n := (source#>>'{request,strategy,package,execution,warmupBars}')::bigint;
+ ELSIF source#>>'{request,strategy,selection,strategyId}'='sma_crossover' THEN
+ n := (candidate#>>'{parameters,slowPeriod}')::integer+1;
+ ELSIF source#>>'{request,strategy,selection,strategyId}'='mean_reversion' THEN
+ n := GREATEST((candidate#>>'{parameters,lookbackPeriod}')::integer,(candidate#>>'{parameters,trendPeriod}')::integer,
+ (candidate#>>'{parameters,momentumPeriod}')::integer+1,(candidate#>>'{parameters,volatilityPeriod}')::integer+1);
+ ELSE RAISE EXCEPTION 'Unsupported validation strategy' USING ERRCODE='23514'; END IF;
+ required_history := GREATEST(required_history,n);
+ END LOOP;
+ SELECT value INTO calendar FROM jsonb_array_elements(retained#>'{manifest,calendars}') WHERE value->>'id'=retained#>>'{manifest,series,0,calendarId}';
+ FOREACH phase IN ARRAY ARRAY['train','validation','test'] LOOP
+ partition := manifest->'partitions'->idx; bounds := manifest#>ARRAY['input','recipe',phase];
+ warmup := (bounds->>'warmupStart')::bigint; start_at := (bounds->>'tradeStart')::bigint; end_at := (bounds->>'tradeEnd')::bigint;
+ IF (partition->>'phase'=phase AND warmup=(retained#>>'{manifest,bounds,warmupStart}')::bigint
+ AND start_at>=(retained#>>'{manifest,bounds,tradeStart}')::bigint
+ AND end_at<=(retained#>>'{manifest,bounds,tradeEnd}')::bigint
+ AND (prior_end IS NULL OR prior_end<=start_at)
+ AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(retained->'bars') b, unnest(ARRAY[warmup,start_at,end_at]) boundary
+ WHERE (b->>'intervalStart')::bigint>'intervalEnd')::bigint)) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Validation windows must be exact chronological in-source boundaries' USING ERRCODE='23514';
+ END IF;
+ SELECT COALESCE(jsonb_agg(value ORDER BY ordinality),'[]'::jsonb) INTO expected_bars FROM jsonb_array_elements(retained->'bars') WITH ORDINALITY
+ WHERE (value->>'intervalStart')::bigint>=warmup AND (value->>'intervalEnd')::bigint<=end_at;
+ total := jsonb_array_length(expected_bars);
+ expected_manifest := ((retained->'manifest')-'hash'-'bounds'-'barCount') || jsonb_build_object('hash',partition#>'{dataset,hash}','bounds',bounds,'barCount',total);
+ SELECT payload INTO slice FROM backtest_datasets WHERE hash=partition#>>'{dataset,hash}';
+ IF (total>0 AND slice->'bars'=expected_bars AND slice->'manifest'=expected_manifest AND partition->'dataset'=expected_manifest
+ AND partition#>>'{dataset,hash}' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Validation slice must preserve exact source bars, availability and metadata' USING ERRCODE='23514';
+ END IF;
+ available_warmup:=0; admitted:=0; evaluation:=0; terminal:=0; delayed:=0; previous_event:=NULL; previous_sequence:=NULL;
+ FOR bar IN SELECT value FROM jsonb_array_elements(expected_bars) LOOP
+ arrival:=(bar->>'availableAt')::bigint; event_at:=(bar->>'eventTime')::bigint; sequence:=(bar->>'sourceSequence')::bigint;
+ IF arrivalprevious_event OR (event_at=previous_event AND sequence>previous_sequence) THEN
+ admitted:=admitted+1; previous_event:=event_at; previous_sequence:=sequence;
+ END IF;
+ ELSIF arrival'counts'=counts AND (partition->>'requiredWarmup')::bigint=required_history AND admitted>=required_history AND evaluation>0
+ AND jsonb_typeof(partition->'warnings')='array') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Validation history readiness and availability counts must be exact' USING ERRCODE='23514';
+ END IF;
+ SELECT value INTO initial_session FROM jsonb_array_elements(calendar->'sessions') WHERE (value->>'open')::bigint<=warmup ORDER BY (value->>'open')::bigint DESC LIMIT 1;
+ SELECT COALESCE(jsonb_agg(jsonb_build_object('calendarId',calendar->'id','calendarRevision',calendar->'revision','sessionId',value->'date','startsAt',value->'open') ORDER BY ordinality),'[]'::jsonb)
+ INTO boundaries FROM jsonb_array_elements(calendar->'sessions') WITH ORDINALITY WHERE (value->>'open')::bigint>warmup AND (value->>'open')::bigint<=end_at;
+ expected_request:=jsonb_set(source->'request','{datasetHash}',partition#>'{dataset,hash}');
+ expected_request:=jsonb_set(expected_request,'{policy,matching,risk,ledger,riskSession}',jsonb_build_object('calendarId',calendar->'id','calendarRevision',calendar->'revision','sessionId',initial_session->'date','startsAt',initial_session->'open'));
+ expected_request:=jsonb_set(expected_request,'{policy,risk_boundaries}',boundaries);
+ IF (initial_session IS NOT NULL AND partition->'request'=expected_request) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Validation phases may change only their dataset and exact retained account clock' USING ERRCODE='23514';
+ END IF;
+ idx:=idx+1; prior_end:=end_at;
+ END LOOP;
+END $$;
+
+CREATE OR REPLACE FUNCTION require_validation_experiment() RETURNS trigger LANGUAGE plpgsql AS $$
+DECLARE source_row research_experiments; root research_experiments; selected RECORD; approval RECORD; phase_id TEXT;
+BEGIN
+ IF NEW.validation_selection IS NOT NULL OR NEW.validation_report IS NOT NULL OR NEW.cancel_requested THEN
+ RAISE EXCEPTION 'New validation phases cannot invent selection, report or cancellation' USING ERRCODE='23514';
+ END IF;
+ IF NEW.validation_phase='train' THEN
+ source_row:=NEW; source_row.preview:=NEW.validation_manifest->'source'; source_row.preview_hash:=source_row.preview->>'previewHash'; source_row.name:=source_row.preview#>>'{input,name}';
+ PERFORM validate_experiment_manifest(source_row);
+ PERFORM assert_validation_preparation(NEW.validation_manifest);
+ PERFORM assert_validation_phase_preview(NEW.preview,NEW.validation_manifest,'train');
+ ELSE
+ -- The service already holds the parent; direct insert follows the same order.
+ PERFORM 1 FROM backtests WHERE id=NEW.backtest_id AND archived_at IS NULL FOR UPDATE;
+ IF NOT FOUND THEN RAISE EXCEPTION 'Holdout requires an active parent' USING ERRCODE='23514'; END IF;
+ SELECT * INTO root FROM research_experiments WHERE id=NEW.validation_parent_id FOR UPDATE;
+ phase_id:=root.validation_selection#>>ARRAY['holdoutExperimentIds',NEW.validation_phase];
+ IF (root.validation_phase='train' AND NOT root.cancel_requested AND root.validation_selection IS NOT NULL
+ AND root.backtest_id=NEW.backtest_id AND phase_id=NEW.id::text AND NEW.name=(root.validation_manifest#>>'{input,name}')||' · '||NEW.validation_phase
+ AND NEW.submission_principal=root.validation_selection->>'principal'
+ AND NEW.submission_key='validation-child:'||NEW.id::text) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Holdout must belong to its uncancelled frozen training selection' USING ERRCODE='23514';
+ END IF;
+ SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id
+ WHERE v.id::text=root.validation_manifest#>>'{source,request,strategy,versionId}' FOR UPDATE OF s;
+ SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1;
+ IF (retained_strategy_authorized(root.validation_manifest#>'{source,request}',root.validation_selection->'reviewId') AND selected.family_archived IS NULL
+ AND root.validation_manifest#>'{source,request,strategy,package}'=selected.envelope) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Holdout requires current approval of the original frozen version' USING ERRCODE='23514';
+ END IF;
+ PERFORM assert_validation_phase_preview(NEW.preview,root.validation_manifest,NEW.validation_phase,root.validation_selection->'winner',root.validation_selection->>'reviewId');
+ END IF;
+ IF (NEW.preview->>'previewHash'=NEW.preview_hash AND NEW.preview#>>'{input,name}'=NEW.name
+ AND NEW.preview#>>'{input,backtestId}'=NEW.backtest_id::text) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Validation phase row identity must match its preview' USING ERRCODE='23514';
+ END IF;
+ RETURN NEW;
+END $$;
+
+CREATE OR REPLACE FUNCTION protect_validation_evidence() RETURNS trigger LANGUAGE plpgsql AS $$
+DECLARE document JSONB; candidate JSONB; item JSONB; idx INTEGER; winner_index INTEGER; best numeric; score numeric;
+ selected RECORD; approval RECORD; root research_experiments; phase TEXT; child_id UUID;
+BEGIN
+ IF NEW.validation_manifest IS DISTINCT FROM OLD.validation_manifest OR NEW.validation_parent_id IS DISTINCT FROM OLD.validation_parent_id
+ OR NEW.validation_phase IS DISTINCT FROM OLD.validation_phase THEN
+ RAISE EXCEPTION 'Validation preparation and phase lineage are immutable' USING ERRCODE='23514';
+ END IF;
+ IF OLD.validation_selection IS NOT NULL AND NEW.validation_selection IS DISTINCT FROM OLD.validation_selection THEN
+ RAISE EXCEPTION 'Validation selection is write once' USING ERRCODE='23514';
+ END IF;
+ IF OLD.validation_report IS NOT NULL AND NEW.validation_report IS DISTINCT FROM OLD.validation_report THEN
+ RAISE EXCEPTION 'Validation report is write once' USING ERRCODE='23514';
+ END IF;
+ IF OLD.validation_selection IS NULL AND NEW.validation_selection IS NOT NULL THEN
+ document:=NEW.validation_selection;
+ IF (NEW.validation_phase='train' AND NOT NEW.cancel_requested AND OLD.validation_report IS NULL
+ AND document->>'version'='chronological-validation-selection/v1' AND document->>'validationId'=NEW.id::text
+ AND document->>'previewHash'=NEW.validation_manifest->>'previewHash' AND document->>'selectionHash' ~ '^[a-f0-9]{64}$'
+ AND document->>'id' ~ '^[a-f0-9-]{36}$' AND (document->>'createdAt')::timestamptz IS NOT NULL
+ AND is_research_actor(document->>'principal') AND document#>>'{_receipt,key}' ~ '^[!-~]{1,200}$'
+ AND document#>>'{_receipt,hash}' ~ '^[a-f0-9]{64}$' AND jsonb_typeof(document->'training')='array'
+ AND jsonb_array_length(document->'training')=jsonb_array_length(NEW.preview->'candidates')
+ AND (SELECT count(*) FROM runs WHERE experiment_id=NEW.id)=jsonb_array_length(NEW.preview->'candidates')
+ AND NOT EXISTS (SELECT 1 FROM research_experiments WHERE validation_parent_id=NEW.id)
+ AND document#>>'{holdoutExperimentIds,validation}' ~ '^[a-f0-9-]{36}$'
+ AND document#>>'{holdoutExperimentIds,test}' ~ '^[a-f0-9-]{36}$'
+ AND document#>>'{holdoutExperimentIds,validation}'<>document#>>'{holdoutExperimentIds,test}') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Selection requires a complete uncancelled training experiment and immutable receipt' USING ERRCODE='23514';
+ END IF;
+ idx:=0; best:=NULL; winner_index:=NULL;
+ FOR item IN SELECT value FROM jsonb_array_elements(document->'training') LOOP
+ score:=assert_validation_evidence(item,NEW.id,'train',idx);
+ candidate:=NEW.preview->'candidates'->idx;
+ IF item->>'trialKey' IS DISTINCT FROM candidate->>'trialKey' THEN RAISE EXCEPTION 'Training evidence must follow original candidate order' USING ERRCODE='23514'; END IF;
+ IF best IS NULL OR score>best THEN best:=score; winner_index:=idx; END IF;
+ idx:=idx+1;
+ END LOOP;
+ IF document->'winner' IS DISTINCT FROM NEW.preview->'candidates'->winner_index THEN
+ RAISE EXCEPTION 'Winner must maximize training return with original-index tie break' USING ERRCODE='23514';
+ END IF;
+ SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id
+ WHERE v.id::text=NEW.validation_manifest#>>'{source,request,strategy,versionId}' FOR UPDATE OF s;
+ SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1;
+ IF (retained_strategy_authorized(NEW.validation_manifest#>'{source,request}',document->'reviewId') AND selected.family_archived IS NULL AND NEW.validation_manifest#>'{source,request,strategy,package}'=selected.envelope) IS NOT TRUE THEN
+ RAISE EXCEPTION 'New holdouts require current approval of their original version' USING ERRCODE='23514';
+ END IF;
+ END IF;
+ IF OLD.validation_report IS NULL AND NEW.validation_report IS NOT NULL THEN
+ document:=NEW.validation_report;
+ IF (NEW.validation_phase='train' AND NOT NEW.cancel_requested AND OLD.validation_selection IS NOT NULL
+ AND document->>'version'='chronological-validation-report/v1' AND document->>'validationId'=NEW.id::text
+ AND document->>'previewHash'=NEW.validation_manifest->>'previewHash' AND document->>'selectionHash'=OLD.validation_selection->>'selectionHash'
+ AND document->>'reportHash' ~ '^[a-f0-9]{64}$' AND document->>'id' ~ '^[a-f0-9-]{36}$' AND (document->>'createdAt')::timestamptz IS NOT NULL
+ AND is_research_actor(document->>'principal') AND document#>>'{_receipt,key}' ~ '^[!-~]{1,200}$'
+ AND document#>>'{_receipt,hash}' ~ '^[a-f0-9]{64}$' AND document->'training'=OLD.validation_selection->'training'
+ AND document->>'reset'='initial-capital-empty-positions' AND jsonb_typeof(document->'limitations')='array') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Report requires exact frozen selection and independent reset evidence' USING ERRCODE='23514';
+ END IF;
+ idx:=0;
+ FOR item IN SELECT value FROM jsonb_array_elements(document->'training') LOOP
+ PERFORM assert_validation_evidence(item,NEW.id,'train',idx); idx:=idx+1;
+ END LOOP;
+ FOREACH phase IN ARRAY ARRAY['validation','test'] LOOP
+ child_id:=(OLD.validation_selection#>>ARRAY['holdoutExperimentIds',phase])::uuid;
+ IF NOT EXISTS (SELECT 1 FROM research_experiments WHERE id=child_id AND validation_parent_id=NEW.id AND validation_phase=phase AND NOT cancel_requested)
+ OR (SELECT count(*) FROM runs WHERE experiment_id=child_id)<>1 THEN
+ RAISE EXCEPTION 'Report requires each exact complete holdout child' USING ERRCODE='23514';
+ END IF;
+ PERFORM assert_validation_evidence(document->phase,child_id,phase,(OLD.validation_selection#>>'{winner,index}')::integer);
+ END LOOP;
+ END IF;
+ RETURN NEW;
+END $$;
+
+
+CREATE OR REPLACE FUNCTION require_canonical_result_identity() RETURNS trigger
+LANGUAGE plpgsql AS $$
+DECLARE snapshot JSONB;
+BEGIN
+ SELECT request_snapshot INTO snapshot FROM runs WHERE id=NEW.run_id;
+ IF snapshot->>'kind'='canonical-research/v1' THEN
+ IF (NEW.canonical_result->>'kind'='canonical-result/v1'
+ AND NEW.canonical_result->'request'=snapshot
+ AND NEW.canonical_result->>'runId'=NEW.run_id::text
+ AND NEW.canonical_result->>'backtestId'=snapshot->>'backtestId'
+ AND NEW.canonical_result->>'financialEngine'='rust'
+ AND NEW.canonical_result->>'strategyExecution'=(CASE WHEN snapshot#>>'{strategy,origin}'='candidate' THEN 'typescript-isolated-candidate/v1' ELSE 'typescript-retained-builtin/v1' END)) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Canonical result must retain its exact admitted request' USING ERRCODE='23514';
+ END IF;
+ ELSIF NEW.canonical_result IS NOT NULL THEN
+ RAISE EXCEPTION 'Legacy runs cannot receive canonical results' USING ERRCODE='23514';
+ END IF;
+ RETURN NEW;
+END $$;
+
+CREATE OR REPLACE FUNCTION assert_validation_evidence(item JSONB, phase_experiment_id UUID, phase TEXT, source_index INTEGER)
+RETURNS numeric LANGUAGE plpgsql AS $$
+DECLARE experiment research_experiments; run RECORD; result JSONB; expected_request JSONB; expected JSONB; candidate JSONB; analysis_policy JSONB; metric RECORD;
+BEGIN
+ SELECT * INTO experiment FROM research_experiments WHERE id=phase_experiment_id;
+ SELECT r.*,br.canonical_result INTO run FROM runs r LEFT JOIN backtest_results br ON br.run_id=r.id
+ WHERE r.id::text=item->>'runId' AND r.experiment_id=phase_experiment_id;
+ result:=run.canonical_result; candidate:=experiment.preview->'candidates'->run.trial_index;
+ expected_request:=jsonb_set(experiment.preview->'request','{runId}',to_jsonb(run.id::text));
+ expected_request:=jsonb_set(expected_request,'{policy,matching,risk,ledger,sessionId}',to_jsonb(run.id::text));
+ expected_request:=jsonb_set(expected_request,'{policy,matching,risk,ledger,accountId}',to_jsonb('research:'||run.id::text));
+ expected_request:=jsonb_set(expected_request,'{strategy,selection,parameters}',candidate->'parameters');
+ analysis_policy:=(expected_request->'analyticsPolicy') || jsonb_build_object(
+ 'calendarId',expected_request#>'{policy,matching,risk,ledger,riskSession,calendarId}',
+ 'calendarRevision',expected_request#>'{policy,matching,risk,ledger,riskSession,calendarRevision}',
+ 'sampling','account-boundary-after-observations-v1','marks','last-available-no-per-session-freshness-certification',
+ 'returnUnit','fraction','variance','sample-n-minus-one','riskFreeConversion','annual-rate-divided-by-periods-per-year',
+ 'downside','full-series-rms-relative-to-risk-free','partialPeriods','visible-excluded-from-periodic-statistics',
+ 'drawdown','session-end-and-terminal-sampled','exposureBasis','elapsed-calendar-time',
+ 'cagrBasis','elapsed-calendar-days-365','zeroTerminalCagr','negative-one-for-positive-elapsed-time');
+ IF (experiment.id IS NOT NULL AND NOT experiment.cancel_requested AND experiment.validation_phase=phase
+ AND run.id IS NOT NULL AND run.status='completed' AND NOT run.cancel_requested AND run.backtest_id=experiment.backtest_id
+ AND candidate->>'index'=run.trial_index::text AND candidate->>'trialKey'=run.trial_key
+ AND run.request_snapshot=expected_request AND run.dataset_hash=expected_request->>'datasetHash'
+ AND result->>'kind'='canonical-result/v1' AND result->>'status'='completed'
+ AND result->>'financialEngine'='rust' AND result->>'strategyExecution'=(CASE WHEN expected_request#>>'{strategy,origin}'='candidate' THEN 'typescript-isolated-candidate/v1' ELSE 'typescript-retained-builtin/v1' END)
+ AND result->>'runId'=run.id::text AND result->>'backtestId'=run.backtest_id::text AND result->'request'=expected_request
+ AND result#>'{financial,identity}'=jsonb_build_object('version',1,'sessionId',run.id::text,'datasetHash',run.dataset_hash)
+ AND result#>'{financial,policy}'=expected_request->'policy'
+ AND result#>'{analytics,version}'='1'::jsonb AND result#>'{analytics,policy}'=analysis_policy
+ AND jsonb_typeof(result#>'{analytics,metrics}')='object' AND jsonb_typeof(result#>'{analytics,unavailable}')='object'
+ AND jsonb_typeof(result#>'{financial,limitations}')='array' AND jsonb_typeof(result#>'{financial,modelLimitations}')='array') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Validation evidence requires the exact complete uncancelled canonical phase result and policy' USING ERRCODE='23514';
+ END IF;
+ FOR metric IN SELECT * FROM jsonb_each(result#>'{analytics,metrics}') LOOP
+ IF jsonb_typeof(metric.value) NOT IN ('null','number') OR (metric.value='null'::jsonb) IS DISTINCT FROM (result#>'{analytics,unavailable}' ? metric.key) THEN
+ RAISE EXCEPTION 'Validation metric availability must remain truthful' USING ERRCODE='23514';
+ END IF;
+ END LOOP;
+ expected:=jsonb_build_object('phase',phase,'experimentId',phase_experiment_id::text,'runId',run.id::text,
+ 'sourceCandidateIndex',source_index,'trialKey',candidate->'trialKey','parameters',candidate->'parameters',
+ 'datasetHash',run.dataset_hash,'requestHash',item->'requestHash','economicHash',item->'economicHash',
+ 'metrics',result#>'{analytics,metrics}','unavailable',result#>'{analytics,unavailable}',
+ 'completePeriodCount',result#>'{analytics,completePeriodCount}','periodicSampleCount',result#>'{analytics,periodicSampleCount}',
+ 'fillCount',result#>'{analytics,fillCount}','limitations',(result#>'{financial,limitations}')||(result#>'{financial,modelLimitations}'));
+ IF (item=expected AND item->>'requestHash' ~ '^[a-f0-9]{64}$' AND item->>'economicHash' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Validation evidence must copy the precise retained result facts' USING ERRCODE='23514';
+ END IF;
+ IF phase='train' AND jsonb_typeof(result#>'{analytics,metrics,totalReturn}') IS DISTINCT FROM 'number' THEN
+ RAISE EXCEPTION 'Every training return must be a finite available number' USING ERRCODE='23514';
+ END IF;
+ RETURN (result#>>'{analytics,metrics,totalReturn}')::numeric;
+END $$;
diff --git a/database/postgres/init/30-paper-deployments.sql b/database/postgres/init/30-paper-deployments.sql
new file mode 100644
index 00000000..c764b325
--- /dev/null
+++ b/database/postgres/init/30-paper-deployments.sql
@@ -0,0 +1,128 @@
+-- Explicit immutable human authorization; operational state remains in canonical account custody.
+CREATE TABLE IF NOT EXISTS paper_deployments (
+ id UUID PRIMARY KEY, account_id TEXT NOT NULL UNIQUE,
+ strategy_version_id UUID NOT NULL REFERENCES strategy_versions(id),
+ promotion_hash TEXT NOT NULL CHECK (promotion_hash ~ '^[a-f0-9]{64}$'),
+ idempotency_key TEXT NOT NULL UNIQUE CHECK (idempotency_key ~ '^[!-~]{1,200}$'),
+ request_hash TEXT NOT NULL CHECK (request_hash ~ '^[a-f0-9]{64}$'),
+ document JSONB NOT NULL CHECK (jsonb_typeof(document)='object'),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
+);
+
+-- Enumerated normalization only: costs and replay/account clocks may differ, no risk or parameter erasure.
+CREATE OR REPLACE FUNCTION paper_research_profile(request JSONB) RETURNS JSONB LANGUAGE sql IMMUTABLE AS $$
+ SELECT jsonb_build_object(
+ 'strategy',(request->'strategy')-'reviewId',
+ 'policy',(request->'policy') #- '{matching,risk,ledger,sessionId}' #- '{matching,risk,ledger,accountId}'
+ #- '{matching,risk,ledger,riskSession}' #- '{matching,risk,feeRate}' #- '{matching,slippageRate}' #- '{risk_boundaries}',
+ 'build',request->'build','analyticsPolicy',request->'analyticsPolicy','modelArtifacts',request->'modelArtifacts')
+$$;
+
+CREATE OR REPLACE FUNCTION require_paper_deployment() RETURNS trigger LANGUAGE plpgsql AS $$
+DECLARE p JSONB:=NEW.document->'preview'; i JSONB:=p->'input'; s JSONB:=i->'outOfSample';
+ version strategy_versions; family strategies; review strategy_review_events;
+ cost research_experiments; report JSONB; source_hash TEXT; cost_run runs; test_run runs;
+ result backtest_results; item JSONB; expected JSONB; actual_run runs; trial INTEGER:=0;
+BEGIN
+ IF (NEW.document=jsonb_build_object('version','paper-deployment/v1','id',NEW.id::text,'principal','operator',
+ 'createdAt',NEW.document->'createdAt','promotionHash',NEW.promotion_hash,'preview',p)
+ AND jsonb_typeof(NEW.document->'createdAt')='string'
+ AND p->>'version'='paper-promotion-preview/v1' AND p->>'previewHash' ~ '^[a-f0-9]{64}$'
+ AND p->'strategy'->>'versionId'=NEW.strategy_version_id::text
+ AND p#>>'{configuration,matching,risk,ledger,accountId}'=NEW.account_id
+ AND p#>>'{configuration,version}'='2'
+ AND i->'acknowledgeTrustedCode'='true'::jsonb AND length(i->>'reason')>0
+ AND jsonb_typeof(p->'limitations')='array' AND jsonb_typeof(p->'host')='object'
+ AND p->'host'->>'version'='paper-host/v1' AND p->'host'->>'hostSha256' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Paper promotion requires an explicit immutable operator document' USING ERRCODE='23514';
+ END IF;
+ SELECT * INTO version FROM strategy_versions WHERE id=NEW.strategy_version_id;
+ SELECT * INTO family FROM strategies WHERE id=version.strategy_id FOR UPDATE;
+ SELECT * INTO review FROM strategy_review_events WHERE version_id=version.id ORDER BY ordinal DESC LIMIT 1;
+ IF (family.id IS NOT NULL AND family.archived_at IS NULL AND review.decision='approve'
+ AND p#>>'{strategy,familyId}'=family.id::text AND p#>>'{strategy,reviewId}'=review.id::text
+ AND p#>>'{strategy,origin}'=version.origin
+ AND p#>>'{strategy,artifactSha256}'=version.envelope#>>'{artifact,sha256}'
+ AND p#>>'{strategy,dependencyLockSha256}'=version.envelope#>>'{dependencyLock,sha256}') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Paper promotion requires the exact currently approved version' USING ERRCODE='23514';
+ END IF;
+ SELECT * INTO cost FROM research_experiments WHERE id::text=i->>'costExperimentId';
+ IF (cost.id IS NOT NULL AND cost.validation_phase IS NULL AND cost.preview->>'version'='cost-sensitivity-preview/v1'
+ AND cost.preview_hash=i->>'costPreviewHash' AND cost.preview->>'previewHash'=cost.preview_hash) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Paper promotion requires a cost-sensitivity experiment' USING ERRCODE='23514';
+ END IF;
+ IF s->>'kind'='chronological-report/v1' THEN
+ SELECT validation_report,validation_manifest#>>'{source,request,datasetHash}' INTO report,source_hash
+ FROM research_experiments WHERE id::text=s->>'validationId' AND validation_phase='train';
+ IF (report#>>'{test,runId}'=i->>'testRunId') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Paper evidence must select sealed test data' USING ERRCODE='23514';
+ END IF;
+ ELSIF s->>'kind'='walk-forward-report/v1' THEN
+ SELECT w.report,w.preview#>>'{source,request,datasetHash}' INTO report,source_hash FROM research_walk_forwards w WHERE id::text=s->>'walkForwardId';
+ IF NOT EXISTS(SELECT 1 FROM jsonb_array_elements(report->'segments') x WHERE x#>>'{test,runId}'=i->>'testRunId') THEN
+ RAISE EXCEPTION 'Paper evidence must select a sealed walk-forward test' USING ERRCODE='23514';
+ END IF;
+ ELSE RAISE EXCEPTION 'Paper promotion requires an out-of-sample report' USING ERRCODE='23514'; END IF;
+ IF (report->>'id'=s->>'reportId' AND report->>'reportHash'=s->>'reportHash' AND report->>'previewHash'=s->>'previewHash'
+ AND source_hash=cost.preview#>>'{source,request,datasetHash}') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Paper source report or source dataset mismatch' USING ERRCODE='23514';
+ END IF;
+ SELECT * INTO test_run FROM runs WHERE id::text=i->>'testRunId';
+ SELECT * INTO cost_run FROM runs WHERE id::text=i->>'costRunId' AND experiment_id=cost.id;
+ IF (test_run.status='completed' AND cost_run.status='completed'
+ AND test_run.request_snapshot#>>'{strategy,versionId}'=version.id::text
+ AND test_run.request_snapshot#>'{strategy,package}'=version.envelope
+ AND paper_research_profile(test_run.request_snapshot)=paper_research_profile(cost_run.request_snapshot)) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Paper evidence strategies and financial policies must match' USING ERRCODE='23514';
+ END IF;
+ IF EXISTS(SELECT 1 FROM unnest(ARRAY['engineWrapperSha256','engineBinarySha256','dependencyLockSha256','runtime','runtimeVersion','platform','arch']) field
+ WHERE (p->'host'->field=test_run.request_snapshot->'build'->field) IS NOT TRUE) THEN
+ RAISE EXCEPTION 'Paper and research require the same native dependency and runtime build' USING ERRCODE='23514';
+ END IF;
+ expected:=jsonb_build_object('version',2,'matching',cost_run.request_snapshot#>'{policy,matching}',
+ 'strategies',jsonb_build_array(cost_run.request_snapshot#>'{strategy,selection}'),'policy',i#>'{transport,policy}');
+ expected:=jsonb_set(expected,'{matching,risk,ledger,accountId}',i#>'{transport,accountId}');
+ expected:=jsonb_set(expected,'{matching,risk,ledger,sessionId}',i#>'{transport,sessionId}');
+ expected:=jsonb_set(expected,'{matching,risk,ledger,riskSession}',i#>'{transport,riskSession}');
+ expected:=jsonb_set(expected,'{matching,series}',jsonb_build_array(jsonb_build_object('instrumentId',cost_run.request_snapshot#>'{strategy,selection,instrumentId}',
+ 'seriesId',i#>'{transport,quoteSeriesId}','mode','Quote')));
+ IF (p->'configuration'=expected) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Paper configuration may only rebind explicit account and quote/session transport' USING ERRCODE='23514';
+ END IF;
+ IF (jsonb_typeof(p#>'{evidence,costs}')='array'
+ AND jsonb_array_length(p#>'{evidence,costs}')=jsonb_array_length(cost.preview->'candidates')
+ AND (SELECT count(*) FROM runs WHERE experiment_id=cost.id)=jsonb_array_length(cost.preview->'candidates')
+ AND p#>>'{evidence,test,runId}'=test_run.id::text) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Paper evidence must include every cost trial and selected test' USING ERRCODE='23514';
+ END IF;
+ FOR item IN SELECT value FROM jsonb_array_elements(p#>'{evidence,costs}') LOOP
+ SELECT * INTO actual_run FROM runs WHERE experiment_id=cost.id AND trial_index=trial;
+ IF (actual_run.status='completed' AND actual_run.id::text=item->>'runId'
+ AND actual_run.request_snapshot=experiment_trial_request(cost.preview,trial,actual_run.id)
+ AND paper_research_profile(test_run.request_snapshot)=paper_research_profile(actual_run.request_snapshot)) IS NOT TRUE THEN
+ RAISE EXCEPTION 'Paper cost evidence membership is incomplete or incompatible' USING ERRCODE='23514';
+ END IF;
+ trial:=trial+1;
+ END LOOP;
+ FOR item IN SELECT value FROM jsonb_array_elements(jsonb_build_array(p#>'{evidence,test}')||(p#>'{evidence,costs}')) LOOP
+ SELECT * INTO actual_run FROM runs WHERE id::text=item->>'runId';
+ SELECT * INTO result FROM backtest_results WHERE run_id=actual_run.id;
+ IF (result.canonical_result->>'kind'='canonical-result/v1' AND result.canonical_result->'request'=actual_run.request_snapshot
+ AND result.canonical_result#>'{analytics,metrics}'=item->'metrics'
+ AND result.canonical_result#>'{analytics,fillCount}'=item->'fillCount'
+ AND actual_run.dataset_hash=item->>'datasetHash'
+ AND item->>'economicHash' ~ '^[a-f0-9]{64}$' AND item->>'resultHash' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN
+ RAISE EXCEPTION 'Paper promotion requires retained canonical result evidence' USING ERRCODE='23514';
+ END IF;
+ END LOOP;
+ IF EXISTS(SELECT 1 FROM simulation_accounts WHERE id=NEW.account_id) THEN
+ RAISE EXCEPTION 'Choose a new paper account; existing custody cannot be overwritten by promotion' USING ERRCODE='23514';
+ END IF;
+ RETURN NEW;
+END $$;
+DROP TRIGGER IF EXISTS paper_deployment_admission ON paper_deployments;
+CREATE TRIGGER paper_deployment_admission BEFORE INSERT ON paper_deployments FOR EACH ROW EXECUTE FUNCTION require_paper_deployment();
+CREATE OR REPLACE FUNCTION protect_paper_deployment() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN RAISE EXCEPTION 'Paper deployments are immutable; use a new account and promotion' USING ERRCODE='23514'; END $$;
+DROP TRIGGER IF EXISTS paper_deployment_immutable ON paper_deployments;
+CREATE TRIGGER paper_deployment_immutable BEFORE UPDATE OR DELETE ON paper_deployments FOR EACH ROW EXECUTE FUNCTION protect_paper_deployment();
diff --git a/database/postgres/init/31-research-agent-project-links.sql b/database/postgres/init/31-research-agent-project-links.sql
new file mode 100644
index 00000000..f6dde02b
--- /dev/null
+++ b/database/postgres/init/31-research-agent-project-links.sql
@@ -0,0 +1,39 @@
+-- An owned strategy link changes project revision metadata, not project content.
+-- Keep the other SQL28 metadata/ownership guards unchanged.
+CREATE OR REPLACE FUNCTION guard_research_agent_project_metadata() RETURNS trigger
+LANGUAGE plpgsql AS $$
+DECLARE
+ principal TEXT;
+ agent research_agents;
+BEGIN
+ principal := CASE WHEN TG_OP='INSERT' THEN NEW.owner_principal ELSE NEW.updated_by END;
+ IF principal NOT LIKE 'agent:%' THEN RETURN NEW; END IF;
+ SELECT * INTO agent FROM research_agents WHERE id=principal FOR UPDATE;
+ IF NOT FOUND OR NOT agent.enabled THEN
+ RAISE EXCEPTION 'research_access:Research principal is disabled';
+ END IF;
+ IF TG_OP <> 'UPDATE' THEN
+ RAISE EXCEPTION 'research_access:Only an operator provisions research projects';
+ END IF;
+ IF OLD.archived_at IS NOT NULL
+ OR NOT (agent.policy->'allowedProjectIds' ? OLD.id::text)
+ OR (to_jsonb(NEW)-ARRAY['revision','updated_by','updated_at'])
+ IS DISTINCT FROM (to_jsonb(OLD)-ARRAY['revision','updated_by','updated_at'])
+ OR NEW.revision <> OLD.revision+1
+ OR NEW.updated_at < OLD.updated_at
+ OR NOT EXISTS (
+ SELECT 1 FROM research_project_strategies link
+ JOIN strategies strategy ON strategy.id=link.strategy_id
+ WHERE link.project_id=OLD.id AND link.added_by=principal
+ AND strategy.owner_principal=principal
+ ) THEN
+ RAISE EXCEPTION 'research_access:Only owned strategy links may update granted project revision metadata';
+ END IF;
+ INSERT INTO research_agent_audit(agent_id,operation,entity_id)
+ VALUES(principal,'research_projects-link-revision',NEW.id::text);
+ RETURN NEW;
+END $$;
+
+DROP TRIGGER IF EXISTS aa_research_agent_metadata ON research_projects;
+CREATE TRIGGER aa_research_agent_metadata BEFORE INSERT OR UPDATE ON research_projects
+FOR EACH ROW EXECUTE FUNCTION guard_research_agent_project_metadata();
diff --git a/docs/development/architecture/decisions/007-ai-boundary.md b/docs/development/architecture/decisions/007-ai-boundary.md
index 9d838204..5b18ef9c 100644
--- a/docs/development/architecture/decisions/007-ai-boundary.md
+++ b/docs/development/architecture/decisions/007-ai-boundary.md
@@ -10,6 +10,10 @@ Unreviewed code is built/imported/evaluated in an OS-restricted process or conta
Trusted registered/reviewed artifacts can run beside NAPI in a worker for speed. Moving an artifact into that tier requires an explicit operator action, never an AI-supplied trust flag. If the sandbox is unavailable, reject untrusted execution; do not silently downgrade.
+Implementation clarification (A02/A04): the trusted **research** path is limited to server-registered built-ins. Catalog approval never changes a candidate's isolated research execution. A separate immutable human paper-promotion receipt may authorize the exact candidate factory in the paper host after held-out/cost evidence and financial-build parity checks. That action is a deliberate trust decision; paper starts unbound/halted, and live remains unavailable.
+
+The first isolation profile is a local Linux x86_64 Docker scratch image containing the installed Bun runtime, trusted protocol host and independent Rust PID1 guardian. It has no host/data mounts or network, uses cgroup limits and a restricted unprivileged child, and dies on supervisor disconnect or a monotonic deadline. Version the image, host, guardian, runtime and policy in retained requests. A standalone restricted transpiler accepts self-contained TypeScript; no dependency installation, remote build service, JavaScript VM security claim or second simulator is introduced.
+
## Evidence
[Current role model](../../../../libs/core/di/src/http/security.ts#L4) is a small operator boundary, not research isolation. [Current registry dependencies](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7) expose execution services that the new decision API must not expose.
diff --git a/docs/development/architecture/research-product.md b/docs/development/architecture/research-product.md
index 22530735..de97c11b 100644
--- a/docs/development/architecture/research-product.md
+++ b/docs/development/architecture/research-product.md
@@ -110,3 +110,16 @@ Validation reports (R08) are immutable experiment-owned outputs, not research fi
R01 now retains immutable bundled JavaScript and exact dependency locks with source/build metadata. Three tables support editable strategy metadata, immutable versions and append-only reviews. The offline seed command registers only locally packaged built-ins; HTTP uploads/clones remain candidates. Catalog parameter validation never evaluates code, and all versions remain explicitly non-runnable. R02 may deliver catalog/forms before R05, but version-based execution requires R05; arbitrary candidates additionally require A02. Review approval is evidence, not activation. Original TS source and complete run reproducibility remain outside this catalog-only claim.
+
+
+## A04 execution: human-reviewed paper promotion
+
+The `/paper` workflow retains an immutable deployment before any account is bound. Select a sealed chronological or walk-forward **test** run and a fully completed standalone cost study from the same source dataset, strategy version, parameters, risk policy and research build. Review the exact retained code, including AI-originated code, and approve its catalog version separately. Supply a new account/session identity and explicit future feed, intraday observation cadence, risk clock and venue sessions; the platform does not infer them. Financial settings come from the selected saved cost scenario. Preview shows the exact evidence, paper-host identity and limitations; **Create halted deployment** records the promotion without activating trading. An uncertain response freezes the draft: use **Retry same promotion receipt**, which retains the original input and key.
+
+To use an explicit paper host, build the orchestrator with `bun run --cwd apps/stock/orchestrator build` and apply the registered database migrations. Configure `services.orchestrator.defaultMode: paper`, durable PostgreSQL, and `services.orchestrator.paperDeploymentHost: { enabled: true }`; do not also configure `canonicalPaper`. An optional `deploymentId` binds that immutable deployment at startup but never activates it. Keep research workers in their separate research role. This configuration is opt-in; promotion does not change application defaults.
+
+The web API requires an explicitly configured `ORCHESTRATOR_URL`. Both services must enable authentication, share the configured administrator credential (`STOCK_BOT_ADMIN_TOKEN`), and explicitly allow the browser origin through `STOCK_BOT_ALLOWED_ORIGINS`; the orchestrator verifies forwarded operator sessions. The original operator credential and Origin are checked at both ends. Development auth bypass, research-agent credentials and service tokens cannot authorize promotion, binding or activation. A missing host or mismatched origin is an unavailable/error state, never a fallback to service privilege.
+
+Open the saved deployment, **Bind halted host**, connect the trusted feed, inspect readiness/recovery diagnostics, then explicitly **Activate paper**. Recovery of pending work requires the displayed acknowledgment. Restart preserves the same account cash, positions, owner checkpoints and execution journal; it does not recopy historical capital or strategy state. Use **Halt paper** before intervention. Later review revocation blocks new binding/activation but does not halt a running session automatically. Historical evidence and halt remain accessible.
+
+Paper-host, native engine, dependency and runtime artifacts must remain immutable while running. Drift fails closed and requires restart; changed build/evidence requires a newly reviewed deployment and a new account, not an in-place account reset. Research and paper must share the native financial build, while their worker/host bundles have separate identities. Human promotion explicitly permits these exact bytes to run as trusted paper-host code; the research candidate sandbox does not extend to paper. Paper starts from factory state, uses quotes/displayed size rather than historical Open/volume fills, currently accepts one intraday strategy/asset, and has no live broker. Holdouts and cost sensitivity are retained evidence, not a performance guarantee.
diff --git a/libs/core/types/src/strategy-version.ts b/libs/core/types/src/strategy-version.ts
index 5b0bde1d..ea824f09 100644
--- a/libs/core/types/src/strategy-version.ts
+++ b/libs/core/types/src/strategy-version.ts
@@ -22,6 +22,8 @@ export interface StrategyParameterSchema {
/** Retained executable bytes; registration never imports or compiles this content. */
export interface StrategyVersionPackage {
version: 1;
+ /** Required for isolated candidate execution; old packages remain readable. */
+ execution?: { kind: 'isolated-candidate/v1'; warmupBars: number };
program: {
strategyId: string;
strategyVersion: string;
diff --git a/scripts/benchmark-candidate-isolation.ts b/scripts/benchmark-candidate-isolation.ts
new file mode 100644
index 00000000..49fcfec7
--- /dev/null
+++ b/scripts/benchmark-candidate-isolation.ts
@@ -0,0 +1,188 @@
+import { createHash, randomUUID } from 'node:crypto';
+import { readFile } from 'node:fs/promises';
+import { cpus } from 'node:os';
+import { canonicalRunRequestSchema } from '../apps/stock/config/src/contracts/canonical-research';
+import { canonicalStrategyJson } from '../apps/stock/config/src/contracts/strategy';
+import {
+ IsolatedCandidateController,
+ readCandidateExecution,
+} from '../apps/stock/orchestrator/src/backtest/candidate-sandbox';
+import { readCanonicalBuildIdentity } from '../apps/stock/orchestrator/src/backtest/canonical-build';
+import {
+ NativeReplaySession,
+ prepareReplayLoad,
+ runReplaySession,
+ runReplaySessionAsync,
+} from '../apps/stock/orchestrator/src/backtest/native-replay';
+import { importRetainedProgram } from '../apps/stock/orchestrator/src/strategies/retained-program';
+import { StrategyController } from '../apps/stock/orchestrator/src/strategies/strategy-controller';
+import { packageBuiltinStrategies } from '../scripts/package-builtin-strategies';
+import { nativeReplayFixture } from '../test/fixtures/native-replay';
+
+/** A diagnostic paired boundary measurement, not a capacity benchmark or optimization gate. */
+async function measure() {
+ const sharedStarted = performance.now();
+ const bars = 1000,
+ versionId = '20000000-0000-4000-8000-000000000001',
+ runId = '10000000-0000-4000-8000-000000000001',
+ ownerId = `strategy:${versionId}`;
+ const fixture = nativeReplayFixture(bars, 1, [ownerId]);
+ fixture.config.matching.risk.ledger.sessionId = runId;
+ fixture.config.matching.risk.ledger.accountId = `research:${runId}`;
+ const pkg = (await packageBuiltinStrategies()).find(
+ value => value.program.strategyId === 'sma_crossover'
+ );
+ if (!pkg) {
+ throw new Error('Reviewed SMA benchmark package missing');
+ }
+ const request = canonicalRunRequestSchema.parse({
+ kind: 'canonical-research/v1',
+ runId,
+ backtestId: '30000000-0000-4000-8000-000000000001',
+ name: 'Candidate IPC fixture',
+ datasetHash: fixture.dataset.manifest.hash,
+ strategy: {
+ familyId: '40000000-0000-4000-8000-000000000001',
+ versionId,
+ baselineVersionId: '50000000-0000-4000-8000-000000000001',
+ origin: 'candidate',
+ reviewId: null,
+ package: { ...pkg, execution: { kind: 'isolated-candidate/v1', warmupBars: 0 } },
+ execution: await readCandidateExecution(),
+ selection: {
+ ownerId,
+ strategyId: pkg.program.strategyId,
+ strategyVersion: pkg.program.strategyVersion,
+ seed: 17,
+ instrumentId: 'X0.US',
+ seriesId: 'X0.US:1m',
+ ownerBudget: '100',
+ parameters: { fastPeriod: 2, slowPeriod: 3 },
+ },
+ },
+ policy: fixture.config,
+ analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
+ modelArtifacts: [],
+ build: await readCanonicalBuildIdentity(),
+ });
+ const sharedSetupMs = performance.now() - sharedStarted;
+ const runs: Record[] = [];
+ async function trial(mode: 'trusted-fixture' | 'isolated', index: number) {
+ const began = performance.now();
+ let at = began;
+ const load = prepareReplayLoad(fixture.dataset, request.policy);
+ const preparationMs = performance.now() - at;
+ at = performance.now();
+ // This trusted branch imports only the locally authored, reviewed builtin fixture package.
+ // Production research candidates never enter this branch.
+ const controller =
+ mode === 'isolated'
+ ? await IsolatedCandidateController.start(request, `stock-bot-candidate-${randomUUID()}`)
+ : new StrategyController(
+ load.identity,
+ [await importRetainedProgram(request.strategy.package, request.strategy.selection)],
+ load.config
+ );
+ const startupMs = performance.now() - at;
+ at = performance.now();
+ const session = new NativeReplaySession(load);
+ const nativeLoadMs = performance.now() - at;
+ at = performance.now();
+ let result, replayMs: number, cleanupMs: number;
+ try {
+ result =
+ controller instanceof IsolatedCandidateController
+ ? await runReplaySessionAsync(session, controller, { resultFormat: 'report' })
+ : runReplaySession(session, controller, { resultFormat: 'report' });
+ replayMs = performance.now() - at;
+ at = performance.now();
+ if (controller instanceof IsolatedCandidateController) {
+ await controller.finish();
+ await controller.dispose();
+ }
+ cleanupMs = performance.now() - at;
+ } catch (error) {
+ if (controller instanceof IsolatedCandidateController) {
+ await controller.dispose();
+ }
+ throw error;
+ }
+ const totalMs = performance.now() - began;
+ const financialHash = createHash('sha256')
+ .update(canonicalStrategyJson(result.result))
+ .digest('hex');
+ const row = {
+ index,
+ phase: index === 0 ? 'first-pair-in-process' : 'warm-pair',
+ mode,
+ preparationMs,
+ startupMs,
+ nativeLoadMs,
+ replayMs,
+ cleanupMs,
+ totalMs,
+ barsPerReplaySecond: bars / (replayMs / 1000),
+ financialHash,
+ metrics: result.metrics,
+ };
+ runs.push(row);
+ return financialHash;
+ }
+ for (let i = 0; i < 6; i++) {
+ const modes =
+ i % 2 === 0
+ ? (['trusted-fixture', 'isolated'] as const)
+ : (['isolated', 'trusted-fixture'] as const);
+ const one = await trial(modes[0], i),
+ two = await trial(modes[1], i);
+ if (one !== two) {
+ throw Error('Financial parity failed');
+ }
+ }
+ console.log(
+ JSON.stringify(
+ {
+ version: 1,
+ sharedSetupMs,
+ measuredCommandMs: performance.now() - sharedStarted,
+ timingNotes:
+ 'The first pair is first measured in this process, not OS-cold. No caches are flushed. Shared setup includes dataset construction, package generation and descriptor/build preflight; module imports and Bun startup precede measurement. Each trial total excludes shared setup and final hash comparison. This shared-host diagnostic does not certify capacity.',
+ source: {
+ package: pkg.source,
+ artifactHash: pkg.artifact.sha256,
+ dependencyLockHash: pkg.dependencyLock.sha256,
+ harnessSha256: createHash('sha256')
+ .update(await readFile(new URL(import.meta.url)))
+ .digest('hex'),
+ },
+ workload: {
+ bars,
+ assets: 1,
+ strategies: 1,
+ warmPairs: 5,
+ firstPairs: 1,
+ source: 'retained nativeReplayFixture',
+ parameters: request.strategy.selection.parameters,
+ },
+ runtime: {
+ bun: Bun.version,
+ platform: process.platform,
+ arch: process.arch,
+ cpu: cpus()[0]?.model,
+ },
+ datasetHash: request.datasetHash,
+ build: request.build,
+ execution: request.strategy.origin === 'candidate' ? request.strategy.execution : null,
+ runs,
+ },
+ null,
+ 2
+ )
+ );
+}
+if (import.meta.main) {
+ if (process.argv.slice(2).join(' ') !== '--measure') {
+ throw new Error('Usage: bun scripts/benchmark-candidate-isolation.ts --measure');
+ }
+ await measure();
+}
diff --git a/scripts/build-candidate-sandbox.ts b/scripts/build-candidate-sandbox.ts
new file mode 100644
index 00000000..403064a0
--- /dev/null
+++ b/scripts/build-candidate-sandbox.ts
@@ -0,0 +1,119 @@
+/** Build only trusted host/runtime files. No candidate source is evaluated by this script. */
+import { execFile } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { copyFile, mkdir, mkdtemp, readFile, realpath, rm, writeFile } 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,
+} from '../apps/stock/config/src/contracts/candidate-execution';
+
+const execute = promisify(execFile);
+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const dist = join(root, 'apps/stock/orchestrator/dist');
+const digest = async (path: string) =>
+ createHash('sha256')
+ .update(await readFile(path))
+ .digest('hex');
+if (process.platform !== 'linux' || process.arch !== 'x64') {
+ throw new Error('Candidate sandbox currently requires Linux x86_64');
+}
+await mkdir(dist, { recursive: true });
+const host = join(dist, 'candidate-host.js');
+const guardian = join(dist, 'candidate-guardian');
+const built = await Bun.build({
+ entrypoints: [join(root, 'apps/stock/orchestrator/src/backtest/candidate-host.ts')],
+ target: 'bun',
+ minify: false,
+ outdir: dist,
+ naming: '[name].js',
+});
+if (!built.success) {
+ throw new Error(`Candidate host build failed: ${built.logs.join('\n')}`);
+}
+await execute('rustc', [
+ join(root, 'apps/stock/orchestrator/src/backtest/sandbox/guardian.rs'),
+ '--edition=2021',
+ '-O',
+ '-o',
+ guardian,
+]);
+const bun = await realpath(process.execPath);
+const context = await mkdtemp(join(tmpdir(), 'stock-bot-candidate-image-'));
+try {
+ const copy = async (source: string, destination: string) => {
+ const path = join(context, destination);
+ await mkdir(dirname(path), { recursive: true });
+ await copyFile(source, path);
+ };
+ await copy(bun, 'usr/bin/bun');
+ await copy(guardian, 'usr/bin/guardian');
+ await copy(host, 'app/candidate-host.js');
+ const libraries = new Set();
+ for (const binary of [bun, guardian]) {
+ const output = (await execute('/usr/bin/ldd', [binary])).stdout;
+ for (const line of output.split('\n')) {
+ const path = /(?:=>\s+)?(\/[^\s]+)\s+\(/.exec(line)?.[1];
+ if (!path) {
+ if (line.includes('not found')) {
+ throw new Error('Required runtime library is missing');
+ }
+ continue;
+ }
+ if (!/^\/(?:lib(?:64)?|usr\/lib)\//.test(path)) {
+ throw new Error('Runtime library lies outside system libraries');
+ }
+ libraries.add(path);
+ }
+ }
+ for (const library of libraries) {
+ await copy(library, library.replace(/^\//, ''));
+ }
+ await writeFile(
+ join(context, 'Dockerfile'),
+ 'FROM scratch\nCOPY usr/ /usr/\nCOPY lib/ /lib/\nCOPY lib64/ /lib64/\nCOPY app/ /app/\nENTRYPOINT ["/usr/bin/guardian"]\n'
+ );
+ const imageFile = join(context, 'image-id');
+ const dockerConfig = join(context, 'docker-config');
+ await mkdir(dockerConfig, { mode: 0o700 });
+ await execute(
+ '/usr/bin/docker',
+ [
+ '--host',
+ 'unix:///var/run/docker.sock',
+ 'build',
+ '--network=none',
+ '--pull=false',
+ '--iidfile',
+ imageFile,
+ context,
+ ],
+ {
+ env: { PATH: '/usr/bin:/bin', DOCKER_CONFIG: dockerConfig },
+ timeout: 120000,
+ maxBuffer: 1024 * 1024,
+ }
+ );
+ const descriptor = candidateExecutionSchema.parse({
+ kind: 'typescript-isolated-candidate/v1',
+ imageId: (await readFile(imageFile, 'utf8')).trim(),
+ profile: {
+ version: 1,
+ policy: 'linux-docker-guardian/v1',
+ protocol: 'candidate-controller/v1',
+ platform: 'linux',
+ arch: 'x64',
+ hostSha256: await digest(host),
+ guardianSha256: await digest(guardian),
+ bunSha256: await digest(bun),
+ limits: candidateSandboxLimits,
+ },
+ });
+ await writeFile(join(dist, 'candidate-sandbox.json'), JSON.stringify(descriptor, null, 2) + '\n');
+ console.log(JSON.stringify(descriptor));
+} finally {
+ await rm(context, { recursive: true, force: true });
+}
diff --git a/scripts/examples/research-cycle.ts b/scripts/examples/research-cycle.ts
new file mode 100644
index 00000000..d47ae479
--- /dev/null
+++ b/scripts/examples/research-cycle.ts
@@ -0,0 +1,505 @@
+/**
+ * A bounded, sequential research example using only the public research APIs.
+ * The caller supplies prepared bundles; this process never imports candidate code.
+ * Persist every onEvent before returning. On interruption, inspect that journal and
+ * reopen saved IDs. Replay only an exact idempotent intent, never rerun this whole
+ * function blindly: hypothesis, strategy-family and finding creation have no key.
+ * No model SDK, financial calculations, automatic promotion, or trading credentials.
+ */
+import { open, readFile } from 'node:fs/promises';
+import { z } from 'zod';
+import { chronologicalValidationInputSchema } from '@stock-bot/stock-config/chronological-validation';
+import { costSensitivityInputSchema } from '@stock-bot/stock-config/cost-sensitivity';
+import { experimentInputSchema, MAX_EXPERIMENT_TRIALS } from '@stock-bot/stock-config/experiments';
+import { createResearchHypothesisSchema } from '@stock-bot/stock-config/research';
+import { parseStrategyVersionPackage } from '@stock-bot/stock-config/strategy';
+import type { StrategyVersionPackage } from '@stock-bot/types';
+import { ResearchClient, ResearchRequestError } from '../research-client';
+
+const uuid = z
+ .string()
+ .uuid()
+ .transform(value => value.toLowerCase());
+const slug = z.string().regex(/^[a-z0-9-]{1,40}$/);
+const metricNames = ['totalReturn', 'maxDrawdown', 'sharpeRatio'] as const;
+const planSchema = z
+ .object({
+ cycleId: slug,
+ projectId: uuid,
+ backtestId: uuid,
+ /** A caller-approved total, including training, two holdouts and post-validation costs. */
+ maxTotalTrials: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
+ hypothesis: createResearchHypothesisSchema,
+ candidates: z
+ .array(
+ z
+ .object({
+ key: slug,
+ name: z.string().trim().min(1),
+ rationale: z.string().trim().min(1),
+ package: z.unknown().transform(value => parseStrategyVersionPackage(value)),
+ parameters: z.record(z.union([z.string(), z.number().finite(), z.boolean()])),
+ grid: experimentInputSchema.shape.grid,
+ recipe: chronologicalValidationInputSchema.shape.recipe,
+ costScenarios: costSensitivityInputSchema.shape.scenarios,
+ })
+ .strict()
+ )
+ .min(1),
+ })
+ .strict();
+
+export type ResearchCyclePlan = Omit, 'candidates'> & {
+ candidates: (Omit['candidates'][number], 'package'> & {
+ package: StrategyVersionPackage;
+ })[];
+};
+export interface ResearchCycleEvent {
+ cycleId: string;
+ candidateKey: string | null;
+ operation: string;
+ phase: 'intent' | 'accepted' | 'stopped';
+ /** Null means this operation must not be blindly retried after a lost response. */
+ key: string | null;
+ /** Parent resource for endpoint-specific manual replay (never inferred from current state). */
+ resourceId?: string;
+ input: unknown;
+ result?: unknown;
+ error?: string;
+ uncertain?: boolean;
+}
+export class ResearchCycleStopped extends Error {
+ constructor(
+ public readonly event: ResearchCycleEvent,
+ cause: unknown
+ ) {
+ super(
+ `Research cycle stopped at ${event.operation}; inspect persisted receipts before continuing`,
+ { cause }
+ );
+ this.name = 'ResearchCycleStopped';
+ }
+}
+type Experiment = Awaited>;
+type Validation = Awaited>;
+type Finding = Awaited>;
+export interface CandidateResearchOutcome {
+ key: string;
+ strategyId: string;
+ versionId: string;
+ /** The existing ordinary training child, never a full-period preselection backtest. */
+ screening: Experiment | null;
+ validation: Validation | null;
+ costs: Experiment | null;
+ findings: Finding[];
+ stoppedReason: string | null;
+}
+export interface ResearchCycleOptions {
+ /** Await durable receipt storage; throwing stops all subsequent admissions. */
+ onEvent: (event: ResearchCycleEvent) => Promise;
+ poll: { timeoutMs: number; intervalMs?: number };
+ signal?: AbortSignal;
+}
+
+/** Local bounds are early feedback; backend grants/quotas remain authoritative. */
+export function validateResearchCycle(input: ResearchCyclePlan) {
+ const plan = planSchema.parse(input);
+ if (new Set(plan.candidates.map(candidate => candidate.key)).size !== plan.candidates.length) {
+ throw new Error('Candidate keys must be unique');
+ }
+ let totalTrials = 0;
+ const counts = plan.candidates.map(candidate => {
+ if (candidate.package.execution?.kind !== 'isolated-candidate/v1') {
+ throw new Error('Prepare an explicitly isolated candidate package');
+ }
+ const gridCount = Object.values(candidate.grid).reduce(
+ (count, values) => count * values.length,
+ 1
+ );
+ const costs = candidate.costScenarios.length + 1; // Server always includes the baseline.
+ if (!Number.isSafeInteger(gridCount) || gridCount > MAX_EXPERIMENT_TRIALS) {
+ throw new Error('Parameter grid exceeds the experiment trial bound');
+ }
+ totalTrials += gridCount + 2 + costs;
+ return { training: gridCount, holdouts: 2, costs };
+ });
+ if (!Number.isSafeInteger(totalTrials) || totalTrials > plan.maxTotalTrials) {
+ throw new Error('Research cycle exceeds its caller-approved total trial bound');
+ }
+ return { plan, counts, totalTrials };
+}
+
+export async function runResearchCycle(
+ client: ResearchClient,
+ input: ResearchCyclePlan,
+ options: ResearchCycleOptions
+) {
+ // Capture all proposals before any performance evidence is read. Later caller edits
+ // cannot adapt the next candidate to a holdout exposed by an earlier one.
+ const { plan, counts, totalTrials } = validateResearchCycle(input);
+ const poll = {
+ ...z
+ .object({
+ timeoutMs: z.number().int().positive().max(2147483647),
+ intervalMs: z.number().int().positive().max(2147483647).optional(),
+ })
+ .strict()
+ .parse(options.poll),
+ signal: options.signal,
+ };
+ const assertActive = () => options.signal?.throwIfAborted();
+ assertActive();
+ const budget = await client.budget(options.signal);
+ if (
+ !budget.agent.enabled ||
+ !budget.agent.allowedProjectIds.includes(plan.projectId) ||
+ !budget.agent.grants.some(
+ grant => grant.backtestId === plan.backtestId && grant.allowOwnCandidates
+ )
+ ) {
+ throw new Error('An enabled agent needs explicit project and own-candidate template grants');
+ }
+ if (
+ counts.some(
+ count =>
+ Math.max(count.training, count.holdouts, count.costs) >
+ Math.min(budget.agent.limits.maxTrialsPerExperiment, budget.agent.limits.maxActiveTrials)
+ )
+ ) {
+ throw new Error('A planned admission exceeds the agent trial budget');
+ }
+ async function write(
+ candidateKey: string | null,
+ operation: string,
+ body: unknown,
+ invoke: () => Promise,
+ suffix?: string,
+ resourceId?: string
+ ): Promise {
+ assertActive();
+ const event: ResearchCycleEvent = {
+ cycleId: plan.cycleId,
+ candidateKey,
+ operation,
+ phase: 'intent',
+ key: suffix ? `${plan.cycleId}:${candidateKey ?? 'cycle'}:${suffix}` : null,
+ input: structuredClone(body),
+ ...(resourceId ? { resourceId } : {}),
+ };
+ await options.onEvent(structuredClone(event));
+ assertActive();
+ try {
+ const result = await invoke();
+ const accepted = { ...event, phase: 'accepted' as const, result: structuredClone(result) };
+ try {
+ await options.onEvent(accepted);
+ } catch (error) {
+ throw new ResearchCycleStopped(accepted, error);
+ }
+ return result;
+ } catch (error) {
+ if (error instanceof ResearchCycleStopped) {
+ throw error;
+ }
+ const stopped: ResearchCycleEvent = {
+ ...event,
+ phase: 'stopped',
+ error: error instanceof Error ? error.message : String(error),
+ uncertain: error instanceof ResearchRequestError ? error.uncertain : true,
+ };
+ await options.onEvent(stopped);
+ throw new ResearchCycleStopped(stopped, error);
+ }
+ }
+ const key = (candidateKey: string, suffix: string) => `${plan.cycleId}:${candidateKey}:${suffix}`;
+ const hypothesisInput = { ...plan.hypothesis, contentOrigin: 'ai' as const };
+ const hypothesis = await write(
+ null,
+ 'create-hypothesis',
+ hypothesisInput,
+ () => client.createHypothesis(plan.projectId, hypothesisInput),
+ undefined,
+ plan.projectId
+ );
+ const outcomes: CandidateResearchOutcome[] = [];
+ for (const candidate of plan.candidates) {
+ const familyInput = { name: candidate.name, description: candidate.rationale };
+ const family = await write(candidate.key, 'create-strategy', familyInput, () =>
+ client.createStrategy(familyInput)
+ );
+ await write(
+ candidate.key,
+ 'link-strategy',
+ { projectId: plan.projectId, strategyId: family.id },
+ () => client.linkStrategy(plan.projectId, family.id)
+ );
+ const version = await write(
+ candidate.key,
+ 'publish-version',
+ { strategyId: family.id, package: candidate.package, parentVersionId: null },
+ () => client.publishVersion(family.id, candidate.package, key(candidate.key, 'version')),
+ 'version',
+ family.id
+ );
+ const validationPreview = await client.previewValidation(
+ {
+ backtestId: plan.backtestId,
+ name: `${candidate.name} · chronological`,
+ candidate: { versionId: version.id, parameters: candidate.parameters },
+ grid: candidate.grid,
+ recipe: candidate.recipe,
+ },
+ options.signal
+ );
+ const validationInput = {
+ ...validationPreview.input,
+ previewHash: validationPreview.previewHash,
+ };
+ const validation = await write(
+ candidate.key,
+ 'submit-training',
+ validationInput,
+ () => client.submitValidation(validationInput, key(candidate.key, 'training')),
+ 'training'
+ );
+ const training = await client.waitForValidation(validation.id, poll);
+ const screening = training.phases.find(phase => phase.phase === 'train')?.experiment ?? null;
+ const outcome: CandidateResearchOutcome = {
+ key: candidate.key,
+ strategyId: family.id,
+ versionId: version.id,
+ screening,
+ validation: training,
+ costs: null,
+ findings: [],
+ stoppedReason: null,
+ };
+ outcomes.push(outcome);
+ if (
+ !screening ||
+ screening.trials.length !== screening.trialCount ||
+ screening.trials.some(trial => trial.status !== 'completed' || !trial.comparable)
+ ) {
+ outcome.stoppedReason =
+ 'Training contains failed, cancelled, missing, or incomparable trials; no selection or performance claim was made.';
+ continue;
+ }
+ if (!training.actions.select.available) {
+ outcome.stoppedReason =
+ training.actions.select.reason ?? 'Training is not eligible for selection';
+ continue;
+ }
+ // The server freezes the winner using training evidence only. Never rank holdouts here.
+ const selectInput = { previewHash: validation.previewHash };
+ const selected = await write(
+ candidate.key,
+ 'select-training-and-admit-holdouts',
+ selectInput,
+ () =>
+ client.advanceValidation(
+ validation.id,
+ 'select',
+ selectInput,
+ key(candidate.key, 'select')
+ ),
+ 'select',
+ validation.id
+ );
+ outcome.validation = await client.waitForValidation(validation.id, poll);
+ if (!outcome.validation.actions.finalize.available || !selected.validation.selection) {
+ outcome.stoppedReason =
+ outcome.validation.actions.finalize.reason ??
+ 'Holdouts are not eligible for a sealed report';
+ continue;
+ }
+ const finalizeInput = {
+ previewHash: validation.previewHash,
+ selectionHash: selected.validation.selection.selectionHash,
+ };
+ const finalized = await write(
+ candidate.key,
+ 'finalize-report',
+ finalizeInput,
+ () =>
+ client.advanceValidation(
+ validation.id,
+ 'finalize',
+ finalizeInput,
+ key(candidate.key, 'finalize')
+ ),
+ 'finalize',
+ validation.id
+ );
+ outcome.validation = finalized.validation;
+ const report = finalized.validation.report;
+ if (!report) {
+ throw new Error('Finalization returned no report');
+ }
+ const evidence = [report.validation, report.test].flatMap(run =>
+ metricNames.map(metric => ({
+ runId: run.runId,
+ strategyVersionId: version.id,
+ metricsVersion: 'canonical-analytics/v1' as const,
+ metricPath: `analytics.metrics.${metric}` as `analytics.metrics.${typeof metric}`,
+ }))
+ );
+ const findingInput = {
+ kind: 'finding' as const,
+ hypothesisRevisionId: hypothesis.latestRevision.id,
+ title: `${candidate.name} · chronological evidence`,
+ body: `${candidate.rationale}\nAI-generated interpretation, unvalidated. The winner was selected using training only. Validation is diagnostic; test is held out. Candidate determinism and absence of fitting are unverified. Regime attribution is unavailable: no retained as-of regime labels. Independent reset accounts are not a continuous portfolio.`,
+ source: {
+ kind: 'chronological-report/v1' as const,
+ validationId: validation.id,
+ previewHash: validation.previewHash,
+ reportId: report.id,
+ reportHash: report.reportHash,
+ },
+ evidence,
+ };
+ const finding = await write(
+ candidate.key,
+ 'save-chronological-finding',
+ findingInput,
+ () => client.saveFinding(plan.projectId, findingInput),
+ undefined,
+ plan.projectId
+ );
+ // Compare copied server evidence only; never derive a second financial calculation.
+ for (const item of finding.latestRevision.evidence) {
+ const source = [report.validation, report.test].find(run => run.runId === item.runId);
+ const metric = metricNames.find(name => item.metricPath === `analytics.metrics.${name}`);
+ if (
+ !source ||
+ !metric ||
+ item.datasetHash !== source.datasetHash ||
+ item.value !== source.metrics[metric] ||
+ item.unavailableReason !==
+ (source.metrics[metric] === null ? (source.unavailable[metric] ?? 'not-reported') : null)
+ ) {
+ const mismatch: ResearchCycleEvent = {
+ cycleId: plan.cycleId,
+ candidateKey: candidate.key,
+ operation: 'verify-finding-evidence',
+ phase: 'stopped',
+ key: null,
+ input: findingInput,
+ result: finding,
+ error: 'Saved evidence differs from its sealed report',
+ };
+ await options.onEvent(mismatch);
+ throw new ResearchCycleStopped(mismatch, new Error('Evidence mismatch'));
+ }
+ }
+ outcome.findings.push(finding);
+ const costPreview = await client.previewCosts(
+ {
+ backtestId: plan.backtestId,
+ name: `${candidate.name} · costs`,
+ candidate: {
+ versionId: version.id,
+ parameters: selected.validation.selection.winner.parameters,
+ },
+ scenarios: candidate.costScenarios,
+ },
+ options.signal
+ );
+ const costInput = { ...costPreview.input, previewHash: costPreview.previewHash };
+ const costs = await write(
+ candidate.key,
+ 'submit-cost-sensitivity',
+ costInput,
+ () => client.submitCosts(costInput, key(candidate.key, 'costs')),
+ 'costs'
+ );
+ outcome.costs = await client.waitForExperiment(costs.id, poll);
+ }
+ // Chronological children retain their own report workflow. Compare only the existing
+ // standalone post-validation cost studies; this read-only comparison never ranks candidates.
+ const [left, right] = outcomes;
+ const comparison =
+ left?.costs && right?.costs
+ ? await client.compareExperiments(
+ {
+ leftId: left.costs.id,
+ rightId: right.costs.id,
+ },
+ options.signal
+ )
+ : null;
+ return {
+ cycleId: plan.cycleId,
+ totalPlannedTrials: totalTrials,
+ hypothesis,
+ outcomes,
+ comparison,
+ regimeAttribution: 'unavailable: no retained as-of regime labels' as const,
+ };
+}
+
+/**
+ * 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
+ * A fresh journal is mandatory. Existing journals require explicit inspection/recovery,
+ * not restarting non-idempotent writes. Prepared-plan JSON contains retained package bytes.
+ */
+if (import.meta.main) {
+ try {
+ const args = process.argv.slice(2);
+ if (
+ args.length !== 4 ||
+ args[0] !== '--plan' ||
+ !args[1] ||
+ args[2] !== '--receipts' ||
+ !args[3]
+ ) {
+ throw new Error(
+ 'Usage: research-cycle.ts --plan --receipts '
+ );
+ }
+ const input: ResearchCyclePlan = JSON.parse(await readFile(args[1], 'utf8'));
+ validateResearchCycle(input);
+ const client = new ResearchClient({
+ origin: process.env.RESEARCH_API_ORIGIN ?? '',
+ token: process.env.RESEARCH_API_TOKEN ?? '',
+ });
+ const journal = await open(args[3], 'wx', 0o600);
+ try {
+ const result = await runResearchCycle(client, input, {
+ poll: { timeoutMs: 300000 },
+ onEvent: async event => {
+ await journal.writeFile(JSON.stringify(event) + '\n');
+ await journal.sync();
+ },
+ });
+ console.log(
+ JSON.stringify(
+ {
+ cycleId: result.cycleId,
+ hypothesisId: result.hypothesis.id,
+ outcomes: result.outcomes.map(outcome => ({
+ key: outcome.key,
+ versionId: outcome.versionId,
+ experimentId: outcome.screening?.id ?? null,
+ counts: outcome.screening?.counts ?? null,
+ validationId: outcome.validation?.id ?? null,
+ reportId: outcome.validation?.report?.id ?? null,
+ costExperimentId: outcome.costs?.id ?? null,
+ costCounts: outcome.costs?.counts ?? null,
+ findingIds: outcome.findings.map(finding => finding.id),
+ stoppedReason: outcome.stoppedReason,
+ })),
+ regimeAttribution: result.regimeAttribution,
+ },
+ null,
+ 2
+ )
+ );
+ } finally {
+ await journal.close();
+ }
+ } catch (error) {
+ console.error(error instanceof Error ? error.message : String(error));
+ process.exitCode = 1;
+ }
+}
diff --git a/scripts/package-candidate-strategy.ts b/scripts/package-candidate-strategy.ts
new file mode 100644
index 00000000..a2ce5451
--- /dev/null
+++ b/scripts/package-candidate-strategy.ts
@@ -0,0 +1,88 @@
+/** Candidate TypeScript transformation occurs only in the pinned OS sandbox.
+ * CLI: bun scripts/package-candidate-strategy.ts metadata.json strategy.ts > package.json
+ * Metadata supplies program/parameterSchema/execution/source. No dependency install or code evaluation. */
+import { createHash, randomUUID } from 'node:crypto';
+import { readFile } from 'node:fs/promises';
+import { resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { z } from 'zod';
+import type { StrategyVersionPackage } from '@stock-bot/types';
+import { candidatePackageExecutionSchema } from '../apps/stock/config/src/contracts/candidate-execution';
+import {
+ assertStrategyJsonText,
+ parseStrategyVersionPackage,
+} from '../apps/stock/config/src/contracts/strategy';
+import { IsolatedCandidateController } from '../apps/stock/orchestrator/src/backtest/candidate-sandbox';
+
+const hash = (value: string) => createHash('sha256').update(value, 'utf8').digest('hex');
+/** This function reads source as data; the container owns the TS compiler. Computed/eval imports
+ * cannot be proven absent by static scanning; runtime OS isolation remains authoritative. */
+export async function packageCandidateStrategy(
+ metadata: unknown,
+ source: string
+): Promise {
+ assertStrategyJsonText(metadata);
+ const raw = z
+ .object({
+ program: z.unknown(),
+ parameterSchema: z.unknown(),
+ execution: candidatePackageExecutionSchema,
+ source: z.unknown(),
+ entryExport: z.string().regex(/^[A-Za-z_$][\w$]*$/),
+ })
+ .strict()
+ .parse(metadata);
+ // Validate inert declarations before allocating an isolated process.
+ const dependencyLock = await readFile(
+ fileURLToPath(new URL('../bun.lock', import.meta.url)),
+ 'utf8'
+ );
+ const preliminary = parseStrategyVersionPackage({
+ version: 1,
+ program: raw.program,
+ parameterSchema: raw.parameterSchema,
+ execution: raw.execution,
+ source: raw.source,
+ artifact: {
+ format: 'esm-bundle/v1',
+ entryExport: raw.entryExport,
+ content: source,
+ sha256: hash(source),
+ },
+ dependencyLock: {
+ format: 'bun-lock/v1',
+ content: dependencyLock,
+ sha256: hash(dependencyLock),
+ },
+ build: { tool: 'bun', version: Bun.version, target: 'browser' },
+ });
+ const transformed = await IsolatedCandidateController.transpile(
+ source,
+ `stock-bot-candidate-${randomUUID()}`
+ );
+ return parseStrategyVersionPackage({
+ ...preliminary,
+ artifact: {
+ ...preliminary.artifact,
+ content: transformed.content,
+ sha256: hash(transformed.content),
+ },
+ build: { tool: 'bun', version: transformed.runtimeVersion, target: 'browser' },
+ });
+}
+if (import.meta.main) {
+ const [metadataPath, sourcePath, ...extra] = process.argv.slice(2);
+ if (!metadataPath || !sourcePath || extra.length) {
+ throw new Error('Usage: package-candidate-strategy.ts metadata.json strategy.ts');
+ }
+ console.log(
+ JSON.stringify(
+ await packageCandidateStrategy(
+ JSON.parse(await readFile(resolve(metadataPath), 'utf8')),
+ await readFile(resolve(sourcePath), 'utf8')
+ ),
+ null,
+ 2
+ )
+ );
+}
diff --git a/scripts/research-client.ts b/scripts/research-client.ts
new file mode 100644
index 00000000..aff2e9dd
--- /dev/null
+++ b/scripts/research-client.ts
@@ -0,0 +1,863 @@
+/** Authorized research API client. No strategy import, financial simulation, or trading controls. */
+import { z } from 'zod';
+import {
+ chronologicalValidationInputSchema,
+ chronologicalValidationSubmissionSchema,
+ type ChronologicalValidationInput,
+ type ChronologicalValidationSubmission,
+} from '@stock-bot/stock-config/chronological-validation';
+import {
+ costSensitivityInputSchema,
+ costSensitivitySubmissionSchema,
+ type CostSensitivityInput,
+ type CostSensitivitySubmission,
+} from '@stock-bot/stock-config/cost-sensitivity';
+import {
+ experimentComparisonInputSchema,
+ type ExperimentComparisonInput,
+} from '@stock-bot/stock-config/experiment-comparison';
+import {
+ experimentInputSchema,
+ experimentSubmissionSchema,
+ type ExperimentInput,
+ type ExperimentSubmission,
+} from '@stock-bot/stock-config/experiments';
+import {
+ createResearchArtifactSchema,
+ createResearchHypothesisSchema,
+ researchActorSchema,
+ researchEvidenceReferenceSchema,
+ researchFindingSourceSchema,
+} from '@stock-bot/stock-config/research';
+import {
+ researchAgentBudgetSchema,
+ researchAgentIdSchema,
+} from '@stock-bot/stock-config/research-agents';
+import {
+ parseChronologicalValidationPreview,
+ parseCostSensitivityPreview,
+ parseExperimentComparison,
+ parseExperimentDetail,
+ parseExperimentPreview,
+ parseValidationDetail,
+ parseWalkForwardDetail,
+ parseWalkForwardPreview,
+ parseWorkbenchExperimentDetail,
+ validationReceiptSchema,
+ type ValidationDetailView,
+ type WorkbenchExperimentDetailView,
+} from '@stock-bot/stock-config/research-responses';
+import {
+ canonicalStrategyJson,
+ parseStrategyVersionPackage,
+} from '@stock-bot/stock-config/strategy';
+import {
+ walkForwardInputSchema,
+ walkForwardSubmissionSchema,
+ type WalkForwardInput,
+ type WalkForwardSubmission,
+} from '@stock-bot/stock-config/walk-forward';
+import type { StrategyVersionPackage } from '@stock-bot/types';
+
+const uuid = z
+ .string()
+ .uuid()
+ .transform(value => value.toLowerCase());
+const hash = z.string().regex(/^[a-f0-9]{64}$/);
+const keySchema = z.string().regex(/^[\x21-\x7e]{1,200}$/);
+const object = z.record(z.unknown());
+const id = (value: string) => encodeURIComponent(uuid.parse(value));
+const same = (a: unknown, b: unknown) => canonicalStrategyJson(a) === canonicalStrategyJson(b);
+const expect = (condition: unknown): void => {
+ if (!condition) {
+ throw new Error('Research response does not match the requested identity');
+ }
+};
+const envelope = (body: unknown, field: string) => object.parse(body)[field];
+const strategyRecord = z.object({
+ id: uuid,
+ name: z.string(),
+ description: z.string(),
+ ownerPrincipal: researchAgentIdSchema,
+ archived: z.boolean(),
+});
+const versionRecord = z.object({
+ id: uuid,
+ strategyId: uuid,
+ ordinal: z.number().int().positive(),
+ origin: z.enum(['candidate', 'builtin']),
+ createdBy: researchAgentIdSchema,
+ parentVersionId: uuid.nullable(),
+ package: z.object({
+ artifact: z.object({ sha256: hash }),
+ dependencyLock: z.object({ sha256: hash }),
+ }),
+});
+const hypothesisRecord = z.object({
+ id: uuid,
+ projectId: uuid,
+ latestRevision: z.object({
+ id: uuid,
+ ordinal: z.number().int().positive(),
+ title: z.string(),
+ proposition: z.string(),
+ validationCriteria: z.string(),
+ contentOrigin: z.literal('ai'),
+ submittedBy: researchAgentIdSchema,
+ validationState: z.literal('unvalidated'),
+ }),
+});
+const findingRecord = z.object({
+ id: uuid,
+ projectId: uuid,
+ hypothesisRevisionId: uuid.nullable(),
+ kind: z.enum(['note', 'finding']),
+ latestRevision: z.object({
+ id: uuid,
+ title: z.string(),
+ body: z.string(),
+ contentOrigin: z.literal('ai'),
+ submittedBy: researchAgentIdSchema,
+ validationState: z.literal('unvalidated'),
+ evidenceState: z.enum(['none', 'referenced']),
+ source: researchFindingSourceSchema.nullable(),
+ evidence: z.array(
+ z
+ .object({
+ runId: uuid,
+ strategyVersionId: uuid.nullable().optional(),
+ metricsVersion: z.literal('canonical-analytics/v1'),
+ metricPath: z.string(),
+ value: z.number().finite().nullable(),
+ availability: z.enum(['available', 'unavailable']),
+ unavailableReason: z.string().nullable(),
+ datasetHash: hash,
+ resultKind: z.literal('canonical'),
+ financialEngine: z.literal('rust'),
+ limitations: z.array(z.object({ code: z.string(), message: z.string() })),
+ })
+ .refine(
+ metric =>
+ metric.availability === 'available'
+ ? metric.value !== null && metric.unavailableReason === null
+ : metric.value === null &&
+ typeof metric.unavailableReason === 'string' &&
+ metric.unavailableReason.trim().length > 0,
+ 'Metric availability must match its value and reason'
+ )
+ ),
+ }),
+});
+
+export class ResearchRequestError extends Error {
+ constructor(
+ message: string,
+ public readonly status: number | null,
+ /** A mutation may have committed. Reuse its exact receipt; never generate a new one blindly. */
+ public readonly uncertain: boolean,
+ public readonly operation: string
+ ) {
+ super(message);
+ this.name = 'ResearchRequestError';
+ }
+}
+export class ResearchWaitExpired extends Error {
+ constructor(public readonly last: T | null) {
+ super('Research polling deadline reached; accepted jobs remain saved and can be reopened');
+ this.name = 'ResearchWaitExpired';
+ }
+}
+export interface PollOptions {
+ timeoutMs: number;
+ intervalMs?: number;
+ signal?: AbortSignal;
+ onUpdate?: (value: T) => void;
+}
+type ClientOptions = {
+ origin: string;
+ token: string;
+ fetch?: typeof fetch;
+ requestTimeoutMs?: number;
+};
+type HypothesisInput = z.input;
+type FindingInput = z.input;
+
+/** The backend is authoritative for grants, quotas, evidence, and financial constraints. */
+export class ResearchClient {
+ readonly #origin: string;
+ readonly #token: string;
+ readonly #fetch: typeof fetch;
+ readonly #timeout: number;
+
+ constructor(options: ClientOptions) {
+ const origin = new URL(options.origin);
+ if (
+ !['https:', 'http:'].includes(origin.protocol) ||
+ origin.username ||
+ origin.password ||
+ origin.search ||
+ origin.hash ||
+ origin.pathname !== '/' ||
+ (origin.protocol === 'http:' &&
+ !['localhost', '127.0.0.1', '[::1]'].includes(origin.hostname))
+ ) {
+ throw new Error('Use an HTTPS API origin or local loopback HTTP origin without a path');
+ }
+ if (!/^sb-research\.[A-Za-z0-9_-]+$/.test(options.token)) {
+ throw new Error('A research-only credential is required');
+ }
+ this.#origin = origin.origin;
+ this.#token = options.token;
+ this.#fetch = options.fetch ?? globalThis.fetch;
+ this.#timeout = z
+ .number()
+ .int()
+ .positive()
+ .max(2147483647)
+ .parse(options.requestTimeoutMs ?? 30000);
+ }
+
+ async #request(
+ path: string,
+ method: 'GET' | 'POST' | 'PUT',
+ status: number,
+ parse: (body: unknown) => T,
+ body?: unknown,
+ key?: string,
+ signal?: AbortSignal
+ ): Promise {
+ const operation = `${method} ${path}`;
+ const mutation = method !== 'GET';
+ if (key !== undefined) {
+ keySchema.parse(key);
+ }
+ // Capture once. A caller changing its draft while awaiting IO cannot change this request.
+ const bytes = body === undefined ? undefined : JSON.stringify(body);
+ const deadline = timedSignal(this.#timeout);
+ const requestSignal = signal ? AbortSignal.any([signal, deadline.signal]) : deadline.signal;
+ try {
+ let response: Response;
+ try {
+ response = await abortable(
+ () =>
+ this.#fetch(`${this.#origin}/api/v2/${path}`, {
+ method,
+ body: bytes,
+ redirect: 'error',
+ credentials: 'omit',
+ headers: {
+ Authorization: `Bearer ${this.#token}`,
+ 'Content-Type': 'application/json',
+ ...(key === undefined ? {} : { 'Idempotency-Key': key }),
+ },
+ signal: requestSignal,
+ }),
+ requestSignal
+ );
+ } catch {
+ throw new ResearchRequestError(
+ 'Research response lost or aborted. Reopen saved work before resubmitting.',
+ null,
+ mutation,
+ operation
+ );
+ }
+ const payload: unknown =
+ response.status === 204
+ ? undefined
+ : await abortable(() => response.json(), requestSignal).catch(() => undefined);
+ if (!response.ok) {
+ const error = z.object({ error: z.string() }).safeParse(payload);
+ throw new ResearchRequestError(
+ error.success ? error.data.error : `Research request failed (${response.status})`,
+ response.status,
+ mutation && response.status >= 500,
+ operation
+ );
+ }
+ try {
+ expect(response.status === status);
+ return parse(payload);
+ } catch {
+ throw new ResearchRequestError(
+ 'Research response identity or evidence could not be verified',
+ null,
+ mutation,
+ operation
+ );
+ }
+ } finally {
+ deadline.dispose();
+ }
+ }
+
+ budget(signal?: AbortSignal) {
+ return this.#request(
+ 'research-agent/budget',
+ 'GET',
+ 200,
+ value => researchAgentBudgetSchema.parse(value),
+ undefined,
+ undefined,
+ signal
+ );
+ }
+ compareExperiments(input: ExperimentComparisonInput, signal?: AbortSignal) {
+ const normalized = experimentComparisonInputSchema.parse(input);
+ return this.#request(
+ `experiments/compare?${new URLSearchParams(normalized)}`,
+ 'GET',
+ 200,
+ value => parseExperimentComparison(envelope(value, 'comparison'), normalized),
+ undefined,
+ undefined,
+ signal
+ );
+ }
+ createHypothesis(projectId: string, input: HypothesisInput) {
+ projectId = uuid.parse(projectId);
+ const body = createResearchHypothesisSchema.parse({ ...input, contentOrigin: 'ai' });
+ return this.#request(
+ `research-projects/${id(projectId)}/hypotheses`,
+ 'POST',
+ 201,
+ value => {
+ const saved = hypothesisRecord.parse(envelope(value, 'hypothesis'));
+ expect(
+ saved.projectId === projectId &&
+ same(
+ {
+ title: saved.latestRevision.title,
+ proposition: saved.latestRevision.proposition,
+ validationCriteria: saved.latestRevision.validationCriteria,
+ contentOrigin: saved.latestRevision.contentOrigin,
+ },
+ body
+ )
+ );
+ return saved;
+ },
+ body
+ );
+ }
+ createStrategy(input: { name: string; description: string }) {
+ const body = z
+ .object({ name: z.string().trim().min(1), description: z.string() })
+ .strict()
+ .parse(input);
+ return this.#request(
+ 'strategies',
+ 'POST',
+ 201,
+ value => {
+ const saved = strategyRecord.parse(envelope(value, 'strategy'));
+ expect(saved.name === body.name && saved.description === body.description);
+ return saved;
+ },
+ body
+ );
+ }
+ linkStrategy(projectId: string, strategyId: string) {
+ projectId = uuid.parse(projectId);
+ strategyId = uuid.parse(strategyId);
+ return this.#request(
+ `research-projects/${id(projectId)}/strategies/${id(strategyId)}`,
+ 'PUT',
+ 204,
+ () => undefined
+ );
+ }
+ publishVersion(
+ strategyId: string,
+ input: StrategyVersionPackage,
+ key: string,
+ parentVersionId: string | null = null
+ ) {
+ strategyId = uuid.parse(strategyId);
+ const pkg = parseStrategyVersionPackage(input);
+ if (parentVersionId !== null) {
+ parentVersionId = uuid.parse(parentVersionId);
+ }
+ return this.#request(
+ `strategies/${id(strategyId)}/versions`,
+ 'POST',
+ 201,
+ value => {
+ const saved = versionRecord.parse(envelope(value, 'version'));
+ expect(
+ saved.strategyId === strategyId &&
+ saved.origin === 'candidate' &&
+ saved.parentVersionId === parentVersionId &&
+ saved.package.artifact.sha256 === pkg.artifact.sha256 &&
+ saved.package.dependencyLock.sha256 === pkg.dependencyLock.sha256
+ );
+ return saved;
+ },
+ { package: pkg, parentVersionId },
+ key
+ );
+ }
+ previewExperiment(input: ExperimentInput, signal?: AbortSignal) {
+ const body = experimentInputSchema.parse({
+ ...input,
+ backtestId: uuid.parse(input.backtestId),
+ });
+ return this.#request(
+ 'experiments/preview',
+ 'POST',
+ 200,
+ value => {
+ const preview = parseExperimentPreview(envelope(value, 'preview'));
+ expect(same(preview.input, body));
+ return preview;
+ },
+ body,
+ undefined,
+ signal
+ );
+ }
+ submitExperiment(input: ExperimentSubmission, key: string) {
+ const body = experimentSubmissionSchema.parse({
+ ...input,
+ backtestId: uuid.parse(input.backtestId),
+ });
+ return this.#request(
+ 'experiments',
+ 'POST',
+ 202,
+ value => {
+ const saved = parseExperimentDetail(envelope(value, 'experiment'));
+ const { previewHash, ...original } = body;
+ expect(saved.previewHash === previewHash && same(saved.preview.input, original));
+ return saved;
+ },
+ body,
+ key
+ );
+ }
+ experiment(experimentId: string, signal?: AbortSignal) {
+ experimentId = uuid.parse(experimentId);
+ return this.#request(
+ `experiments/${id(experimentId)}`,
+ 'GET',
+ 200,
+ value => {
+ const saved = parseWorkbenchExperimentDetail(envelope(value, 'experiment'));
+ expect(saved.id === experimentId);
+ return saved;
+ },
+ undefined,
+ undefined,
+ signal
+ );
+ }
+ cancelExperiment(experimentId: string) {
+ experimentId = uuid.parse(experimentId);
+ return this.#request(
+ `experiments/${id(experimentId)}/cancel`,
+ 'POST',
+ 200,
+ value => {
+ const saved = parseWorkbenchExperimentDetail(envelope(value, 'experiment'));
+ expect(saved.id === experimentId && saved.cancelRequested);
+ return saved;
+ },
+ {}
+ );
+ }
+ previewCosts(input: CostSensitivityInput, signal?: AbortSignal) {
+ const body = costSensitivityInputSchema.parse({
+ ...input,
+ backtestId: uuid.parse(input.backtestId),
+ });
+ return this.#request(
+ 'experiments/cost-sensitivity/preview',
+ 'POST',
+ 200,
+ value => {
+ const preview = parseCostSensitivityPreview(envelope(value, 'preview'));
+ expect(same(preview.input, body));
+ return preview;
+ },
+ body,
+ undefined,
+ signal
+ );
+ }
+ submitCosts(input: CostSensitivitySubmission, key: string) {
+ const body = costSensitivitySubmissionSchema.parse({
+ ...input,
+ backtestId: uuid.parse(input.backtestId),
+ });
+ return this.#request(
+ 'experiments/cost-sensitivity',
+ 'POST',
+ 202,
+ value => {
+ const saved = parseWorkbenchExperimentDetail(envelope(value, 'experiment'));
+ const { previewHash, ...original } = body;
+ expect(
+ saved.preview.version === 'cost-sensitivity-preview/v1' &&
+ saved.previewHash === previewHash &&
+ same(saved.preview.input, original)
+ );
+ return saved;
+ },
+ body,
+ key
+ );
+ }
+ previewValidation(input: ChronologicalValidationInput, signal?: AbortSignal) {
+ const body = chronologicalValidationInputSchema.parse({
+ ...input,
+ backtestId: uuid.parse(input.backtestId),
+ });
+ return this.#request(
+ 'experiments/validation/preview',
+ 'POST',
+ 200,
+ value => parseChronologicalValidationPreview(value, body),
+ body,
+ undefined,
+ signal
+ );
+ }
+ submitValidation(input: ChronologicalValidationSubmission, key: string) {
+ const body = chronologicalValidationSubmissionSchema.parse({
+ ...input,
+ backtestId: uuid.parse(input.backtestId),
+ });
+ return this.#request(
+ 'experiments/validation',
+ 'POST',
+ 202,
+ value => {
+ const saved = parseValidationDetail(envelope(value, 'validation'));
+ const { previewHash, ...original } = body;
+ expect(saved.previewHash === previewHash && same(saved.preview.input, original));
+ return saved;
+ },
+ body,
+ key
+ );
+ }
+ validation(validationId: string, signal?: AbortSignal) {
+ validationId = uuid.parse(validationId);
+ return this.#request(
+ `experiments/validation/${id(validationId)}`,
+ 'GET',
+ 200,
+ value => {
+ const saved = parseValidationDetail(envelope(value, 'validation'));
+ expect(saved.id === validationId);
+ return saved;
+ },
+ undefined,
+ undefined,
+ signal
+ );
+ }
+ advanceValidation(
+ validationId: string,
+ operation: 'select' | 'finalize',
+ input: { previewHash: string; selectionHash?: string },
+ key: string
+ ) {
+ validationId = uuid.parse(validationId);
+ z.enum(['select', 'finalize']).parse(operation);
+ const body = (
+ operation === 'select'
+ ? z.object({ previewHash: hash }).strict()
+ : z.object({ previewHash: hash, selectionHash: hash }).strict()
+ ).parse(input);
+ return this.#request(
+ `experiments/validation/${id(validationId)}/${operation}`,
+ 'POST',
+ 202,
+ value => {
+ const receipt = validationReceiptSchema.parse(envelope(value, 'receipt'));
+ const saved = parseValidationDetail(envelope(value, 'validation'));
+ const record = operation === 'select' ? saved.selection : saved.report;
+ expect(
+ saved.id === validationId &&
+ receipt.validationId === validationId &&
+ saved.previewHash === body.previewHash &&
+ receipt.previewHash === body.previewHash &&
+ receipt.selectionHash === saved.selection?.selectionHash &&
+ receipt.operation ===
+ (operation === 'select' ? 'select-and-admit-holdouts' : 'finalize-report') &&
+ record &&
+ receipt.id === record.id &&
+ receipt.createdAt === record.createdAt &&
+ receipt.principal === record.principal &&
+ (operation === 'select' ||
+ ('selectionHash' in body && receipt.selectionHash === body.selectionHash))
+ );
+ return { receipt, validation: saved };
+ },
+ body,
+ key
+ );
+ }
+ previewWalkForward(input: WalkForwardInput, signal?: AbortSignal) {
+ const body = walkForwardInputSchema.parse({
+ ...input,
+ backtestId: uuid.parse(input.backtestId),
+ });
+ return this.#request(
+ 'experiments/walk-forward/preview',
+ 'POST',
+ 200,
+ value => parseWalkForwardPreview(envelope(value, 'preview'), body),
+ body,
+ undefined,
+ signal
+ );
+ }
+ submitWalkForward(input: WalkForwardSubmission, key: string) {
+ const body = walkForwardSubmissionSchema.parse({
+ ...input,
+ backtestId: uuid.parse(input.backtestId),
+ });
+ return this.#request(
+ 'experiments/walk-forward',
+ 'POST',
+ 202,
+ value => {
+ const saved = parseWalkForwardDetail(envelope(value, 'walkForward'));
+ const { previewHash, ...original } = body;
+ expect(saved.previewHash === previewHash && same(saved.preview.input, original));
+ return saved;
+ },
+ body,
+ key
+ );
+ }
+ walkForward(walkForwardId: string, signal?: AbortSignal) {
+ walkForwardId = uuid.parse(walkForwardId);
+ return this.#request(
+ `experiments/walk-forward/${id(walkForwardId)}`,
+ 'GET',
+ 200,
+ value => {
+ const saved = parseWalkForwardDetail(envelope(value, 'walkForward'));
+ expect(saved.id === walkForwardId);
+ return saved;
+ },
+ undefined,
+ undefined,
+ signal
+ );
+ }
+ finalizeWalkForward(walkForwardId: string, previewHash: string, key: string) {
+ walkForwardId = uuid.parse(walkForwardId);
+ hash.parse(previewHash);
+ return this.#request(
+ `experiments/walk-forward/${id(walkForwardId)}/finalize`,
+ 'POST',
+ 202,
+ value => {
+ const receipt = z
+ .object({
+ id: uuid,
+ walkForwardId: uuid,
+ operation: z.literal('finalize-walk-forward-report'),
+ previewHash: hash,
+ reportHash: hash,
+ createdAt: z.string().min(1),
+ principal: researchActorSchema,
+ })
+ .parse(envelope(value, 'receipt'));
+ const saved = parseWalkForwardDetail(envelope(value, 'walkForward'));
+ expect(
+ saved.id === walkForwardId &&
+ receipt.walkForwardId === walkForwardId &&
+ saved.previewHash === previewHash &&
+ receipt.previewHash === previewHash &&
+ saved.report &&
+ receipt.id === saved.report.id &&
+ receipt.reportHash === saved.report.reportHash &&
+ receipt.createdAt === saved.report.createdAt &&
+ receipt.principal === saved.report.principal
+ );
+ return { receipt, walkForward: saved };
+ },
+ { previewHash },
+ key
+ );
+ }
+ saveFinding(projectId: string, input: FindingInput) {
+ projectId = uuid.parse(projectId);
+ const body = createResearchArtifactSchema.parse({
+ ...input,
+ contentOrigin: 'ai',
+ hypothesisRevisionId:
+ input.hypothesisRevisionId === null || input.hypothesisRevisionId === undefined
+ ? null
+ : uuid.parse(input.hypothesisRevisionId),
+ evidence: input.evidence?.map(item => ({
+ ...item,
+ runId: uuid.parse(item.runId),
+ strategyVersionId:
+ item.strategyVersionId === null || item.strategyVersionId === undefined
+ ? item.strategyVersionId
+ : uuid.parse(item.strategyVersionId),
+ })),
+ });
+ expect(body.kind === 'finding' && body.evidence.length > 0 && body.source);
+ for (const evidence of body.evidence) {
+ researchEvidenceReferenceSchema.parse(evidence);
+ expect(evidence.metricsVersion === 'canonical-analytics/v1' && evidence.strategyVersionId);
+ }
+ return this.#request(
+ `research-projects/${id(projectId)}/analysis-artifacts`,
+ 'POST',
+ 201,
+ value => {
+ const saved = findingRecord.parse(envelope(value, 'artifact'));
+ const revision = saved.latestRevision;
+ expect(
+ saved.projectId === projectId &&
+ saved.hypothesisRevisionId === body.hypothesisRevisionId &&
+ saved.kind === 'finding' &&
+ revision.title === body.title &&
+ revision.body === body.body &&
+ revision.evidenceState === 'referenced' &&
+ same(revision.source, body.source) &&
+ revision.evidence.length === body.evidence.length &&
+ body.evidence.every(item =>
+ revision.evidence.some(
+ evidence =>
+ evidence.runId === item.runId &&
+ evidence.strategyVersionId === item.strategyVersionId &&
+ evidence.metricsVersion === item.metricsVersion &&
+ evidence.metricPath === item.metricPath
+ )
+ )
+ );
+ return saved;
+ },
+ body
+ );
+ }
+
+ async waitForExperiment(
+ experimentId: string,
+ options: PollOptions
+ ) {
+ return pollResearch(
+ signal => this.experiment(experimentId, signal),
+ value =>
+ value.trials.every(trial =>
+ ['completed', 'failed', 'cancelled', 'missing'].includes(trial.status)
+ ),
+ options
+ );
+ }
+ async waitForValidation(validationId: string, options: PollOptions) {
+ return pollResearch(
+ signal => this.validation(validationId, signal),
+ value => {
+ const admitted = value.phases.filter(phase => phase.status !== 'not-admitted');
+ return admitted.every(
+ phase =>
+ phase.status === 'missing' ||
+ phase.experiment?.trials.every(trial =>
+ ['completed', 'failed', 'cancelled', 'missing'].includes(trial.status)
+ )
+ );
+ },
+ options
+ );
+ }
+}
+
+/** Stops waiting without cancelling accepted jobs; all failed/cancelled/missing trials remain visible. */
+export async function pollResearch(
+ read: (signal: AbortSignal) => Promise,
+ done: (value: T) => boolean,
+ options: PollOptions
+): Promise {
+ const timeout = z.number().int().positive().max(2147483647).parse(options.timeoutMs);
+ const interval = z
+ .number()
+ .int()
+ .positive()
+ .max(2147483647)
+ .parse(options.intervalMs ?? 500);
+ const deadline = timedSignal(timeout);
+ const signal = options.signal
+ ? AbortSignal.any([options.signal, deadline.signal])
+ : deadline.signal;
+ let last: T | null = null;
+ try {
+ while (!signal.aborted) {
+ try {
+ last = await abortable(() => read(signal), signal);
+ } catch (error) {
+ if (options.signal?.aborted) {
+ throw options.signal.reason;
+ }
+ if (!deadline.signal.aborted) {
+ throw error;
+ }
+ break;
+ }
+ if (signal.aborted) {
+ break;
+ }
+ options.onUpdate?.(last);
+ if (done(last)) {
+ return last;
+ }
+ await new Promise(resolve => {
+ const finish = () => {
+ clearTimeout(timer);
+ signal.removeEventListener('abort', finish);
+ resolve();
+ };
+ const timer = setTimeout(finish, interval);
+ signal.addEventListener('abort', finish, { once: true });
+ if (signal.aborted) {
+ finish();
+ }
+ });
+ }
+ if (options.signal?.aborted) {
+ throw options.signal.reason;
+ }
+ throw new ResearchWaitExpired(last);
+ } finally {
+ deadline.dispose();
+ }
+}
+
+/** Bound an operation even when a supplied transport ignores cancellation. Late results are ignored. */
+function abortable(read: () => Promise, signal: AbortSignal): Promise {
+ return new Promise((resolve, reject) => {
+ const stop = () => reject(signal.reason);
+ if (signal.aborted) {
+ stop();
+ return;
+ }
+ signal.addEventListener('abort', stop, { once: true });
+ try {
+ read()
+ .then(resolve, reject)
+ .finally(() => signal.removeEventListener('abort', stop));
+ } catch (error) {
+ signal.removeEventListener('abort', stop);
+ reject(error);
+ }
+ });
+}
+
+function timedSignal(timeoutMs: number) {
+ const controller = new AbortController();
+ // Keep the event loop alive while callers await an otherwise uncooperative transport.
+ const timer = setTimeout(
+ () => controller.abort(new Error('Research deadline reached')),
+ timeoutMs
+ );
+ return { signal: controller.signal, dispose: () => clearTimeout(timer) };
+}
diff --git a/scripts/test/architecture.test.ts b/scripts/test/architecture.test.ts
index de2f18a7..0d6ff1d1 100644
--- a/scripts/test/architecture.test.ts
+++ b/scripts/test/architecture.test.ts
@@ -89,6 +89,8 @@ describe('orchestrator architecture boundaries', () => {
'@stock-bot/stock-config/strategy',
'@stock-bot/stock-config/canonical-replay',
'@stock-bot/stock-config/canonical-research',
+ '@stock-bot/stock-config/candidate-execution',
+ '@stock-bot/stock-config/paper-deployments',
'@stock-bot/calculations/analytics',
'@stock-bot/calculations/returns',
].includes(specifier)
@@ -122,6 +124,8 @@ describe('orchestrator architecture boundaries', () => {
'strategy-names.ts',
'canonical-research.ts',
'canonical-replay.ts',
+ 'candidate-execution.ts',
+ 'paper-deployments.ts',
'research.ts',
]) {
for (const specifier of runtimeImports(join(directory, name))) {
@@ -133,6 +137,8 @@ describe('orchestrator architecture boundaries', () => {
'./strategy-names',
'./strategy',
'./canonical-replay',
+ './candidate-execution',
+ './research',
].includes(specifier)
).toBe(true);
}
diff --git a/scripts/test/research-client.test.ts b/scripts/test/research-client.test.ts
new file mode 100644
index 00000000..c4207f6f
--- /dev/null
+++ b/scripts/test/research-client.test.ts
@@ -0,0 +1,471 @@
+import { createHash } from 'node:crypto';
+import { describe, expect, test } from 'bun:test';
+import type { ExperimentDetail } from '@stock-bot/stock-config/experiments';
+import { comparisonFixture, tableFixture } from '../benchmark-experiment-tables';
+import {
+ pollResearch,
+ ResearchClient,
+ ResearchRequestError,
+ ResearchWaitExpired,
+} from '../research-client';
+
+const token = 'sb-research.fixture-only-token';
+const agent = 'agent:11111111-1111-4111-8111-111111111111';
+const projectId = '22222222-2222-4222-8222-222222222222';
+const hypothesisId = '33333333-3333-4333-8333-333333333333';
+const revisionId = '44444444-4444-4444-8444-444444444444';
+const artifactId = '55555555-5555-4555-8555-555555555555';
+const requestKey = 'research-cycle-fixture:trial:1';
+type Call = { url: URL; init: RequestInit; body: unknown };
+function client(handler: (call: Call, index: number) => Response | Promise) {
+ const calls: Call[] = [];
+ const value = new ResearchClient({
+ origin: 'http://127.0.0.1:2003',
+ token,
+ fetch: ((url: string | URL | Request, init?: RequestInit) => {
+ const call = {
+ url: new URL(String(url)),
+ init: init!,
+ body: init?.body ? JSON.parse(String(init.body)) : undefined,
+ };
+ calls.push(call);
+ return Promise.resolve(handler(call, calls.length - 1));
+ }) as typeof fetch,
+ });
+ return { value, calls };
+}
+const ordinary = () => tableFixture(1) as ExperimentDetail;
+
+describe('authorized research client', () => {
+ test('only research credentials, fixed API origin, no trading methods or redirect credential forwarding', async () => {
+ for (const origin of [
+ 'http://example.org',
+ 'https://u:p@example.org',
+ 'https://example.org/a',
+ 'https://example.org/?token=x',
+ 'file:///tmp/a',
+ ]) {
+ expect(() => new ResearchClient({ origin, token })).toThrow();
+ }
+ expect(
+ () => new ResearchClient({ origin: 'https://example.org', token: 'operator-secret' })
+ ).toThrow();
+ const detail = ordinary();
+ const { value, calls } = client(() => Response.json({ experiment: detail }));
+ await value.experiment(detail.id);
+ expect(calls[0]!.url.origin).toBe('http://127.0.0.1:2003');
+ expect(calls[0]!.url.pathname).toBe(`/api/v2/experiments/${detail.id}`);
+ expect(calls[0]!.init.redirect).toBe('error');
+ expect(calls[0]!.init.credentials).toBe('omit');
+ expect(new Headers(calls[0]!.init.headers).get('authorization')).toBe(`Bearer ${token}`);
+ expect(JSON.stringify(value)).not.toContain(token);
+ expect('activate' in value || 'paper' in value || 'request' in value).toBe(false);
+ expect(() =>
+ value.advanceValidation(
+ detail.id,
+ '../../paper/activate' as 'select',
+ { previewHash: detail.previewHash },
+ requestKey
+ )
+ ).toThrow();
+ expect(calls).toHaveLength(1);
+ });
+
+ test('preview and admission preserve captured inputs; uncertain submission recovers with the same exact key and body', async () => {
+ const detail = ordinary();
+ let release!: (response: Response) => void;
+ const { value, calls } = client((_call, index) =>
+ index === 0
+ ? new Promise(resolve => {
+ release = resolve;
+ })
+ : index === 1
+ ? Promise.reject(new Error('Response lost after durable admission'))
+ : Response.json({ experiment: detail }, { status: 202 })
+ );
+ const input = structuredClone(detail.preview.input);
+ const checking = value.previewExperiment(input);
+ input.name = 'Changed after sending';
+ release(Response.json({ preview: detail.preview }));
+ expect((await checking).input.name).toBe(detail.name);
+ const body = { ...detail.preview.input, previewHash: detail.previewHash };
+ await expect(value.submitExperiment(body, requestKey)).rejects.toMatchObject({
+ uncertain: true,
+ });
+ expect(calls).toHaveLength(2);
+ expect((await value.submitExperiment(body, requestKey)).id).toBe(detail.id);
+ expect(String(calls[1]!.init.body)).toBe(String(calls[2]!.init.body));
+ expect(new Headers(calls[1]!.init.headers).get('idempotency-key')).toBe(requestKey);
+ expect(new Headers(calls[2]!.init.headers).get('idempotency-key')).toBe(requestKey);
+ });
+
+ test('wrong receipt identities, lost response and 429 are surfaced without automatic new admission', async () => {
+ const detail = ordinary(),
+ body = { ...detail.preview.input, previewHash: detail.previewHash };
+ const malformed = client(() =>
+ Response.json({ experiment: { ...detail, previewHash: 'f'.repeat(64) } }, { status: 202 })
+ );
+ await expect(malformed.value.submitExperiment(body, requestKey)).rejects.toMatchObject({
+ status: null,
+ uncertain: true,
+ });
+ expect(malformed.calls).toHaveLength(1);
+ const lost = client(() => {
+ throw new Error('private transport details');
+ });
+ await expect(lost.value.submitExperiment(body, requestKey)).rejects.toMatchObject({
+ status: null,
+ uncertain: true,
+ });
+ const denied = client(() =>
+ Response.json({ error: 'Bounded work budget exceeded' }, { status: 429 })
+ );
+ await expect(denied.value.previewExperiment(detail.preview.input)).rejects.toMatchObject({
+ status: 429,
+ uncertain: false,
+ message: 'Bounded work budget exceeded',
+ });
+ expect(denied.calls).toHaveLength(1);
+ const oversized = {
+ ...detail.preview.input,
+ grid: { fastPeriod: Array.from({ length: 101 }, (_, i) => i + 1) },
+ };
+ expect(() => denied.value.previewExperiment(oversized)).toThrow();
+ expect(denied.calls).toHaveLength(1);
+ });
+
+ test('candidate publication is inert data; it cannot import generated source or substitute a version identity', async () => {
+ const detail = ordinary();
+ const pkg = structuredClone(detail.preview.request.strategy.package);
+ pkg.artifact.content =
+ 'globalThis.__research_client_executed = true; throw new Error("Never import");';
+ pkg.artifact.sha256 = createHash('sha256').update(pkg.artifact.content).digest('hex');
+ const saved = {
+ id: detail.strategyVersionId,
+ strategyId: detail.preview.request.strategy.familyId,
+ ordinal: 2,
+ origin: 'candidate',
+ createdBy: agent,
+ parentVersionId: null,
+ package: pkg,
+ };
+ const good = client(() => Response.json({ version: saved }, { status: 201 }));
+ expect((await good.value.publishVersion(saved.strategyId, pkg, requestKey)).id).toBe(saved.id);
+ expect((globalThis as Record).__research_client_executed).toBeUndefined();
+ expect(good.calls[0]!.body).toEqual({ package: pkg, parentVersionId: null });
+ const bad = client(() =>
+ Response.json({ version: { ...saved, origin: 'builtin' } }, { status: 201 })
+ );
+ await expect(bad.value.publishVersion(saved.strategyId, pkg, requestKey)).rejects.toMatchObject(
+ { uncertain: true }
+ );
+ });
+
+ test('normalizes uppercase identities before captures and binds cancellation and publication receipts', async () => {
+ const detail = ordinary();
+ detail.id = 'abcdefab-abcd-4bcd-8bcd-abcdefabcdef';
+ detail.cancelRequested = true;
+ const cancel = client(() => Response.json({ experiment: detail }));
+ expect((await cancel.value.cancelExperiment(detail.id.toUpperCase())).id).toBe(detail.id);
+ expect(cancel.calls[0]!.url.pathname).toContain(detail.id);
+ const strategyId = 'abcdefab-abcd-4bcd-8bcd-000000000001';
+ const parentVersionId = 'abcdefab-abcd-4bcd-8bcd-000000000002';
+ const pkg = detail.preview.request.strategy.package;
+ const saved = {
+ id: detail.strategyVersionId,
+ strategyId,
+ parentVersionId,
+ ordinal: 2,
+ origin: 'candidate',
+ createdBy: agent,
+ package: pkg,
+ };
+ const publication = client(() => Response.json({ version: saved }, { status: 201 }));
+ expect(
+ (
+ await publication.value.publishVersion(
+ strategyId.toUpperCase(),
+ pkg,
+ requestKey,
+ parentVersionId.toUpperCase()
+ )
+ ).strategyId
+ ).toBe(strategyId);
+ expect(publication.calls[0]!.body).toMatchObject({ parentVersionId });
+ });
+
+ test('malformed selection/finalization receipts are uncertain and never resubmitted automatically', async () => {
+ const request = client(() =>
+ Response.json(
+ { receipt: { id: projectId }, validation: {}, walkForward: {} },
+ { status: 202 }
+ )
+ );
+ await expect(
+ request.value.advanceValidation(
+ projectId,
+ 'select',
+ { previewHash: 'a'.repeat(64) },
+ requestKey
+ )
+ ).rejects.toMatchObject({ uncertain: true });
+ await expect(
+ request.value.advanceValidation(
+ projectId,
+ 'finalize',
+ { previewHash: 'a'.repeat(64), selectionHash: 'b'.repeat(64) },
+ requestKey
+ )
+ ).rejects.toMatchObject({ uncertain: true });
+ await expect(
+ request.value.finalizeWalkForward(projectId, 'a'.repeat(64), requestKey)
+ ).rejects.toMatchObject({ uncertain: true });
+ expect(request.calls).toHaveLength(3);
+ });
+
+ test('failed, cancelled, missing and noncomparable outcomes survive polling and comparison', async () => {
+ const detail = tableFixture(25);
+ for (const trial of detail.trials) {
+ if (['pending', 'running', 'paused'].includes(trial.status)) {
+ trial.status = 'failed';
+ trial.error = 'Explicit worker diagnostic';
+ }
+ }
+ for (const status of [
+ 'pending',
+ 'running',
+ 'paused',
+ 'completed',
+ 'failed',
+ 'cancelled',
+ ] as const) {
+ detail.counts[status] = detail.trials.filter(trial => trial.status === status).length;
+ }
+ const polling = client(() => Response.json({ experiment: detail }));
+ const result = await polling.value.waitForExperiment(detail.id, { timeoutMs: 1000 });
+ expect(result.trials).toEqual(detail.trials);
+ expect(result.trials.some(trial => trial.status === 'failed' && trial.error)).toBe(true);
+ expect(result.trials.some(trial => trial.status === 'missing')).toBe(true);
+ expect(result.trials.some(trial => trial.status === 'completed' && !trial.comparable)).toBe(
+ true
+ );
+ expect(polling.calls).toHaveLength(1);
+ const comparison = comparisonFixture();
+ const read = client(() => Response.json({ comparison }));
+ expect((await read.value.compareExperiments(comparison.selection)).rows).toEqual(
+ comparison.rows
+ );
+ expect(comparison.rows.some(row => !row.ready)).toBe(true);
+ });
+
+ test('AI hypotheses stay unvalidated and findings retain exact canonical sources without validating prose', async () => {
+ const detail = ordinary(),
+ runId = detail.trials[0]!.runId!;
+ const input = {
+ title: 'A hypothesis',
+ proposition: 'Trend might persist',
+ validationCriteria: 'Use chronological holdouts',
+ };
+ const evidence = [
+ {
+ runId,
+ strategyVersionId: detail.strategyVersionId,
+ metricsVersion: 'canonical-analytics/v1' as const,
+ metricPath: 'analytics.metrics.totalReturn' as const,
+ },
+ ];
+ const source = {
+ kind: 'experiment/v1' as const,
+ experimentId: detail.id,
+ previewHash: detail.previewHash,
+ };
+ const finding = {
+ kind: 'finding' as const,
+ hypothesisRevisionId: revisionId,
+ title: 'Observed fixture',
+ body: 'This synthetic result is not a profitability claim.',
+ evidence,
+ source,
+ };
+ let metric = {
+ value: 0 as number | null,
+ availability: 'available',
+ unavailableReason: null as string | null,
+ };
+ const { value, calls } = client((_call, index) =>
+ Response.json(
+ index === 0
+ ? {
+ hypothesis: {
+ id: hypothesisId,
+ projectId,
+ latestRevision: {
+ ...input,
+ id: revisionId,
+ ordinal: 1,
+ contentOrigin: 'ai',
+ submittedBy: agent,
+ validationState: 'unvalidated',
+ },
+ },
+ }
+ : {
+ artifact: {
+ id: artifactId,
+ projectId,
+ hypothesisRevisionId: revisionId,
+ kind: 'finding',
+ latestRevision: {
+ id: revisionId,
+ title: finding.title,
+ body: finding.body,
+ contentOrigin: 'ai',
+ submittedBy: agent,
+ validationState: 'unvalidated',
+ evidenceState: 'referenced',
+ source,
+ evidence: [
+ {
+ ...evidence[0],
+ ...metric,
+ datasetHash: detail.datasetHash,
+ resultKind: 'canonical',
+ financialEngine: 'rust',
+ limitations: [{ code: 'fixture', message: 'Synthetic demonstration' }],
+ },
+ ],
+ },
+ },
+ },
+ { status: 201 }
+ )
+ );
+ const hypothesis = await value.createHypothesis(projectId, input);
+ expect(hypothesis.latestRevision.validationState).toBe('unvalidated');
+ const saved = await value.saveFinding(projectId, finding);
+ expect(calls[1]!.url.pathname).toBe(
+ `/api/v2/research-projects/${projectId}/analysis-artifacts`
+ );
+ expect(saved.latestRevision.validationState).toBe('unvalidated');
+ expect(saved.latestRevision.evidence[0]!.value).toBe(0);
+ expect(saved.latestRevision.source).toEqual(source);
+ for (const bad of [
+ { value: null, availability: 'available', unavailableReason: null },
+ { value: 1, availability: 'unavailable', unavailableReason: 'Too few bars' },
+ { value: null, availability: 'unavailable', unavailableReason: null },
+ { value: null, availability: 'unavailable', unavailableReason: ' ' },
+ { value: 0, availability: 'available', unavailableReason: 'Contradictory reason' },
+ ]) {
+ metric = bad;
+ await expect(value.saveFinding(projectId, finding)).rejects.toMatchObject({
+ uncertain: true,
+ });
+ }
+ metric = { value: null, availability: 'unavailable', unavailableReason: 'Too few bars' };
+ expect((await value.saveFinding(projectId, finding)).latestRevision.evidence[0]).toMatchObject(
+ metric
+ );
+
+ expect((calls[0]!.body as { contentOrigin: string }).contentOrigin).toBe('ai');
+ const denied = client(() =>
+ Response.json({ error: 'Evidence is not a member of this source' }, { status: 409 })
+ );
+ await expect(denied.value.saveFinding(projectId, finding)).rejects.toMatchObject({
+ status: 409,
+ uncertain: false,
+ });
+ expect(denied.calls).toHaveLength(1);
+ expect(() => denied.value.saveFinding(projectId, { ...finding, evidence: [] })).toThrow();
+ });
+});
+
+describe('bounded research polling', () => {
+ test('deadline preserves last diagnostic snapshot and never cancels server work', async () => {
+ let reads = 0;
+ const error = await pollResearch(
+ async () => ({ status: 'running', attempt: ++reads }),
+ () => false,
+ { timeoutMs: 15, intervalMs: 5 }
+ ).catch(error => error);
+ expect(error).toBeInstanceOf(ResearchWaitExpired);
+ expect(error.last.status).toBe('running');
+ expect(reads).toBeGreaterThan(0);
+ });
+ test('explicit abort and failed read stop polling without hiding 429 or other diagnostics', async () => {
+ const controller = new AbortController();
+ const aborted = pollResearch(
+ async () => {
+ controller.abort(new Error('Owner stopped waiting'));
+ return 1;
+ },
+ () => false,
+ { timeoutMs: 1000, intervalMs: 1, signal: controller.signal }
+ );
+ await expect(aborted).rejects.toThrow('Owner stopped waiting');
+ let calls = 0;
+ const error = new ResearchRequestError('Budget unavailable', 429, false, 'GET fixture');
+ await expect(
+ pollResearch(
+ async () => {
+ calls++;
+ throw error;
+ },
+ () => false,
+ { timeoutMs: 1000 }
+ )
+ ).rejects.toBe(error);
+ expect(calls).toBe(1);
+ expect(
+ () => new ResearchClient({ origin: 'http://localhost', token, requestTimeoutMs: Infinity })
+ ).toThrow();
+ });
+});
+
+test('polling deadlines and aborts bound a transport that ignores cancellation', async () => {
+ const never = () => new Promise(() => {});
+ const timeout = await pollResearch(never, () => false, { timeoutMs: 10 }).catch(error => error);
+ expect(timeout).toBeInstanceOf(ResearchWaitExpired);
+ expect(timeout.last).toBeNull();
+ const controller = new AbortController();
+ const pending = pollResearch(never, () => false, { timeoutMs: 1000, signal: controller.signal });
+ controller.abort(new Error('Stop uncooperative transport'));
+ await expect(pending).rejects.toThrow('Stop uncooperative transport');
+ const bounded = new ResearchClient({
+ origin: 'http://localhost',
+ token,
+ requestTimeoutMs: 10,
+ fetch: never as unknown as typeof fetch,
+ });
+ await expect(bounded.budget()).rejects.toMatchObject({ uncertain: false, status: null });
+});
+
+test('captured recipe inputs normalize template UUIDs before preview and receipt submission', async () => {
+ const value = ordinary();
+ const read = client(() =>
+ Response.json({ error: 'Fixture stops before admission' }, { status: 429 })
+ );
+ const backtestId = 'abcdefab-abcd-4bcd-8bcd-abcdefabcdef';
+ await expect(
+ read.value.previewExperiment({ ...value.preview.input, backtestId: backtestId.toUpperCase() })
+ ).rejects.toMatchObject({ status: 429 });
+ expect(read.calls[0]!.body).toMatchObject({ backtestId });
+ await expect(
+ read.value.submitExperiment(
+ {
+ ...value.preview.input,
+ backtestId: backtestId.toUpperCase(),
+ previewHash: value.previewHash,
+ },
+ requestKey
+ )
+ ).rejects.toMatchObject({ status: 429 });
+ expect(read.calls[1]!.body).toMatchObject({ backtestId });
+ await expect(
+ read.value.previewCosts({
+ name: 'Uppercase costs',
+ backtestId: backtestId.toUpperCase(),
+ scenarios: [{ feeRate: '0.01', slippageRate: '0.01' }],
+ })
+ ).rejects.toMatchObject({ status: 429 });
+ expect(read.calls[2]!.body).toMatchObject({ backtestId });
+});
diff --git a/scripts/test/research-cycle.test.ts b/scripts/test/research-cycle.test.ts
new file mode 100644
index 00000000..4a3bcb75
--- /dev/null
+++ b/scripts/test/research-cycle.test.ts
@@ -0,0 +1,230 @@
+import { describe, expect, test } from 'bun:test';
+import { walkForwardDataset } from '../../test/fixtures/walk-forward';
+import { tableFixture } from '../benchmark-experiment-tables';
+import {
+ runResearchCycle,
+ validateResearchCycle,
+ type ResearchCycleEvent,
+ type ResearchCyclePlan,
+} from '../examples/research-cycle';
+import { ResearchClient } from '../research-client';
+
+const projectId = '22222222-2222-4222-8222-222222222222';
+const detail = tableFixture(1);
+const plan = (): ResearchCyclePlan => ({
+ cycleId: 'bounded-example',
+ projectId,
+ backtestId: detail.backtestId,
+ maxTotalTrials: 5,
+ hypothesis: {
+ title: 'Unvalidated suggestion',
+ proposition: 'A regime filter may help',
+ validationCriteria: 'Train-only selection then untouched test and costs',
+ },
+ candidates: [
+ {
+ key: 'trend',
+ name: 'Trend',
+ rationale: 'Test an explicit volatility filter',
+ package: {
+ ...structuredClone(detail.preview.request.strategy.package),
+ execution: { kind: 'isolated-candidate/v1', warmupBars: 3 },
+ },
+ parameters: { fastPeriod: 2, slowPeriod: 3 },
+ grid: {},
+ recipe: walkForwardDataset().windows[0]!,
+ costScenarios: [{ feeRate: '0.02', slippageRate: '0.01' }],
+ },
+ ],
+});
+const budget = () => ({
+ agent: {
+ id: 'agent:11111111-1111-4111-8111-111111111111',
+ name: 'Research only',
+ enabled: true,
+ revision: 1,
+ allowedProjectIds: [projectId],
+ grants: [
+ { backtestId: detail.backtestId, policyHash: 'a'.repeat(64), allowOwnCandidates: true },
+ ],
+ limits: {
+ maxActiveTrials: 4,
+ maxTrialsPerExperiment: 4,
+ maxBarEvaluationsPerExperiment: 10000,
+ maxAttemptWallMs: 60000,
+ maxAttempts: 1,
+ },
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ },
+ activeTrials: 0,
+ remainingActiveTrials: 4,
+});
+function client(reply: (path: string, body: unknown) => Response | Promise) {
+ const calls: { path: string; body: unknown }[] = [];
+ const api = new ResearchClient({
+ origin: 'http://127.0.0.1:2003',
+ token: 'sb-research.fixture-only-token',
+ fetch: (async (input: string | URL | Request, init?: RequestInit) => {
+ const path = new URL(String(input)).pathname,
+ body: unknown = init?.body ? JSON.parse(String(init.body)) : undefined;
+ calls.push({ path, body });
+ return reply(path, body);
+ }) as typeof fetch,
+ });
+ return { api, calls };
+}
+describe('bounded executable research cycle', () => {
+ test('counts training, future holdouts and baseline costs before any request', async () => {
+ const value = plan();
+ expect(validateResearchCycle(value).totalTrials).toBe(5);
+ value.maxTotalTrials = 4;
+ const f = client(() => {
+ throw new Error('No network expected');
+ });
+ await expect(
+ runResearchCycle(f.api, value, { onEvent: async () => {}, poll: { timeoutMs: 1000 } })
+ ).rejects.toThrow('total trial bound');
+ expect(f.calls).toHaveLength(0);
+ });
+ test('rejects Cartesian overflow, duplicate candidate keys and nonisolated packages', () => {
+ const overflow = plan();
+ overflow.maxTotalTrials = 10000;
+ overflow.candidates[0]!.grid = {
+ a: Array.from({ length: 11 }, (_, i) => i),
+ b: Array.from({ length: 10 }, (_, i) => i),
+ };
+ expect(() => validateResearchCycle(overflow)).toThrow('experiment trial bound');
+ const duplicate = plan();
+ duplicate.candidates.push(structuredClone(duplicate.candidates[0]!));
+ expect(() => validateResearchCycle(duplicate)).toThrow('unique');
+ const unsafe = plan();
+ delete unsafe.candidates[0]!.package.execution;
+ expect(() => validateResearchCycle(unsafe)).toThrow('explicitly isolated');
+ });
+ test('grant, per-admission budgets and poll input fail before hypothesis mutation', async () => {
+ const revoked = budget();
+ revoked.agent.grants[0]!.allowOwnCandidates = false;
+ const f = client(() => Response.json(revoked));
+ await expect(
+ runResearchCycle(f.api, plan(), { onEvent: async () => {}, poll: { timeoutMs: 1000 } })
+ ).rejects.toThrow('explicit');
+ expect(f.calls).toHaveLength(1);
+ const narrow = budget();
+ narrow.agent.limits.maxActiveTrials = 1;
+ const g = client(() => Response.json(narrow));
+ await expect(
+ runResearchCycle(g.api, plan(), { onEvent: async () => {}, poll: { timeoutMs: 1000 } })
+ ).rejects.toThrow('trial budget');
+ expect(g.calls).toHaveLength(1);
+ await expect(
+ runResearchCycle(g.api, plan(), { onEvent: async () => {}, poll: { timeoutMs: 0 } })
+ ).rejects.toThrow();
+ expect(g.calls).toHaveLength(1);
+ });
+ test('a lost non-idempotent hypothesis response stops once and retains its exact intent', async () => {
+ const events: ResearchCycleEvent[] = [];
+ const f = client(path => {
+ if (path.endsWith('/budget')) {
+ return Response.json(budget());
+ }
+ throw new Error('Accepted response lost');
+ });
+ const value = plan();
+ await expect(
+ runResearchCycle(f.api, value, {
+ onEvent: async event => {
+ events.push(event);
+ },
+ poll: { timeoutMs: 1000 },
+ })
+ ).rejects.toMatchObject({
+ name: 'ResearchCycleStopped',
+ event: { phase: 'stopped', key: null, operation: 'create-hypothesis', uncertain: true },
+ });
+ expect(f.calls).toHaveLength(2);
+ expect(events.map(event => event.phase)).toEqual(['intent', 'stopped']);
+ expect(events[0]!.input).toEqual({ ...value.hypothesis, contentOrigin: 'ai' });
+ expect(events[0]!.resourceId).toBe(projectId);
+ });
+ test('receipt persistence and cancellation stop subsequent writes', async () => {
+ const f = client(() => Response.json(budget()));
+ await expect(
+ runResearchCycle(f.api, plan(), {
+ onEvent: async () => {
+ throw new Error('Journal unavailable');
+ },
+ poll: { timeoutMs: 1000 },
+ })
+ ).rejects.toThrow('Journal unavailable');
+ expect(f.calls).toHaveLength(1);
+ const controller = new AbortController();
+ await expect(
+ runResearchCycle(f.api, plan(), {
+ onEvent: async () => {
+ controller.abort(new Error('Stop here'));
+ },
+ signal: controller.signal,
+ poll: { timeoutMs: 1000 },
+ })
+ ).rejects.toThrow('Stop here');
+ expect(f.calls).toHaveLength(2);
+ });
+ test('a receipt journal failure preserves the accepted resource in the thrown error', async () => {
+ const value = plan();
+ const saved = {
+ id: '33333333-3333-4333-8333-333333333333',
+ projectId,
+ latestRevision: {
+ id: '44444444-4444-4444-8444-444444444444',
+ ordinal: 1,
+ ...value.hypothesis,
+ contentOrigin: 'ai',
+ submittedBy: budget().agent.id,
+ validationState: 'unvalidated',
+ },
+ };
+ const f = client(path =>
+ path.endsWith('/budget')
+ ? Response.json(budget())
+ : Response.json({ hypothesis: saved }, { status: 201 })
+ );
+ await expect(
+ runResearchCycle(f.api, value, {
+ poll: { timeoutMs: 1000 },
+ onEvent: async event => {
+ if (event.phase === 'accepted') {
+ throw new Error('Disk unavailable after acceptance');
+ }
+ },
+ })
+ ).rejects.toMatchObject({
+ name: 'ResearchCycleStopped',
+ event: {
+ phase: 'accepted',
+ key: null,
+ resourceId: projectId,
+ result: { id: saved.id, latestRevision: { id: saved.latestRevision.id } },
+ },
+ });
+ expect(f.calls).toHaveLength(2);
+ });
+ test('a definitive 429 stops without retries or creating another family', async () => {
+ const events: ResearchCycleEvent[] = [];
+ const f = client(path =>
+ path.endsWith('/budget')
+ ? Response.json(budget())
+ : Response.json({ error: 'Research budget exceeded' }, { status: 429 })
+ );
+ await expect(
+ runResearchCycle(f.api, plan(), {
+ onEvent: async event => {
+ events.push(event);
+ },
+ poll: { timeoutMs: 1000 },
+ })
+ ).rejects.toMatchObject({ event: { uncertain: false } });
+ expect(events.at(-1)?.error).toBe('Research budget exceeded');
+ expect(f.calls).toHaveLength(2);
+ });
+});
diff --git a/test/e2e/fixture.ts b/test/e2e/fixture.ts
index 6acc2c66..12e83b91 100644
--- a/test/e2e/fixture.ts
+++ b/test/e2e/fixture.ts
@@ -263,8 +263,11 @@ export async function fixture(browser: Browser, native = false) {
for (const name of [
'09-backtest-run-contract.sql',
'10-durable-backtest-dispatch.sql',
+ '11-simulation-execution-ledger.sql',
'12-historical-datasets.sql',
+ '13-strategy-recovery.sql',
'14-backtest-submission.sql',
+ '15-canonical-paper-intents.sql',
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
@@ -278,6 +281,9 @@ export async function fixture(browser: Browser, native = false) {
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
'28-research-agents.sql',
+ '29-isolated-candidates.sql',
+ '30-paper-deployments.sql',
+ '31-research-agent-project-links.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
@@ -410,7 +416,7 @@ export async function fixture(browser: Browser, native = false) {
origins: [],
resolveResearchCredential: request => researchAgents.authenticate(request),
});
- const routes = createRoutes(container, security);
+ const routes = createRoutes(container, security, {});
const wsRoute = createWebSocketRoute(container, security);
const sockets = new Set>();
const unexpectedNetwork: string[] = [];
@@ -446,6 +452,7 @@ export async function fixture(browser: Browser, native = false) {
!pathname.startsWith('/api/v2/research-agents') &&
!pathname.startsWith('/api/v2/research-agent/') &&
!pathname.startsWith('/api/v2/experiments') &&
+ !pathname.startsWith('/api/v2/paper-deployments') &&
!pathname.startsWith('/api/v2/hypotheses/') &&
!pathname.startsWith('/api/v2/analysis-artifacts/') &&
pathname !== '/api/auth/session') ||
@@ -507,6 +514,7 @@ export async function fixture(browser: Browser, native = false) {
}
});
const origin = `http://127.0.0.1:${server.port}`;
+ security.allowedOrigins.push(origin);
const context = await browser.newContext({ viewport: { width: 1440, height: 1080 } });
cleanup.push(() => context.close());
await context.route('**/*', route => {
diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts
index e46b0f1a..c4987b85 100644
--- a/test/e2e/workbench.test.ts
+++ b/test/e2e/workbench.test.ts
@@ -3010,3 +3010,262 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_
await f.close();
}
});
+
+test('isolated_candidate_publication_research_validation_and_reviewed_paper_history_browser', async () => {
+ const f = await fixture(true);
+ try {
+ const data = chronologicalDataset();
+ await retainResearchDataset(f.pool, data.dataset);
+ const builtin = (await f.seedCatalog()).find(
+ item => item.package.program.strategyId === 'sma_crossover'
+ )!;
+ await f.request(`/api/v2/strategy-versions/${builtin.id}/reviews`, 'POST', {
+ decision: 'approve',
+ reason: 'Disposable template baseline',
+ });
+ const retained = (await f.request(`/api/v2/strategy-versions/${builtin.id}/artifact`)).package;
+ const pkg = { ...retained, execution: { kind: 'isolated-candidate/v1', warmupBars: 3 } };
+ const family = (
+ await f.request('/api/v2/strategies', 'POST', {
+ name: 'Browser isolated candidate',
+ description: 'Retained controlled parity program',
+ })
+ ).strategy;
+ await f.login();
+ await f.page.goto(`${f.origin}/strategies/${family.id}`);
+ await f.page.getByLabel('Candidate package (JSON)').setInputFiles({
+ name: 'candidate.json',
+ mimeType: 'application/json',
+ buffer: Buffer.from(JSON.stringify(pkg)),
+ });
+ await visible(f.page, pkg.artifact.sha256);
+ const published = f.page.waitForResponse(
+ response =>
+ response.request().method() === 'POST' &&
+ response.url().endsWith(`/strategies/${family.id}/versions`)
+ );
+ await f.page.getByRole('button', { name: 'Publish immutable candidate', exact: true }).click();
+ const publication = await published;
+ expect(publication.status()).toBe(201);
+ const version = (await publication.json()).version;
+ expect(version.origin).toBe('candidate');
+ await f.page.waitForURL(url => url.pathname.endsWith(`/versions/${version.id}`));
+ expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(0);
+ const draft = await f.request('/api/v2/backtests', 'POST', {
+ name: 'Browser candidate template',
+ autoStart: false,
+ strategy: 'catalog',
+ strategyVersionId: builtin.id,
+ strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
+ symbols: ['X0.US'],
+ startDate: new Date(data.dataset.manifest.bounds.tradeStart).toISOString(),
+ endDate: new Date(data.dataset.manifest.bounds.tradeEnd).toISOString(),
+ initialCapital: 10000,
+ config: {
+ datasetHash: data.dataset.manifest.hash,
+ dataFrequency: '1m',
+ canonical: canonicalSettings,
+ },
+ });
+ await f.page.goto(`${f.origin}/experiments?backtestId=${draft.id}`);
+ await f.page.getByLabel('Experiment name', { exact: true }).fill('Isolated browser experiment');
+ await f.page.getByLabel('Use an isolated candidate version', { exact: true }).check();
+ const section = f.page.getByRole('region', {
+ name: 'Candidate experiment strategy',
+ exact: true,
+ });
+ await section.getByLabel('Strategy family', { exact: true }).selectOption(family.id);
+ await section
+ .getByLabel('Immutable strategy version', { exact: true })
+ .selectOption(version.id);
+ await section.getByLabel('fastPeriod', { exact: true }).fill('2');
+ await section.getByLabel('slowPeriod', { exact: true }).fill('3');
+ await section.getByRole('button', { name: 'Validate parameters', exact: true }).click();
+ await visible(f.page, /Parameters validated/);
+ await f.page.getByRole('button', { name: 'Preview experiment', exact: true }).click();
+ await visible(f.page, /Isolated TypeScript candidate/);
+ const submitted = f.page.waitForResponse(
+ response =>
+ response.request().method() === 'POST' && response.url().endsWith('/api/v2/experiments')
+ );
+ await f.page.getByRole('button', { name: 'Confirm experiment', exact: true }).click();
+ const experiment = (await (await submitted).json()).experiment as ExperimentDetail;
+ expect(experiment.preview.input.candidate).toEqual({
+ versionId: version.id,
+ parameters: { fastPeriod: 2, slowPeriod: 3 },
+ });
+ expect(experiment.preview.request.strategy.reviewId).toBeNull();
+ await f.dispatcher.start();
+ const completeExperiment = async (id: string) => {
+ await until(
+ async () =>
+ (await f.request(`/api/v2/experiments/${id}`)).experiment.trials.every(
+ (trial: { status: string }) =>
+ ['completed', 'failed', 'cancelled', 'missing'].includes(trial.status)
+ ),
+ 'candidate trials finish',
+ 45000
+ );
+ const result = (await f.request(`/api/v2/experiments/${id}`)).experiment;
+ expect(result.trials.every((trial: { status: string }) => trial.status === 'completed')).toBe(
+ true
+ );
+ return result;
+ };
+ const completed = await completeExperiment(experiment.id);
+ const runId = completed.trials[0].runId;
+ const result = (await f.request(`/api/v2/runs/${runId}/results`)) as CanonicalRunResult;
+ expect(result.strategyExecution).toBe('typescript-isolated-candidate/v1');
+ expect(result.request.strategy.origin).toBe('candidate');
+ await f.page.goto(`${f.origin}/backtests/${draft.id}/run/${runId}`);
+ await visible(f.page, /isolated TypeScript candidate/);
+ await f.page.reload();
+ await visible(f.page, result.request.datasetHash);
+
+ // Real immutable validation and cost evidence prepare the human promotion screen.
+ const candidate = { versionId: version.id, parameters: { fastPeriod: 2, slowPeriod: 3 } };
+ const validationInput = {
+ backtestId: draft.id,
+ name: 'Browser candidate holdouts',
+ grid: {},
+ recipe: data.recipe,
+ candidate,
+ };
+ const previewResponse = await f.request(
+ '/api/v2/experiments/validation/preview',
+ 'POST',
+ validationInput
+ );
+ const preview = previewResponse.preview as ChronologicalValidationPreview;
+ const validation = (
+ await f.request(
+ '/api/v2/experiments/validation',
+ 'POST',
+ { ...validationInput, previewHash: preview.previewHash },
+ { 'Idempotency-Key': randomUUID() }
+ )
+ ).validation as ChronologicalValidationDetail;
+ expect(preview.policy.model).toBe('unverified-candidate');
+ await completeExperiment(validation.phases[0]!.experimentId!);
+ const selected = (await f.request(
+ `/api/v2/experiments/validation/${validation.id}/select`,
+ 'POST',
+ { previewHash: preview.previewHash },
+ { 'Idempotency-Key': randomUUID() }
+ )) as ChronologicalValidationActionResult;
+ for (const phase of selected.validation.phases.slice(1)) {
+ await completeExperiment(phase.experimentId!);
+ }
+ const finished = (await f.request(
+ `/api/v2/experiments/validation/${validation.id}/finalize`,
+ 'POST',
+ {
+ previewHash: preview.previewHash,
+ selectionHash: selected.validation.selection!.selectionHash,
+ },
+ { 'Idempotency-Key': randomUUID() }
+ )) as ChronologicalValidationActionResult;
+ expect(finished.validation.report).not.toBeNull();
+ const costInput = {
+ backtestId: draft.id,
+ name: 'Browser candidate costs',
+ scenarios: [{ feeRate: '0.02', slippageRate: '0.01' }],
+ candidate,
+ };
+ const costPreview = (
+ await f.request('/api/v2/experiments/cost-sensitivity/preview', 'POST', costInput)
+ ).preview as CostSensitivityPreview;
+ const cost = (
+ await f.request(
+ '/api/v2/experiments/cost-sensitivity',
+ 'POST',
+ { ...costInput, previewHash: costPreview.previewHash },
+ { 'Idempotency-Key': randomUUID() }
+ )
+ ).experiment as CostSensitivityDetail;
+ await completeExperiment(cost.id);
+ await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
+ decision: 'approve',
+ reason: 'Human reviewed controlled candidate bytes and actual held-out/cost evidence',
+ });
+ await f.page.goto(`${f.origin}/paper`);
+ await visible(f.page, /No paper deployments/);
+ await f.page.getByLabel('Deployment name', { exact: true }).fill('Reviewed browser candidate');
+ await f.page.getByLabel('Report owner ID', { exact: true }).fill(validation.id);
+ await f.page.getByLabel('Cost experiment ID', { exact: true }).fill(cost.id);
+ await f.page.getByRole('button', { name: 'Load evidence', exact: true }).click();
+ await f.page
+ .getByLabel('Paper cost scenario', { exact: true })
+ .selectOption(cost.trials[1]!.runId!);
+ const start = Date.parse('2030-01-01T14:30:00Z');
+ await f.page.getByLabel('Paper transport', { exact: true }).fill(
+ JSON.stringify({
+ accountId: `paper:${randomUUID()}`,
+ sessionId: `paper:${randomUUID()}`,
+ quoteSeriesId: 'X0.US:quote',
+ riskSession: {
+ calendarId: 'paper-risk',
+ calendarRevision: 'v1',
+ sessionId: 'paper-day',
+ startsAt: start,
+ },
+ policy: {
+ version: 1,
+ sourceId: 'disposable-browser-feed',
+ priceBasis: 'raw',
+ maxFeedAgeMs: 300000,
+ observations: [
+ {
+ instrumentId: 'X0.US',
+ seriesId: 'X0.US:1m',
+ intervalMs: 60000,
+ staleAfterMs: 300000,
+ },
+ ],
+ cadence: [{ ownerId: `strategy:${version.id}`, seriesIds: ['X0.US:1m'] }],
+ calendars: [
+ {
+ instrumentId: 'X0.US',
+ calendarId: 'explicit-venue',
+ revision: 'v1',
+ sessions: [{ sessionId: 'paper-day', opensAt: start, closesAt: start + 3600000 }],
+ },
+ ],
+ riskBoundaries: [],
+ },
+ })
+ );
+ await f.page
+ .getByLabel('Review rationale', { exact: true })
+ .fill(
+ 'Controlled fixture evidence and code reviewed; no profitability claim or real activation.'
+ );
+ await f.page.getByLabel('Authorize trusted paper code', { exact: true }).check();
+ await f.page.getByRole('button', { name: 'Preview promotion', exact: true }).click();
+ await visible(f.page, 'Exact promotion preview');
+ const promotionResponse = f.page.waitForResponse(
+ response =>
+ response.request().method() === 'POST' &&
+ response.url().endsWith('/api/v2/paper-deployments')
+ );
+ await f.page.getByRole('button', { name: 'Create halted deployment', exact: true }).click();
+ const promoted = await promotionResponse;
+ expect(promoted.status()).toBe(201);
+ const deployment = await promoted.json();
+ await f.page.waitForURL(url => url.pathname.endsWith(`/paper/${deployment.id}`));
+ await visible(f.page, 'Reviewed browser candidate');
+ await visible(f.page, /Paper orchestrator origin is not configured/);
+ expect(
+ (await f.pool.query('SELECT count(*)::int AS count FROM simulation_accounts')).rows[0].count
+ ).toBe(0);
+ await f.page.reload();
+ await visible(f.page, 'Reviewed browser candidate');
+ expect(
+ (await f.request(`/api/v2/paper-deployments/${deployment.id}`)).preview.strategy.versionId
+ ).toBe(version.id);
+ expect(f.unexpectedNetwork).toEqual([]);
+ expect(f.historicalDataReads).toEqual([]);
+ } finally {
+ await f.close();
+ }
+}, 180000);
diff --git a/test/integration/candidate-contract.test.ts b/test/integration/candidate-contract.test.ts
new file mode 100644
index 00000000..1b5d2a64
--- /dev/null
+++ b/test/integration/candidate-contract.test.ts
@@ -0,0 +1,200 @@
+import { randomUUID } from 'node:crypto';
+import { PassThrough } from 'node:stream';
+import { describe, expect, test } from 'bun:test';
+import {
+ candidateExecutionSchema,
+ candidateSandboxLimits,
+} from '../../apps/stock/config/src/contracts/candidate-execution';
+import {
+ canonicalRunRequestSchema,
+ canonicalStrategyExecution,
+} from '../../apps/stock/config/src/contracts/canonical-research';
+import {
+ chronologicalPolicyForOrigin,
+ chronologicalValidationPolicy,
+} from '../../apps/stock/config/src/contracts/chronological-validation';
+import { experimentInputSchema } from '../../apps/stock/config/src/contracts/experiments';
+import {
+ readCandidateFrames,
+ writeCandidateFrame,
+} from '../../apps/stock/orchestrator/src/backtest/candidate-protocol';
+import { researchGrantPolicy } from '../../apps/stock/web-api/src/services/research-agent-budget';
+import { canonicalRunnerFixture } from '../fixtures/canonical-runner';
+
+export const fakeCandidateExecution = () =>
+ candidateExecutionSchema.parse({
+ kind: 'typescript-isolated-candidate/v1',
+ imageId: `sha256:${'a'.repeat(64)}`,
+ profile: {
+ version: 1,
+ policy: 'linux-docker-guardian/v1',
+ protocol: 'candidate-controller/v1',
+ platform: 'linux',
+ arch: 'x64',
+ hostSha256: 'b'.repeat(64),
+ guardianSha256: 'c'.repeat(64),
+ bunSha256: 'd'.repeat(64),
+ limits: candidateSandboxLimits,
+ },
+ });
+function candidateFixture() {
+ const { request } = canonicalRunnerFixture();
+ const candidateId = randomUUID(),
+ ownerId = `strategy:${candidateId}`;
+ const policy = structuredClone(request.policy);
+ policy.matching.risk.ledger.ownerIds = [ownerId];
+ policy.matching.owners = [{ ownerId, mode: 'Target' }];
+ policy.cadence = [{ owner_id: ownerId, series_ids: [request.strategy.selection.seriesId] }];
+ const candidate = {
+ ...request,
+ policy,
+ strategy: {
+ ...request.strategy,
+ origin: 'candidate',
+ versionId: candidateId,
+ baselineVersionId: request.strategy.versionId,
+ reviewId: null,
+ execution: fakeCandidateExecution(),
+ package: {
+ ...request.strategy.package,
+ execution: { kind: 'isolated-candidate/v1', warmupBars: 0 },
+ },
+ selection: { ...request.strategy.selection, ownerId },
+ },
+ };
+ return { builtin: request, candidate: canonicalRunRequestSchema.parse(candidate) };
+}
+describe('isolated candidate contracts', () => {
+ test('builtin snapshots and grant projection retain exact existing bytes', () => {
+ const { builtin } = candidateFixture();
+ expect(JSON.stringify(canonicalRunRequestSchema.parse(builtin))).toBe(JSON.stringify(builtin));
+ expect(canonicalStrategyExecution(builtin)).toBe('typescript-retained-builtin/v1');
+ expect(builtin.strategy).not.toHaveProperty('execution');
+ expect(builtin.strategy).not.toHaveProperty('baselineVersionId');
+ const policy = researchGrantPolicy(builtin);
+ expect(policy.versionId).toBe(builtin.strategy.versionId);
+ expect(policy.policy.matching.owners).toEqual(builtin.policy.matching.owners);
+ });
+ test('candidate alone accepts no review, generic identity and fixed declared warmup', () => {
+ const { builtin, candidate } = candidateFixture();
+ expect(candidate.strategy.reviewId).toBeNull();
+ expect(canonicalStrategyExecution(candidate)).toBe('typescript-isolated-candidate/v1');
+ expect(
+ canonicalRunRequestSchema.safeParse({
+ ...builtin,
+ strategy: { ...builtin.strategy, reviewId: null },
+ }).success
+ ).toBeFalse();
+ for (const field of ['execution', 'baselineVersionId']) {
+ const malformed = {
+ ...candidate,
+ strategy: Object.fromEntries(
+ Object.entries(candidate.strategy).filter(([name]) => name !== field)
+ ),
+ };
+ expect(canonicalRunRequestSchema.safeParse(malformed).success).toBeFalse();
+ }
+ expect(
+ canonicalRunRequestSchema.safeParse({
+ ...builtin,
+ strategy: { ...builtin.strategy, execution: fakeCandidateExecution() },
+ }).success
+ ).toBeFalse();
+ });
+ test('candidate maps only its derived identities back to the frozen baseline grant', () => {
+ const { builtin, candidate } = candidateFixture();
+ expect(researchGrantPolicy(candidate)).toEqual(researchGrantPolicy(builtin));
+ const changed = structuredClone(candidate);
+ changed.policy.matching.risk.maxGrossExposure =
+ '1.00000000' as typeof changed.policy.matching.risk.maxGrossExposure;
+ expect(researchGrantPolicy(changed)).not.toEqual(researchGrantPolicy(builtin));
+ if (changed.strategy.origin !== 'candidate') {
+ throw new Error('fixture origin');
+ }
+ changed.strategy.baselineVersionId = randomUUID();
+ expect(researchGrantPolicy(changed).versionId).not.toBe(researchGrantPolicy(builtin).versionId);
+ });
+ test('profile cannot raise limits, choose trusted execution, add host flags or choose an unsupported platform', () => {
+ const execution = fakeCandidateExecution();
+ for (const changed of [
+ { ...execution, kind: 'typescript-retained-builtin/v1' },
+ { ...execution, flags: ['--privileged'] },
+ { ...execution, profile: { ...execution.profile, arch: 'arm64' } },
+ {
+ ...execution,
+ profile: {
+ ...execution.profile,
+ limits: { ...execution.profile.limits, memoryBytes: 1073741824 },
+ },
+ },
+ ]) {
+ expect(candidateExecutionSchema.safeParse(changed).success).toBeFalse();
+ }
+ });
+ test('candidate input is explicit and strategy policy never claims inferred determinism', () => {
+ const input = {
+ backtestId: randomUUID(),
+ name: 'Candidate',
+ grid: {},
+ candidate: { versionId: randomUUID(), parameters: {} },
+ };
+ expect(experimentInputSchema.parse(input)).toEqual(input);
+ expect(
+ experimentInputSchema.safeParse({ ...input, candidate: { ...input.candidate, feeRate: '0' } })
+ .success
+ ).toBeFalse();
+ expect(chronologicalPolicyForOrigin('builtin')).toBe(chronologicalValidationPolicy);
+ expect(chronologicalPolicyForOrigin('candidate')).toEqual({
+ ...chronologicalValidationPolicy,
+ model: 'unverified-candidate',
+ });
+ });
+ test('framing preserves exact JSON across chunks and rejects truncation/oversize before parsing', async () => {
+ const encoded = new PassThrough();
+ const output: unknown[] = [];
+ const read = (async () => {
+ for await (const frame of readCandidateFrames(encoded)) {
+ output.push(frame);
+ }
+ })();
+ await writeCandidateFrame(encoded, { version: 1, string: 'Unicode α', sequence: 1 });
+ encoded.end();
+ await read;
+ expect(output).toEqual([{ version: 1, string: 'Unicode α', sequence: 1 }]);
+ for (const length of [0, candidateSandboxLimits.frameBytes + 1]) {
+ const input = new PassThrough(),
+ bytes = Buffer.alloc(4);
+ bytes.writeUInt32BE(length);
+ input.end(bytes);
+ await expect(readCandidateFrames(input).next()).rejects.toThrow('Invalid or oversized');
+ }
+ const input = new PassThrough();
+ input.end(Buffer.from([0, 0, 0, 5, 123]));
+ await expect(readCandidateFrames(input).next()).rejects.toThrow('Truncated');
+ });
+ test('split UTF-8 frames are decoded only when complete; malformed UTF-8 and flooding are rejected', async () => {
+ const content = Buffer.from(JSON.stringify({ value: 'αβ😀' }));
+ const header = Buffer.alloc(4);
+ header.writeUInt32BE(content.length);
+ const input = new PassThrough();
+ const collected = (async () => {
+ const out: unknown[] = [];
+ for await (const value of readCandidateFrames(input)) {
+ out.push(value);
+ }
+ return out;
+ })();
+ for (const byte of Buffer.concat([header, content])) {
+ input.write(Buffer.from([byte]));
+ await Promise.resolve();
+ }
+ input.end();
+ expect(await collected).toEqual([{ value: 'αβ😀' }]);
+ const invalid = new PassThrough();
+ invalid.end(Buffer.from([0, 0, 0, 1, 255]));
+ await expect(readCandidateFrames(invalid).next()).rejects.toThrow();
+ const flood = new PassThrough();
+ flood.end(Buffer.alloc(candidateSandboxLimits.frameBytes + 5));
+ await expect(readCandidateFrames(flood).next()).rejects.toThrow('buffer exceeds');
+ });
+});
diff --git a/test/integration/candidate-publication-ui.test.tsx b/test/integration/candidate-publication-ui.test.tsx
new file mode 100644
index 00000000..5387ee6c
--- /dev/null
+++ b/test/integration/candidate-publication-ui.test.tsx
@@ -0,0 +1,296 @@
+import { createHash } from 'node:crypto';
+import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test';
+import { GlobalWindow } from 'happy-dom';
+import { act, createElement } from 'react';
+import type { Root } from 'react-dom/client';
+import type { StrategyVersionPackage } from '@stock-bot/types';
+import { tableFixture } from '../../scripts/benchmark-experiment-tables';
+
+const browser = new GlobalWindow({ url: 'http://localhost:5173' });
+const keys = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const;
+const originals = keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)] as const);
+const familyId = '11111111-1111-4111-8111-111111111111';
+const versionId = '22222222-2222-4222-8222-222222222222';
+let createRoot: typeof import('react-dom/client').createRoot;
+let Publication: typeof import('../../apps/stock/web-app/src/features/strategies/components/CandidatePublication').CandidatePublication;
+let readPackage: typeof import('../../apps/stock/web-app/src/features/strategies/services/candidatePublication').readCandidatePackage;
+let publish: typeof import('../../apps/stock/web-app/src/features/strategies/services/candidatePublication').publishCandidate;
+let root: Root | undefined;
+let host: HTMLDivElement;
+const saved: unknown[] = [];
+const dirty: boolean[] = [];
+type Pending = {
+ url: string;
+ body: { package: StrategyVersionPackage; parentVersionId: string | null };
+ key: string;
+ resolve: (response: Response) => void;
+ reject: (error: Error) => void;
+ settled: boolean;
+};
+const calls: Pending[] = [];
+function pkg(label = 'first'): StrategyVersionPackage {
+ const value = structuredClone(tableFixture(1).preview.request.strategy.package);
+ value.execution = { kind: 'isolated-candidate/v1', warmupBars: 0 };
+ value.artifact.content = `globalThis.__candidatePublicationExecuted = '${label}';`;
+ value.artifact.sha256 = createHash('sha256').update(value.artifact.content).digest('hex');
+ value.dependencyLock.sha256 = createHash('sha256')
+ .update(value.dependencyLock.content)
+ .digest('hex');
+ return value;
+}
+async function flush(action = () => {}) {
+ await act(async () => {
+ action();
+ await Promise.resolve();
+ });
+}
+function button(text: string) {
+ return [...host.querySelectorAll('button')].find(item => item.textContent?.trim() === text)!;
+}
+const fileField = () => host.querySelector('input[type="file"]') as HTMLInputElement;
+async function choose(value: { name: string; text: () => Promise }) {
+ await flush(() => {
+ Object.defineProperty(fileField(), 'files', { configurable: true, value: [value] });
+ fileField().dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event);
+ });
+}
+async function upload(value = pkg()) {
+ await choose({ name: 'candidate.json', text: async () => JSON.stringify(value) });
+}
+function reply(request: Pending, body: unknown, status: number) {
+ request.settled = true;
+ request.resolve(Response.json(body, { status }));
+}
+function receipt(request: Pending) {
+ return {
+ version: {
+ id: versionId,
+ strategyId: familyId,
+ ordinal: 1,
+ origin: 'candidate',
+ parentVersionId: request.body.parentVersionId,
+ package: request.body.package,
+ },
+ };
+}
+async function mount(parentVersionId: string | null = null) {
+ root = createRoot(host);
+ await flush(() =>
+ root!.render(
+ createElement(Publication, {
+ strategyId: familyId,
+ parentVersionId,
+ disabled: false,
+ onDirtyChange: value => dirty.push(value),
+ onPublished: value => saved.push(value),
+ })
+ )
+ );
+}
+beforeAll(async () => {
+ for (const [key, value] of Object.entries({
+ window: browser,
+ document: browser.document,
+ IS_REACT_ACT_ENVIRONMENT: true,
+ })) {
+ Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
+ }
+ ({ createRoot } = await import('react-dom/client'));
+ ({ CandidatePublication: Publication } = await import(
+ '../../apps/stock/web-app/src/features/strategies/components/CandidatePublication'
+ ));
+ ({ readCandidatePackage: readPackage, publishCandidate: publish } = await import(
+ '../../apps/stock/web-app/src/features/strategies/services/candidatePublication'
+ ));
+});
+beforeEach(() => {
+ calls.length = 0;
+ saved.length = 0;
+ dirty.length = 0;
+ host = browser.document.createElement('div') as unknown as HTMLDivElement;
+ browser.document.body.append(host as never);
+ browser.fetch = ((url: unknown, init?: RequestInit) =>
+ new Promise((resolve, reject) => {
+ calls.push({
+ url: String(url),
+ body: JSON.parse(String(init?.body)),
+ key: new Headers(init?.headers).get('Idempotency-Key')!,
+ resolve,
+ reject,
+ settled: false,
+ });
+ })) as unknown as typeof browser.fetch;
+});
+afterEach(async () => {
+ await flush(() => root?.unmount());
+ root = undefined;
+ host.remove();
+});
+afterAll(() => {
+ for (const [key, descriptor] of originals) {
+ if (descriptor) {
+ Object.defineProperty(globalThis, key, descriptor);
+ } else {
+ Reflect.deleteProperty(globalThis, key);
+ }
+ }
+ browser.happyDOM.abort();
+});
+
+test('package upload verifies retained hashes and declaration without executing generated source', async () => {
+ await mount();
+ expect(button('Publish immutable candidate').disabled).toBe(true);
+ const value = pkg();
+ await upload(value);
+ expect(host.textContent).toContain(value.artifact.sha256);
+ expect(host.textContent).toContain('Author-declared warmup bars');
+ expect((globalThis as Record).__candidatePublicationExecuted).toBeUndefined();
+ expect(calls).toHaveLength(0);
+ await flush(() => button('Publish immutable candidate').click());
+ expect(calls[0]!.body).toEqual({ package: value, parentVersionId: null });
+ expect(calls[0]!.key).not.toBe('');
+ await flush(() => reply(calls[0]!, receipt(calls[0]!), 201));
+ expect(saved).toEqual([{ id: versionId, strategyId: familyId, ordinal: 1 }]);
+ expect(dirty.at(-1)).toBe(false);
+ expect(button('Publish immutable candidate').disabled).toBe(true);
+});
+
+test('invalid bytes, absent execution declaration and stale file reads never become a publication', async () => {
+ const invalid = pkg();
+ invalid.artifact.sha256 = 'f'.repeat(64);
+ await expect(readPackage(JSON.stringify(invalid))).rejects.toThrow('hash does not match');
+ const legacy = pkg();
+ delete legacy.execution;
+ await expect(readPackage(JSON.stringify(legacy))).rejects.toThrow('must declare');
+ await mount();
+ await upload(invalid);
+ expect(host.querySelector('[role="alert"]')).not.toBeNull();
+ expect(button('Publish immutable candidate').disabled).toBe(true);
+ let release!: (text: string) => void;
+ await choose({
+ name: 'old.json',
+ text: () =>
+ new Promise(resolve => {
+ release = resolve;
+ }),
+ });
+ const current = pkg('current');
+ await upload(current);
+ await flush(() => release(JSON.stringify(pkg('old'))));
+ expect(host.textContent).toContain(current.artifact.sha256);
+ expect(host.textContent).not.toContain(pkg('old').artifact.sha256);
+ await flush(() => button('Clear package').click());
+ expect(button('Publish immutable candidate').disabled).toBe(true);
+ expect(calls).toHaveLength(0);
+});
+
+test('lost publication freezes package, lineage and key; repeated clicks recover one receipt', async () => {
+ const parent = '33333333-3333-4333-8333-333333333333';
+ await mount(parent);
+ await upload();
+ await flush(() => {
+ button('Publish immutable candidate').click();
+ button('Publish immutable candidate').click();
+ });
+ expect(calls).toHaveLength(1);
+ await flush(() => {
+ calls[0]!.settled = true;
+ calls[0]!.reject(new Error('Connection lost'));
+ });
+ expect(fileField().disabled).toBe(true);
+ expect(button('Clear package').disabled).toBe(true);
+ await upload(pkg('changed'));
+ await flush(() => button('Retry same publication').click());
+ expect(calls).toHaveLength(2);
+ expect(calls[1]!.body).toEqual(calls[0]!.body);
+ expect(calls[1]!.key).toBe(calls[0]!.key);
+ expect(calls[1]!.body.parentVersionId).toBe(parent);
+ await flush(() => reply(calls[1]!, receipt(calls[1]!), 201));
+ expect(saved).toHaveLength(1);
+});
+
+test('definitive rejection permits correction; wrong success receipt remains uncertain', async () => {
+ await mount();
+ await upload();
+ await flush(() => button('Publish immutable candidate').click());
+ await flush(() => reply(calls[0]!, { error: 'Archived family' }, 409));
+ expect(fileField().disabled).toBe(false);
+ expect(host.textContent).toContain('Archived family');
+ await flush(() => button('Publish immutable candidate').click());
+ expect(calls[1]!.key).not.toBe(calls[0]!.key);
+ const wrong = receipt(calls[1]!);
+ wrong.version.strategyId = versionId;
+ await flush(() => reply(calls[1]!, wrong, 201));
+ expect(fileField().disabled).toBe(true);
+ expect(button('Retry same publication')).not.toBeUndefined();
+ expect(saved).toHaveLength(0);
+});
+
+test('unmounted publication cannot navigate or replace a new family', async () => {
+ await mount();
+ await upload();
+ await flush(() => button('Publish immutable candidate').click());
+ await flush(() => root!.unmount());
+ root = undefined;
+ await flush(() => reply(calls[0]!, receipt(calls[0]!), 201));
+ expect(saved).toHaveLength(0);
+ expect(host.textContent).toBe('');
+});
+
+test('same-event Publish then Clear preserves the only recoverable package and receipt', async () => {
+ await mount();
+ const value = pkg();
+ await upload(value);
+ await flush(() => {
+ button('Publish immutable candidate').click();
+ button('Clear package').click();
+ });
+ expect(calls).toHaveLength(1);
+ expect(host.textContent).toContain(value.artifact.sha256);
+ await flush(() => calls[0]!.reject(new Error('Lost accepted response')));
+ expect(button('Retry same publication').disabled).toBe(false);
+ await flush(() => button('Retry same publication').click());
+ expect(calls[1]!.key).toBe(calls[0]!.key);
+ expect(calls[1]!.body).toEqual(calls[0]!.body);
+ await flush(() => reply(calls[1]!, receipt(calls[1]!), 201));
+ expect(saved).toHaveLength(1);
+});
+
+test('later archive or eligibility loss blocks new publication but preserves an accepted receipt retry', async () => {
+ await mount();
+ await upload();
+ await flush(() => button('Publish immutable candidate').click());
+ await flush(() => calls[0]!.reject(new Error('Lost accepted response')));
+ await flush(() =>
+ root!.render(
+ createElement(Publication, {
+ strategyId: familyId,
+ parentVersionId: null,
+ disabled: true,
+ onDirtyChange: value => dirty.push(value),
+ onPublished: value => saved.push(value),
+ })
+ )
+ );
+ expect(fileField().disabled).toBe(true);
+ expect(button('Retry same publication').disabled).toBe(false);
+ await flush(() => button('Retry same publication').click());
+ expect(calls[1]!.body).toEqual(calls[0]!.body);
+ expect(calls[1]!.key).toBe(calls[0]!.key);
+ await flush(() => reply(calls[1]!, receipt(calls[1]!), 201));
+ expect(saved).toHaveLength(1);
+ expect(button('Publish immutable candidate').disabled).toBe(true);
+});
+
+test('uppercase family and parent identities normalize before sending and checking publication', async () => {
+ const family = 'abcdefab-abcd-4bcd-8bcd-abcdefabcdef';
+ const parent = 'fabcdefa-abcd-4bcd-8bcd-abcdefabcdef';
+ const published = publish(family.toUpperCase(), pkg(), parent.toUpperCase(), 'case-normalized');
+ const call = calls[0]!;
+ expect(call.url).toContain(`/strategies/${family}/versions`);
+ expect(call.body.parentVersionId).toBe(parent);
+ const body = receipt(call);
+ body.version.strategyId = family;
+ reply(call, body, 201);
+ expect((await published).strategyId).toBe(family);
+});
diff --git a/test/integration/candidate-response-contract.test.ts b/test/integration/candidate-response-contract.test.ts
new file mode 100644
index 00000000..d40d2651
--- /dev/null
+++ b/test/integration/candidate-response-contract.test.ts
@@ -0,0 +1,63 @@
+import { expect, test } from 'bun:test';
+import { candidateSandboxLimits } from '@stock-bot/stock-config/candidate-execution';
+import { validateStrategyParameters } from '@stock-bot/stock-config/strategy';
+import { parseExperimentPreview } from '../../apps/stock/config/src/contracts/research-responses/experiment';
+import { tableFixture } from '../../scripts/benchmark-experiment-tables';
+
+function candidatePreview() {
+ const value = structuredClone(tableFixture(1).preview);
+ const strategy = value.request.strategy;
+ value.input.candidate = {
+ versionId: strategy.versionId,
+ parameters: { ...strategy.selection.parameters },
+ };
+ value.request.strategy = {
+ ...strategy,
+ origin: 'candidate',
+ reviewId: null,
+ baselineVersionId: strategy.versionId,
+ package: { ...strategy.package, execution: { kind: 'isolated-candidate/v1', warmupBars: 0 } },
+ execution: {
+ kind: 'typescript-isolated-candidate/v1',
+ imageId: `sha256:${'a'.repeat(64)}`,
+ profile: {
+ version: 1,
+ policy: 'linux-docker-guardian/v1',
+ protocol: 'candidate-controller/v1',
+ platform: 'linux',
+ arch: 'x64',
+ hostSha256: 'b'.repeat(64),
+ guardianSha256: 'c'.repeat(64),
+ bunSha256: 'd'.repeat(64),
+ limits: candidateSandboxLimits,
+ },
+ },
+ };
+ return value;
+}
+test('candidate preview binds normalized base parameters independently of valid package/version identity', () => {
+ const value = candidatePreview();
+ expect(parseExperimentPreview(value).input.candidate).toEqual(value.input.candidate!);
+ const changed = structuredClone(value);
+ changed.input.candidate!.parameters.fastPeriod = 1;
+ expect(() => parseExperimentPreview(changed)).toThrow('could not be verified');
+ const changedRequest = structuredClone(value);
+ if (changedRequest.request.strategy.origin !== 'candidate') {
+ throw new Error('Expected candidate fixture');
+ }
+ changedRequest.request.strategy.selection.parameters.fastPeriod = 1;
+ expect(() => parseExperimentPreview(changedRequest)).toThrow('could not be verified');
+});
+test('candidate parameter defaults are accepted when they exactly match the retained base selection', () => {
+ const value = candidatePreview();
+ value.input.candidate!.parameters = {};
+ value.request.strategy.selection.parameters = validateStrategyParameters(
+ value.request.strategy.package,
+ {}
+ );
+ expect(parseExperimentPreview(value).request.strategy.selection.parameters).toEqual(
+ value.request.strategy.selection.parameters
+ );
+ value.input.candidate!.parameters.fastPeriod = 1;
+ expect(() => parseExperimentPreview(value)).toThrow('could not be verified');
+});
diff --git a/test/integration/candidate-sandbox.test.ts b/test/integration/candidate-sandbox.test.ts
new file mode 100644
index 00000000..e6d71acd
--- /dev/null
+++ b/test/integration/candidate-sandbox.test.ts
@@ -0,0 +1,497 @@
+import { execFile, fork, type ChildProcessWithoutNullStreams } from 'node:child_process';
+import { createHash, randomUUID } from 'node:crypto';
+import { readlinkSync } from 'node:fs';
+import { access, mkdtemp, rename, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { promisify } from 'node:util';
+import { describe, expect, test } from 'bun:test';
+import { canonicalRunRequestSchema } from '../../apps/stock/config/src/contracts/canonical-research';
+import {
+ candidateDescriptorPath,
+ IsolatedCandidateController,
+ readCandidateExecution,
+ removeCandidateContainer,
+} from '../../apps/stock/orchestrator/src/backtest/candidate-sandbox';
+import {
+ canonicalWorkerUrl,
+ readCanonicalBuildIdentity,
+} from '../../apps/stock/orchestrator/src/backtest/canonical-build';
+import {
+ NativeReplaySession,
+ prepareReplayLoad,
+ runReplaySessionAsync,
+} from '../../apps/stock/orchestrator/src/backtest/native-replay';
+import { packageCandidateStrategy } from '../../scripts/package-candidate-strategy';
+import { canonicalRunnerFixture } from '../fixtures/canonical-runner';
+import { canonicalSmaFixture } from '../fixtures/canonical-sma';
+
+const suite = process.env.CANDIDATE_SANDBOX_TESTS === '1' ? describe : describe.skip;
+const hash = (s: string) => createHash('sha256').update(s).digest('hex');
+const runFile = promisify(execFile);
+const hostPidNamespace = readlinkSync('/proc/self/ns/pid');
+const program = (
+ decision = "return {nextState:c.state,intent:{mode:'target',targets:[]}}",
+ prefix = ''
+) =>
+ `${prefix}\nexport function createStrategy(s) { return {ownerId:s.ownerId,strategyId:s.strategyId,strategyVersion:s.strategyVersion,seed:s.seed,mode:'target',initialState:null,decide(c){${decision}}}; }`;
+async function fixture(content: string) {
+ const f = canonicalRunnerFixture();
+ const pkg = {
+ ...f.request.strategy.package,
+ execution: { kind: 'isolated-candidate/v1', warmupBars: 0 },
+ program: {
+ strategyId: 'isolated-probe',
+ strategyVersion: 'v1',
+ apiVersion: 'canonical-ts/v1',
+ checkpointVersion: '1',
+ },
+ parameterSchema: {
+ version: 1,
+ type: 'object',
+ properties: {},
+ required: [],
+ additionalProperties: false,
+ },
+ artifact: {
+ format: 'esm-bundle/v1',
+ entryExport: 'createStrategy',
+ content,
+ sha256: hash(content),
+ },
+ dependencyLock: { format: 'bun-lock/v1', content: '{}', sha256: hash('{}') },
+ };
+ const request = canonicalRunRequestSchema.parse({
+ ...f.request,
+ strategy: {
+ ...f.request.strategy,
+ origin: 'candidate',
+ baselineVersionId: f.request.strategy.versionId,
+ reviewId: null,
+ execution: await readCandidateExecution(),
+ package: pkg,
+ selection: {
+ ...f.request.strategy.selection,
+ strategyId: 'isolated-probe',
+ strategyVersion: 'v1',
+ parameters: {},
+ },
+ },
+ });
+ return { ...f, request, name: `stock-bot-candidate-${randomUUID()}` };
+}
+async function absent(name: string) {
+ expect(
+ (
+ await runFile('/usr/bin/docker', [
+ '--host',
+ 'unix:///var/run/docker.sock',
+ 'ps',
+ '-a',
+ '-q',
+ '--filter',
+ `name=^/${name}$`,
+ ])
+ ).stdout.trim()
+ ).toBe('');
+}
+suite('actual OS-isolated candidate runtime', () => {
+ test('host environment/files/network/process spawning denied; ordinary prefix-only computation completes under native finance', async () => {
+ const f = await fixture(
+ program(
+ "if(c.observations.some(o=>o.available_at>c.now))throw Error('future observation'); if('dataset' in c || 'history' in c)throw Error('unexpected dataset'); return {nextState:null,intent:{mode:'target',targets:[]}}",
+ `
+ if(Object.keys(process.env).length!==0)throw Error('inherited environment');
+ if(process.getuid()!==65534)throw Error('privileged child');
+ const fs=await import('node:fs');
+ try{fs.readFileSync('/home/boki/repos/stock-bot/.env');throw Error('host file visible')}catch(e){if(e.code!=='ENOENT')throw e}
+ try{fs.writeFileSync('/app/forbidden','x');throw Error('root writable')}catch(e){if(!['EROFS','EACCES'].includes(e.code))throw e}
+ const cp=await import('node:child_process');
+ const spawned=cp.spawnSync('/usr/bin/bun',['--version']); if(!spawned.error)throw Error('process spawn allowed');
+ try{await fetch('http://127.0.0.1:5432');throw Error('network allowed')}catch(e){if(e.message==='network allowed')throw e}
+ if(fs.readlinkSync('/proc/self/ns/pid')===${JSON.stringify(hostPidNamespace)})throw Error('host PID namespace');
+ const ffi=await import('bun:ffi'); const libc=ffi.dlopen('/lib/x86_64-linux-gnu/libc.so.6',{unshare:{args:['i32'],returns:'i32'}}); if(libc.symbols.unshare(0x10000000)!==-1)throw Error('namespace creation allowed');libc.close();
+ try{fs.writeFileSync('/tmp/overflow',Buffer.alloc(20*1024*1024));throw Error('tmp quota absent')}catch(e){if(e.code!=='ENOSPC')throw e}
+ const status=fs.readFileSync('/proc/self/status','utf8'); if(!/NoNewPrivs:\\s+1/.test(status)||!/Seccomp:\\s+2/.test(status))throw Error('seccomp missing');
+ `
+ )
+ );
+ const c = await IsolatedCandidateController.start(f.request, f.name);
+ try {
+ const result = await runReplaySessionAsync(
+ new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
+ c,
+ { resultFormat: 'report' }
+ );
+ await c.finish();
+ if (!('format' in result.result) || result.result.format !== 'report') {
+ throw new Error('Expected native report');
+ }
+ expect(result.result.projection.fills).toEqual([]);
+ expect(String(result.result.view.equity)).toBe('10000.00000000');
+ } finally {
+ await c.dispose();
+ }
+ await absent(f.name);
+ }, 30000);
+ test('native financial risk rejects malicious huge targets without treating ownerBudget as an allocation constraint', async () => {
+ const f = await fixture(
+ program(
+ "return {nextState:null,intent:{mode:'target',targets:[{instrumentId:'X0.US',quantity:'999999999'}]}}"
+ )
+ );
+ const c = await IsolatedCandidateController.start(f.request, f.name);
+ try {
+ const admissions: unknown[] = [];
+ const result = await runReplaySessionAsync(
+ new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
+ {
+ stage: c.stage.bind(c),
+ async committed(outcome) {
+ admissions.push(outcome);
+ await c.committed(outcome);
+ },
+ },
+ { resultFormat: 'report' }
+ );
+ await c.finish();
+ if (!('format' in result.result) || result.result.format !== 'report') {
+ throw new Error('Expected native report');
+ }
+ expect(result.result.projection.fills).toEqual([]);
+ expect(String(result.result.view.equity)).toBe('10000.00000000');
+ expect(JSON.stringify(admissions)).toContain('OrderSize');
+ } finally {
+ await c.dispose();
+ }
+ await absent(f.name);
+ }, 30000);
+ test('infinite callback deadline fails and disposal confirms no surviving container', async () => {
+ const f = await fixture(program('for(;;){}'));
+ const c = await IsolatedCandidateController.start(f.request, f.name, Date.now() + 2500);
+ const start = performance.now();
+ try {
+ await expect(
+ runReplaySessionAsync(
+ new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
+ c
+ )
+ ).rejects.toThrow();
+ } finally {
+ await c.dispose();
+ }
+ expect(performance.now() - start).toBeLessThan(8000);
+ await absent(f.name);
+ }, 15000);
+ test('process exit between ready and first callback rejects promptly instead of waiting for the wall budget', async () => {
+ const f = await fixture(program(undefined, 'setTimeout(()=>process.exit(0),50);'));
+ const c = await IsolatedCandidateController.start(f.request, f.name);
+ await Bun.sleep(150);
+ const start = performance.now();
+ try {
+ await expect(
+ runReplaySessionAsync(
+ new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
+ c
+ )
+ ).rejects.toThrow(/closed|exited/);
+ } finally {
+ await c.dispose();
+ }
+ expect(performance.now() - start).toBeLessThan(3000);
+ await absent(f.name);
+ }, 15000);
+ test('unsolicited stdout frames, oversized frames and stderr flood cannot create a valid financial result', async () => {
+ for (const attack of [
+ "const b=Buffer.from(JSON.stringify({version:1,type:'ready',sequence:999}));const h=Buffer.alloc(4);h.writeUInt32BE(b.length);process.stdout.write(Buffer.concat([h,b]));",
+ 'process.stdout.write(Buffer.from([255,255,255,255]));',
+ "process.stderr.write('x'.repeat(200000));throw Error('bounded diagnostic');",
+ ]) {
+ const f = await fixture(program(undefined, attack));
+ await expect(IsolatedCandidateController.start(f.request, f.name)).rejects.toThrow();
+ await absent(f.name);
+ }
+ }, 30000);
+ test('isolated TS packaging transforms types without evaluating top-level code and refuses dependency edges', async () => {
+ const f = await fixture(program());
+ const metadata = {
+ program: f.request.strategy.package.program,
+ parameterSchema: f.request.strategy.package.parameterSchema,
+ execution: f.request.strategy.package.execution,
+ source: f.request.strategy.package.source,
+ entryExport: 'createStrategy',
+ };
+ const pkg = await packageCandidateStrategy(
+ metadata,
+ `const typed: number = 1; ${program()}\nfor(;;){}`
+ );
+ expect(pkg.artifact.content).not.toContain(': number');
+ expect(pkg.artifact.sha256).toBe(hash(pkg.artifact.content));
+ expect(pkg.build.version).toBe(Bun.version);
+ for (const source of [
+ "import x from 'node:fs'; export {x};",
+ "const x = import('node:fs');",
+ 'const x:number = ;',
+ ]) {
+ await expect(packageCandidateStrategy(metadata, source)).rejects.toThrow();
+ }
+ }, 30000);
+ test('Docker client SIGKILL and stdin EOF independently trigger guardian cleanup during infinite callback', async () => {
+ for (const disconnect of ['kill', 'stdin'] as const) {
+ const f = await fixture(program('for(;;){}'));
+ const c = await IsolatedCandidateController.start(f.request, f.name);
+ const pending = runReplaySessionAsync(
+ new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
+ c
+ );
+ void pending.catch(() => undefined);
+ await Bun.sleep(100);
+ const child = Reflect.get(c, 'child') as ChildProcessWithoutNullStreams;
+ const started = performance.now();
+ if (disconnect === 'kill') {
+ child.kill('SIGKILL');
+ } else {
+ child.stdin.destroy();
+ }
+ await expect(pending).rejects.toThrow();
+ // Verify the independent guardian has removed the namespace BEFORE explicit cleanup.
+ for (let i = 0; i < 80; i++) {
+ const present = (
+ await runFile('/usr/bin/docker', ['ps', '-a', '-q', '--filter', `name=^/${f.name}$`])
+ ).stdout.trim();
+ if (!present) {
+ break;
+ }
+ await Bun.sleep(25);
+ }
+ await absent(f.name);
+ expect(performance.now() - started).toBeLessThan(5000);
+ await c.dispose();
+ }
+ }, 20000);
+ test('memory allocation failure cannot produce a successful result or leave the container running', async () => {
+ const f = await fixture(
+ program('const blocks=[];for(;;)blocks.push(new Uint8Array(16*1024*1024).fill(1));')
+ );
+ const c = await IsolatedCandidateController.start(f.request, f.name, Date.now() + 10000);
+ try {
+ await expect(
+ runReplaySessionAsync(
+ new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
+ c
+ )
+ ).rejects.toThrow();
+ } finally {
+ await c.dispose();
+ }
+ await absent(f.name);
+ }, 20000);
+ test('forged owner/decision identity on raw stdout is rejected before native admission', async () => {
+ const attack = `const d={version:1,sessionId:c.portfolio.portfolio.sessionId,barrierId:c.barrier.barrier_id,revision:c.barrier.revision,decision:{ownerId:'forged',decisionId:JSON.stringify(['strategy','forged',c.strategyId,c.strategyVersion,0]),sequence:0},intent:{mode:'target',targets:[]}};const b=Buffer.from(JSON.stringify({version:1,type:'decisions',sequence:1,decisions:[d]}));const h=Buffer.alloc(4);h.writeUInt32BE(b.length);process.stdout.write(Buffer.concat([h,b]));for(;;){}`;
+ const f = await fixture(program(attack));
+ const c = await IsolatedCandidateController.start(f.request, f.name);
+ try {
+ await expect(
+ runReplaySessionAsync(
+ new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
+ c
+ )
+ ).rejects.toThrow('forged decision');
+ } finally {
+ await c.dispose();
+ }
+ await absent(f.name);
+ }, 15000);
+ test('changing a future suffix cannot alter the earlier published prefix or candidate decisions', async () => {
+ const content = program(
+ "const last=c.observations.at(-1);return {nextState:null,intent:{mode:'target',targets:last?[{instrumentId:'X0.US',quantity:Number(last.close)>2?'1':'0'}]:[]}}"
+ );
+ const first = await fixture(content);
+ const changed = canonicalSmaFixture([first.request.strategy.selection.ownerId], {
+ closes: [3, 2, 1, 4, 5, 90, 100],
+ }).dataset;
+ const cutoff = changed.bars[5]!.availableAt;
+ const prefixes: unknown[][] = [];
+ for (const dataset of [first.dataset, changed]) {
+ const request = canonicalRunRequestSchema.parse({
+ ...first.request,
+ datasetHash: dataset.manifest.hash,
+ });
+ const name = `stock-bot-candidate-${randomUUID()}`,
+ c = await IsolatedCandidateController.start(request, name),
+ seen: unknown[] = [];
+ try {
+ await runReplaySessionAsync(
+ new NativeReplaySession(prepareReplayLoad(dataset, request.policy)),
+ {
+ async stage(context, observations) {
+ const decisions = await c.stage(context, observations);
+ if (context.barrier.at < cutoff) {
+ seen.push({
+ at: context.barrier.at,
+ observations,
+ intents: decisions.map(d => d.intent),
+ });
+ }
+ return decisions;
+ },
+ committed: c.committed.bind(c),
+ }
+ );
+ await c.finish();
+ } finally {
+ await c.dispose();
+ }
+ prefixes.push(seen);
+ await absent(name);
+ }
+ const [original, changedPrefix] = prefixes;
+ if (!original || !changedPrefix) {
+ throw new Error('Missing prefix comparisons');
+ }
+ expect(original.length).toBeGreaterThan(1);
+ expect(changedPrefix).toEqual(original);
+ }, 20000);
+
+ test('killing the actual native worker or its parent leaves no isolated candidate descendant', async () => {
+ for (const target of ['worker', 'parent'] as const) {
+ const f = await fixture(program('for(;;){}'));
+ f.request.build = await readCanonicalBuildIdentity();
+ const input = {
+ type: 'runRetainedStrategy',
+ request: f.request,
+ dataset: f.dataset,
+ candidateContainerName: f.name,
+ executionDeadlineAt: Date.now() + 30000,
+ };
+ const directory = await mkdtemp(join(tmpdir(), 'stock-bot-candidate-parent-'));
+ const parentPath = join(directory, 'parent.mjs');
+ // The candidate artifact remains inert JSON in this trusted supervisor fixture.
+ await writeFile(
+ parentPath,
+ `import {fork} from 'node:child_process';const child=fork(${JSON.stringify(fileURLToPath(canonicalWorkerUrl))},[],{execPath:process.execPath,execArgv:[],serialization:'json',stdio:['ignore','ignore','pipe','ipc']});child.stderr?.resume();child.send(${JSON.stringify(input)});`
+ );
+ const child = fork(target === 'worker' ? fileURLToPath(canonicalWorkerUrl) : parentPath, [], {
+ execPath: process.execPath,
+ execArgv: [],
+ serialization: 'json',
+ stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
+ });
+ child.stderr?.resume();
+ const closed = new Promise(resolve => child.once('close', () => resolve()));
+ if (target === 'worker') {
+ child.send(input);
+ }
+ try {
+ let running = false;
+ for (let i = 0; i < 100; i++) {
+ if (
+ (
+ await runFile('/usr/bin/docker', ['ps', '-q', '--filter', `name=^/${f.name}$`])
+ ).stdout.trim()
+ ) {
+ running = true;
+ break;
+ }
+ await Bun.sleep(25);
+ }
+ expect(running).toBeTrue();
+ const started = performance.now();
+ child.kill('SIGKILL');
+ await closed;
+ for (let i = 0; i < 100; i++) {
+ if (
+ !(
+ await runFile('/usr/bin/docker', ['ps', '-a', '-q', '--filter', `name=^/${f.name}$`])
+ ).stdout.trim()
+ ) {
+ break;
+ }
+ await Bun.sleep(25);
+ }
+ await absent(f.name);
+ expect(performance.now() - started).toBeLessThan(6000);
+ } finally {
+ child.kill('SIGKILL');
+ await closed;
+ await removeCandidateContainer(f.name);
+ await rm(directory, { recursive: true, force: true });
+ }
+ }
+ }, 20000);
+
+ test('cleanup still closes the client and removes private configuration when explicit removal fails', async () => {
+ const f = await fixture(program());
+ const c = await IsolatedCandidateController.start(f.request, f.name);
+ const directory = Reflect.get(c, 'dockerConfig') as string;
+ const child = Reflect.get(c, 'child') as ChildProcessWithoutNullStreams;
+ // Fault injection at the exact-name validation seam; never disables the daemon or another container.
+ Reflect.set(c, 'name', 'invalid-owned-container-name');
+ await expect(c.dispose()).rejects.toThrow('Candidate cleanup failed');
+ expect(child.exitCode !== null || child.signalCode !== null).toBeTrue();
+ await expect(access(directory)).rejects.toThrow();
+ for (let i = 0; i < 80; i++) {
+ if (
+ !(
+ await runFile('/usr/bin/docker', ['ps', '-a', '-q', '--filter', `name=^/${f.name}$`])
+ ).stdout.trim()
+ ) {
+ break;
+ }
+ await Bun.sleep(25);
+ }
+ await absent(f.name);
+ }, 15000);
+ test('missing installed descriptor and altered retained runtime fail closed before candidate launch', async () => {
+ const f = await fixture(program());
+ const altered = structuredClone(f.request);
+ if (altered.strategy.origin !== 'candidate') {
+ throw Error('candidate fixture');
+ }
+ altered.strategy.execution.imageId = `sha256:${'0'.repeat(64)}`;
+ await expect(IsolatedCandidateController.start(altered, f.name)).rejects.toThrow(
+ 'not installed'
+ );
+ await absent(f.name);
+ const hidden = candidateDescriptorPath + '.missing-test-' + randomUUID();
+ await rename(candidateDescriptorPath, hidden);
+ try {
+ await expect(IsolatedCandidateController.start(f.request, f.name)).rejects.toThrow(
+ 'unavailable'
+ );
+ } finally {
+ await rename(hidden, candidateDescriptorPath);
+ }
+ await absent(f.name);
+ if (f.request.strategy.origin !== 'candidate') {
+ throw new Error('Expected candidate fixture');
+ }
+ expect(await readCandidateExecution()).toEqual(f.request.strategy.execution);
+ }, 15000);
+ test('closing stdout while continuing an infinite callback fails promptly before the wall deadline', async () => {
+ const f = await fixture(
+ program(
+ "const pipe=fs.readlinkSync('/proc/self/fd/1');for(const name of fs.readdirSync('/proc/self/fd')){try{if(fs.readlinkSync('/proc/self/fd/'+name)===pipe){libc.symbols.close(Number(name));}}catch{}}const remaining=fs.readdirSync('/proc/self/fd').filter(name=>{try{return fs.readlinkSync('/proc/self/fd/'+name)===pipe}catch{return false}});if(remaining.length)throw Error('stdout still open');process.stderr.write('candidate-test:stdout-eof-confirmed');for(;;){}",
+ "const fs=await import('node:fs');const ffi=await import('bun:ffi');const libc=ffi.dlopen('/lib/x86_64-linux-gnu/libc.so.6',{close:{args:['i32'],returns:'i32'}});"
+ )
+ );
+ const c = await IsolatedCandidateController.start(f.request, f.name, Date.now() + 5000);
+ const started = performance.now();
+ try {
+ await expect(
+ runReplaySessionAsync(
+ new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
+ c
+ )
+ ).rejects.toThrow();
+ } finally {
+ await c.dispose();
+ }
+ expect((Reflect.get(c, 'stderr') as Buffer).toString()).toContain(
+ 'candidate-test:stdout-eof-confirmed'
+ );
+ expect(performance.now() - started).toBeLessThan(3000);
+ await absent(f.name);
+ }, 10000);
+});
diff --git a/test/integration/experiments-ui.test.tsx b/test/integration/experiments-ui.test.tsx
index 60360056..b4169cbd 100644
--- a/test/integration/experiments-ui.test.tsx
+++ b/test/integration/experiments-ui.test.tsx
@@ -296,6 +296,22 @@ async function ready(value = preview()) {
await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: value }));
return value;
}
+
+test('same-event candidate toggle then Preview never captures the old builtin strategy', async () => {
+ await list();
+ await flush(() => change('Experiment name', 'Candidate draft'));
+ const checkbox = [...host.querySelectorAll('input[type="checkbox"]')].find(input =>
+ input.closest('label')?.textContent?.includes('Use an isolated candidate version')
+ ) as HTMLInputElement;
+ expect(checkbox).toBeDefined();
+ await flush(() => {
+ checkbox.click();
+ button('Preview experiment').click();
+ });
+ expect(requests.filter(item => item.path === '/api/v2/experiments/preview')).toHaveLength(0);
+ expect(button('Preview experiment').disabled).toBe(true);
+ expect(host.textContent).toContain('Select an immutable candidate');
+});
async function showDetail(value?: ExperimentDetail) {
const routes = createElement(
router.Routes,
diff --git a/test/integration/paper-composition.test.ts b/test/integration/paper-composition.test.ts
index 93311395..23682524 100644
--- a/test/integration/paper-composition.test.ts
+++ b/test/integration/paper-composition.test.ts
@@ -1,9 +1,12 @@
-import { asFunction, createContainer as createDiContainer } from 'awilix';
+import { asFunction, asValue, createContainer as createDiContainer } from 'awilix';
import { expect, test } from 'bun:test';
-import type { ServiceCradle } from '@stock-bot/di';
+import { ServiceContainerBuilder, type ServiceCradle } from '@stock-bot/di';
import type { StockAppConfig } from '@stock-bot/stock-config';
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
+import type { PaperConfigurationInput } from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
import { createContainer } from '../../apps/stock/orchestrator/src/simple-container';
+import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
+import { logger } from '../fixtures/execution';
import { paperFeedConfiguration } from '../fixtures/paper-feed';
test('canonical paper rejects invalid role/configuration before resolving services', async () => {
@@ -44,3 +47,83 @@ test('live defaults, research canonical configuration and missing custody fail b
createContainer(config({ defaultMode: 'paper', canonicalPaper: paperFeedConfiguration() }))
).rejects.toThrow('requires durable PostgreSQL');
});
+
+test('reviewed deployment host is explicit, exclusive, durable and never enabled for research', async () => {
+ const container = createDiContainer();
+ let resolved = 0;
+ container.register({
+ serviceContainer: asFunction(() => {
+ resolved++;
+ throw new Error('Unexpected service resolution');
+ }),
+ });
+ await expect(
+ registerOrchestratorServices(container, {
+ role: 'research-only',
+ paperDeploymentHost: { enabled: true },
+ })
+ ).rejects.toThrow('requires a paper composition');
+ await expect(
+ registerOrchestratorServices(container, {
+ role: 'paper',
+ canonicalPaper: paperFeedConfiguration(),
+ paperDeploymentHost: { enabled: true },
+ })
+ ).rejects.toThrow('never two account owners');
+ await expect(
+ registerOrchestratorServices(container, {
+ role: 'paper',
+ paperDeploymentHost: { enabled: true, deploymentId: 'not-a-uuid' },
+ })
+ ).rejects.toThrow();
+ await expect(
+ registerOrchestratorServices(container, {
+ role: 'paper',
+ canonicalPaper: { ...paperFeedConfiguration(), version: 2 } as PaperConfigurationInput,
+ })
+ ).rejects.toThrow('reviewed deployment host');
+ expect(resolved).toBe(0);
+ const config = {
+ services: { orchestrator: { defaultMode: 'paper', paperDeploymentHost: { enabled: true } } },
+ } as StockAppConfig;
+ await expect(createContainer(config)).rejects.toThrow('requires durable PostgreSQL');
+});
+
+test('explicit deployment host initializes unbound without account reads, writes or activation', async () => {
+ const container = await new ServiceContainerBuilder()
+ .withOptions({
+ enableCache: false,
+ enableQueue: false,
+ enableMongoDB: false,
+ enablePostgres: false,
+ enableQuestDB: false,
+ enableBrowser: false,
+ enableProxy: false,
+ })
+ .build();
+ let transactions = 0;
+ const services: OrchestratorServices = {
+ logger,
+ postgres: {
+ transaction() {
+ transactions++;
+ throw new Error('Unbound host must not access account state');
+ },
+ } as unknown as NonNullable,
+ };
+ container.register({ serviceContainer: asValue(services) });
+ try {
+ await registerOrchestratorServices(container, {
+ role: 'paper',
+ paperDeploymentHost: { enabled: true },
+ });
+ expect(services.custom?.PaperDeploymentHost).toBeDefined();
+ expect(services.custom?.CanonicalPaperRuntime).toBeUndefined();
+ expect(() => services.custom!.PaperDeploymentHost!.runtime()).toThrow('not bound');
+ expect(transactions).toBe(0);
+ } finally {
+ await services.custom?.PaperDeploymentHost?.shutdown();
+ await services.custom?.BacktestRunner?.shutdown();
+ await container.dispose();
+ }
+});
diff --git a/test/integration/paper-deployments-api.test.ts b/test/integration/paper-deployments-api.test.ts
new file mode 100644
index 00000000..fd0c9f4d
--- /dev/null
+++ b/test/integration/paper-deployments-api.test.ts
@@ -0,0 +1,226 @@
+import { expect, test } from 'bun:test';
+import { Hono } from 'hono';
+import { createHttpSecurity } from '@stock-bot/di';
+import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper';
+import { createPaperDeploymentHostRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper-deployments';
+import {
+ PaperDeploymentHost,
+ unboundPaperReadiness,
+} from '../../apps/stock/orchestrator/src/paper/PaperDeploymentHost';
+import {
+ createPaperDeploymentRoutes,
+ forwardPaperCommand,
+} from '../../apps/stock/web-api/src/routes/paper-deployments.routes';
+import type { PaperDeploymentsService } from '../../apps/stock/web-api/src/services/paper-deployments.service';
+import { logger } from '../fixtures/execution';
+
+const id = 'abcdefab-1234-4234-8234-123456789abc',
+ admin = 'paper-admin-fixture-only-01234567890123456789',
+ serviceToken = 'paper-service-fixture-only-01234567890123456789',
+ origin = 'http://localhost:5173';
+const status = { deploymentId: id, boundDeploymentId: null, readiness: unboundPaperReadiness() };
+const security = (disabled = false) =>
+ createHttpSecurity({
+ adminToken: admin,
+ serviceToken,
+ environment: 'test',
+ hostname: '127.0.0.1',
+ origins: [origin],
+ browserSessions: true,
+ disabled,
+ });
+const json = (token = admin, extra: Record = {}) => ({
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', ...extra },
+ body: '{}',
+});
+function fixture(disabled = false) {
+ const events: string[] = [],
+ host = {
+ async bind(value: string) {
+ events.push('bind:' + value);
+ return status;
+ },
+ async activate(value: string) {
+ events.push('activate:' + value);
+ return status;
+ },
+ async halt(value: string) {
+ events.push('halt:' + value);
+ return status;
+ },
+ async status() {
+ return status;
+ },
+ } as unknown as PaperDeploymentHost;
+ const orchestrator = new Hono();
+ security(disabled).mount(orchestrator);
+ orchestrator.route('/api/paper/deployments', createPaperDeploymentHostRoutes(host, [origin]));
+ orchestrator.route(
+ '/api/paper',
+ createPaperRoutes({ logger, custom: {} }, { origins: [origin] })
+ );
+ const api = new Hono();
+ security(disabled).mount(api);
+ const custody = {
+ async authorizeCommand(value: string) {
+ events.push('authorize:' + value);
+ },
+ async get() {
+ return {};
+ },
+ async list() {
+ return [];
+ },
+ } as unknown as PaperDeploymentsService;
+ let forwarded: Request | undefined;
+ let forwardedInit: RequestInit | undefined;
+ const transport = async (url: string | URL | Request, init?: RequestInit) => {
+ forwardedInit = init;
+ forwarded = new Request(url, init);
+ return orchestrator.fetch(forwarded);
+ };
+ api.route(
+ '/',
+ createPaperDeploymentRoutes(
+ { logger },
+ {
+ service: custody,
+ origin: 'http://paper.internal',
+ origins: [origin],
+ request: transport as typeof fetch,
+ }
+ )
+ );
+ return {
+ api,
+ orchestrator,
+ events,
+ forwarded: () => forwarded,
+ forwardedInit: () => forwardedInit,
+ };
+}
+test('original human bearer is verified by both endpoints, normalizes IDs, and never substitutes service credentials', async () => {
+ const f = fixture(),
+ response = await f.api.request(`/api/v2/paper-deployments/${id.toUpperCase()}/bind`, json());
+ expect(response.status).toBe(200);
+ expect(response.headers.get('cache-control')).toBe('no-store');
+ expect(await response.json()).toEqual(status);
+ expect(f.events).toEqual(['authorize:' + id, 'bind:' + id]);
+ expect(f.forwarded()?.headers.get('authorization')).toBe('Bearer ' + admin);
+ expect(f.forwardedInit()?.redirect).toBe('error');
+ for (const token of [serviceToken, 'sb-research.' + id + '.untrusted']) {
+ expect((await f.api.request(`/api/v2/paper-deployments/${id}/bind`, json(token))).status).toBe(
+ 403
+ );
+ expect(
+ (await f.orchestrator.request(`/api/paper/deployments/${id}/bind`, json(token))).status
+ ).toBe(403);
+ }
+ expect(f.events).toHaveLength(2);
+});
+test('signed browser session keeps original Origin and is independently verified upstream', async () => {
+ const f = fixture(),
+ login = await f.api.request('/api/auth/session', {
+ method: 'POST',
+ headers: { Origin: origin, 'Content-Type': 'application/json' },
+ body: JSON.stringify({ token: admin }),
+ });
+ expect(login.status).toBe(200);
+ const cookie = login.headers.get('set-cookie')?.split(';')[0];
+ expect(cookie).toBeDefined();
+ const response = await f.api.request(`/api/v2/paper-deployments/${id}/activate`, {
+ method: 'POST',
+ headers: { Cookie: cookie!, Origin: origin, 'Content-Type': 'application/json' },
+ body: '{}',
+ });
+ expect(response.status).toBe(200);
+ expect(f.forwarded()?.headers.get('cookie')).toBe(cookie!);
+ expect(f.forwarded()?.headers.get('origin')).toBe(origin);
+ expect(f.forwarded()?.headers.has('authorization')).toBe(false);
+ for (const app of [f.api, f.orchestrator]) {
+ const prefix = app === f.api ? '/api/v2/paper-deployments' : '/api/paper/deployments';
+ expect(
+ (
+ await app.request(
+ `${prefix}/${id}/bind`,
+ json(admin, { Origin: 'https://untrusted.invalid' })
+ )
+ ).status
+ ).toBe(403);
+ }
+ expect(f.events).toHaveLength(2);
+});
+test('auth-disabled development bypass cannot promote or activate through either endpoint or old direct activation', async () => {
+ const f = fixture(true);
+ expect((await f.api.request(`/api/v2/paper-deployments/${id}/bind`, json())).status).toBe(403);
+ expect(
+ (await f.orchestrator.request(`/api/paper/deployments/${id}/activate`, json())).status
+ ).toBe(403);
+ expect((await f.orchestrator.request('/api/paper/activate', json())).status).toBe(403);
+ expect(f.events).toEqual([]);
+});
+test('unconfigured fixed origin and mismatched upstream identity fail honestly without arbitrary routing', async () => {
+ const request = new Request('http://web/api', { headers: { Authorization: 'Bearer ' + admin } });
+ await expect(forwardPaperCommand(request, id, 'bind', {}, {})).rejects.toThrow('not configured');
+ for (const origin of [
+ 'file:///tmp/private',
+ 'http://user:pass@paper',
+ 'http://paper/other',
+ 'http://paper?token=x',
+ ]) {
+ await expect(forwardPaperCommand(request, id, 'bind', {}, { origin })).rejects.toThrow(
+ 'fixed HTTP origin'
+ );
+ }
+ await expect(
+ forwardPaperCommand(
+ request,
+ id,
+ 'bind',
+ {},
+ {
+ origin: 'http://paper',
+ request: async () =>
+ Response.json({ ...status, deploymentId: '11111111-1111-4111-8111-111111111111' }),
+ }
+ )
+ ).rejects.toThrow('another deployment');
+});
+test('missing upstream origin policy rejects browser command even with valid operator token', async () => {
+ const app = new Hono();
+ security().mount(app);
+ app.route('/api/paper/deployments', createPaperDeploymentHostRoutes(undefined, []));
+ const response = await app.request(
+ `/api/paper/deployments/${id}/bind`,
+ json(admin, { Origin: origin })
+ );
+ expect(response.status).toBe(403);
+ expect(await response.json()).toEqual({
+ error: 'Paper commands require an explicitly configured trusted Origin',
+ });
+});
+
+test('unbound legacy readiness remains truthful and never creates an account or imports a program', async () => {
+ let calls = 0;
+ const unexpected = async () => {
+ calls++;
+ throw new Error('No persistence on unbound readiness');
+ };
+ const host = new PaperDeploymentHost({
+ database: { transaction: unexpected },
+ repository: { initialize: unexpected, transact: unexpected },
+ });
+ const app = new Hono();
+ security().mount(app);
+ app.route(
+ '/api/paper',
+ createPaperRoutes({ logger, custom: {} }, { deploymentHost: host, origins: [origin] })
+ );
+ const response = await app.request('/api/paper/readiness', {
+ headers: { Authorization: `Bearer ${admin}` },
+ });
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual(unboundPaperReadiness());
+ expect(calls).toBe(0);
+});
diff --git a/test/integration/paper-deployments-ui.test.tsx b/test/integration/paper-deployments-ui.test.tsx
new file mode 100644
index 00000000..3c5bbf41
--- /dev/null
+++ b/test/integration/paper-deployments-ui.test.tsx
@@ -0,0 +1,448 @@
+import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test';
+import { GlobalWindow } from 'happy-dom';
+import { act, createElement } from 'react';
+import type { Root } from 'react-dom/client';
+import {
+ paperPromotionPreviewSchema,
+ type PaperDeployment,
+ type PaperPromotionInput,
+} from '@stock-bot/stock-config/paper-deployments';
+import { paperConfig } from '../fixtures/paper-runtime';
+
+const browser = new GlobalWindow({ url: 'http://localhost:5173' }),
+ names = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const,
+ old = names.map(name => [name, Object.getOwnPropertyDescriptor(globalThis, name)] as const);
+let createRoot: typeof import('react-dom/client').createRoot,
+ router: typeof import('react-router-dom'),
+ Page: typeof import('../../apps/stock/web-app/src/features/paper/PaperDeploymentsPage').PaperDeploymentsPage,
+ Detail: typeof import('../../apps/stock/web-app/src/features/paper/PaperDeploymentPage').PaperDeploymentPage,
+ api: typeof import('../../apps/stock/web-app/src/features/paper/paperApi').paperApi,
+ ApiError: typeof import('../../apps/stock/web-app/src/features/paper/paperApi').PaperApiError,
+ validationApi: typeof import('../../apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi').chronologicalValidationDurableApi,
+ experimentApi: typeof import('../../apps/stock/web-app/src/features/experiments/services/experimentApi').experimentApi;
+let root: Root | undefined, host: HTMLDivElement;
+const restore: Array<() => void> = [];
+const id = '11111111-1111-4111-8111-111111111111',
+ testId = '22222222-2222-4222-8222-222222222222',
+ costId = '33333333-3333-4333-8333-333333333333',
+ hash = 'a'.repeat(64);
+const configuration = paperConfig();
+const transport = {
+ accountId: 'new-paper',
+ sessionId: 'new-session',
+ quoteSeriesId: 'X:quote',
+ riskSession: configuration.matching.risk.ledger.riskSession,
+ policy: configuration.policy,
+};
+function preview(input: PaperPromotionInput) {
+ return paperPromotionPreviewSchema.parse({
+ version: 'paper-promotion-preview/v1',
+ previewHash: hash,
+ input,
+ strategy: {
+ familyId: id,
+ versionId: id,
+ reviewId: id,
+ origin: 'candidate',
+ artifactSha256: hash,
+ dependencyLockSha256: hash,
+ },
+ configuration: { ...configuration, version: 2 },
+ host: {
+ version: 'paper-host/v1',
+ hostSha256: hash,
+ engineWrapperSha256: hash,
+ engineBinarySha256: hash,
+ dependencyLockSha256: hash,
+ runtime: 'bun',
+ runtimeVersion: 'test',
+ platform: 'linux',
+ arch: 'x64',
+ },
+ evidence: {
+ test: {
+ runId: testId,
+ datasetHash: hash,
+ economicHash: hash,
+ resultHash: hash,
+ metrics: { totalReturn: null },
+ fillCount: 0,
+ limitations: [],
+ },
+ costs: [
+ {
+ runId: costId,
+ datasetHash: hash,
+ economicHash: hash,
+ resultHash: hash,
+ metrics: { totalReturn: 0 },
+ fillCount: 0,
+ limitations: [],
+ },
+ {
+ runId: id,
+ datasetHash: hash,
+ economicHash: hash,
+ resultHash: hash,
+ metrics: { totalReturn: -0.1 },
+ fillCount: 1,
+ limitations: [],
+ },
+ ],
+ },
+ limitations: ['Trusted code requires human review.'],
+ });
+}
+function patch(object: T, key: K, value: T[K]) {
+ const previous = object[key];
+ object[key] = value;
+ restore.push(() => {
+ object[key] = previous;
+ });
+}
+async function flush(fn: () => void = () => {}) {
+ await act(async () => {
+ fn();
+ await Promise.resolve();
+ });
+}
+function button(text: string) {
+ const value = [...host.querySelectorAll('button')].find(e => e.textContent?.trim() === text);
+ if (!value) {
+ throw new Error('Missing button ' + text);
+ }
+ return value;
+}
+function fieldEvent(label: string, value: string) {
+ const element = host.querySelector(`[aria-label="${label}"]`)!;
+ const prototype =
+ element.tagName === 'TEXTAREA'
+ ? browser.HTMLTextAreaElement.prototype
+ : browser.HTMLInputElement.prototype;
+ Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(element, value);
+ element.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event);
+}
+async function fill(label: string, value: string) {
+ await flush(() => fieldEvent(label, value));
+}
+function LocationProbe() {
+ return createElement('output', { 'aria-label': 'Route' }, router.useLocation().pathname);
+}
+async function mount() {
+ root = createRoot(host);
+ await flush(() =>
+ root!.render(
+ createElement(
+ router.MemoryRouter,
+ { initialEntries: ['/paper'] },
+ createElement(Page),
+ createElement(LocationProbe)
+ )
+ )
+ );
+}
+beforeAll(async () => {
+ Object.defineProperty(globalThis, 'window', { value: browser, configurable: true });
+ Object.defineProperty(globalThis, 'document', { value: browser.document, configurable: true });
+ Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
+ value: true,
+ configurable: true,
+ });
+ createRoot = (await import('react-dom/client')).createRoot;
+ router = await import('react-router-dom');
+ ({ PaperDeploymentsPage: Page } = await import(
+ '../../apps/stock/web-app/src/features/paper/PaperDeploymentsPage'
+ ));
+ ({ PaperDeploymentPage: Detail } = await import(
+ '../../apps/stock/web-app/src/features/paper/PaperDeploymentPage'
+ ));
+ ({ paperApi: api, PaperApiError: ApiError } = await import(
+ '../../apps/stock/web-app/src/features/paper/paperApi'
+ ));
+ validationApi = (
+ await import(
+ '../../apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi'
+ )
+ ).chronologicalValidationDurableApi;
+ experimentApi = (
+ await import('../../apps/stock/web-app/src/features/experiments/services/experimentApi')
+ ).experimentApi;
+});
+beforeEach(() => {
+ host = browser.document.createElement('div') as unknown as HTMLDivElement;
+ browser.document.body.appendChild(host as never);
+ patch(api, 'list', async () => ({ deployments: [] }));
+});
+afterEach(async () => {
+ await flush(() => root?.unmount());
+ root = undefined;
+ host.remove();
+ for (const reset of restore.splice(0).reverse()) {
+ reset();
+ }
+});
+afterAll(() => {
+ for (const [name, value] of old) {
+ if (value) {
+ Object.defineProperty(globalThis, name, value);
+ } else {
+ delete (globalThis as Record)[name];
+ }
+ }
+ browser.happyDOM.cancelAsync();
+});
+async function review() {
+ patch(
+ validationApi,
+ 'get',
+ async () =>
+ ({
+ id,
+ report: { id, reportHash: hash, previewHash: hash, test: { runId: testId } },
+ }) as never
+ );
+ patch(
+ experimentApi,
+ 'get',
+ async () =>
+ ({
+ id: costId,
+ previewHash: hash,
+ preview: {
+ version: 'cost-sensitivity-preview/v1',
+ candidates: [{ costs: { feeRate: '0', slippageRate: '0' } }],
+ },
+ trials: [{ runId: costId, status: 'completed' }],
+ }) as never
+ );
+ patch(api, 'preview', async input => preview(input));
+ await fill('Deployment name', 'Reviewed candidate');
+ await fill('Report owner ID', id);
+ await fill('Cost experiment ID', costId);
+ await flush(() => button('Load evidence').click());
+ await fill('Paper transport', JSON.stringify(transport));
+ await fill('Review rationale', 'I reviewed exact evidence and strategy');
+ await flush(() =>
+ (host.querySelector('[aria-label="Authorize trusted paper code"]') as HTMLInputElement).click()
+ );
+ await flush(() => button('Preview promotion').click());
+}
+test('empty/loading/error states and explicit human review precede promotion; cost data never implies approval', async () => {
+ await mount();
+ expect(host.textContent).toContain('No paper deployments yet');
+ expect(host.textContent).toContain('Live trading is unavailable');
+ await flush(() => button('Preview promotion').click());
+ expect(host.textContent).toContain('Load sealed test');
+ await review();
+ expect(host.textContent).toContain('candidate');
+ expect(host.textContent).toContain('Test return: Unavailable');
+ expect(host.textContent).toContain('Trusted code requires human review.');
+ expect(button('Create halted deployment').disabled).toBe(false);
+ await fill('Review rationale', 'Changed review');
+ expect(host.textContent).not.toContain('Exact promotion preview');
+});
+test('uncertain create freezes the exact preview and retries the same idempotency key', async () => {
+ const requests: Array<{ input: PaperPromotionInput; previewHash: string; key: string }> = [];
+ patch(api, 'create', async (input, previewHash, key) => {
+ requests.push({ input, previewHash, key });
+ throw new ApiError('Response lost', null);
+ });
+ await mount();
+ await review();
+ await flush(() => button('Create halted deployment').click());
+ expect(host.textContent).toContain('draft is frozen');
+ expect((host.querySelector('fieldset') as HTMLFieldSetElement).disabled).toBe(true);
+ await flush(() => button('Retry same promotion receipt').click());
+ expect(requests).toHaveLength(2);
+ expect(requests[1]!).toEqual(requests[0]!);
+});
+test('same-event withdrawal of trusted-code authorization cannot preview or submit the previous consent', async () => {
+ await mount();
+ await review();
+ const previews: PaperPromotionInput[] = [],
+ creates: PaperPromotionInput[] = [];
+ patch(api, 'preview', async input => {
+ previews.push(input);
+ return preview(input);
+ });
+ patch(api, 'create', async input => {
+ creates.push(input);
+ throw new ApiError('Unexpected create', 422);
+ });
+ const oldCreate = button('Create halted deployment');
+ await flush(() => {
+ (host.querySelector('[aria-label="Authorize trusted paper code"]') as HTMLInputElement).click();
+ button('Preview promotion').click();
+ oldCreate.click();
+ });
+ expect(previews).toHaveLength(0);
+ expect(creates).toHaveLength(0);
+ expect(host.textContent).not.toContain('Exact promotion preview');
+ expect(
+ (host.querySelector('[aria-label="Authorize trusted paper code"]') as HTMLInputElement).checked
+ ).toBe(false);
+ await flush(() =>
+ (host.querySelector('[aria-label="Authorize trusted paper code"]') as HTMLInputElement).click()
+ );
+ await fill('Deployment name', 'Current draft');
+ await flush(() => button('Preview promotion').click());
+ expect(previews).toHaveLength(1);
+ expect(previews[0]?.name).toBe('Current draft');
+});
+test('same-event edits cannot discard an inflight receipt or mutate an uncertain promotion draft', async () => {
+ const requests: Array<{ input: PaperPromotionInput; previewHash: string; key: string }> = [];
+ let rejectCreate: (cause: Error) => void = () => {
+ throw new Error('Create not started');
+ };
+ const pendingCreate = new Promise((_resolve, reject) => {
+ rejectCreate = reject;
+ });
+ patch(api, 'create', async (input, previewHash, key) => {
+ requests.push({ input, previewHash, key });
+ if (requests.length === 1) {
+ return pendingCreate;
+ }
+ throw new ApiError('Response still uncertain', null);
+ });
+ await mount();
+ await review();
+ await flush(() => {
+ button('Create halted deployment').click();
+ fieldEvent('Deployment name', 'Must not replace the submitted name');
+ });
+ expect(requests).toHaveLength(1);
+ expect((host.querySelector('[aria-label="Deployment name"]') as HTMLInputElement).value).toBe(
+ 'Reviewed candidate'
+ );
+ await flush(() => rejectCreate(new ApiError('Response lost', null)));
+ expect(host.textContent).toContain('draft is frozen');
+ await flush(() => {
+ fieldEvent('Review rationale', 'Must not replace the frozen rationale');
+ button('Retry same promotion receipt').click();
+ });
+ expect(requests).toHaveLength(2);
+ expect(requests.slice(1)).toEqual(requests.slice(0, 1));
+ expect(requests[1]?.input.name).toBe('Reviewed candidate');
+ expect(requests[1]?.input.reason).toBe('I reviewed exact evidence and strategy');
+});
+test('owned links confirm discarding pending or uncertain receipts and refusal preserves the exact retry', async () => {
+ patch(api, 'list', async () => ({ deployments: [savedDeployment()] }));
+ const requests: Array<{ input: PaperPromotionInput; previewHash: string; key: string }> = [];
+ let rejectCreate: (cause: Error) => void = () => {
+ throw new Error('Create not started');
+ };
+ const pendingCreate = new Promise((_resolve, reject) => {
+ rejectCreate = reject;
+ });
+ patch(api, 'create', async (input, previewHash, key) => {
+ requests.push({ input, previewHash, key });
+ if (requests.length === 1) {
+ return pendingCreate;
+ }
+ throw new ApiError('Response lost', null);
+ });
+ let confirmations = 0;
+ patch(browser as unknown as Window, 'confirm', () => {
+ confirmations++;
+ return false;
+ });
+ await mount();
+ await review();
+ const link = (href: string) => {
+ const element = host.querySelector(`a[href="${href}"]`) as HTMLAnchorElement | null;
+ if (!element) {
+ throw new Error('Missing link');
+ }
+ return element;
+ };
+ await flush(() => {
+ button('Create halted deployment').click();
+ link('/experiments').click();
+ });
+ expect(confirmations).toBe(1);
+ expect(host.querySelector('[aria-label="Route"]')?.textContent).toBe('/paper');
+ await flush(() => rejectCreate(new ApiError('Response lost', null)));
+ await flush(() => link(`/paper/${id}`).click());
+ expect(confirmations).toBe(2);
+ expect(host.querySelector('[aria-label="Route"]')?.textContent).toBe('/paper');
+ await flush(() => {
+ link('/experiments').dispatchEvent(
+ new browser.MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ ctrlKey: true,
+ }) as unknown as MouseEvent
+ );
+ link(`/paper/${id}`).dispatchEvent(
+ new browser.MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ button: 1,
+ }) as unknown as MouseEvent
+ );
+ });
+ expect(confirmations).toBe(2);
+ expect(host.querySelector('[aria-label="Route"]')?.textContent).toBe('/paper');
+ await flush(() => button('Retry same promotion receipt').click());
+ expect(requests).toHaveLength(2);
+ expect(requests.slice(1)).toEqual(requests.slice(0, 1));
+});
+function savedDeployment(): PaperDeployment {
+ const input: PaperPromotionInput = {
+ name: 'History',
+ outOfSample: {
+ kind: 'chronological-report/v1',
+ validationId: id,
+ reportId: id,
+ reportHash: hash,
+ previewHash: hash,
+ },
+ testRunId: testId,
+ costExperimentId: costId,
+ costPreviewHash: hash,
+ costRunId: costId,
+ transport,
+ reason: 'Reviewed',
+ acknowledgeTrustedCode: true,
+ };
+ return {
+ id,
+ version: 'paper-deployment/v1',
+ principal: 'operator',
+ createdAt: '2026-10-24T12:00:00.000Z',
+ promotionHash: hash,
+ preview: preview(input),
+ };
+}
+test('historical deployment remains visible when host is unavailable; activation stays disabled and halt can still be requested', async () => {
+ const deployment = savedDeployment();
+ patch(api, 'get', async () => deployment);
+ patch(api, 'status', async () => {
+ throw new ApiError('Host disabled', 503);
+ });
+ root = createRoot(host);
+ await flush(() =>
+ root!.render(
+ createElement(
+ router.MemoryRouter,
+ { initialEntries: [`/paper/${id}`] },
+ createElement(
+ router.Routes,
+ {},
+ createElement(router.Route, {
+ path: '/paper/:deploymentId',
+ element: createElement(Detail),
+ })
+ )
+ )
+ )
+ );
+ await flush();
+ expect(host.textContent).toContain('Host disabled');
+ expect(host.textContent).toContain('History');
+ expect(host.textContent).toContain('Activation is unavailable');
+ expect([...host.querySelectorAll('button')].some(b => b.textContent === 'Activate paper')).toBe(
+ false
+ );
+ expect(button('Halt paper').disabled).toBe(false);
+});
diff --git a/test/integration/paper-native-identity.test.ts b/test/integration/paper-native-identity.test.ts
new file mode 100644
index 00000000..61955fe6
--- /dev/null
+++ b/test/integration/paper-native-identity.test.ts
@@ -0,0 +1,66 @@
+import { createHash } from 'node:crypto';
+import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { expect, test } from 'bun:test';
+import { loadedNativeIdentity } from '@stock-bot/engine';
+import { readPaperHostIdentity } from '../../apps/stock/orchestrator/src/paper/paper-host-identity';
+
+test('paper identity names the actual bundle and loaded immutable native bytes, not the research worker', async () => {
+ const identity = await readPaperHostIdentity();
+ expect(identity.version).toBe('paper-host/v1');
+ expect(Object.isFrozen(loadedNativeIdentity)).toBe(true);
+ expect(loadedNativeIdentity.engineWrapperSha256).toBe(identity.engineWrapperSha256);
+ expect(loadedNativeIdentity.engineBinarySha256).toBe(identity.engineBinarySha256);
+ const hash = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex');
+ expect(identity.hostSha256).toBe(
+ hash(
+ await readFile(new URL('../../apps/stock/orchestrator/dist/paper-host.js', import.meta.url))
+ )
+ );
+ expect(identity.hostSha256).not.toBe(
+ hash(
+ await readFile(
+ new URL('../../apps/stock/orchestrator/dist/native-worker.js', import.meta.url)
+ )
+ )
+ );
+});
+test('cached loaded identity remains the original bytes after a temporary wrapper file changes; artifacts require restart', async () => {
+ const directory = await mkdtemp(join(tmpdir(), 'stock-bot-native-identity-'));
+ try {
+ await mkdir(join(directory, 'dist'));
+ await copyFile(
+ new URL('../../apps/stock/engine/index.mjs', import.meta.url),
+ join(directory, 'index.mjs')
+ );
+ await copyFile(
+ new URL('../../apps/stock/engine/dist/engine.node', import.meta.url),
+ join(directory, 'dist/engine.node')
+ );
+ await writeFile(
+ join(directory, 'check.mjs'),
+ `import { readFileSync, appendFileSync } from 'node:fs';
+import { createHash } from 'node:crypto';
+import { loadedNativeIdentity as before } from './index.mjs';
+const path = new URL('./index.mjs', import.meta.url);
+appendFileSync(path, '\\n// temporary post-load change\\n');
+const { loadedNativeIdentity: after } = await import('./index.mjs');
+const current = createHash('sha256').update(readFileSync(path)).digest('hex');
+console.log(JSON.stringify({same:before===after,frozen:Object.isFrozen(after),loaded:after.engineWrapperSha256,current}));`
+ );
+ const child = Bun.spawn([process.execPath, join(directory, 'check.mjs')], {
+ stdout: 'pipe',
+ stderr: 'pipe',
+ });
+ const output = await new Response(child.stdout).text(),
+ error = await new Response(child.stderr).text();
+ expect(await child.exited, error).toBe(0);
+ const value = JSON.parse(output);
+ expect(value.same).toBe(true);
+ expect(value.frozen).toBe(true);
+ expect(value.loaded).not.toBe(value.current);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
diff --git a/test/integration/research-agents-ui.test.tsx b/test/integration/research-agents-ui.test.tsx
index 8f800973..fb8c493a 100644
--- a/test/integration/research-agents-ui.test.tsx
+++ b/test/integration/research-agents-ui.test.tsx
@@ -343,3 +343,32 @@ test('per-agent budget request order fences older success and failure responses'
expect(host.textContent).toContain('Active trials: 1; available slots: 0');
expect(host.textContent).not.toContain('Obsolete unavailable response');
});
+
+test('owned candidate permission is explicit per template and visible on saved grants', async () => {
+ await mount();
+ await draft();
+ await fill('Allow own candidates on backtest IDs', backtestId);
+ await flush(() => button('Create credential').click());
+ const request = pending('', 'POST');
+ expect(request.body).toMatchObject({ allowOwnCandidateBacktestIds: [backtestId] });
+ await flush(() =>
+ reply(
+ request,
+ {
+ agent: record({
+ grants: [{ backtestId, policyHash: 'a'.repeat(64), allowOwnCandidates: true }],
+ }),
+ token: 'fixture-only-token',
+ },
+ 201
+ )
+ );
+ expect(host.textContent).toContain('Owned isolated candidates allowed');
+ expect(
+ (
+ host.querySelector(
+ '[aria-label="Allow own candidates on backtest IDs"]'
+ ) as HTMLTextAreaElement
+ ).value
+ ).toBe('');
+});
diff --git a/test/postgres/ai-research-workflow.test.ts b/test/postgres/ai-research-workflow.test.ts
new file mode 100644
index 00000000..3520e975
--- /dev/null
+++ b/test/postgres/ai-research-workflow.test.ts
@@ -0,0 +1,460 @@
+/** Real authenticated APIs + disposable PostgreSQL + isolated candidate/Rust execution. No finance mocks. */
+import { createHash, randomUUID } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { afterEach, describe, expect, test } from 'bun:test';
+import { Hono } from 'hono';
+import { Pool } from 'pg';
+import { createHttpSecurity } from '@stock-bot/di';
+import { getLogger, setLoggerConfig } from '@stock-bot/logger';
+import { PostgreSQLClient } from '@stock-bot/postgres';
+import type { StrategyVersionPackage } from '@stock-bot/types';
+import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
+import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
+import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
+import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
+import { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes';
+import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes';
+import { createStrategyRoutes } from '../../apps/stock/web-api/src/routes/strategies.routes';
+import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
+import { ResearchService } from '../../apps/stock/web-api/src/services/research.service';
+import {
+ runResearchCycle,
+ type ResearchCycleEvent,
+ type ResearchCyclePlan,
+} from '../../scripts/examples/research-cycle';
+import { retainResearchDataset } from '../../scripts/import-research-dataset';
+import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
+import { ResearchClient } from '../../scripts/research-client';
+import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
+import { canonicalRegimeSelection } from '../fixtures/canonical-regime-research';
+import { walkForwardDataset } from '../fixtures/walk-forward';
+
+setLoggerConfig({ logLevel: 'fatal', logConsole: false });
+const logger = getLogger('ai-research-workflow');
+const url = process.env.PIPELINE_TEST_DATABASE_URL;
+const cleanups: (() => Promise)[] = [];
+afterEach(async () => {
+ for (const close of cleanups.splice(0).reverse()) {
+ await close();
+ }
+});
+let packages: ReturnType | undefined;
+async function fixture() {
+ if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
+ throw new Error('Disposable safety database required');
+ }
+ const schema = `stock_bot_safety_ai_cycle_${randomUUID().replaceAll('-', '')}`;
+ const admin = new Pool({ connectionString: url });
+ await admin.query(`CREATE SCHEMA ${schema}`);
+ const pool = new Pool({
+ connectionString: url,
+ max: 4,
+ options: `-c search_path=${schema} -c statement_timeout=10000`,
+ });
+ cleanups.push(async () => {
+ await pool.end();
+ await admin.query(`DROP SCHEMA ${schema} CASCADE`);
+ await admin.end();
+ });
+ const postgres = new PostgreSQLClient(
+ { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
+ logger
+ );
+ Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
+ const base = await canonicalAdmissionFixture(pool, postgres);
+ for (const name of [
+ '20-research-workspace.sql',
+ '27-research-evidence-sources.sql',
+ '28-research-agents.sql',
+ '29-isolated-candidates.sql',
+ '31-research-agent-project-links.sql',
+ ]) {
+ await pool.query(
+ readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
+ );
+ }
+ const dataset = walkForwardDataset();
+ await retainResearchDataset(pool, dataset.dataset);
+ const draft = await base.api.createBacktest(
+ {
+ ...base.definition,
+ name: 'AI workflow granted source',
+ startDate: new Date(dataset.dataset.manifest.bounds.tradeStart).toISOString(),
+ endDate: new Date(dataset.dataset.manifest.bounds.tradeEnd).toISOString(),
+ config: { ...base.definition.config, datasetHash: dataset.dataset.manifest.hash },
+ },
+ { autoStart: false }
+ );
+ const container = { postgres, logger };
+ const agents = new ResearchAgentsService(container),
+ research = new ResearchService(container);
+ const project = await research.createProject({ title: 'AI research acceptance' }, 'operator');
+ const provisioned = await agents.create({
+ name: 'Workflow researcher',
+ allowedProjectIds: [project.id],
+ allowedBacktestIds: [draft.id],
+ allowOwnCandidateBacktestIds: [draft.id],
+ limits: {
+ maxActiveTrials: 4,
+ maxTrialsPerExperiment: 4,
+ maxBarEvaluationsPerExperiment: 10000,
+ maxAttemptWallMs: 60000,
+ maxAttempts: 1,
+ },
+ });
+ const app = new Hono();
+ const security = createHttpSecurity({
+ adminToken: 'operator-test-secret-12345678901234567890',
+ serviceToken: 'service-test-secret-123456789012345678901',
+ environment: 'test',
+ resolveResearchCredential: request => agents.authenticate(request),
+ });
+ security.mount(app);
+ app.route('/', createResearchAgentRoutes(container, security.researchEnabled));
+ app.route('/', createStrategyRoutes(container));
+ app.route('/', createResearchRoutes(container));
+ app.route('/', createExperimentRoutes(container));
+ const engine = new RustBacktestAdapter({
+ logger,
+ storage: {
+ async getHistoricalBars() {
+ throw new Error('Research must use the frozen dataset');
+ },
+ },
+ });
+ const runner = new BacktestRunner({
+ engine,
+ engineName: 'native',
+ repository: new PostgresBacktestRunRepository(postgres),
+ logger,
+ });
+ const executionErrors: unknown[] = [];
+ let pending = Promise.resolve();
+ // A small test worker drives the existing durable runner. It changes no engine/fill behavior.
+ const drain = () => {
+ pending = pending.then(async () => {
+ for (const row of (
+ await pool.query<{ id: string }>(
+ "SELECT id FROM runs WHERE status='pending' ORDER BY created_at,id"
+ )
+ ).rows) {
+ try {
+ await runner.runQueued(row.id);
+ } catch (error) {
+ executionErrors.push(error);
+ }
+ }
+ });
+ };
+ cleanups.push(async () => {
+ await pending;
+ await runner.shutdown();
+ await engine.shutdown();
+ });
+ const requests: {
+ path: string;
+ method: string;
+ key: string | null;
+ body: unknown;
+ status: number;
+ }[] = [];
+ const transport: typeof fetch = (async (input: string | URL | Request, init?: RequestInit) => {
+ const request = new Request(input, init);
+ const body: unknown = request.body === null ? undefined : await request.clone().json();
+ const response = await app.fetch(request);
+ requests.push({
+ path: new URL(request.url).pathname,
+ method: request.method,
+ key: request.headers.get('Idempotency-Key'),
+ body,
+ status: response.status,
+ });
+ if (response.status === 202) {
+ drain();
+ }
+ return response;
+ }) as typeof fetch;
+ const client = new ResearchClient({
+ origin: 'http://127.0.0.1:2003',
+ token: provisioned.token,
+ fetch: transport,
+ });
+ const prepared = await (packages ??= packageBuiltinStrategies());
+ function candidate(index: number): StrategyVersionPackage {
+ const pkg = prepared[index];
+ if (!pkg) {
+ throw new Error('Missing prepared fixture');
+ }
+ return { ...structuredClone(pkg), execution: { kind: 'isolated-candidate/v1', warmupBars: 3 } };
+ }
+ function suggestions(): ResearchCyclePlan {
+ const trend = candidate(0),
+ regime = candidate(1),
+ failure = candidate(0);
+ failure.artifact.content += '\nthrow new Error("Deliberate research candidate failure");\n';
+ failure.artifact.sha256 = createHash('sha256').update(failure.artifact.content).digest('hex');
+ const common = {
+ recipe: dataset.windows[0]!,
+ costScenarios: [{ feeRate: '0.02', slippageRate: '0.01' }],
+ };
+ // Deterministic fake-model suggestions; bundles are inert input until the real isolated worker.
+ return {
+ cycleId: 'acceptance-cycle',
+ projectId: project.id,
+ backtestId: draft.id,
+ maxTotalTrials: 16,
+ hypothesis: {
+ title: 'Trend and regime-aware mean reversion',
+ proposition:
+ 'These independent candidates may respond differently to the same market observations',
+ validationCriteria:
+ 'Train-only selection, held-out diagnostics, fixed cost scenarios; no fitted-model or profitable-strategy claim',
+ },
+ candidates: [
+ {
+ ...common,
+ key: 'trend',
+ name: 'Trend candidate',
+ rationale: 'Short/long trend signals',
+ package: trend,
+ parameters: { fastPeriod: 2, slowPeriod: 3 },
+ grid: { fastPeriod: [1, 2] },
+ },
+ {
+ ...common,
+ key: 'regime',
+ name: 'Regime candidate',
+ rationale: 'Mean reversion with momentum, trend, volume and volatility gates',
+ package: regime,
+ parameters: canonicalRegimeSelection().parameters,
+ grid: {},
+ },
+ {
+ ...common,
+ key: 'broken',
+ name: 'Broken candidate',
+ rationale: 'Failure is evidence of implementation failure, not a zero return',
+ package: failure,
+ parameters: { fastPeriod: 2, slowPeriod: 3 },
+ grid: {},
+ },
+ ],
+ };
+ }
+ return {
+ ...base,
+ pool,
+ agents,
+ research,
+ project,
+ provisioned,
+ app,
+ client,
+ requests,
+ suggestions,
+ executionErrors,
+ transport,
+ drain,
+ };
+}
+
+describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust', () => {
+ test('two generated candidates, train-only selection, costs, exact saved evidence and a retained failure', async () => {
+ const f = await fixture();
+ const events: ResearchCycleEvent[] = [];
+ const result = await runResearchCycle(f.client, f.suggestions(), {
+ onEvent: async event => {
+ events.push(structuredClone(event));
+ },
+ poll: { timeoutMs: 60000, intervalMs: 20 },
+ });
+ expect(result.totalPlannedTrials).toBe(16);
+ expect(result.outcomes).toHaveLength(3);
+ expect(result.hypothesis.latestRevision.contentOrigin).toBe('ai');
+ expect(result.hypothesis.latestRevision.validationState).toBe('unvalidated');
+ expect(result.regimeAttribution).toContain('unavailable');
+ for (const outcome of result.outcomes.slice(0, 2)) {
+ expect(outcome.stoppedReason).toBeNull();
+ expect(
+ outcome.screening?.trials.every(trial => trial.status === 'completed' && trial.comparable)
+ ).toBeTrue();
+ const report = outcome.validation?.report,
+ selection = outcome.validation?.selection;
+ if (!report || !selection || !outcome.costs) {
+ throw new Error('Missing sealed native evidence');
+ }
+ expect(outcome.validation?.preview.policy.model).toBe('unverified-candidate');
+ expect(selection.training.every(run => run.phase === 'train')).toBeTrue();
+ expect(report.test.phase).toBe('test');
+ expect(outcome.costs.trials).toHaveLength(2);
+ for (const trial of outcome.costs.trials) {
+ expect(trial.status).toBe('completed');
+ expect(trial.comparable).toBeTrue();
+ expect(trial.parameters).toEqual(selection.winner.parameters);
+ }
+ const finding = outcome.findings[0]!;
+ expect(finding.latestRevision.source).toEqual({
+ kind: 'chronological-report/v1',
+ validationId: outcome.validation!.id,
+ previewHash: outcome.validation!.previewHash,
+ reportId: report.id,
+ reportHash: report.reportHash,
+ });
+ expect(finding.latestRevision.evidence).toHaveLength(6);
+ for (const evidence of finding.latestRevision.evidence) {
+ const saved = await f.api.getRunResults(evidence.runId);
+ if (!saved || !('kind' in saved) || saved.kind !== 'canonical-result/v1') {
+ throw new Error('Missing native result');
+ }
+ expect(saved.strategyExecution).toBe('typescript-isolated-candidate/v1');
+ expect(saved.request.strategy.versionId).toBe(outcome.versionId);
+ expect(saved.request.strategy.package.artifact.sha256).toHaveLength(64);
+ expect(evidence.datasetHash).toBe(saved.request.datasetHash);
+ const metric = evidence.metricPath.slice('analytics.metrics.'.length) as
+ | 'totalReturn'
+ | 'maxDrawdown'
+ | 'sharpeRatio';
+ expect(evidence.value).toBe(saved.analytics.metrics[metric]);
+ expect(evidence.availability).toBe(evidence.value === null ? 'unavailable' : 'available');
+ if (evidence.value === null) {
+ expect(evidence.unavailableReason).toBeTruthy();
+ }
+ }
+ }
+ const broken = result.outcomes[2]!;
+ expect(broken.screening?.trials[0]?.status).toBe('failed');
+ expect(broken.screening?.trials[0]?.metrics).toBeNull();
+ expect(broken.screening?.trials[0]?.error).toContain('Deliberate research candidate failure');
+ expect(broken.validation?.report).toBeNull();
+ expect(broken.validation?.selection).toBeNull();
+ expect(
+ broken.validation?.phases.slice(1).every(phase => phase.status === 'not-admitted')
+ ).toBeTrue();
+ expect(broken.findings).toEqual([]);
+ expect(broken.stoppedReason).toContain('failed');
+ expect(result.comparison?.rows).toHaveLength(4);
+ expect(result.comparison?.selection.leftId).toBe(result.outcomes[0]!.costs!.id);
+ expect(result.comparison?.selection.rightId).toBe(result.outcomes[1]!.costs!.id);
+ expect(
+ events.filter(event => event.phase === 'accepted' && event.operation === 'submit-training')
+ ).toHaveLength(3);
+ const keyed = events.filter(event => event.phase === 'intent' && event.key);
+ expect(new Set(keyed.map(event => event.key)).size).toBe(keyed.length);
+ expect(
+ keyed.every(
+ event =>
+ f.requests.some(
+ request =>
+ request.key === event.key &&
+ JSON.stringify(request.body) === JSON.stringify(event.input)
+ ) || event.operation === 'publish-version'
+ )
+ ).toBeTrue();
+ expect(
+ f.requests.some(request =>
+ /\/(?:paper(?:-deployments)?|deployments|live|reviews)(?:\/|$)/.test(request.path)
+ )
+ ).toBeFalse();
+ expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(12);
+ const accepted = events.find(
+ event => event.operation === 'submit-training' && event.phase === 'intent'
+ )!;
+ const before = (await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count;
+ const replay = await f.client.submitValidation(
+ accepted.input as Parameters[0],
+ accepted.key!
+ );
+ expect(replay.id).toBe(result.outcomes[0]!.validation!.id);
+ expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(
+ before
+ );
+ const reopened = await f.client.validation(result.outcomes[0]!.validation!.id);
+ expect(reopened.report).toEqual(result.outcomes[0]!.validation!.report);
+ }, 180000);
+
+ test('real quota refusal and oversized search create no runs; nonmember evidence cannot become a finding', async () => {
+ const f = await fixture(),
+ plan = f.suggestions();
+ const hypothesis = await f.client.createHypothesis(f.project.id, plan.hypothesis);
+ const family = await f.client.createStrategy({
+ name: 'Bounded candidate',
+ description: 'Budget adversary',
+ });
+ const version = await f.client.publishVersion(
+ family.id,
+ plan.candidates[0]!.package,
+ 'bounded-version'
+ );
+ const input = {
+ backtestId: plan.backtestId,
+ name: 'Exceeds admission',
+ candidate: { versionId: version.id, parameters: { fastPeriod: 2, slowPeriod: 10 } },
+ grid: { fastPeriod: [1, 2, 3, 4, 5] },
+ };
+ const overBudget = await f.client.previewExperiment(input);
+ await expect(
+ f.client.submitExperiment(
+ { ...overBudget.input, previewHash: overBudget.previewHash },
+ 'over-budget'
+ )
+ ).rejects.toMatchObject({
+ status: 429,
+ uncertain: false,
+ });
+ expect(() =>
+ f.client.previewExperiment({
+ ...input,
+ grid: { fastPeriod: Array.from({ length: 101 }, (_, i) => i + 1) },
+ })
+ ).toThrow();
+ expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(0);
+ const good = await f.client.previewExperiment({ ...input, grid: {} });
+ const admitted = await f.client.submitExperiment(
+ { ...good.input, previewHash: good.previewHash },
+ 'bounded-admitted'
+ );
+ const complete = await f.client.waitForExperiment(admitted.id, {
+ timeoutMs: 60000,
+ intervalMs: 20,
+ });
+ expect(complete.trials[0]?.status).toBe('completed');
+ const evidence = {
+ kind: 'finding' as const,
+ title: 'Incorrect evidence',
+ body: 'Must not be retained',
+ hypothesisRevisionId: hypothesis.latestRevision.id,
+ source: {
+ kind: 'experiment/v1' as const,
+ experimentId: admitted.id,
+ previewHash: admitted.previewHash,
+ },
+ evidence: [
+ {
+ runId: randomUUID(),
+ strategyVersionId: version.id,
+ metricsVersion: 'canonical-analytics/v1' as const,
+ metricPath: 'analytics.metrics.totalReturn' as const,
+ },
+ ],
+ };
+ await expect(f.client.saveFinding(f.project.id, evidence)).rejects.toMatchObject({
+ uncertain: false,
+ });
+ expect(
+ (await f.pool.query('SELECT count(*)::int AS count FROM analysis_artifacts')).rows[0].count
+ ).toBe(0);
+ const wrongVersion = {
+ ...evidence,
+ evidence: [
+ {
+ ...evidence.evidence[0]!,
+ runId: complete.trials[0]!.runId!,
+ strategyVersionId: f.version.id,
+ },
+ ],
+ };
+ await expect(f.client.saveFinding(f.project.id, wrongVersion)).rejects.toMatchObject({
+ uncertain: false,
+ });
+ }, 60000);
+});
diff --git a/test/postgres/canonical-research.test.ts b/test/postgres/canonical-research.test.ts
index 4ceab009..3f628793 100644
--- a/test/postgres/canonical-research.test.ts
+++ b/test/postgres/canonical-research.test.ts
@@ -219,7 +219,7 @@ describe.skipIf(!url)('canonical research admission and saved evidence', () => {
expect(result.analytics.metrics.totalReturn).toBe(0);
});
- test('candidates, legacy settings, wrong asset/timeframe, multi-asset datasets and pacing never admit work', async () => {
+ test('undeclared candidates, legacy settings, wrong asset/timeframe, multi-asset datasets and pacing never admit work', async () => {
const f = await fixture();
await f.approve();
const clone = await f.catalog.cloneVersion(
@@ -237,7 +237,9 @@ describe.skipIf(!url)('canonical research admission and saved evidence', () => {
{ ...f.definition, strategyVersionId: clone.version.id },
{ autoStart: false }
);
- await expect(f.api.createRun({ backtestId: candidate.id })).rejects.toThrow('candidates');
+ await expect(f.api.createRun({ backtestId: candidate.id })).rejects.toThrow(
+ 'Candidate requires a retained isolated execution declaration'
+ );
await expect(f.api.createRun({ backtestId: f.draft.id, speedMultiplier: 2 })).rejects.toThrow(
'maximum speed'
);
diff --git a/test/postgres/isolated-candidates.test.ts b/test/postgres/isolated-candidates.test.ts
new file mode 100644
index 00000000..fb14fd54
--- /dev/null
+++ b/test/postgres/isolated-candidates.test.ts
@@ -0,0 +1,537 @@
+import { randomUUID } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { afterEach, describe, expect, test } from 'bun:test';
+import { Pool } from 'pg';
+import { getLogger, setLoggerConfig } from '@stock-bot/logger';
+import { PostgreSQLClient } from '@stock-bot/postgres';
+import { isResearchAgent, type ResearchActor } from '@stock-bot/types';
+import { canonicalRunRequestSchema } from '../../apps/stock/config/src/contracts/canonical-research';
+import { builtinStrategySelectionSchema } from '../../apps/stock/config/src/contracts/strategy';
+import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
+import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
+import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
+import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
+import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
+import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
+import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service';
+import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
+import { researchGrantPolicy } from '../../apps/stock/web-api/src/services/research-agent-budget';
+import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
+import { WalkForwardService } from '../../apps/stock/web-api/src/services/walk-forward.service';
+import { retainResearchDataset } from '../../scripts/import-research-dataset';
+import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
+import { walkForwardDataset } from '../fixtures/walk-forward';
+
+setLoggerConfig({ logLevel: 'fatal', logConsole: false });
+const logger = getLogger('isolated-candidate-test');
+const url = process.env.PIPELINE_TEST_DATABASE_URL;
+const cleanups: (() => Promise)[] = [];
+afterEach(async () => {
+ for (const close of cleanups.splice(0).reverse()) {
+ await close();
+ }
+});
+const migrations = [
+ '06-create-backtest-tables.sql',
+ '07-fix-execution-time-type.sql',
+ '08-create-runs-table.sql',
+ '09-backtest-run-contract.sql',
+ '10-durable-backtest-dispatch.sql',
+ '12-historical-datasets.sql',
+ '14-backtest-submission.sql',
+ '16-strategy-catalog.sql',
+ '17-research-retention.sql',
+ '18-backtest-strategy-versions.sql',
+ '19-canonical-research.sql',
+ '20-research-workspace.sql',
+ '21-run-reproduction.sql',
+ '22-experiments.sql',
+ '23-experiment-retries.sql',
+ '24-chronological-validation.sql',
+ '25-walk-forward.sql',
+ '26-cost-sensitivity.sql',
+ '27-research-evidence-sources.sql',
+ '28-research-agents.sql',
+];
+async function fixture() {
+ if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
+ throw new Error('Disposable safety database required');
+ }
+ const schema = 'stock_bot_safety_candidate_' + randomUUID().replaceAll('-', '');
+ const admin = new Pool({ connectionString: url });
+ await admin.query(`CREATE SCHEMA ${schema}`);
+ const pool = new Pool({
+ connectionString: url,
+ max: 4,
+ options: `-c search_path=${schema} -c statement_timeout=10000`,
+ });
+ cleanups.push(async () => {
+ await pool.end();
+ await admin.query(`DROP SCHEMA ${schema} CASCADE`);
+ await admin.end();
+ });
+ for (const file of migrations) {
+ await pool.query(
+ readFileSync(new URL(`../../database/postgres/init/${file}`, import.meta.url), 'utf8')
+ );
+ }
+ const postgres = new PostgreSQLClient(
+ { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
+ logger
+ );
+ Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
+ const base = await canonicalAdmissionFixture(pool, postgres, false);
+ const container = { postgres, logger },
+ experiments = new ExperimentsService(container),
+ agents = new ResearchAgentsService(container);
+ const apply = () =>
+ pool.query(
+ readFileSync(
+ new URL('../../database/postgres/init/29-isolated-candidates.sql', import.meta.url),
+ 'utf8'
+ )
+ );
+ const candidate = async (principal: ResearchActor = 'operator', warmupBars = 0) => {
+ const family = await base.catalog.createStrategy(
+ { name: 'Isolated SMA', description: 'Controlled parity fixture' },
+ principal
+ );
+ const pkg = {
+ ...(await base.catalog.getVersionArtifact(base.version.id)),
+ execution: { kind: 'isolated-candidate/v1' as const, warmupBars },
+ };
+ return base.catalog.publishVersion(family.id, pkg, null, principal, randomUUID());
+ };
+ const execute = async (runId: string) => {
+ const engine = new RustBacktestAdapter({
+ logger,
+ storage: {
+ async getHistoricalBars() {
+ throw new Error('Candidate must use retained data only');
+ },
+ },
+ });
+ const runner = new BacktestRunner({
+ engine,
+ engineName: 'native',
+ repository: new PostgresBacktestRunRepository(postgres),
+ logger,
+ });
+ try {
+ await runner.runQueued(runId);
+ } finally {
+ await runner.shutdown();
+ await engine.shutdown();
+ }
+ return base.api.getRunResults(runId);
+ };
+ return { ...base, pool, postgres, container, experiments, agents, apply, candidate, execute };
+}
+const suite = url ? describe : describe.skip;
+suite('isolated candidate durable research', () => {
+ test('SQL29 first upgrade/reapply preserves existing evidence and authoritative SQL28 resource guards', async () => {
+ const f = await fixture();
+ const before = (
+ await f.pool.query(
+ "SELECT pg_get_functiondef('guard_agent_run_budget()'::regprocedure) AS budget,pg_get_functiondef('require_agent_result_deadline()'::regprocedure) AS deadline"
+ )
+ ).rows;
+ const old = await f.experiments.preview({
+ name: 'Old builtin',
+ backtestId: f.draft.id,
+ grid: {},
+ });
+ const admitted = await f.experiments.submit(
+ { ...old.input, previewHash: old.previewHash },
+ { principal: 'operator', key: 'before-upgrade' }
+ );
+ const pending = (
+ await f.pool.query('SELECT request_snapshot FROM runs WHERE experiment_id=$1', [admitted.id])
+ ).rows[0];
+ await new PostgresBacktestRunRepository(f.postgres).startCanonical(
+ canonicalRunRequestSchema.parse(pending.request_snapshot)
+ );
+ const bytes = (
+ await f.pool.query('SELECT to_jsonb(r) AS row FROM runs r WHERE experiment_id=$1', [
+ admitted.id,
+ ])
+ ).rows;
+ expect(bytes[0].row.status).toBe('running');
+ expect(bytes[0].row.attempt_id).not.toBeNull();
+ await f.apply();
+ await f.apply();
+ expect(
+ (
+ await f.pool.query(
+ "SELECT pg_get_functiondef('guard_agent_run_budget()'::regprocedure) AS budget,pg_get_functiondef('require_agent_result_deadline()'::regprocedure) AS deadline"
+ )
+ ).rows
+ ).toEqual(before);
+ expect(
+ (
+ await f.pool.query('SELECT to_jsonb(r) AS row FROM runs r WHERE experiment_id=$1', [
+ admitted.id,
+ ])
+ ).rows
+ ).toEqual(bytes);
+ expect(
+ (
+ await f.experiments.submit(
+ { ...old.input, previewHash: old.previewHash },
+ { principal: 'operator', key: 'before-upgrade' }
+ )
+ ).id
+ ).toBe(admitted.id);
+ });
+ test('unreviewed candidate admission runs the same Rust economics as the trusted controlled program', async () => {
+ const f = await fixture();
+ await f.apply();
+ const candidate = await f.candidate();
+ const input = {
+ name: 'Candidate parity',
+ backtestId: f.draft.id,
+ grid: {},
+ candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } },
+ };
+ const preview = await f.experiments.preview(input);
+ expect(preview.request.strategy.origin).toBe('candidate');
+ expect(preview.request.strategy.reviewId).toBeNull();
+ const experiment = await f.experiments.submit(
+ { ...input, previewHash: preview.previewHash },
+ { principal: 'operator', key: 'candidate-once' }
+ );
+ const runId = experiment.trials[0]?.runId;
+ if (!runId) {
+ throw new Error('Missing candidate trial');
+ }
+ const result = await f.execute(runId);
+ if (!result || !('kind' in result) || result.kind !== 'canonical-result/v1') {
+ throw new Error('Missing canonical candidate result');
+ }
+ expect(result.strategyExecution).toBe('typescript-isolated-candidate/v1');
+ const trusted = runStrategyReplay(
+ prepareReplayLoad(f.dataset, result.request.policy),
+ [
+ createBuiltinStrategy(
+ builtinStrategySelectionSchema.parse(result.request.strategy.selection)
+ ),
+ ],
+ { resultFormat: 'report' }
+ );
+ expect(result.financial).toEqual(trusted.result);
+ expect(String(result.financial.view.equity)).toBe('9969.30000000');
+ expect((await f.experiments.get(experiment.id)).trials[0]?.comparable).toBeTrue();
+ expect(
+ (
+ await f.experiments.submit(
+ { ...input, previewHash: preview.previewHash },
+ { principal: 'operator', key: 'candidate-once' }
+ )
+ ).id
+ ).toBe(experiment.id);
+ }, 30000);
+ test('agent own-candidate opt-in maps exactly to its frozen grant and rejects another principal/version or financial drift', async () => {
+ const f = await fixture();
+ await f.apply();
+ const created = await f.agents.create({
+ name: 'Candidate researcher',
+ allowedProjectIds: [],
+ allowedBacktestIds: [f.draft.id],
+ limits: {
+ maxActiveTrials: 2,
+ maxTrialsPerExperiment: 10,
+ maxBarEvaluationsPerExperiment: 10000,
+ maxAttemptWallMs: 60000,
+ maxAttempts: 2,
+ },
+ });
+ const principal = created.agent.id;
+ if (!isResearchAgent(principal)) {
+ throw new Error('Expected agent identity');
+ }
+ const candidate = await f.candidate(principal);
+ const input = {
+ name: 'Own candidate',
+ backtestId: f.draft.id,
+ grid: {},
+ candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } },
+ };
+ await expect(f.experiments.preview(input, principal)).rejects.toThrow('candidate permission');
+ const before = (
+ await f.pool.query('SELECT policy FROM research_agents WHERE id=$1', [principal])
+ ).rows[0].policy;
+ await f.agents.update(principal, {
+ expectedRevision: 1,
+ allowOwnCandidateBacktestIds: [f.draft.id],
+ });
+ const preview = await f.experiments.preview(input, principal);
+ expect(researchGrantPolicy(preview.request)).toEqual(before.grants[0].policy);
+ expect(
+ (await f.pool.query('SELECT research_grant_policy($1::jsonb) AS policy', [preview.request]))
+ .rows[0].policy
+ ).toEqual(researchGrantPolicy(preview.request));
+ const foreign = await f.candidate('operator');
+ await expect(
+ f.experiments.preview(
+ { ...input, candidate: { ...input.candidate, versionId: foreign.id } },
+ principal
+ )
+ ).rejects.toThrow('belong');
+ const [experiment, duplicate] = await Promise.all([
+ f.experiments.submit(
+ { ...input, previewHash: preview.previewHash },
+ { principal, key: 'agent-candidate' }
+ ),
+ f.experiments.submit(
+ { ...input, previewHash: preview.previewHash },
+ { principal, key: 'agent-candidate' }
+ ),
+ ]);
+ expect(duplicate.id).toBe(experiment.id);
+ expect(experiment.trialCount).toBe(1);
+ const after = (
+ await f.pool.query('SELECT policy FROM research_agents WHERE id=$1', [principal])
+ ).rows[0].policy;
+ expect(after.grants[0].policy).toEqual(before.grants[0].policy);
+ expect(after.grants[0].policyHash).toBe(before.grants[0].policyHash);
+ }, 30000);
+ test('candidate retry and reproduction preserve the original package, null review, runtime and baseline after template edits', async () => {
+ const f = await fixture();
+ await f.apply();
+ const candidate = await f.candidate();
+ const input = {
+ name: 'Retry candidate',
+ backtestId: f.draft.id,
+ grid: {},
+ candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } },
+ };
+ const preview = await f.experiments.preview(input);
+ const experiment = await f.experiments.submit(
+ { ...input, previewHash: preview.previewHash },
+ { principal: 'operator', key: 'create' }
+ );
+ const runId = experiment.trials[0]!.runId!;
+ const repository = new PostgresBacktestRunRepository(f.postgres);
+ await repository.rejectPending(runId, 'controlled preclaim failure');
+ const original = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId]))
+ .rows[0].request_snapshot;
+ await f.api.updateBacktest(f.draft.id, {
+ strategyParameters: { fastPeriod: 1, slowPeriod: 4 },
+ });
+ const retryBody = { expectedAttemptNumber: 0, expectedRetryCount: 0 },
+ actor = { principal: 'operator', key: 'retry' };
+ const retry = await f.experiments.retryTrial(experiment.id, runId, retryBody, actor);
+ expect(retry.retry.reviewId).toBeNull();
+ expect(
+ (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0]
+ .request_snapshot
+ ).toEqual(original);
+ await f.execute(runId);
+ expect((await f.experiments.retryTrial(experiment.id, runId, retryBody, actor)).retry.id).toBe(
+ retry.retry.id
+ );
+ expect((await f.api.getReproductionPreview(runId)).available).toBeTrue();
+ const reproduced = await f.api.reproduceRun(runId, {
+ principal: 'operator',
+ key: 'reproduction',
+ });
+ await f.execute(reproduced.id);
+ expect((await f.api.getReproductionComparison(reproduced.id)).status).toBe('match');
+ await f.catalog.reviewVersion(
+ candidate.id,
+ { decision: 'revoke', reason: 'deny later admission' },
+ 'operator'
+ );
+ expect((await f.api.getReproductionPreview(runId)).available).toBeFalse();
+ expect(
+ (await f.api.reproduceRun(runId, { principal: 'operator', key: 'reproduction' })).id
+ ).toBe(reproduced.id);
+ await expect(
+ f.api.reproduceRun(runId, { principal: 'operator', key: 'after-revoke' })
+ ).rejects.toThrow();
+ }, 30000);
+ test('candidate declared warmup and original baseline propagate through two native walk-forward windows and sealed reports', async () => {
+ const f = await fixture();
+ await f.apply();
+ const candidate = await f.candidate('operator', 4);
+ const data = walkForwardDataset();
+ await retainResearchDataset(f.pool, data.dataset);
+ await f.api.updateBacktest(f.draft.id, {
+ startDate: new Date(data.dataset.manifest.bounds.tradeStart).toISOString(),
+ endDate: new Date(data.dataset.manifest.bounds.tradeEnd).toISOString(),
+ config: { ...f.definition.config, datasetHash: data.dataset.manifest.hash },
+ });
+ const walks = new WalkForwardService(f.container),
+ validations = new ChronologicalValidationService(f.container);
+ const input = {
+ name: 'Candidate rolling windows',
+ backtestId: f.draft.id,
+ grid: {},
+ windows: data.windows,
+ candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } },
+ };
+ const preview = await walks.preview(input);
+ const walk = await walks.submit(
+ { ...input, previewHash: preview.previewHash },
+ { principal: 'operator', key: 'rolling' }
+ );
+ for (const member of walk.windows) {
+ const initial = await validations.get(member.validationId);
+ expect(initial.preview.policy.model).toBe('unverified-candidate');
+ for (const trial of initial.phases[0]!.experiment!.trials) {
+ await f.execute(trial.runId!);
+ }
+ const selected = await validations.select(
+ initial.id,
+ { previewHash: initial.previewHash },
+ { principal: 'operator', key: randomUUID() }
+ );
+ expect(selected.validation.selection!.reviewId).toBeNull();
+ const heldout = selected.validation.phases[1]!.experiment!.preview;
+ for (const field of ['baselineVersionId', 'execution'] as const) {
+ const forged = structuredClone(heldout);
+ if (forged.request.strategy.origin !== 'candidate') {
+ throw Error('candidate fixture');
+ }
+ if (field === 'baselineVersionId') {
+ forged.request.strategy.baselineVersionId = randomUUID();
+ } else {
+ forged.request.strategy.execution.imageId = `sha256:${'0'.repeat(64)}`;
+ }
+ await expect(
+ f.pool.query("SELECT assert_validation_phase_preview($1,$2,'validation',$3,NULL)", [
+ forged,
+ initial.preview,
+ selected.validation.selection!.winner,
+ ])
+ ).rejects.toThrow();
+ }
+ for (const phase of selected.validation.phases.slice(1)) {
+ expect(phase.experiment!.preview.request.strategy.origin).toBe('candidate');
+ for (const trial of phase.experiment!.trials) {
+ await f.execute(trial.runId!);
+ }
+ }
+ await validations.finalize(
+ initial.id,
+ {
+ previewHash: initial.previewHash,
+ selectionHash: selected.validation.selection!.selectionHash,
+ },
+ { principal: 'operator', key: randomUUID() }
+ );
+ }
+ const sealed = await walks.finalize(
+ walk.id,
+ { previewHash: preview.previewHash },
+ { principal: 'operator', key: 'seal' }
+ );
+ expect(sealed.walkForward.report!.segments).toHaveLength(2);
+ const stored = (
+ await f.pool.query(
+ "SELECT request_snapshot#>>'{strategy,baselineVersionId}' AS baseline, request_snapshot#>'{strategy,reviewId}' AS review FROM runs"
+ )
+ ).rows;
+ expect(stored).toHaveLength(6);
+ expect(stored.every(row => row.baseline === f.version.id && row.review === null)).toBeTrue();
+ }, 60000);
+ test('direct SQL refuses forged candidate ownership, baseline, execution profile and financial grant drift', async () => {
+ const f = await fixture();
+ await f.apply();
+ const created = await f.agents.create({
+ name: 'Direct guard',
+ allowedProjectIds: [],
+ allowedBacktestIds: [f.draft.id],
+ allowOwnCandidateBacktestIds: [f.draft.id],
+ limits: {
+ maxActiveTrials: 2,
+ maxTrialsPerExperiment: 10,
+ maxBarEvaluationsPerExperiment: 10000,
+ maxAttemptWallMs: 60000,
+ maxAttempts: 2,
+ },
+ });
+ const principal = created.agent.id;
+ if (!isResearchAgent(principal)) {
+ throw Error('agent identity');
+ }
+ const candidate = await f.candidate(principal);
+ const input = {
+ name: 'Guard candidate',
+ backtestId: f.draft.id,
+ grid: {},
+ candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } },
+ };
+ const preview = await f.experiments.preview(input, principal);
+ const admitted = await f.experiments.submit(
+ { ...input, previewHash: preview.previewHash },
+ { principal, key: 'admit' }
+ );
+ const row = (
+ await f.pool.query('SELECT to_jsonb(e) AS value FROM research_experiments e WHERE id=$1', [
+ admitted.id,
+ ])
+ ).rows[0].value;
+ await f.pool.query(
+ 'SELECT validate_experiment_manifest(jsonb_populate_record(NULL::research_experiments,$1))',
+ [row]
+ );
+ for (const [path, value] of [
+ [['strategy', 'baselineVersionId'], randomUUID()],
+ [['strategy', 'selection', 'ownerId'], 'strategy:' + randomUUID()],
+ [['strategy', 'origin'], 'builtin'],
+ [['strategy', 'execution', 'kind'], 'typescript-retained-builtin/v1'],
+ [['strategy', 'execution', 'profile', 'limits', 'memoryBytes'], 1073741824],
+ [['policy', 'matching', 'risk', 'maxGrossExposure'], '999999999'],
+ ] as const) {
+ const forged = structuredClone(row);
+ let parent = forged.preview.request;
+ for (const key of path.slice(0, -1)) {
+ parent = parent[key];
+ }
+ parent[path.at(-1)!] = value;
+ await expect(
+ f.pool.query(
+ 'SELECT validate_experiment_manifest(jsonb_populate_record(NULL::research_experiments,$1))',
+ [forged]
+ )
+ ).rejects.toThrow();
+ }
+ const drift = structuredClone(preview.request);
+ drift.policy.matching.risk.maxGrossExposure =
+ '999999999' as typeof drift.policy.matching.risk.maxGrossExposure;
+ await expect(
+ f.pool.query(
+ 'SELECT assert_research_agent_grant(a,$2,$3) FROM research_agents a WHERE id=$1',
+ [principal, f.draft.id, drift]
+ )
+ ).rejects.toThrow();
+ const foreign = await f.candidate('operator');
+ const foreignPreview = await f.experiments.preview({
+ ...input,
+ candidate: { ...input.candidate, versionId: foreign.id },
+ });
+ await expect(
+ f.pool.query(
+ 'SELECT assert_research_agent_grant(a,$2,$3) FROM research_agents a WHERE id=$1',
+ [principal, f.draft.id, foreignPreview.request]
+ )
+ ).rejects.toThrow();
+ await f.agents.update(principal, { expectedRevision: 1, allowOwnCandidateBacktestIds: [] });
+ await expect(
+ f.pool.query(
+ 'SELECT assert_research_agent_grant(a,$2,$3) FROM research_agents a WHERE id=$1',
+ [principal, f.draft.id, preview.request]
+ )
+ ).rejects.toThrow();
+ expect(
+ (
+ await f.experiments.submit(
+ { ...input, previewHash: preview.previewHash },
+ { principal, key: 'admit' }
+ )
+ ).id
+ ).toBe(admitted.id);
+ expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(1);
+ }, 30000);
+});
diff --git a/test/postgres/migration-runner.test.ts b/test/postgres/migration-runner.test.ts
index a148b986..3824c6ae 100644
--- a/test/postgres/migration-runner.test.ts
+++ b/test/postgres/migration-runner.test.ts
@@ -31,6 +31,9 @@ const migrations = [
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
'28-research-agents.sql',
+ '29-isolated-candidates.sql',
+ '30-paper-deployments.sql',
+ '31-research-agent-project-links.sql',
];
const cleanup: (() => Promise)[] = [];
afterEach(async () => {
diff --git a/test/postgres/paper-deployments.test.ts b/test/postgres/paper-deployments.test.ts
new file mode 100644
index 00000000..301d037d
--- /dev/null
+++ b/test/postgres/paper-deployments.test.ts
@@ -0,0 +1,573 @@
+import { createHash, randomUUID } from 'node:crypto';
+import { readdirSync, readFileSync } from 'node:fs';
+import { afterEach, describe, expect, test } from 'bun:test';
+import { Pool } from 'pg';
+import { getLogger, setLoggerConfig } from '@stock-bot/logger';
+import { PostgreSQLClient } from '@stock-bot/postgres';
+import type { PaperPromotionInput } from '@stock-bot/stock-config/paper-deployments';
+import { parseFinancialDecimal } from '@stock-bot/types';
+import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
+import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
+import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
+import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository';
+import {
+ readPaperDeployment,
+ verifyPaperEvidenceCustody,
+} from '../../apps/stock/orchestrator/src/paper/paper-deployment-custody';
+import { readPaperHostIdentity } from '../../apps/stock/orchestrator/src/paper/paper-host-identity';
+import { PaperDeploymentHost } from '../../apps/stock/orchestrator/src/paper/PaperDeploymentHost';
+import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
+import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service';
+import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
+import { PaperDeploymentsService } from '../../apps/stock/web-api/src/services/paper-deployments.service';
+import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
+import { retainResearchDataset } from '../../scripts/import-research-dataset';
+import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
+import { canonicalSettings } from '../fixtures/canonical-research';
+import { chronologicalDataset } from '../fixtures/chronological-validation';
+
+setLoggerConfig({ logLevel: 'fatal', logConsole: false });
+const logger = getLogger('paper-promotion'),
+ url = process.env.PIPELINE_TEST_DATABASE_URL;
+const closes: Array<() => Promise> = [];
+afterEach(async () => {
+ for (const close of closes.splice(0).reverse()) {
+ await close();
+ }
+});
+const actor = () => ({ principal: 'operator' as const, key: randomUUID() });
+async function fixture(max = 1, withPromotion = true, candidate = false) {
+ if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
+ throw new Error('Disposable database required');
+ }
+ const schema = 'stock_bot_safety_promotion_' + randomUUID().replaceAll('-', ''),
+ admin = new Pool({ connectionString: url });
+ await admin.query(`CREATE SCHEMA ${schema}`);
+ const pool = new Pool({
+ connectionString: url,
+ max,
+ options: `-c search_path=${schema} -c statement_timeout=15000`,
+ });
+ closes.push(async () => {
+ await pool.end();
+ await admin.query(`DROP SCHEMA ${schema} CASCADE`);
+ await admin.end();
+ });
+ const directory = new URL('../../database/postgres/init/', import.meta.url);
+ for (const file of readdirSync(directory)
+ .filter(
+ n =>
+ /^\d\d-/.test(n) &&
+ Number(n.slice(0, 2)) >= 6 &&
+ Number(n.slice(0, 2)) <= 30 &&
+ (withPromotion || Number(n.slice(0, 2)) !== 30)
+ )
+ .sort()) {
+ await pool.query(readFileSync(new URL(file, directory), 'utf8'));
+ }
+ const postgres = new PostgreSQLClient(
+ { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
+ logger
+ );
+ Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
+ Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
+ const container = { postgres, logger },
+ api = new BacktestServiceV2(container),
+ experiments = new ExperimentsService(container),
+ validations = new ChronologicalValidationService(container),
+ catalog = new StrategyCatalogService(container),
+ service = new PaperDeploymentsService(container);
+ const pkg = (await packageBuiltinStrategies())[0];
+ if (!pkg) {
+ throw new Error('Missing builtin');
+ }
+ const baseline = await catalog.seedBuiltin('Promotion SMA', pkg, 'seed');
+ let version = baseline;
+ await catalog.reviewVersion(
+ version.id,
+ { decision: 'approve', reason: 'Disposable proof' },
+ 'operator'
+ );
+ if (candidate) {
+ const family = await catalog.createStrategy(
+ { name: 'Generic retained paper candidate' },
+ 'operator'
+ );
+ const content = `export function createPaperCandidate(selection) {
+ return { ownerId: selection.ownerId, strategyId: selection.strategyId, strategyVersion: selection.strategyVersion,
+ seed: selection.seed, mode: 'target', initialState: {count:0, marker:'retained-candidate'},
+ decide(context) { return { nextState:{count:context.state.count+1,marker:'retained-candidate'},
+ intent:{mode:'target',targets:[{instrumentId:selection.instrumentId,quantity:'1.00000000'}]} }; }
+ };
+ }`;
+ version = await catalog.publishVersion(
+ family.id,
+ {
+ ...pkg,
+ program: {
+ ...pkg.program,
+ strategyId: 'paper_fixture_candidate',
+ strategyVersion: 'candidate/v1',
+ checkpointVersion: 'candidate-state/v1',
+ },
+ artifact: {
+ ...pkg.artifact,
+ entryExport: 'createPaperCandidate',
+ content,
+ sha256: createHash('sha256').update(content).digest('hex'),
+ },
+ execution: { kind: 'isolated-candidate/v1', warmupBars: 0 },
+ },
+ null,
+ 'operator',
+ randomUUID()
+ );
+ }
+ const candidateOverride = candidate
+ ? { candidate: { versionId: version.id, parameters: { fastPeriod: 2, slowPeriod: 3 } } }
+ : {};
+ const data = chronologicalDataset(),
+ dataset = data.dataset;
+ await retainResearchDataset(pool, dataset);
+ const draft = await api.createBacktest(
+ {
+ name: 'Promotion template',
+ strategy: 'catalog',
+ strategyVersionId: baseline.id,
+ strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
+ symbols: ['X0.US'],
+ startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
+ endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
+ initialCapital: 10000,
+ config: {
+ datasetHash: dataset.manifest.hash,
+ dataFrequency: '1m',
+ canonical: canonicalSettings,
+ },
+ },
+ { autoStart: false }
+ );
+ const repository = new PostgresBacktestRunRepository(postgres);
+ const execute = async (id: string) => {
+ const engine = new RustBacktestAdapter({
+ logger,
+ storage: {
+ async getHistoricalBars() {
+ throw new Error('No provider allowed');
+ },
+ },
+ });
+ const runner = new BacktestRunner({ engine, engineName: 'native', repository, logger });
+ try {
+ await runner.runQueued(id);
+ } finally {
+ await runner.shutdown();
+ }
+ };
+ const input = {
+ backtestId: draft.id,
+ name: 'Frozen OOS',
+ grid: {},
+ recipe: data.recipe,
+ ...candidateOverride,
+ },
+ preview = await experiments.previewValidation(input),
+ validation = await validations.submit({ ...input, previewHash: preview.previewHash }, actor());
+ for (const trial of validation.phases[0]!.experiment!.trials) {
+ await execute(trial.runId!);
+ }
+ const selected = await validations.select(
+ validation.id,
+ { previewHash: preview.previewHash },
+ actor()
+ );
+ for (const phase of selected.validation.phases.slice(1)) {
+ for (const trial of phase.experiment!.trials) {
+ await execute(trial.runId!);
+ }
+ }
+ const finished = await validations.finalize(
+ validation.id,
+ {
+ previewHash: preview.previewHash,
+ selectionHash: selected.validation.selection!.selectionHash,
+ },
+ actor()
+ ),
+ report = finished.validation.report!;
+ const costInput = {
+ backtestId: draft.id,
+ name: 'Cost evidence',
+ ...candidateOverride,
+ scenarios: [{ feeRate: '0.02', slippageRate: '0.01' }],
+ },
+ costPreview = await experiments.previewCosts(costInput),
+ cost = await experiments.submitCosts(
+ { ...costInput, previewHash: costPreview.previewHash },
+ actor()
+ );
+ for (const trial of cost.trials) {
+ await execute(trial.runId!);
+ }
+ if (candidate) {
+ const researchResult = await api.getRunResults(report.test.runId);
+ expect(
+ researchResult && 'strategyExecution' in researchResult
+ ? researchResult.strategyExecution
+ : null
+ ).toBe('typescript-isolated-candidate/v1');
+ await catalog.reviewVersion(
+ version.id,
+ { decision: 'approve', reason: 'Separate human review for trusted paper promotion' },
+ 'operator'
+ );
+ }
+ const start = Date.parse('2030-01-01T14:30:00Z'),
+ ownerId = `strategy:${version.id}`;
+ const promotion: PaperPromotionInput = {
+ name: 'Reviewed paper trial',
+ outOfSample: {
+ kind: 'chronological-report/v1',
+ validationId: validation.id,
+ reportId: report.id,
+ reportHash: report.reportHash,
+ previewHash: report.previewHash,
+ },
+ testRunId: report.test.runId,
+ costExperimentId: cost.id,
+ costPreviewHash: cost.previewHash,
+ costRunId: cost.trials[1]!.runId!,
+ reason: 'Reviewed held-out results, costs and trusted-code limitations',
+ acknowledgeTrustedCode: true,
+ transport: {
+ accountId: 'paper:' + randomUUID(),
+ sessionId: 'paper:' + randomUUID(),
+ quoteSeriesId: 'X0.US:quote',
+ riskSession: {
+ calendarId: 'paper-risk',
+ calendarRevision: 'v1',
+ sessionId: 'paper-day',
+ startsAt: start,
+ },
+ policy: {
+ version: 1,
+ sourceId: 'disposable-producer',
+ priceBasis: 'raw',
+ maxFeedAgeMs: 300000,
+ observations: [
+ { instrumentId: 'X0.US', seriesId: 'X0.US:1m', intervalMs: 60000, staleAfterMs: 300000 },
+ ],
+ cadence: [{ ownerId, seriesIds: ['X0.US:1m'] }],
+ calendars: [
+ {
+ instrumentId: 'X0.US',
+ calendarId: 'explicit-venue',
+ revision: 'v1',
+ sessions: [{ sessionId: 'paper-day', opensAt: start, closesAt: start + 3600000 }],
+ },
+ ],
+ riskBoundaries: [],
+ },
+ },
+ };
+ return {
+ pool,
+ postgres,
+ container,
+ service,
+ catalog,
+ version,
+ promotion,
+ report,
+ cost,
+ preview,
+ start,
+ validation,
+ api,
+ draft,
+ repository,
+ };
+}
+const submit = async (
+ f: Awaited>,
+ input = f.promotion,
+ key = randomUUID()
+) => {
+ const preview = await f.service.preview(input);
+ const body = { ...input, previewHash: preview.previewHash };
+ return { deployment: await f.service.create(body, key), body, key };
+};
+
+describe.skipIf(!url)('human-reviewed paper deployment', () => {
+ for (const candidate of [false, true]) {
+ test(`${candidate ? 'generic candidate' : 'builtin'} native OOS/cost promotion binds halted, fills through Rust, and restarts without resetting custody`, async () => {
+ const f = await fixture(1, true, candidate),
+ before = (await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0]
+ .n;
+ const saved = await submit(f),
+ deployment = saved.deployment;
+ expect(
+ (await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0].n
+ ).toBe(before);
+ expect(deployment.preview.evidence.test.fillCount).toBeGreaterThan(0);
+ expect(deployment.preview.evidence.costs.every(e => e.fillCount > 0)).toBe(true);
+ expect(deployment.preview.configuration.matching.risk.feeRate).toBe(
+ parseFinancialDecimal('0.02')
+ );
+ let now = f.start + 60000;
+ const repository = new PostgresCanonicalExecutionRepository(f.postgres),
+ host = new PaperDeploymentHost({ database: f.postgres, repository, now: () => now });
+ closes.push(() => host.shutdown());
+ expect((await host.bind(deployment.id.toUpperCase())).readiness.active).toBe(false);
+ expect((await host.status(deployment.id)).readiness.operatorHalted).toBe(true);
+ await expect(host.activate(deployment.id)).rejects.toThrow('feed');
+ const runtime = host.runtime(),
+ connection = { sourceId: 'disposable-producer', connectionId: 'one' };
+ await runtime.connect(connection);
+ const send = async (sequence: number, price: number, bars = true) => {
+ now = f.start + sequence * 60000;
+ const decimal = parseFinancialDecimal(String(price));
+ return runtime.ingest({
+ version: 1,
+ ...connection,
+ id: 'frame:' + sequence,
+ sequence,
+ availableAt: now,
+ quotes: [
+ {
+ instrumentId: 'X0.US',
+ seriesId: 'X0.US:quote',
+ observedAt: now,
+ sourceSequence: sequence,
+ bid: decimal,
+ ask: decimal,
+ bidSize: parseFinancialDecimal('1000'),
+ askSize: parseFinancialDecimal('1000'),
+ },
+ ],
+ observations: bars
+ ? [
+ {
+ series_id: 'X0.US:1m',
+ instrument_id: 'X0.US',
+ interval_start: now - 60000,
+ interval_end: now,
+ event_time: now,
+ available_at: now,
+ source_sequence: sequence,
+ open: decimal,
+ high: decimal,
+ low: decimal,
+ close: decimal,
+ volume: parseFinancialDecimal('1000'),
+ },
+ ]
+ : [],
+ });
+ };
+ await send(1, 3);
+ await host.activate(deployment.id);
+ await send(2, 3);
+ await send(3, 2);
+ await send(4, 1);
+ await send(5, 4);
+ await send(6, 5);
+ await send(7, 5, false);
+ const accountId = f.promotion.transport.accountId;
+ const snapshot = async () => ({
+ account: (
+ await f.pool.query('SELECT state FROM simulation_accounts WHERE id=$1', [accountId])
+ ).rows[0].state,
+ owners: (
+ await f.pool.query(
+ 'SELECT payload FROM simulation_strategy_checkpoints WHERE account_id=$1 ORDER BY strategy_id',
+ [accountId]
+ )
+ ).rows,
+ });
+ const filled = await snapshot();
+ expect(filled.account.view.portfolio.positions.length).toBeGreaterThan(0);
+ expect(filled.account.host.deployment.deploymentId).toBe(deployment.id);
+ expect(deployment.preview.strategy.origin).toBe(candidate ? 'candidate' : 'builtin');
+ if (candidate) {
+ expect(filled.owners[0].payload.definition.strategyId).toBe('paper_fixture_candidate');
+ expect(filled.owners[0].payload.diagnostic.state.marker).toBe('retained-candidate');
+ expect(filled.owners[0].payload.diagnostic.state.count).toBeGreaterThan(0);
+ expect(filled.account.view.portfolio.positions[0].quantity).toBe('1.00000000');
+ }
+
+ await host.halt(deployment.id, 'Review complete');
+ await host.shutdown();
+ const restarted = new PaperDeploymentHost({
+ database: f.postgres,
+ repository,
+ now: () => now,
+ });
+ closes.push(() => restarted.shutdown());
+ expect((await restarted.bind(deployment.id)).readiness.active).toBe(false);
+ const restored = await snapshot();
+ expect(restored.account.view).toEqual(filled.account.view);
+ expect(restored.account.checkpoint).toEqual(filled.account.checkpoint);
+ expect(restored.owners).toEqual(filled.owners);
+ expect(restored.account.host.deployment).toEqual(filled.account.host.deployment);
+ await f.catalog.reviewVersion(
+ f.version.id,
+ { decision: 'revoke', reason: 'Stop new activation' },
+ 'operator'
+ );
+ await expect(restarted.activate(deployment.id)).rejects.toThrow('current operator approval');
+ expect((await restarted.halt(deployment.id, 'Still allowed')).readiness.active).toBe(false);
+ expect(await f.service.create(saved.body, saved.key)).toEqual(deployment);
+ }, 60000);
+ }
+ test('exact receipts survive review changes; wrong evidence, cost drift, SQL tampering and custody reuse fail closed', async () => {
+ const f = await fixture(4),
+ saved = await submit(f);
+ const race = await Promise.all([
+ f.service.create(saved.body, saved.key),
+ f.service.create(saved.body, saved.key),
+ ]);
+ expect(race).toEqual([saved.deployment, saved.deployment]);
+ await expect(f.service.create({ ...saved.body, name: 'different' }, saved.key)).rejects.toThrow(
+ 'another request'
+ );
+ await expect(
+ f.service.preview({ ...f.promotion, testRunId: f.report.validation.runId })
+ ).rejects.toThrow('test run');
+ await expect(
+ f.service.preview({ ...f.promotion, costRunId: f.report.test.runId })
+ ).rejects.toThrow('cost scenario');
+ await expect(f.service.create(saved.body, randomUUID())).rejects.toThrow('already');
+ const original = saved.deployment;
+ for (const mutate of [
+ (d: typeof original) => {
+ d.principal = 'service' as 'operator';
+ },
+ (d: typeof original) => {
+ d.preview.configuration.matching.risk.maxGrossExposure = parseFinancialDecimal('999999');
+ },
+ (d: typeof original) => {
+ d.preview.input.testRunId = f.report.validation.runId;
+ },
+ (d: typeof original) => {
+ d.preview.evidence.costs = [];
+ },
+ (d: typeof original) => {
+ d.preview.evidence.test.metrics.totalReturn = 999;
+ },
+ (d: typeof original) => {
+ d.preview.host.engineBinarySha256 = 'f'.repeat(64);
+ },
+ ]) {
+ const d = structuredClone(original);
+ d.id = randomUUID();
+ d.preview.input.transport.accountId = 'other:' + randomUUID();
+ d.preview.configuration.matching.risk.ledger.accountId = d.preview.input.transport.accountId;
+ mutate(d);
+ await expect(
+ f.pool.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)',
+ [
+ d.id,
+ d.preview.configuration.matching.risk.ledger.accountId,
+ d.preview.strategy.versionId,
+ d.promotionHash,
+ randomUUID(),
+ 'a'.repeat(64),
+ d,
+ ]
+ )
+ ).rejects.toThrow();
+ }
+ await expect(
+ f.pool.query(
+ 'UPDATE paper_deployments SET document=document||\'{"principal":"service"}\' WHERE id=$1',
+ [original.id]
+ )
+ ).rejects.toThrow('immutable');
+ await expect(
+ f.pool.query('DELETE FROM paper_deployments WHERE id=$1', [original.id])
+ ).rejects.toThrow('immutable');
+ expect((await f.service.get(original.id)).promotionHash).toBe(original.promotionHash);
+ await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER');
+ await f.pool.query(
+ "UPDATE backtest_results SET canonical_result=jsonb_set(canonical_result,'{analytics,metrics,totalReturn}','999'::jsonb) WHERE run_id=$1",
+ [f.promotion.testRunId]
+ );
+ await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER');
+ await expect(f.service.authorizeCommand(original.id)).rejects.toThrow();
+ await expect(verifyPaperEvidenceCustody(f.pool, original)).rejects.toThrow('result identity');
+ }, 60000);
+ test('changed installed host and retained artifact cannot initialize or overwrite an account', async () => {
+ const f = await fixture(),
+ drifted = new PaperDeploymentsService(f.container, async () => ({
+ ...(await readPaperHostIdentity()),
+ hostSha256: 'f'.repeat(64),
+ }));
+ const wrongNative = new PaperDeploymentsService(f.container, async () => ({
+ ...(await readPaperHostIdentity()),
+ engineBinarySha256: 'f'.repeat(64),
+ }));
+ await expect(wrongNative.preview(f.promotion)).rejects.toThrow('same native');
+ const preview = await drifted.preview(f.promotion),
+ saved = await drifted.create(
+ { ...f.promotion, previewHash: preview.previewHash },
+ randomUUID()
+ );
+ const host = new PaperDeploymentHost({
+ database: f.postgres,
+ repository: new PostgresCanonicalExecutionRepository(f.postgres),
+ });
+ closes.push(() => host.shutdown());
+ await expect(host.bind(saved.id)).rejects.toThrow('differs');
+ expect(
+ (await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0].n
+ ).toBe(0);
+ await f.postgres.transaction(async tx => {
+ await tx.query('ALTER TABLE strategy_versions DISABLE TRIGGER USER');
+ await tx.query(
+ "UPDATE strategy_versions SET envelope=jsonb_set(envelope,'{artifact,content}',to_jsonb((envelope#>>'{artifact,content}')||' changed')) WHERE id=$1",
+ [f.version.id]
+ );
+ await tx.query('ALTER TABLE strategy_versions ENABLE TRIGGER USER');
+ });
+ await expect(host.bind(saved.id)).rejects.toThrow('hash mismatch');
+ await expect(f.service.preview(f.promotion)).rejects.toThrow();
+ expect(
+ (await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0].n
+ ).toBe(0);
+ }, 60000);
+ test('first migration/reapply preserves accepted research and leases, and archived evidence remains readable', async () => {
+ const f = await fixture(1, false),
+ pending = await f.api.createRun({ backtestId: f.draft.id }, actor()),
+ request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [pending.id]))
+ .rows[0].request_snapshot;
+ await f.repository.startCanonical(request);
+ const snapshot = async () =>
+ (await f.pool.query('SELECT to_jsonb(r) AS row FROM runs r ORDER BY id')).rows;
+ const before = await snapshot();
+ expect(
+ before.some(
+ item => item.row.status === 'running' && item.row.attempt_id && item.row.lease_expires_at
+ )
+ ).toBe(true);
+ const migration = readFileSync(
+ new URL('../../database/postgres/init/30-paper-deployments.sql', import.meta.url),
+ 'utf8'
+ );
+ await f.pool.query(migration);
+ expect(await snapshot()).toEqual(before);
+ const saved = await submit(f);
+ await f.pool.query(migration);
+ expect(await snapshot()).toEqual(before);
+ expect(await readPaperDeployment(f.pool, saved.deployment.id)).toEqual(saved.deployment);
+ await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
+ f.version.strategyId,
+ ]);
+ expect(await f.service.get(saved.deployment.id)).toEqual(saved.deployment);
+ await expect(f.service.authorizeCommand(saved.deployment.id)).rejects.toThrow('active family');
+ expect(
+ (await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0].n
+ ).toBe(0);
+ }, 60000);
+});
diff --git a/test/postgres/research-agents.test.ts b/test/postgres/research-agents.test.ts
index 29e31269..ec0a8fd3 100644
--- a/test/postgres/research-agents.test.ts
+++ b/test/postgres/research-agents.test.ts
@@ -236,6 +236,84 @@ function http(f: Fixture) {
});
}
describe.skipIf(!url)('authoritative research principals and budgets', () => {
+ test('owned project links advance only revision metadata after additive migration; project authority stays operator-only', async () => {
+ const f = await fixture(),
+ p = await provision(f);
+ const actor = p.agent.id as `agent:${string}`;
+ const clone = await f.catalog.cloneVersion(
+ f.version.id,
+ { name: 'Owned link candidate' },
+ actor,
+ randomUUID()
+ );
+ const before = await f.research.getProject(p.project.id);
+ await expect(f.research.linkStrategy(p.project.id, clone.strategy.id, actor)).rejects.toThrow(
+ 'Only an operator'
+ );
+ expect(await f.research.listProjectStrategies(p.project.id)).toEqual([]);
+ const migration = readFileSync(
+ new URL('../../database/postgres/init/31-research-agent-project-links.sql', import.meta.url),
+ 'utf8'
+ );
+ await f.pool.query(migration);
+ await f.research.linkStrategy(p.project.id, clone.strategy.id, actor);
+ const after = await f.research.getProject(p.project.id);
+ expect(after.revision).toBe(before.revision + 1);
+ expect(after.updatedBy).toBe(actor);
+ expect(after.ownerPrincipal).toBe(before.ownerPrincipal);
+ expect(after.title).toBe(before.title);
+ expect((await f.research.listProjectStrategies(p.project.id)).map(s => s.id)).toEqual([
+ clone.strategy.id,
+ ]);
+ await f.pool.query(migration);
+ await f.research.linkStrategy(p.project.id, clone.strategy.id, actor);
+ expect(await f.research.getProject(p.project.id)).toEqual(after);
+ const update = (fragment: string, id = p.project.id) =>
+ f.pool.query(
+ `UPDATE research_projects SET revision=revision+1,updated_by=$2,updated_at=NOW(),${fragment} WHERE id=$1`,
+ [id, actor]
+ );
+ for (const fragment of [
+ "title='changed'",
+ "description='changed'",
+ "owner_principal='service'",
+ 'archived_at=NOW()',
+ "created_at=created_at-INTERVAL '1 day'",
+ ]) {
+ await expect(update(fragment)).rejects.toThrow('Only owned strategy links');
+ }
+ await expect(
+ f.pool.query('UPDATE research_projects SET revision=revision+2,updated_by=$2 WHERE id=$1', [
+ p.project.id,
+ actor,
+ ])
+ ).rejects.toThrow('Only owned strategy links');
+ await expect(
+ f.research.createProject({ title: 'Unauthorized provisioning' }, actor)
+ ).rejects.toThrow('Only an operator');
+ const foreign = await f.research.createProject({ title: 'Ungranted' }, 'operator');
+ await expect(update('description=description', foreign.id)).rejects.toThrow(
+ 'Only owned strategy links'
+ );
+ await expect(f.research.linkStrategy(foreign.id, clone.strategy.id, actor)).rejects.toThrow(
+ 'not permitted'
+ );
+ await expect(
+ f.research.linkStrategy(p.project.id, f.version.strategyId, actor)
+ ).rejects.toThrow('not permitted');
+ expect(await f.research.getProject(p.project.id)).toEqual(after);
+ expect(
+ (
+ await f.pool.query(
+ "SELECT count(*)::int n FROM research_agent_audit WHERE agent_id=$1 AND operation='research_projects-link-revision'",
+ [actor]
+ )
+ ).rows[0].n
+ ).toBe(1);
+ await f.agents.update(actor, { expectedRevision: 1, enabled: false });
+ await expect(update('description=description')).rejects.toThrow('disabled');
+ expect(await f.research.getProject(p.project.id)).toEqual(after);
+ });
test('operator provisioning stores only a hash; real mounted authentication, AI authorship and scoped writes', async () => {
const f = await fixture(1),
p = await provision(f);
diff --git a/test/postgres/research-runtime-isolation.test.ts b/test/postgres/research-runtime-isolation.test.ts
index 34e7bf25..10ac8c0e 100644
--- a/test/postgres/research-runtime-isolation.test.ts
+++ b/test/postgres/research-runtime-isolation.test.ts
@@ -1,7 +1,8 @@
import { asValue } from 'awilix';
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, spyOn, test } from 'bun:test';
import { ServiceContainerBuilder } from '@stock-bot/di';
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
+import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
@@ -38,14 +39,13 @@ async function fixture() {
container.register({ serviceContainer: asValue(services) });
await registerOrchestratorServices(container);
const runtime = services.custom!,
- runner = runtime.BacktestRunner!,
- engine = runtime.BacktestEngine!;
+ runner = runtime.BacktestRunner!;
cleanup.push(async () => {
await runner.shutdown();
await paper.runtime.shutdown();
await container.dispose();
});
- return { paper, ...admitted, container, services, runtime, runner, engine };
+ return { paper, ...admitted, container, services, runtime, runner };
}
describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
'canonical research isolation from durable paper custody',
@@ -95,25 +95,29 @@ describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
for (let index = 0; index < 2; index++) {
const run = await accept();
let stopped: Promise | undefined;
- f.runner.once('progress', () => {
+ const cancelOnProgress = () => {
+ f.runner.off('progress', cancelOnProgress);
stopped = f.runner.stopBacktest();
- });
+ };
+ f.runner.on('progress', cancelOnProgress);
const cancelled = await f.runner.runQueued(run.id).catch(error => error);
await stopped;
expect(stopped).toBeDefined();
expect(cancelled).toBeInstanceOf(BacktestCancelledError);
await unchanged();
- const failed = await accept(),
- original = f.engine.runCanonical;
- f.engine.runCanonical = async () => {
- throw new Error('Injected canonical execution failure');
- };
+ const failed = await accept();
+ // The pool deliberately keeps engines private; inject only at the adapter seam.
+ const failure = spyOn(RustBacktestAdapter.prototype, 'runCanonical').mockImplementationOnce(
+ async () => {
+ throw new Error('Injected canonical execution failure');
+ }
+ );
try {
await expect(f.runner.runQueued(failed.id)).rejects.toThrow(
'Injected canonical execution failure'
);
} finally {
- f.engine.runCanonical = original;
+ failure.mockRestore();
}
await unchanged();
}
diff --git a/test/postgres/strategy-catalog.test.ts b/test/postgres/strategy-catalog.test.ts
index 3fd10a38..84d4607c 100644
--- a/test/postgres/strategy-catalog.test.ts
+++ b/test/postgres/strategy-catalog.test.ts
@@ -155,7 +155,7 @@ describe.skipIf(!url)('immutable strategy catalog on real PostgreSQL', () => {
reviewStatus: 'pending',
runnable: false,
});
- expect(v.reason).toContain('A02');
+ expect(v.reason).toContain('isolated execution declaration');
expect(v.package.artifact).not.toHaveProperty('content');
expect(v.package.dependencyLock).not.toHaveProperty('content');
expect(await f.api.getVersionArtifact(v.id)).toEqual(pkg);