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

@ -263,8 +263,11 @@ export async function fixture(browser: Browser, native = false) {
for (const name of [
'09-backtest-run-contract.sql',
'10-durable-backtest-dispatch.sql',
'11-simulation-execution-ledger.sql',
'12-historical-datasets.sql',
'13-strategy-recovery.sql',
'14-backtest-submission.sql',
'15-canonical-paper-intents.sql',
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
@ -278,6 +281,9 @@ export async function fixture(browser: Browser, native = false) {
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
'28-research-agents.sql',
'29-isolated-candidates.sql',
'30-paper-deployments.sql',
'31-research-agent-project-links.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
@ -410,7 +416,7 @@ export async function fixture(browser: Browser, native = false) {
origins: [],
resolveResearchCredential: request => researchAgents.authenticate(request),
});
const routes = createRoutes(container, security);
const routes = createRoutes(container, security, {});
const wsRoute = createWebSocketRoute(container, security);
const sockets = new Set<ServerWebSocket<RunSocketData>>();
const unexpectedNetwork: string[] = [];
@ -446,6 +452,7 @@ export async function fixture(browser: Browser, native = false) {
!pathname.startsWith('/api/v2/research-agents') &&
!pathname.startsWith('/api/v2/research-agent/') &&
!pathname.startsWith('/api/v2/experiments') &&
!pathname.startsWith('/api/v2/paper-deployments') &&
!pathname.startsWith('/api/v2/hypotheses/') &&
!pathname.startsWith('/api/v2/analysis-artifacts/') &&
pathname !== '/api/auth/session') ||
@ -507,6 +514,7 @@ export async function fixture(browser: Browser, native = false) {
}
});
const origin = `http://127.0.0.1:${server.port}`;
security.allowedOrigins.push(origin);
const context = await browser.newContext({ viewport: { width: 1440, height: 1080 } });
cleanup.push(() => context.close());
await context.route('**/*', route => {

View file

@ -3010,3 +3010,262 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_
await f.close();
}
});
test('isolated_candidate_publication_research_validation_and_reviewed_paper_history_browser', async () => {
const f = await fixture(true);
try {
const data = chronologicalDataset();
await retainResearchDataset(f.pool, data.dataset);
const builtin = (await f.seedCatalog()).find(
item => item.package.program.strategyId === 'sma_crossover'
)!;
await f.request(`/api/v2/strategy-versions/${builtin.id}/reviews`, 'POST', {
decision: 'approve',
reason: 'Disposable template baseline',
});
const retained = (await f.request(`/api/v2/strategy-versions/${builtin.id}/artifact`)).package;
const pkg = { ...retained, execution: { kind: 'isolated-candidate/v1', warmupBars: 3 } };
const family = (
await f.request('/api/v2/strategies', 'POST', {
name: 'Browser isolated candidate',
description: 'Retained controlled parity program',
})
).strategy;
await f.login();
await f.page.goto(`${f.origin}/strategies/${family.id}`);
await f.page.getByLabel('Candidate package (JSON)').setInputFiles({
name: 'candidate.json',
mimeType: 'application/json',
buffer: Buffer.from(JSON.stringify(pkg)),
});
await visible(f.page, pkg.artifact.sha256);
const published = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith(`/strategies/${family.id}/versions`)
);
await f.page.getByRole('button', { name: 'Publish immutable candidate', exact: true }).click();
const publication = await published;
expect(publication.status()).toBe(201);
const version = (await publication.json()).version;
expect(version.origin).toBe('candidate');
await f.page.waitForURL(url => url.pathname.endsWith(`/versions/${version.id}`));
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(0);
const draft = await f.request('/api/v2/backtests', 'POST', {
name: 'Browser candidate template',
autoStart: false,
strategy: 'catalog',
strategyVersionId: builtin.id,
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
symbols: ['X0.US'],
startDate: new Date(data.dataset.manifest.bounds.tradeStart).toISOString(),
endDate: new Date(data.dataset.manifest.bounds.tradeEnd).toISOString(),
initialCapital: 10000,
config: {
datasetHash: data.dataset.manifest.hash,
dataFrequency: '1m',
canonical: canonicalSettings,
},
});
await f.page.goto(`${f.origin}/experiments?backtestId=${draft.id}`);
await f.page.getByLabel('Experiment name', { exact: true }).fill('Isolated browser experiment');
await f.page.getByLabel('Use an isolated candidate version', { exact: true }).check();
const section = f.page.getByRole('region', {
name: 'Candidate experiment strategy',
exact: true,
});
await section.getByLabel('Strategy family', { exact: true }).selectOption(family.id);
await section
.getByLabel('Immutable strategy version', { exact: true })
.selectOption(version.id);
await section.getByLabel('fastPeriod', { exact: true }).fill('2');
await section.getByLabel('slowPeriod', { exact: true }).fill('3');
await section.getByRole('button', { name: 'Validate parameters', exact: true }).click();
await visible(f.page, /Parameters validated/);
await f.page.getByRole('button', { name: 'Preview experiment', exact: true }).click();
await visible(f.page, /Isolated TypeScript candidate/);
const submitted = f.page.waitForResponse(
response =>
response.request().method() === 'POST' && response.url().endsWith('/api/v2/experiments')
);
await f.page.getByRole('button', { name: 'Confirm experiment', exact: true }).click();
const experiment = (await (await submitted).json()).experiment as ExperimentDetail;
expect(experiment.preview.input.candidate).toEqual({
versionId: version.id,
parameters: { fastPeriod: 2, slowPeriod: 3 },
});
expect(experiment.preview.request.strategy.reviewId).toBeNull();
await f.dispatcher.start();
const completeExperiment = async (id: string) => {
await until(
async () =>
(await f.request(`/api/v2/experiments/${id}`)).experiment.trials.every(
(trial: { status: string }) =>
['completed', 'failed', 'cancelled', 'missing'].includes(trial.status)
),
'candidate trials finish',
45000
);
const result = (await f.request(`/api/v2/experiments/${id}`)).experiment;
expect(result.trials.every((trial: { status: string }) => trial.status === 'completed')).toBe(
true
);
return result;
};
const completed = await completeExperiment(experiment.id);
const runId = completed.trials[0].runId;
const result = (await f.request(`/api/v2/runs/${runId}/results`)) as CanonicalRunResult;
expect(result.strategyExecution).toBe('typescript-isolated-candidate/v1');
expect(result.request.strategy.origin).toBe('candidate');
await f.page.goto(`${f.origin}/backtests/${draft.id}/run/${runId}`);
await visible(f.page, /isolated TypeScript candidate/);
await f.page.reload();
await visible(f.page, result.request.datasetHash);
// Real immutable validation and cost evidence prepare the human promotion screen.
const candidate = { versionId: version.id, parameters: { fastPeriod: 2, slowPeriod: 3 } };
const validationInput = {
backtestId: draft.id,
name: 'Browser candidate holdouts',
grid: {},
recipe: data.recipe,
candidate,
};
const previewResponse = await f.request(
'/api/v2/experiments/validation/preview',
'POST',
validationInput
);
const preview = previewResponse.preview as ChronologicalValidationPreview;
const validation = (
await f.request(
'/api/v2/experiments/validation',
'POST',
{ ...validationInput, previewHash: preview.previewHash },
{ 'Idempotency-Key': randomUUID() }
)
).validation as ChronologicalValidationDetail;
expect(preview.policy.model).toBe('unverified-candidate');
await completeExperiment(validation.phases[0]!.experimentId!);
const selected = (await f.request(
`/api/v2/experiments/validation/${validation.id}/select`,
'POST',
{ previewHash: preview.previewHash },
{ 'Idempotency-Key': randomUUID() }
)) as ChronologicalValidationActionResult;
for (const phase of selected.validation.phases.slice(1)) {
await completeExperiment(phase.experimentId!);
}
const finished = (await f.request(
`/api/v2/experiments/validation/${validation.id}/finalize`,
'POST',
{
previewHash: preview.previewHash,
selectionHash: selected.validation.selection!.selectionHash,
},
{ 'Idempotency-Key': randomUUID() }
)) as ChronologicalValidationActionResult;
expect(finished.validation.report).not.toBeNull();
const costInput = {
backtestId: draft.id,
name: 'Browser candidate costs',
scenarios: [{ feeRate: '0.02', slippageRate: '0.01' }],
candidate,
};
const costPreview = (
await f.request('/api/v2/experiments/cost-sensitivity/preview', 'POST', costInput)
).preview as CostSensitivityPreview;
const cost = (
await f.request(
'/api/v2/experiments/cost-sensitivity',
'POST',
{ ...costInput, previewHash: costPreview.previewHash },
{ 'Idempotency-Key': randomUUID() }
)
).experiment as CostSensitivityDetail;
await completeExperiment(cost.id);
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
decision: 'approve',
reason: 'Human reviewed controlled candidate bytes and actual held-out/cost evidence',
});
await f.page.goto(`${f.origin}/paper`);
await visible(f.page, /No paper deployments/);
await f.page.getByLabel('Deployment name', { exact: true }).fill('Reviewed browser candidate');
await f.page.getByLabel('Report owner ID', { exact: true }).fill(validation.id);
await f.page.getByLabel('Cost experiment ID', { exact: true }).fill(cost.id);
await f.page.getByRole('button', { name: 'Load evidence', exact: true }).click();
await f.page
.getByLabel('Paper cost scenario', { exact: true })
.selectOption(cost.trials[1]!.runId!);
const start = Date.parse('2030-01-01T14:30:00Z');
await f.page.getByLabel('Paper transport', { exact: true }).fill(
JSON.stringify({
accountId: `paper:${randomUUID()}`,
sessionId: `paper:${randomUUID()}`,
quoteSeriesId: 'X0.US:quote',
riskSession: {
calendarId: 'paper-risk',
calendarRevision: 'v1',
sessionId: 'paper-day',
startsAt: start,
},
policy: {
version: 1,
sourceId: 'disposable-browser-feed',
priceBasis: 'raw',
maxFeedAgeMs: 300000,
observations: [
{
instrumentId: 'X0.US',
seriesId: 'X0.US:1m',
intervalMs: 60000,
staleAfterMs: 300000,
},
],
cadence: [{ ownerId: `strategy:${version.id}`, seriesIds: ['X0.US:1m'] }],
calendars: [
{
instrumentId: 'X0.US',
calendarId: 'explicit-venue',
revision: 'v1',
sessions: [{ sessionId: 'paper-day', opensAt: start, closesAt: start + 3600000 }],
},
],
riskBoundaries: [],
},
})
);
await f.page
.getByLabel('Review rationale', { exact: true })
.fill(
'Controlled fixture evidence and code reviewed; no profitability claim or real activation.'
);
await f.page.getByLabel('Authorize trusted paper code', { exact: true }).check();
await f.page.getByRole('button', { name: 'Preview promotion', exact: true }).click();
await visible(f.page, 'Exact promotion preview');
const promotionResponse = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith('/api/v2/paper-deployments')
);
await f.page.getByRole('button', { name: 'Create halted deployment', exact: true }).click();
const promoted = await promotionResponse;
expect(promoted.status()).toBe(201);
const deployment = await promoted.json();
await f.page.waitForURL(url => url.pathname.endsWith(`/paper/${deployment.id}`));
await visible(f.page, 'Reviewed browser candidate');
await visible(f.page, /Paper orchestrator origin is not configured/);
expect(
(await f.pool.query('SELECT count(*)::int AS count FROM simulation_accounts')).rows[0].count
).toBe(0);
await f.page.reload();
await visible(f.page, 'Reviewed browser candidate');
expect(
(await f.request(`/api/v2/paper-deployments/${deployment.id}`)).preview.strategy.versionId
).toBe(version.id);
expect(f.unexpectedNetwork).toEqual([]);
expect(f.historicalDataReads).toEqual([]);
} finally {
await f.close();
}
}, 180000);