feat(research): retain exact experiment and report citations in findings

This commit is contained in:
Boki 2026-10-24 14:42:14 -04:00
parent 46a4f13acd
commit 06039d17ba
36 changed files with 4170 additions and 253 deletions

View file

@ -298,6 +298,7 @@ export async function fixture(browser: Browser, native = false) {
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')

View file

@ -28,6 +28,7 @@ import type {
WalkForwardDetail,
WalkForwardPreview,
} from '@stock-bot/stock-config/walk-forward';
import type { ResearchArtifact, ResearchFindingSource } from '@stock-bot/types';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { canonicalSettings } from '../fixtures/canonical-research';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
@ -55,6 +56,101 @@ afterAll(async () => {
});
const fixture = (native = false) => createFixture(browser, native);
/** Uses real retained native measurements, then reopens the exact source from immutable history. */
async function saveSourceFindingInBrowser(
f: Awaited<ReturnType<typeof fixture>>,
source: ResearchFindingSource,
choices: { runId: string; metricPath: string }[],
title: string
) {
const sourceUrl = f.page.url();
await f.page.getByRole('heading', { name: 'Regime evidence unavailable', exact: true }).waitFor();
const counts = async () =>
(
await f.pool.query(`SELECT
(SELECT count(*)::int FROM runs) AS runs,
(SELECT count(*)::int FROM backtest_dispatch) AS dispatch`)
).rows[0];
const before = await counts();
const { project } = await f.request('/api/v2/research-projects', 'POST', {
title: `${title} project`,
});
await f.page.getByRole('button', { name: 'Save research finding', exact: true }).click();
const dialog = f.page.getByRole('dialog', { name: 'Save finding', exact: true });
await dialog.getByLabel('Finding project', { exact: true }).selectOption(project.id);
await dialog.getByLabel('Finding title', { exact: true }).fill(title);
await dialog
.getByLabel('Finding body', { exact: true })
.fill(
'Selected retained measurements support further investigation; this narrative is not validated alpha.'
);
expect(await dialog.getByRole('button', { name: 'Save finding', exact: true }).isDisabled()).toBe(
true
);
for (const choice of choices) {
await dialog
.locator(`input[data-run-id="${choice.runId}"][data-metric-path="${choice.metricPath}"]`)
.check();
}
const creating = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith(`/research-projects/${project.id}/analysis-artifacts`)
);
await dialog.getByRole('button', { name: 'Save finding', exact: true }).click();
const response = await creating;
expect(response.status()).toBe(201);
expect(response.request().postDataJSON().source).toEqual(source);
const { artifact } = (await response.json()) as { artifact: ResearchArtifact };
expect(artifact.latestRevision.source).toEqual(source);
expect(artifact.latestRevision.validationState).toBe('unvalidated');
expect(artifact.latestRevision.evidence).toHaveLength(choices.length);
for (const choice of choices) {
const item = artifact.latestRevision.evidence.find(
evidence => evidence.runId === choice.runId && evidence.metricPath === choice.metricPath
)!;
const result = (await f.request(`/api/v2/runs/${choice.runId}/results`)) as CanonicalRunResult;
const key = choice.metricPath.slice(
'analytics.metrics.'.length
) as keyof typeof result.analytics.metrics;
expect(item.value).toBe(result.analytics.metrics[key]);
expect(item.unavailableReason).toBe(
item.value === null ? (result.analytics.unavailable[key] ?? 'not-reported') : null
);
expect(item.financialEngine).toBe('rust');
expect(item.datasetHash).toBe(result.request.datasetHash);
}
await dialog.getByRole('link', { name: 'Open saved finding', exact: true }).click();
const findingUrl = `${f.origin}/research/${project.id}?artifact=${artifact.id}`;
await f.page.waitForURL(findingUrl);
const sourceLink = f.page.getByRole('link', { name: 'Open cited source', exact: true });
await sourceLink.waitFor();
expect(await sourceLink.getAttribute('href')).toBe(new URL(sourceUrl).pathname);
await f.page.getByRole('button', { name: 'Edit latest revision', exact: true }).click();
await f.page.getByLabel('Revision title', { exact: true }).fill(`${title} revised`);
const revising = f.page.waitForResponse(
reply =>
reply.request().method() === 'POST' &&
reply.url().endsWith(`/analysis-artifacts/${artifact.id}/revisions`)
);
await f.page.getByRole('button', { name: 'Save new revision', exact: true }).click();
const revised = await revising;
expect(revised.status()).toBe(201);
expect(revised.request().postDataJSON().source).toEqual(source);
const updated = (await revised.json()) as { artifact: ResearchArtifact };
expect(updated.artifact.latestRevision.ordinal).toBe(2);
expect(updated.artifact.latestRevision.source).toEqual(source);
expect(updated.artifact.latestRevision.evidence).toEqual(artifact.latestRevision.evidence);
await f.page.getByRole('button', { name: 'View revision 1', exact: true }).click();
await visible(f.page, 'Immutable history: this revision is read-only.');
await f.page.reload();
await visible(f.page, 'Immutable history: this revision is read-only.');
await sourceLink.click();
await f.page.waitForURL(sourceUrl);
await f.page.getByRole('button', { name: 'Save research finding', exact: true }).waitFor();
expect(await counts()).toEqual(before);
}
test('saved_experiment_comparison_preserves_cost_reference_native_summaries_and_archived_history_browser', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());
@ -377,6 +473,19 @@ test('cost_sensitivity_freezes_policy_runs_native_scenarios_and_reopens_existing
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(3);
await f.page.reload();
await visible(f.page, /completed: 3/);
await saveSourceFindingInBrowser(
f,
{
kind: 'experiment/v1',
experimentId: experiment.id,
previewHash: preview.previewHash,
},
[
{ runId: experiment.trials[0]!.runId!, metricPath: 'analytics.metrics.totalReturn' },
{ runId: experiment.trials[2]!.runId!, metricPath: 'analytics.metrics.sharpeRatio' },
],
'Retained cost comparison finding'
);
await f.page.getByRole('link', { name: 'All experiments', exact: true }).click();
await f.page.getByRole('link', { name: 'Fixed fee and slippage study', exact: true }).click();
await visible(f.page, /completed: 3/);
@ -602,6 +711,45 @@ test('walk_forward_freezes_all_windows_runs_native_members_and_reopens_reset_rep
await visible(f.page, 'Saved walk-forward validations');
await f.page.locator(`a[href="/experiments/walk-forward/${initial.id}"]`).click();
await visible(f.page, 'Execution complete · walk-forward report saved');
await saveSourceFindingInBrowser(
f,
{
kind: 'walk-forward-report/v1',
walkForwardId: initial.id,
previewHash: report.previewHash,
reportId: report.id,
reportHash: report.reportHash,
},
[
{
runId: report.segments[0]!.validation.runId,
metricPath: 'analytics.metrics.totalReturn',
},
{ runId: report.segments[1]!.test.runId, metricPath: 'analytics.metrics.maxDrawdown' },
{ runId: report.segments[1]!.test.runId, metricPath: 'analytics.metrics.sharpeRatio' },
],
'Retained walk-forward finding'
);
await f.page.getByRole('link', { name: 'Open window 1 validation', exact: true }).click();
const child = childReports[0]!;
await visible(f.page, 'Execution complete · report saved');
await saveSourceFindingInBrowser(
f,
{
kind: 'chronological-report/v1',
validationId: child.validationId,
previewHash: child.previewHash,
reportId: child.id,
reportHash: child.reportHash,
},
[
{ runId: child.training[0]!.runId, metricPath: 'analytics.metrics.totalReturn' },
{ runId: child.test.runId, metricPath: 'analytics.metrics.sharpeRatio' },
],
'Retained chronological finding'
);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(8);
expect((await f.pool.query('SELECT * FROM analysis_artifacts')).rowCount).toBe(2);
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {