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,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;
}
}