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,460 @@
/** Real authenticated APIs + disposable PostgreSQL + isolated candidate/Rust execution. No finance mocks. */
import { createHash, randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { afterEach, describe, expect, test } from 'bun:test';
import { Hono } from 'hono';
import { Pool } from 'pg';
import { createHttpSecurity } from '@stock-bot/di';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import type { StrategyVersionPackage } from '@stock-bot/types';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
import { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes';
import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes';
import { createStrategyRoutes } from '../../apps/stock/web-api/src/routes/strategies.routes';
import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
import { ResearchService } from '../../apps/stock/web-api/src/services/research.service';
import {
runResearchCycle,
type ResearchCycleEvent,
type ResearchCyclePlan,
} from '../../scripts/examples/research-cycle';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
import { ResearchClient } from '../../scripts/research-client';
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
import { canonicalRegimeSelection } from '../fixtures/canonical-regime-research';
import { walkForwardDataset } from '../fixtures/walk-forward';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('ai-research-workflow');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanups: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanups.splice(0).reverse()) {
await close();
}
});
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
async function fixture() {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Disposable safety database required');
}
const schema = `stock_bot_safety_ai_cycle_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({
connectionString: url,
max: 4,
options: `-c search_path=${schema} -c statement_timeout=10000`,
});
cleanups.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
const base = await canonicalAdmissionFixture(pool, postgres);
for (const name of [
'20-research-workspace.sql',
'27-research-evidence-sources.sql',
'28-research-agents.sql',
'29-isolated-candidates.sql',
'31-research-agent-project-links.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
);
}
const dataset = walkForwardDataset();
await retainResearchDataset(pool, dataset.dataset);
const draft = await base.api.createBacktest(
{
...base.definition,
name: 'AI workflow granted source',
startDate: new Date(dataset.dataset.manifest.bounds.tradeStart).toISOString(),
endDate: new Date(dataset.dataset.manifest.bounds.tradeEnd).toISOString(),
config: { ...base.definition.config, datasetHash: dataset.dataset.manifest.hash },
},
{ autoStart: false }
);
const container = { postgres, logger };
const agents = new ResearchAgentsService(container),
research = new ResearchService(container);
const project = await research.createProject({ title: 'AI research acceptance' }, 'operator');
const provisioned = await agents.create({
name: 'Workflow researcher',
allowedProjectIds: [project.id],
allowedBacktestIds: [draft.id],
allowOwnCandidateBacktestIds: [draft.id],
limits: {
maxActiveTrials: 4,
maxTrialsPerExperiment: 4,
maxBarEvaluationsPerExperiment: 10000,
maxAttemptWallMs: 60000,
maxAttempts: 1,
},
});
const app = new Hono();
const security = createHttpSecurity({
adminToken: 'operator-test-secret-12345678901234567890',
serviceToken: 'service-test-secret-123456789012345678901',
environment: 'test',
resolveResearchCredential: request => agents.authenticate(request),
});
security.mount(app);
app.route('/', createResearchAgentRoutes(container, security.researchEnabled));
app.route('/', createStrategyRoutes(container));
app.route('/', createResearchRoutes(container));
app.route('/', createExperimentRoutes(container));
const engine = new RustBacktestAdapter({
logger,
storage: {
async getHistoricalBars() {
throw new Error('Research must use the frozen dataset');
},
},
});
const runner = new BacktestRunner({
engine,
engineName: 'native',
repository: new PostgresBacktestRunRepository(postgres),
logger,
});
const executionErrors: unknown[] = [];
let pending = Promise.resolve();
// A small test worker drives the existing durable runner. It changes no engine/fill behavior.
const drain = () => {
pending = pending.then(async () => {
for (const row of (
await pool.query<{ id: string }>(
"SELECT id FROM runs WHERE status='pending' ORDER BY created_at,id"
)
).rows) {
try {
await runner.runQueued(row.id);
} catch (error) {
executionErrors.push(error);
}
}
});
};
cleanups.push(async () => {
await pending;
await runner.shutdown();
await engine.shutdown();
});
const requests: {
path: string;
method: string;
key: string | null;
body: unknown;
status: number;
}[] = [];
const transport: typeof fetch = (async (input: string | URL | Request, init?: RequestInit) => {
const request = new Request(input, init);
const body: unknown = request.body === null ? undefined : await request.clone().json();
const response = await app.fetch(request);
requests.push({
path: new URL(request.url).pathname,
method: request.method,
key: request.headers.get('Idempotency-Key'),
body,
status: response.status,
});
if (response.status === 202) {
drain();
}
return response;
}) as typeof fetch;
const client = new ResearchClient({
origin: 'http://127.0.0.1:2003',
token: provisioned.token,
fetch: transport,
});
const prepared = await (packages ??= packageBuiltinStrategies());
function candidate(index: number): StrategyVersionPackage {
const pkg = prepared[index];
if (!pkg) {
throw new Error('Missing prepared fixture');
}
return { ...structuredClone(pkg), execution: { kind: 'isolated-candidate/v1', warmupBars: 3 } };
}
function suggestions(): ResearchCyclePlan {
const trend = candidate(0),
regime = candidate(1),
failure = candidate(0);
failure.artifact.content += '\nthrow new Error("Deliberate research candidate failure");\n';
failure.artifact.sha256 = createHash('sha256').update(failure.artifact.content).digest('hex');
const common = {
recipe: dataset.windows[0]!,
costScenarios: [{ feeRate: '0.02', slippageRate: '0.01' }],
};
// Deterministic fake-model suggestions; bundles are inert input until the real isolated worker.
return {
cycleId: 'acceptance-cycle',
projectId: project.id,
backtestId: draft.id,
maxTotalTrials: 16,
hypothesis: {
title: 'Trend and regime-aware mean reversion',
proposition:
'These independent candidates may respond differently to the same market observations',
validationCriteria:
'Train-only selection, held-out diagnostics, fixed cost scenarios; no fitted-model or profitable-strategy claim',
},
candidates: [
{
...common,
key: 'trend',
name: 'Trend candidate',
rationale: 'Short/long trend signals',
package: trend,
parameters: { fastPeriod: 2, slowPeriod: 3 },
grid: { fastPeriod: [1, 2] },
},
{
...common,
key: 'regime',
name: 'Regime candidate',
rationale: 'Mean reversion with momentum, trend, volume and volatility gates',
package: regime,
parameters: canonicalRegimeSelection().parameters,
grid: {},
},
{
...common,
key: 'broken',
name: 'Broken candidate',
rationale: 'Failure is evidence of implementation failure, not a zero return',
package: failure,
parameters: { fastPeriod: 2, slowPeriod: 3 },
grid: {},
},
],
};
}
return {
...base,
pool,
agents,
research,
project,
provisioned,
app,
client,
requests,
suggestions,
executionErrors,
transport,
drain,
};
}
describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust', () => {
test('two generated candidates, train-only selection, costs, exact saved evidence and a retained failure', async () => {
const f = await fixture();
const events: ResearchCycleEvent[] = [];
const result = await runResearchCycle(f.client, f.suggestions(), {
onEvent: async event => {
events.push(structuredClone(event));
},
poll: { timeoutMs: 60000, intervalMs: 20 },
});
expect(result.totalPlannedTrials).toBe(16);
expect(result.outcomes).toHaveLength(3);
expect(result.hypothesis.latestRevision.contentOrigin).toBe('ai');
expect(result.hypothesis.latestRevision.validationState).toBe('unvalidated');
expect(result.regimeAttribution).toContain('unavailable');
for (const outcome of result.outcomes.slice(0, 2)) {
expect(outcome.stoppedReason).toBeNull();
expect(
outcome.screening?.trials.every(trial => trial.status === 'completed' && trial.comparable)
).toBeTrue();
const report = outcome.validation?.report,
selection = outcome.validation?.selection;
if (!report || !selection || !outcome.costs) {
throw new Error('Missing sealed native evidence');
}
expect(outcome.validation?.preview.policy.model).toBe('unverified-candidate');
expect(selection.training.every(run => run.phase === 'train')).toBeTrue();
expect(report.test.phase).toBe('test');
expect(outcome.costs.trials).toHaveLength(2);
for (const trial of outcome.costs.trials) {
expect(trial.status).toBe('completed');
expect(trial.comparable).toBeTrue();
expect(trial.parameters).toEqual(selection.winner.parameters);
}
const finding = outcome.findings[0]!;
expect(finding.latestRevision.source).toEqual({
kind: 'chronological-report/v1',
validationId: outcome.validation!.id,
previewHash: outcome.validation!.previewHash,
reportId: report.id,
reportHash: report.reportHash,
});
expect(finding.latestRevision.evidence).toHaveLength(6);
for (const evidence of finding.latestRevision.evidence) {
const saved = await f.api.getRunResults(evidence.runId);
if (!saved || !('kind' in saved) || saved.kind !== 'canonical-result/v1') {
throw new Error('Missing native result');
}
expect(saved.strategyExecution).toBe('typescript-isolated-candidate/v1');
expect(saved.request.strategy.versionId).toBe(outcome.versionId);
expect(saved.request.strategy.package.artifact.sha256).toHaveLength(64);
expect(evidence.datasetHash).toBe(saved.request.datasetHash);
const metric = evidence.metricPath.slice('analytics.metrics.'.length) as
| 'totalReturn'
| 'maxDrawdown'
| 'sharpeRatio';
expect(evidence.value).toBe(saved.analytics.metrics[metric]);
expect(evidence.availability).toBe(evidence.value === null ? 'unavailable' : 'available');
if (evidence.value === null) {
expect(evidence.unavailableReason).toBeTruthy();
}
}
}
const broken = result.outcomes[2]!;
expect(broken.screening?.trials[0]?.status).toBe('failed');
expect(broken.screening?.trials[0]?.metrics).toBeNull();
expect(broken.screening?.trials[0]?.error).toContain('Deliberate research candidate failure');
expect(broken.validation?.report).toBeNull();
expect(broken.validation?.selection).toBeNull();
expect(
broken.validation?.phases.slice(1).every(phase => phase.status === 'not-admitted')
).toBeTrue();
expect(broken.findings).toEqual([]);
expect(broken.stoppedReason).toContain('failed');
expect(result.comparison?.rows).toHaveLength(4);
expect(result.comparison?.selection.leftId).toBe(result.outcomes[0]!.costs!.id);
expect(result.comparison?.selection.rightId).toBe(result.outcomes[1]!.costs!.id);
expect(
events.filter(event => event.phase === 'accepted' && event.operation === 'submit-training')
).toHaveLength(3);
const keyed = events.filter(event => event.phase === 'intent' && event.key);
expect(new Set(keyed.map(event => event.key)).size).toBe(keyed.length);
expect(
keyed.every(
event =>
f.requests.some(
request =>
request.key === event.key &&
JSON.stringify(request.body) === JSON.stringify(event.input)
) || event.operation === 'publish-version'
)
).toBeTrue();
expect(
f.requests.some(request =>
/\/(?:paper(?:-deployments)?|deployments|live|reviews)(?:\/|$)/.test(request.path)
)
).toBeFalse();
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(12);
const accepted = events.find(
event => event.operation === 'submit-training' && event.phase === 'intent'
)!;
const before = (await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count;
const replay = await f.client.submitValidation(
accepted.input as Parameters<ResearchClient['submitValidation']>[0],
accepted.key!
);
expect(replay.id).toBe(result.outcomes[0]!.validation!.id);
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(
before
);
const reopened = await f.client.validation(result.outcomes[0]!.validation!.id);
expect(reopened.report).toEqual(result.outcomes[0]!.validation!.report);
}, 180000);
test('real quota refusal and oversized search create no runs; nonmember evidence cannot become a finding', async () => {
const f = await fixture(),
plan = f.suggestions();
const hypothesis = await f.client.createHypothesis(f.project.id, plan.hypothesis);
const family = await f.client.createStrategy({
name: 'Bounded candidate',
description: 'Budget adversary',
});
const version = await f.client.publishVersion(
family.id,
plan.candidates[0]!.package,
'bounded-version'
);
const input = {
backtestId: plan.backtestId,
name: 'Exceeds admission',
candidate: { versionId: version.id, parameters: { fastPeriod: 2, slowPeriod: 10 } },
grid: { fastPeriod: [1, 2, 3, 4, 5] },
};
const overBudget = await f.client.previewExperiment(input);
await expect(
f.client.submitExperiment(
{ ...overBudget.input, previewHash: overBudget.previewHash },
'over-budget'
)
).rejects.toMatchObject({
status: 429,
uncertain: false,
});
expect(() =>
f.client.previewExperiment({
...input,
grid: { fastPeriod: Array.from({ length: 101 }, (_, i) => i + 1) },
})
).toThrow();
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(0);
const good = await f.client.previewExperiment({ ...input, grid: {} });
const admitted = await f.client.submitExperiment(
{ ...good.input, previewHash: good.previewHash },
'bounded-admitted'
);
const complete = await f.client.waitForExperiment(admitted.id, {
timeoutMs: 60000,
intervalMs: 20,
});
expect(complete.trials[0]?.status).toBe('completed');
const evidence = {
kind: 'finding' as const,
title: 'Incorrect evidence',
body: 'Must not be retained',
hypothesisRevisionId: hypothesis.latestRevision.id,
source: {
kind: 'experiment/v1' as const,
experimentId: admitted.id,
previewHash: admitted.previewHash,
},
evidence: [
{
runId: randomUUID(),
strategyVersionId: version.id,
metricsVersion: 'canonical-analytics/v1' as const,
metricPath: 'analytics.metrics.totalReturn' as const,
},
],
};
await expect(f.client.saveFinding(f.project.id, evidence)).rejects.toMatchObject({
uncertain: false,
});
expect(
(await f.pool.query('SELECT count(*)::int AS count FROM analysis_artifacts')).rows[0].count
).toBe(0);
const wrongVersion = {
...evidence,
evidence: [
{
...evidence.evidence[0]!,
runId: complete.trials[0]!.runId!,
strategyVersionId: f.version.id,
},
],
};
await expect(f.client.saveFinding(f.project.id, wrongVersion)).rejects.toMatchObject({
uncertain: false,
});
}, 60000);
});

View file

@ -219,7 +219,7 @@ describe.skipIf(!url)('canonical research admission and saved evidence', () => {
expect(result.analytics.metrics.totalReturn).toBe(0);
});
test('candidates, legacy settings, wrong asset/timeframe, multi-asset datasets and pacing never admit work', async () => {
test('undeclared candidates, legacy settings, wrong asset/timeframe, multi-asset datasets and pacing never admit work', async () => {
const f = await fixture();
await f.approve();
const clone = await f.catalog.cloneVersion(
@ -237,7 +237,9 @@ describe.skipIf(!url)('canonical research admission and saved evidence', () => {
{ ...f.definition, strategyVersionId: clone.version.id },
{ autoStart: false }
);
await expect(f.api.createRun({ backtestId: candidate.id })).rejects.toThrow('candidates');
await expect(f.api.createRun({ backtestId: candidate.id })).rejects.toThrow(
'Candidate requires a retained isolated execution declaration'
);
await expect(f.api.createRun({ backtestId: f.draft.id, speedMultiplier: 2 })).rejects.toThrow(
'maximum speed'
);

View file

@ -0,0 +1,537 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { afterEach, describe, expect, test } from 'bun:test';
import { Pool } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { isResearchAgent, type ResearchActor } from '@stock-bot/types';
import { canonicalRunRequestSchema } from '../../apps/stock/config/src/contracts/canonical-research';
import { builtinStrategySelectionSchema } from '../../apps/stock/config/src/contracts/strategy';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service';
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
import { researchGrantPolicy } from '../../apps/stock/web-api/src/services/research-agent-budget';
import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
import { WalkForwardService } from '../../apps/stock/web-api/src/services/walk-forward.service';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
import { walkForwardDataset } from '../fixtures/walk-forward';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('isolated-candidate-test');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanups: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanups.splice(0).reverse()) {
await close();
}
});
const migrations = [
'06-create-backtest-tables.sql',
'07-fix-execution-time-type.sql',
'08-create-runs-table.sql',
'09-backtest-run-contract.sql',
'10-durable-backtest-dispatch.sql',
'12-historical-datasets.sql',
'14-backtest-submission.sql',
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
'20-research-workspace.sql',
'21-run-reproduction.sql',
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
'28-research-agents.sql',
];
async function fixture() {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Disposable safety database required');
}
const schema = 'stock_bot_safety_candidate_' + randomUUID().replaceAll('-', '');
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({
connectionString: url,
max: 4,
options: `-c search_path=${schema} -c statement_timeout=10000`,
});
cleanups.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
for (const file of migrations) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${file}`, import.meta.url), 'utf8')
);
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
const base = await canonicalAdmissionFixture(pool, postgres, false);
const container = { postgres, logger },
experiments = new ExperimentsService(container),
agents = new ResearchAgentsService(container);
const apply = () =>
pool.query(
readFileSync(
new URL('../../database/postgres/init/29-isolated-candidates.sql', import.meta.url),
'utf8'
)
);
const candidate = async (principal: ResearchActor = 'operator', warmupBars = 0) => {
const family = await base.catalog.createStrategy(
{ name: 'Isolated SMA', description: 'Controlled parity fixture' },
principal
);
const pkg = {
...(await base.catalog.getVersionArtifact(base.version.id)),
execution: { kind: 'isolated-candidate/v1' as const, warmupBars },
};
return base.catalog.publishVersion(family.id, pkg, null, principal, randomUUID());
};
const execute = async (runId: string) => {
const engine = new RustBacktestAdapter({
logger,
storage: {
async getHistoricalBars() {
throw new Error('Candidate must use retained data only');
},
},
});
const runner = new BacktestRunner({
engine,
engineName: 'native',
repository: new PostgresBacktestRunRepository(postgres),
logger,
});
try {
await runner.runQueued(runId);
} finally {
await runner.shutdown();
await engine.shutdown();
}
return base.api.getRunResults(runId);
};
return { ...base, pool, postgres, container, experiments, agents, apply, candidate, execute };
}
const suite = url ? describe : describe.skip;
suite('isolated candidate durable research', () => {
test('SQL29 first upgrade/reapply preserves existing evidence and authoritative SQL28 resource guards', async () => {
const f = await fixture();
const before = (
await f.pool.query(
"SELECT pg_get_functiondef('guard_agent_run_budget()'::regprocedure) AS budget,pg_get_functiondef('require_agent_result_deadline()'::regprocedure) AS deadline"
)
).rows;
const old = await f.experiments.preview({
name: 'Old builtin',
backtestId: f.draft.id,
grid: {},
});
const admitted = await f.experiments.submit(
{ ...old.input, previewHash: old.previewHash },
{ principal: 'operator', key: 'before-upgrade' }
);
const pending = (
await f.pool.query('SELECT request_snapshot FROM runs WHERE experiment_id=$1', [admitted.id])
).rows[0];
await new PostgresBacktestRunRepository(f.postgres).startCanonical(
canonicalRunRequestSchema.parse(pending.request_snapshot)
);
const bytes = (
await f.pool.query('SELECT to_jsonb(r) AS row FROM runs r WHERE experiment_id=$1', [
admitted.id,
])
).rows;
expect(bytes[0].row.status).toBe('running');
expect(bytes[0].row.attempt_id).not.toBeNull();
await f.apply();
await f.apply();
expect(
(
await f.pool.query(
"SELECT pg_get_functiondef('guard_agent_run_budget()'::regprocedure) AS budget,pg_get_functiondef('require_agent_result_deadline()'::regprocedure) AS deadline"
)
).rows
).toEqual(before);
expect(
(
await f.pool.query('SELECT to_jsonb(r) AS row FROM runs r WHERE experiment_id=$1', [
admitted.id,
])
).rows
).toEqual(bytes);
expect(
(
await f.experiments.submit(
{ ...old.input, previewHash: old.previewHash },
{ principal: 'operator', key: 'before-upgrade' }
)
).id
).toBe(admitted.id);
});
test('unreviewed candidate admission runs the same Rust economics as the trusted controlled program', async () => {
const f = await fixture();
await f.apply();
const candidate = await f.candidate();
const input = {
name: 'Candidate parity',
backtestId: f.draft.id,
grid: {},
candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } },
};
const preview = await f.experiments.preview(input);
expect(preview.request.strategy.origin).toBe('candidate');
expect(preview.request.strategy.reviewId).toBeNull();
const experiment = await f.experiments.submit(
{ ...input, previewHash: preview.previewHash },
{ principal: 'operator', key: 'candidate-once' }
);
const runId = experiment.trials[0]?.runId;
if (!runId) {
throw new Error('Missing candidate trial');
}
const result = await f.execute(runId);
if (!result || !('kind' in result) || result.kind !== 'canonical-result/v1') {
throw new Error('Missing canonical candidate result');
}
expect(result.strategyExecution).toBe('typescript-isolated-candidate/v1');
const trusted = runStrategyReplay(
prepareReplayLoad(f.dataset, result.request.policy),
[
createBuiltinStrategy(
builtinStrategySelectionSchema.parse(result.request.strategy.selection)
),
],
{ resultFormat: 'report' }
);
expect(result.financial).toEqual(trusted.result);
expect(String(result.financial.view.equity)).toBe('9969.30000000');
expect((await f.experiments.get(experiment.id)).trials[0]?.comparable).toBeTrue();
expect(
(
await f.experiments.submit(
{ ...input, previewHash: preview.previewHash },
{ principal: 'operator', key: 'candidate-once' }
)
).id
).toBe(experiment.id);
}, 30000);
test('agent own-candidate opt-in maps exactly to its frozen grant and rejects another principal/version or financial drift', async () => {
const f = await fixture();
await f.apply();
const created = await f.agents.create({
name: 'Candidate researcher',
allowedProjectIds: [],
allowedBacktestIds: [f.draft.id],
limits: {
maxActiveTrials: 2,
maxTrialsPerExperiment: 10,
maxBarEvaluationsPerExperiment: 10000,
maxAttemptWallMs: 60000,
maxAttempts: 2,
},
});
const principal = created.agent.id;
if (!isResearchAgent(principal)) {
throw new Error('Expected agent identity');
}
const candidate = await f.candidate(principal);
const input = {
name: 'Own candidate',
backtestId: f.draft.id,
grid: {},
candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } },
};
await expect(f.experiments.preview(input, principal)).rejects.toThrow('candidate permission');
const before = (
await f.pool.query('SELECT policy FROM research_agents WHERE id=$1', [principal])
).rows[0].policy;
await f.agents.update(principal, {
expectedRevision: 1,
allowOwnCandidateBacktestIds: [f.draft.id],
});
const preview = await f.experiments.preview(input, principal);
expect(researchGrantPolicy(preview.request)).toEqual(before.grants[0].policy);
expect(
(await f.pool.query('SELECT research_grant_policy($1::jsonb) AS policy', [preview.request]))
.rows[0].policy
).toEqual(researchGrantPolicy(preview.request));
const foreign = await f.candidate('operator');
await expect(
f.experiments.preview(
{ ...input, candidate: { ...input.candidate, versionId: foreign.id } },
principal
)
).rejects.toThrow('belong');
const [experiment, duplicate] = await Promise.all([
f.experiments.submit(
{ ...input, previewHash: preview.previewHash },
{ principal, key: 'agent-candidate' }
),
f.experiments.submit(
{ ...input, previewHash: preview.previewHash },
{ principal, key: 'agent-candidate' }
),
]);
expect(duplicate.id).toBe(experiment.id);
expect(experiment.trialCount).toBe(1);
const after = (
await f.pool.query('SELECT policy FROM research_agents WHERE id=$1', [principal])
).rows[0].policy;
expect(after.grants[0].policy).toEqual(before.grants[0].policy);
expect(after.grants[0].policyHash).toBe(before.grants[0].policyHash);
}, 30000);
test('candidate retry and reproduction preserve the original package, null review, runtime and baseline after template edits', async () => {
const f = await fixture();
await f.apply();
const candidate = await f.candidate();
const input = {
name: 'Retry candidate',
backtestId: f.draft.id,
grid: {},
candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } },
};
const preview = await f.experiments.preview(input);
const experiment = await f.experiments.submit(
{ ...input, previewHash: preview.previewHash },
{ principal: 'operator', key: 'create' }
);
const runId = experiment.trials[0]!.runId!;
const repository = new PostgresBacktestRunRepository(f.postgres);
await repository.rejectPending(runId, 'controlled preclaim failure');
const original = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId]))
.rows[0].request_snapshot;
await f.api.updateBacktest(f.draft.id, {
strategyParameters: { fastPeriod: 1, slowPeriod: 4 },
});
const retryBody = { expectedAttemptNumber: 0, expectedRetryCount: 0 },
actor = { principal: 'operator', key: 'retry' };
const retry = await f.experiments.retryTrial(experiment.id, runId, retryBody, actor);
expect(retry.retry.reviewId).toBeNull();
expect(
(await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0]
.request_snapshot
).toEqual(original);
await f.execute(runId);
expect((await f.experiments.retryTrial(experiment.id, runId, retryBody, actor)).retry.id).toBe(
retry.retry.id
);
expect((await f.api.getReproductionPreview(runId)).available).toBeTrue();
const reproduced = await f.api.reproduceRun(runId, {
principal: 'operator',
key: 'reproduction',
});
await f.execute(reproduced.id);
expect((await f.api.getReproductionComparison(reproduced.id)).status).toBe('match');
await f.catalog.reviewVersion(
candidate.id,
{ decision: 'revoke', reason: 'deny later admission' },
'operator'
);
expect((await f.api.getReproductionPreview(runId)).available).toBeFalse();
expect(
(await f.api.reproduceRun(runId, { principal: 'operator', key: 'reproduction' })).id
).toBe(reproduced.id);
await expect(
f.api.reproduceRun(runId, { principal: 'operator', key: 'after-revoke' })
).rejects.toThrow();
}, 30000);
test('candidate declared warmup and original baseline propagate through two native walk-forward windows and sealed reports', async () => {
const f = await fixture();
await f.apply();
const candidate = await f.candidate('operator', 4);
const data = walkForwardDataset();
await retainResearchDataset(f.pool, data.dataset);
await f.api.updateBacktest(f.draft.id, {
startDate: new Date(data.dataset.manifest.bounds.tradeStart).toISOString(),
endDate: new Date(data.dataset.manifest.bounds.tradeEnd).toISOString(),
config: { ...f.definition.config, datasetHash: data.dataset.manifest.hash },
});
const walks = new WalkForwardService(f.container),
validations = new ChronologicalValidationService(f.container);
const input = {
name: 'Candidate rolling windows',
backtestId: f.draft.id,
grid: {},
windows: data.windows,
candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } },
};
const preview = await walks.preview(input);
const walk = await walks.submit(
{ ...input, previewHash: preview.previewHash },
{ principal: 'operator', key: 'rolling' }
);
for (const member of walk.windows) {
const initial = await validations.get(member.validationId);
expect(initial.preview.policy.model).toBe('unverified-candidate');
for (const trial of initial.phases[0]!.experiment!.trials) {
await f.execute(trial.runId!);
}
const selected = await validations.select(
initial.id,
{ previewHash: initial.previewHash },
{ principal: 'operator', key: randomUUID() }
);
expect(selected.validation.selection!.reviewId).toBeNull();
const heldout = selected.validation.phases[1]!.experiment!.preview;
for (const field of ['baselineVersionId', 'execution'] as const) {
const forged = structuredClone(heldout);
if (forged.request.strategy.origin !== 'candidate') {
throw Error('candidate fixture');
}
if (field === 'baselineVersionId') {
forged.request.strategy.baselineVersionId = randomUUID();
} else {
forged.request.strategy.execution.imageId = `sha256:${'0'.repeat(64)}`;
}
await expect(
f.pool.query("SELECT assert_validation_phase_preview($1,$2,'validation',$3,NULL)", [
forged,
initial.preview,
selected.validation.selection!.winner,
])
).rejects.toThrow();
}
for (const phase of selected.validation.phases.slice(1)) {
expect(phase.experiment!.preview.request.strategy.origin).toBe('candidate');
for (const trial of phase.experiment!.trials) {
await f.execute(trial.runId!);
}
}
await validations.finalize(
initial.id,
{
previewHash: initial.previewHash,
selectionHash: selected.validation.selection!.selectionHash,
},
{ principal: 'operator', key: randomUUID() }
);
}
const sealed = await walks.finalize(
walk.id,
{ previewHash: preview.previewHash },
{ principal: 'operator', key: 'seal' }
);
expect(sealed.walkForward.report!.segments).toHaveLength(2);
const stored = (
await f.pool.query(
"SELECT request_snapshot#>>'{strategy,baselineVersionId}' AS baseline, request_snapshot#>'{strategy,reviewId}' AS review FROM runs"
)
).rows;
expect(stored).toHaveLength(6);
expect(stored.every(row => row.baseline === f.version.id && row.review === null)).toBeTrue();
}, 60000);
test('direct SQL refuses forged candidate ownership, baseline, execution profile and financial grant drift', async () => {
const f = await fixture();
await f.apply();
const created = await f.agents.create({
name: 'Direct guard',
allowedProjectIds: [],
allowedBacktestIds: [f.draft.id],
allowOwnCandidateBacktestIds: [f.draft.id],
limits: {
maxActiveTrials: 2,
maxTrialsPerExperiment: 10,
maxBarEvaluationsPerExperiment: 10000,
maxAttemptWallMs: 60000,
maxAttempts: 2,
},
});
const principal = created.agent.id;
if (!isResearchAgent(principal)) {
throw Error('agent identity');
}
const candidate = await f.candidate(principal);
const input = {
name: 'Guard candidate',
backtestId: f.draft.id,
grid: {},
candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } },
};
const preview = await f.experiments.preview(input, principal);
const admitted = await f.experiments.submit(
{ ...input, previewHash: preview.previewHash },
{ principal, key: 'admit' }
);
const row = (
await f.pool.query('SELECT to_jsonb(e) AS value FROM research_experiments e WHERE id=$1', [
admitted.id,
])
).rows[0].value;
await f.pool.query(
'SELECT validate_experiment_manifest(jsonb_populate_record(NULL::research_experiments,$1))',
[row]
);
for (const [path, value] of [
[['strategy', 'baselineVersionId'], randomUUID()],
[['strategy', 'selection', 'ownerId'], 'strategy:' + randomUUID()],
[['strategy', 'origin'], 'builtin'],
[['strategy', 'execution', 'kind'], 'typescript-retained-builtin/v1'],
[['strategy', 'execution', 'profile', 'limits', 'memoryBytes'], 1073741824],
[['policy', 'matching', 'risk', 'maxGrossExposure'], '999999999'],
] as const) {
const forged = structuredClone(row);
let parent = forged.preview.request;
for (const key of path.slice(0, -1)) {
parent = parent[key];
}
parent[path.at(-1)!] = value;
await expect(
f.pool.query(
'SELECT validate_experiment_manifest(jsonb_populate_record(NULL::research_experiments,$1))',
[forged]
)
).rejects.toThrow();
}
const drift = structuredClone(preview.request);
drift.policy.matching.risk.maxGrossExposure =
'999999999' as typeof drift.policy.matching.risk.maxGrossExposure;
await expect(
f.pool.query(
'SELECT assert_research_agent_grant(a,$2,$3) FROM research_agents a WHERE id=$1',
[principal, f.draft.id, drift]
)
).rejects.toThrow();
const foreign = await f.candidate('operator');
const foreignPreview = await f.experiments.preview({
...input,
candidate: { ...input.candidate, versionId: foreign.id },
});
await expect(
f.pool.query(
'SELECT assert_research_agent_grant(a,$2,$3) FROM research_agents a WHERE id=$1',
[principal, f.draft.id, foreignPreview.request]
)
).rejects.toThrow();
await f.agents.update(principal, { expectedRevision: 1, allowOwnCandidateBacktestIds: [] });
await expect(
f.pool.query(
'SELECT assert_research_agent_grant(a,$2,$3) FROM research_agents a WHERE id=$1',
[principal, f.draft.id, preview.request]
)
).rejects.toThrow();
expect(
(
await f.experiments.submit(
{ ...input, previewHash: preview.previewHash },
{ principal, key: 'admit' }
)
).id
).toBe(admitted.id);
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(1);
}, 30000);
});

