feat(research): isolate candidates and add reviewed paper promotion

This commit is contained in:
Boki 2026-10-24 18:46:55 -04:00
parent 26b97265c6
commit 25b5cbf481
128 changed files with 13038 additions and 1388 deletions

View file

@ -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<string, unknown>[] = [];
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();
}

View file

@ -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<string>();
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 });
}

View file

@ -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<z.input<typeof planSchema>, 'candidates'> & {
candidates: (Omit<z.input<typeof planSchema>['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<ReturnType<ResearchClient['experiment']>>;
type Validation = Awaited<ReturnType<ResearchClient['validation']>>;
type Finding = Awaited<ReturnType<ResearchClient['saveFinding']>>;
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<void>;
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<T>(
candidateKey: string | null,
operation: string,
body: unknown,
invoke: () => Promise<T>,
suffix?: string,
resourceId?: string
): Promise<T> {
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 <prepared-plan.json> --receipts <new-receipts.jsonl>'
);
}
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;
}
}

View file

@ -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<StrategyVersionPackage> {
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
)
);
}

863
scripts/research-client.ts Normal file
View file

@ -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<T> 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<T> {
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<typeof createResearchHypothesisSchema>;
type FindingInput = z.input<typeof createResearchArtifactSchema>;
/** 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<T>(
path: string,
method: 'GET' | 'POST' | 'PUT',
status: number,
parse: (body: unknown) => T,
body?: unknown,
key?: string,
signal?: AbortSignal
): Promise<T> {
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<WorkbenchExperimentDetailView>
) {
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<ValidationDetailView>) {
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<T>(
read: (signal: AbortSignal) => Promise<T>,
done: (value: T) => boolean,
options: PollOptions<T>
): Promise<T> {
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<void>(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<T>(read: () => Promise<T>, signal: AbortSignal): Promise<T> {
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) };
}

View file

@ -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);
}

View file

@ -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<Response>) {
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<Response>(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<string, unknown>).__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<never>(() => {});
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 });
});

View file

@ -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<Response>) {
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);
});
});