View file

@ -31,6 +31,9 @@ const migrations = [
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
'28-research-agents.sql',
'29-isolated-candidates.sql',
'30-paper-deployments.sql',
'31-research-agent-project-links.sql',
];
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {

View file

@ -0,0 +1,573 @@
import { createHash, randomUUID } from 'node:crypto';
import { readdirSync, readFileSync } from 'node:fs';
import { afterEach, describe, expect, test } from 'bun:test';
import { Pool } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import type { PaperPromotionInput } from '@stock-bot/stock-config/paper-deployments';
import { parseFinancialDecimal } from '@stock-bot/types';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository';
import {
readPaperDeployment,
verifyPaperEvidenceCustody,
} from '../../apps/stock/orchestrator/src/paper/paper-deployment-custody';
import { readPaperHostIdentity } from '../../apps/stock/orchestrator/src/paper/paper-host-identity';
import { PaperDeploymentHost } from '../../apps/stock/orchestrator/src/paper/PaperDeploymentHost';
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service';
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
import { PaperDeploymentsService } from '../../apps/stock/web-api/src/services/paper-deployments.service';
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
import { canonicalSettings } from '../fixtures/canonical-research';
import { chronologicalDataset } from '../fixtures/chronological-validation';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('paper-promotion'),
url = process.env.PIPELINE_TEST_DATABASE_URL;
const closes: Array<() => Promise<void>> = [];
afterEach(async () => {
for (const close of closes.splice(0).reverse()) {
await close();
}
});
const actor = () => ({ principal: 'operator' as const, key: randomUUID() });
async function fixture(max = 1, withPromotion = true, candidate = false) {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Disposable database required');
}
const schema = 'stock_bot_safety_promotion_' + randomUUID().replaceAll('-', ''),
admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({
connectionString: url,
max,
options: `-c search_path=${schema} -c statement_timeout=15000`,
});
closes.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
const directory = new URL('../../database/postgres/init/', import.meta.url);
for (const file of readdirSync(directory)
.filter(
n =>
/^\d\d-/.test(n) &&
Number(n.slice(0, 2)) >= 6 &&
Number(n.slice(0, 2)) <= 30 &&
(withPromotion || Number(n.slice(0, 2)) !== 30)
)
.sort()) {
await pool.query(readFileSync(new URL(file, directory), 'utf8'));
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
const container = { postgres, logger },
api = new BacktestServiceV2(container),
experiments = new ExperimentsService(container),
validations = new ChronologicalValidationService(container),
catalog = new StrategyCatalogService(container),
service = new PaperDeploymentsService(container);
const pkg = (await packageBuiltinStrategies())[0];
if (!pkg) {
throw new Error('Missing builtin');
}
const baseline = await catalog.seedBuiltin('Promotion SMA', pkg, 'seed');
let version = baseline;
await catalog.reviewVersion(
version.id,
{ decision: 'approve', reason: 'Disposable proof' },
'operator'
);
if (candidate) {
const family = await catalog.createStrategy(
{ name: 'Generic retained paper candidate' },
'operator'
);
const content = `export function createPaperCandidate(selection) {
return { ownerId: selection.ownerId, strategyId: selection.strategyId, strategyVersion: selection.strategyVersion,
seed: selection.seed, mode: 'target', initialState: {count:0, marker:'retained-candidate'},
decide(context) { return { nextState:{count:context.state.count+1,marker:'retained-candidate'},
intent:{mode:'target',targets:[{instrumentId:selection.instrumentId,quantity:'1.00000000'}]} }; }
};
}`;
version = await catalog.publishVersion(
family.id,
{
...pkg,
program: {
...pkg.program,
strategyId: 'paper_fixture_candidate',
strategyVersion: 'candidate/v1',
checkpointVersion: 'candidate-state/v1',
},
artifact: {
...pkg.artifact,
entryExport: 'createPaperCandidate',
content,
sha256: createHash('sha256').update(content).digest('hex'),
},
execution: { kind: 'isolated-candidate/v1', warmupBars: 0 },
},
null,
'operator',
randomUUID()
);
}
const candidateOverride = candidate
? { candidate: { versionId: version.id, parameters: { fastPeriod: 2, slowPeriod: 3 } } }
: {};
const data = chronologicalDataset(),
dataset = data.dataset;
await retainResearchDataset(pool, dataset);
const draft = await api.createBacktest(
{
name: 'Promotion template',
strategy: 'catalog',
strategyVersionId: baseline.id,
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
symbols: ['X0.US'],
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
initialCapital: 10000,
config: {
datasetHash: dataset.manifest.hash,
dataFrequency: '1m',
canonical: canonicalSettings,
},
},
{ autoStart: false }
);
const repository = new PostgresBacktestRunRepository(postgres);
const execute = async (id: string) => {
const engine = new RustBacktestAdapter({
logger,
storage: {
async getHistoricalBars() {
throw new Error('No provider allowed');
},
},
});
const runner = new BacktestRunner({ engine, engineName: 'native', repository, logger });
try {
await runner.runQueued(id);
} finally {
await runner.shutdown();
}
};
const input = {
backtestId: draft.id,
name: 'Frozen OOS',
grid: {},
recipe: data.recipe,
...candidateOverride,
},
preview = await experiments.previewValidation(input),
validation = await validations.submit({ ...input, previewHash: preview.previewHash }, actor());
for (const trial of validation.phases[0]!.experiment!.trials) {
await execute(trial.runId!);
}
const selected = await validations.select(
validation.id,
{ previewHash: preview.previewHash },
actor()
);
for (const phase of selected.validation.phases.slice(1)) {
for (const trial of phase.experiment!.trials) {
await execute(trial.runId!);
}
}
const finished = await validations.finalize(
validation.id,
{
previewHash: preview.previewHash,
selectionHash: selected.validation.selection!.selectionHash,
},
actor()
),
report = finished.validation.report!;
const costInput = {
backtestId: draft.id,
name: 'Cost evidence',
...candidateOverride,
scenarios: [{ feeRate: '0.02', slippageRate: '0.01' }],
},
costPreview = await experiments.previewCosts(costInput),
cost = await experiments.submitCosts(
{ ...costInput, previewHash: costPreview.previewHash },
actor()
);
for (const trial of cost.trials) {
await execute(trial.runId!);
}
if (candidate) {
const researchResult = await api.getRunResults(report.test.runId);
expect(
researchResult && 'strategyExecution' in researchResult
? researchResult.strategyExecution
: null
).toBe('typescript-isolated-candidate/v1');
await catalog.reviewVersion(
version.id,
{ decision: 'approve', reason: 'Separate human review for trusted paper promotion' },
'operator'
);
}
const start = Date.parse('2030-01-01T14:30:00Z'),
ownerId = `strategy:${version.id}`;
const promotion: PaperPromotionInput = {
name: 'Reviewed paper trial',
outOfSample: {
kind: 'chronological-report/v1',
validationId: validation.id,
reportId: report.id,
reportHash: report.reportHash,
previewHash: report.previewHash,
},
testRunId: report.test.runId,
costExperimentId: cost.id,
costPreviewHash: cost.previewHash,
costRunId: cost.trials[1]!.runId!,
reason: 'Reviewed held-out results, costs and trusted-code limitations',
acknowledgeTrustedCode: true,
transport: {
accountId: 'paper:' + randomUUID(),
sessionId: 'paper:' + randomUUID(),
quoteSeriesId: 'X0.US:quote',
riskSession: {
calendarId: 'paper-risk',
calendarRevision: 'v1',
sessionId: 'paper-day',
startsAt: start,
},
policy: {
version: 1,
sourceId: 'disposable-producer',
priceBasis: 'raw',
maxFeedAgeMs: 300000,
observations: [
{ instrumentId: 'X0.US', seriesId: 'X0.US:1m', intervalMs: 60000, staleAfterMs: 300000 },
],
cadence: [{ ownerId, seriesIds: ['X0.US:1m'] }],
calendars: [
{
instrumentId: 'X0.US',
calendarId: 'explicit-venue',
revision: 'v1',
sessions: [{ sessionId: 'paper-day', opensAt: start, closesAt: start + 3600000 }],
},
],
riskBoundaries: [],
},
},
};
return {
pool,
postgres,
container,
service,
catalog,
version,
promotion,
report,
cost,
preview,
start,
validation,
api,
draft,
repository,
};
}
const submit = async (
f: Awaited<ReturnType<typeof fixture>>,
input = f.promotion,
key = randomUUID()
) => {
const preview = await f.service.preview(input);
const body = { ...input, previewHash: preview.previewHash };
return { deployment: await f.service.create(body, key), body, key };
};
describe.skipIf(!url)('human-reviewed paper deployment', () => {
for (const candidate of [false, true]) {
test(`${candidate ? 'generic candidate' : 'builtin'} native OOS/cost promotion binds halted, fills through Rust, and restarts without resetting custody`, async () => {
const f = await fixture(1, true, candidate),
before = (await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0]
.n;
const saved = await submit(f),
deployment = saved.deployment;
expect(
(await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0].n
).toBe(before);
expect(deployment.preview.evidence.test.fillCount).toBeGreaterThan(0);
expect(deployment.preview.evidence.costs.every(e => e.fillCount > 0)).toBe(true);
expect(deployment.preview.configuration.matching.risk.feeRate).toBe(
parseFinancialDecimal('0.02')
);
let now = f.start + 60000;
const repository = new PostgresCanonicalExecutionRepository(f.postgres),
host = new PaperDeploymentHost({ database: f.postgres, repository, now: () => now });
closes.push(() => host.shutdown());
expect((await host.bind(deployment.id.toUpperCase())).readiness.active).toBe(false);
expect((await host.status(deployment.id)).readiness.operatorHalted).toBe(true);
await expect(host.activate(deployment.id)).rejects.toThrow('feed');
const runtime = host.runtime(),
connection = { sourceId: 'disposable-producer', connectionId: 'one' };
await runtime.connect(connection);
const send = async (sequence: number, price: number, bars = true) => {
now = f.start + sequence * 60000;
const decimal = parseFinancialDecimal(String(price));
return runtime.ingest({
version: 1,
...connection,
id: 'frame:' + sequence,
sequence,
availableAt: now,
quotes: [
{
instrumentId: 'X0.US',
seriesId: 'X0.US:quote',
observedAt: now,
sourceSequence: sequence,
bid: decimal,
ask: decimal,
bidSize: parseFinancialDecimal('1000'),
askSize: parseFinancialDecimal('1000'),
},
],
observations: bars
? [
{
series_id: 'X0.US:1m',
instrument_id: 'X0.US',
interval_start: now - 60000,
interval_end: now,
event_time: now,
available_at: now,
source_sequence: sequence,
open: decimal,
high: decimal,
low: decimal,
close: decimal,
volume: parseFinancialDecimal('1000'),
},
]
: [],
});
};
await send(1, 3);
await host.activate(deployment.id);
await send(2, 3);
await send(3, 2);
await send(4, 1);
await send(5, 4);
await send(6, 5);
await send(7, 5, false);
const accountId = f.promotion.transport.accountId;
const snapshot = async () => ({
account: (
await f.pool.query('SELECT state FROM simulation_accounts WHERE id=$1', [accountId])
).rows[0].state,
owners: (
await f.pool.query(
'SELECT payload FROM simulation_strategy_checkpoints WHERE account_id=$1 ORDER BY strategy_id',
[accountId]
)
).rows,
});
const filled = await snapshot();
expect(filled.account.view.portfolio.positions.length).toBeGreaterThan(0);
expect(filled.account.host.deployment.deploymentId).toBe(deployment.id);
expect(deployment.preview.strategy.origin).toBe(candidate ? 'candidate' : 'builtin');
if (candidate) {
expect(filled.owners[0].payload.definition.strategyId).toBe('paper_fixture_candidate');
expect(filled.owners[0].payload.diagnostic.state.marker).toBe('retained-candidate');
expect(filled.owners[0].payload.diagnostic.state.count).toBeGreaterThan(0);
expect(filled.account.view.portfolio.positions[0].quantity).toBe('1.00000000');
}
await host.halt(deployment.id, 'Review complete');
await host.shutdown();
const restarted = new PaperDeploymentHost({
database: f.postgres,
repository,
now: () => now,
});
closes.push(() => restarted.shutdown());
expect((await restarted.bind(deployment.id)).readiness.active).toBe(false);
const restored = await snapshot();
expect(restored.account.view).toEqual(filled.account.view);
expect(restored.account.checkpoint).toEqual(filled.account.checkpoint);
expect(restored.owners).toEqual(filled.owners);
expect(restored.account.host.deployment).toEqual(filled.account.host.deployment);
await f.catalog.reviewVersion(
f.version.id,
{ decision: 'revoke', reason: 'Stop new activation' },
'operator'
);
await expect(restarted.activate(deployment.id)).rejects.toThrow('current operator approval');
expect((await restarted.halt(deployment.id, 'Still allowed')).readiness.active).toBe(false);
expect(await f.service.create(saved.body, saved.key)).toEqual(deployment);
}, 60000);
}
test('exact receipts survive review changes; wrong evidence, cost drift, SQL tampering and custody reuse fail closed', async () => {
const f = await fixture(4),
saved = await submit(f);
const race = await Promise.all([
f.service.create(saved.body, saved.key),
f.service.create(saved.body, saved.key),
]);
expect(race).toEqual([saved.deployment, saved.deployment]);
await expect(f.service.create({ ...saved.body, name: 'different' }, saved.key)).rejects.toThrow(
'another request'
);
await expect(
f.service.preview({ ...f.promotion, testRunId: f.report.validation.runId })
).rejects.toThrow('test run');
await expect(
f.service.preview({ ...f.promotion, costRunId: f.report.test.runId })
).rejects.toThrow('cost scenario');
await expect(f.service.create(saved.body, randomUUID())).rejects.toThrow('already');
const original = saved.deployment;
for (const mutate of [
(d: typeof original) => {
d.principal = 'service' as 'operator';
},
(d: typeof original) => {
d.preview.configuration.matching.risk.maxGrossExposure = parseFinancialDecimal('999999');
},
(d: typeof original) => {
d.preview.input.testRunId = f.report.validation.runId;
},
(d: typeof original) => {
d.preview.evidence.costs = [];
},
(d: typeof original) => {
d.preview.evidence.test.metrics.totalReturn = 999;
},
(d: typeof original) => {
d.preview.host.engineBinarySha256 = 'f'.repeat(64);
},
]) {
const d = structuredClone(original);
d.id = randomUUID();
d.preview.input.transport.accountId = 'other:' + randomUUID();
d.preview.configuration.matching.risk.ledger.accountId = d.preview.input.transport.accountId;
mutate(d);
await expect(
f.pool.query(
'INSERT INTO paper_deployments(id,account_id,strategy_version_id,promotion_hash,idempotency_key,request_hash,document) VALUES($1,$2,$3,$4,$5,$6,$7)',
[
d.id,
d.preview.configuration.matching.risk.ledger.accountId,
d.preview.strategy.versionId,
d.promotionHash,
randomUUID(),
'a'.repeat(64),
d,
]
)
).rejects.toThrow();
}
await expect(
f.pool.query(
'UPDATE paper_deployments SET document=document||\'{"principal":"service"}\' WHERE id=$1',
[original.id]
)
).rejects.toThrow('immutable');
await expect(
f.pool.query('DELETE FROM paper_deployments WHERE id=$1', [original.id])
).rejects.toThrow('immutable');
expect((await f.service.get(original.id)).promotionHash).toBe(original.promotionHash);
await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER');
await f.pool.query(
"UPDATE backtest_results SET canonical_result=jsonb_set(canonical_result,'{analytics,metrics,totalReturn}','999'::jsonb) WHERE run_id=$1",
[f.promotion.testRunId]
);
await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER');
await expect(f.service.authorizeCommand(original.id)).rejects.toThrow();
await expect(verifyPaperEvidenceCustody(f.pool, original)).rejects.toThrow('result identity');
}, 60000);
test('changed installed host and retained artifact cannot initialize or overwrite an account', async () => {
const f = await fixture(),
drifted = new PaperDeploymentsService(f.container, async () => ({
...(await readPaperHostIdentity()),
hostSha256: 'f'.repeat(64),
}));
const wrongNative = new PaperDeploymentsService(f.container, async () => ({
...(await readPaperHostIdentity()),
engineBinarySha256: 'f'.repeat(64),
}));
await expect(wrongNative.preview(f.promotion)).rejects.toThrow('same native');
const preview = await drifted.preview(f.promotion),
saved = await drifted.create(
{ ...f.promotion, previewHash: preview.previewHash },
randomUUID()
);
const host = new PaperDeploymentHost({
database: f.postgres,
repository: new PostgresCanonicalExecutionRepository(f.postgres),
});
closes.push(() => host.shutdown());
await expect(host.bind(saved.id)).rejects.toThrow('differs');
expect(
(await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0].n
).toBe(0);
await f.postgres.transaction(async tx => {
await tx.query('ALTER TABLE strategy_versions DISABLE TRIGGER USER');
await tx.query(
"UPDATE strategy_versions SET envelope=jsonb_set(envelope,'{artifact,content}',to_jsonb((envelope#>>'{artifact,content}')||' changed')) WHERE id=$1",
[f.version.id]
);
await tx.query('ALTER TABLE strategy_versions ENABLE TRIGGER USER');
});
await expect(host.bind(saved.id)).rejects.toThrow('hash mismatch');
await expect(f.service.preview(f.promotion)).rejects.toThrow();
expect(
(await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0].n
).toBe(0);
}, 60000);
test('first migration/reapply preserves accepted research and leases, and archived evidence remains readable', async () => {
const f = await fixture(1, false),
pending = await f.api.createRun({ backtestId: f.draft.id }, actor()),
request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [pending.id]))
.rows[0].request_snapshot;
await f.repository.startCanonical(request);
const snapshot = async () =>
(await f.pool.query('SELECT to_jsonb(r) AS row FROM runs r ORDER BY id')).rows;
const before = await snapshot();
expect(
before.some(
item => item.row.status === 'running' && item.row.attempt_id && item.row.lease_expires_at
)
).toBe(true);
const migration = readFileSync(
new URL('../../database/postgres/init/30-paper-deployments.sql', import.meta.url),
'utf8'
);
await f.pool.query(migration);
expect(await snapshot()).toEqual(before);
const saved = await submit(f);
await f.pool.query(migration);
expect(await snapshot()).toEqual(before);
expect(await readPaperDeployment(f.pool, saved.deployment.id)).toEqual(saved.deployment);
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
f.version.strategyId,
]);
expect(await f.service.get(saved.deployment.id)).toEqual(saved.deployment);
await expect(f.service.authorizeCommand(saved.deployment.id)).rejects.toThrow('active family');
expect(
(await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0].n
).toBe(0);
}, 60000);
});

View file

@ -236,6 +236,84 @@ function http(f: Fixture) {
});
}
describe.skipIf(!url)('authoritative research principals and budgets', () => {
test('owned project links advance only revision metadata after additive migration; project authority stays operator-only', async () => {
const f = await fixture(),
p = await provision(f);
const actor = p.agent.id as `agent:${string}`;
const clone = await f.catalog.cloneVersion(
f.version.id,
{ name: 'Owned link candidate' },
actor,
randomUUID()
);
const before = await f.research.getProject(p.project.id);
await expect(f.research.linkStrategy(p.project.id, clone.strategy.id, actor)).rejects.toThrow(
'Only an operator'
);
expect(await f.research.listProjectStrategies(p.project.id)).toEqual([]);
const migration = readFileSync(
new URL('../../database/postgres/init/31-research-agent-project-links.sql', import.meta.url),
'utf8'
);
await f.pool.query(migration);
await f.research.linkStrategy(p.project.id, clone.strategy.id, actor);
const after = await f.research.getProject(p.project.id);
expect(after.revision).toBe(before.revision + 1);
expect(after.updatedBy).toBe(actor);
expect(after.ownerPrincipal).toBe(before.ownerPrincipal);
expect(after.title).toBe(before.title);
expect((await f.research.listProjectStrategies(p.project.id)).map(s => s.id)).toEqual([
clone.strategy.id,
]);
await f.pool.query(migration);
await f.research.linkStrategy(p.project.id, clone.strategy.id, actor);
expect(await f.research.getProject(p.project.id)).toEqual(after);
const update = (fragment: string, id = p.project.id) =>
f.pool.query(
`UPDATE research_projects SET revision=revision+1,updated_by=$2,updated_at=NOW(),${fragment} WHERE id=$1`,
[id, actor]
);
for (const fragment of [
"title='changed'",
"description='changed'",
"owner_principal='service'",
'archived_at=NOW()',
"created_at=created_at-INTERVAL '1 day'",
]) {
await expect(update(fragment)).rejects.toThrow('Only owned strategy links');
}
await expect(
f.pool.query('UPDATE research_projects SET revision=revision+2,updated_by=$2 WHERE id=$1', [
p.project.id,
actor,
])
).rejects.toThrow('Only owned strategy links');
await expect(
f.research.createProject({ title: 'Unauthorized provisioning' }, actor)
).rejects.toThrow('Only an operator');
const foreign = await f.research.createProject({ title: 'Ungranted' }, 'operator');
await expect(update('description=description', foreign.id)).rejects.toThrow(
'Only owned strategy links'
);
await expect(f.research.linkStrategy(foreign.id, clone.strategy.id, actor)).rejects.toThrow(
'not permitted'
);
await expect(
f.research.linkStrategy(p.project.id, f.version.strategyId, actor)
).rejects.toThrow('not permitted');
expect(await f.research.getProject(p.project.id)).toEqual(after);
expect(
(
await f.pool.query(
"SELECT count(*)::int n FROM research_agent_audit WHERE agent_id=$1 AND operation='research_projects-link-revision'",
[actor]
)
).rows[0].n
).toBe(1);
await f.agents.update(actor, { expectedRevision: 1, enabled: false });
await expect(update('description=description')).rejects.toThrow('disabled');
expect(await f.research.getProject(p.project.id)).toEqual(after);
});
test('operator provisioning stores only a hash; real mounted authentication, AI authorship and scoped writes', async () => {
const f = await fixture(1),
p = await provision(f);

View file

@ -1,7 +1,8 @@
import { asValue } from 'awilix';
import { afterEach, describe, expect, test } from 'bun:test';
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
import { ServiceContainerBuilder } from '@stock-bot/di';
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
@ -38,14 +39,13 @@ async function fixture() {
container.register({ serviceContainer: asValue(services) });
await registerOrchestratorServices(container);
const runtime = services.custom!,
runner = runtime.BacktestRunner!,
engine = runtime.BacktestEngine!;
runner = runtime.BacktestRunner!;
cleanup.push(async () => {
await runner.shutdown();
await paper.runtime.shutdown();
await container.dispose();
});
return { paper, ...admitted, container, services, runtime, runner, engine };
return { paper, ...admitted, container, services, runtime, runner };
}
describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
'canonical research isolation from durable paper custody',
@ -95,25 +95,29 @@ describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
for (let index = 0; index < 2; index++) {
const run = await accept();
let stopped: Promise<void> | undefined;
f.runner.once('progress', () => {
const cancelOnProgress = () => {
f.runner.off('progress', cancelOnProgress);
stopped = f.runner.stopBacktest();
});
};
f.runner.on('progress', cancelOnProgress);
const cancelled = await f.runner.runQueued(run.id).catch(error => error);
await stopped;
expect(stopped).toBeDefined();
expect(cancelled).toBeInstanceOf(BacktestCancelledError);
await unchanged();
const failed = await accept(),
original = f.engine.runCanonical;
f.engine.runCanonical = async () => {
throw new Error('Injected canonical execution failure');
};
const failed = await accept();
// The pool deliberately keeps engines private; inject only at the adapter seam.
const failure = spyOn(RustBacktestAdapter.prototype, 'runCanonical').mockImplementationOnce(
async () => {
throw new Error('Injected canonical execution failure');
}
);
try {
await expect(f.runner.runQueued(failed.id)).rejects.toThrow(
'Injected canonical execution failure'
);
} finally {
f.engine.runCanonical = original;
failure.mockRestore();
}
await unchanged();
}

View file

@ -155,7 +155,7 @@ describe.skipIf(!url)('immutable strategy catalog on real PostgreSQL', () => {
reviewStatus: 'pending',
runnable: false,
});
expect(v.reason).toContain('A02');
expect(v.reason).toContain('isolated execution declaration');
expect(v.package.artifact).not.toHaveProperty('content');
expect(v.package.dependencyLock).not.toHaveProperty('content');
expect(await f.api.getVersionArtifact(v.id)).toEqual(pkg);