fix(research): verify revision acknowledgements before clearing drafts (RP30)

This commit is contained in:
Boki 2026-10-28 09:10:46 -04:00
parent dd8955ecbf
commit e4056c7d13
7 changed files with 434 additions and 21 deletions

View file

@ -38,6 +38,7 @@ import type {
ResearchArtifact,
ResearchArtifactRevision,
ResearchFindingSource,
ResearchHypothesis,
ResearchHypothesisRevision,
} from '@stock-bot/types';
import {
@ -2187,6 +2188,147 @@ test('canonical_native_smoke', async () => {
}
});
test('revision_acknowledgements_preserve_drafts_and_reopen_exact_committed_history_browser', async () => {
const f = await fixture(true);
try {
await f.login();
await createCanonicalInBrowser(f, 'Revision acknowledgement oracle', true);
const runId = f.page.url().split('/').at(-1)!;
f.dispatcher.start();
await visible(f.page, 'Canonical research result');
const native = (await f.request(`/api/v2/runs/${runId}/results`)) as CanonicalRunResult;
const { project } = await f.request('/api/v2/research-projects', 'POST', {
title: 'Revision acknowledgement recovery',
});
const { hypothesis } = (await f.request(
`/api/v2/research-projects/${project.id}/hypotheses`,
'POST',
{
title: 'Original question',
proposition: 'An unvalidated question.',
validationCriteria: 'Retain untouched holdouts.',
contentOrigin: 'ai',
}
)) as { hypothesis: ResearchHypothesis };
const { artifact } = (await f.request(
`/api/v2/research-projects/${project.id}/analysis-artifacts`,
'POST',
{
kind: 'finding',
hypothesisRevisionId: hypothesis.latestRevision.id,
title: 'Original finding',
body: 'An unvalidated interpretation.',
contentOrigin: 'human',
evidence: [
{
runId,
strategyVersionId: native.request.strategy.versionId,
metricsVersion: 'canonical-analytics/v1',
metricPath: 'analytics.metrics.totalReturn',
},
],
}
)) as { artifact: ResearchArtifact };
const counts = async () =>
(
await f.pool.query(`SELECT
(SELECT count(*)::int FROM runs) AS runs,
(SELECT count(*)::int FROM backtest_dispatch) AS dispatch,
(SELECT count(*)::int FROM research_hypothesis_revisions) AS hypotheses,
(SELECT count(*)::int FROM analysis_artifact_revisions) AS artifacts`)
).rows[0];
expect(await counts()).toEqual({ runs: 1, dispatch: 1, hypotheses: 1, artifacts: 1 });
f.page.on('dialog', event => void event.accept());
for (const [kind, original] of [
['hypothesis', hypothesis],
['artifact', artifact],
] as const) {
const path = kind === 'hypothesis' ? 'hypotheses' : 'analysis-artifacts';
const endpoint = `**/api/v2/${path}/${original.id}/revisions`;
await f.page.goto(`${f.origin}/research/${project.id}?${kind}=${original.id}`);
await f.page.getByRole('button', { name: 'Edit latest revision', exact: true }).click();
const title = ` Revised ${kind} `;
const body = ` Retained ${kind} draft.\n`;
await f.page.getByLabel('Revision title', { exact: true }).fill(title);
await f.page.getByLabel('Revision body', { exact: true }).fill(body);
await f.page.getByLabel('Revision content origin', { exact: true }).selectOption('ai');
if (kind === 'hypothesis') {
await f.page
.getByLabel('Revision validation criteria', { exact: true })
.fill('Additional untouched validation.');
}
let posts = 0;
let committed: ResearchHypothesis | ResearchArtifact | undefined;
await f.page.route(endpoint, async route => {
if (route.request().method() !== 'POST') {
await route.continue();
return;
}
posts++;
const response = await route.fetch();
expect(response.status()).toBe(201);
const payload = (await response.json()) as {
hypothesis: ResearchHypothesis;
artifact: ResearchArtifact;
};
committed = structuredClone(payload[kind]);
// The write commits unchanged. Only the browser acknowledgement is corrupted.
if (kind === 'hypothesis') {
payload.hypothesis.latestRevision.ordinal = original.latestRevision.ordinal;
} else {
payload.artifact.latestRevision.evidence = [];
}
await route.fulfill({ response, json: payload });
});
await f.page.getByRole('button', { name: 'Save new revision', exact: true }).click();
await visible(f.page, 'The saved revision response could not be verified.');
await visible(f.page, /The draft is preserved/);
expect(await f.page.getByLabel('Revision title', { exact: true }).inputValue()).toBe(title);
expect(await f.page.getByLabel('Revision body', { exact: true }).inputValue()).toBe(body);
expect(await f.page.getByLabel('Revision content origin', { exact: true }).inputValue()).toBe(
'ai'
);
expect(
await f.page.getByRole('button', { name: 'Save new revision', exact: true }).isDisabled()
).toBe(true);
expect(posts).toBe(1);
if (!committed) {
throw new Error('Expected the ordinary revision write to commit');
}
expect(committed.latestRevision.ordinal).toBe(2);
expect(committed.latestRevision.title).toBe(title.trim());
await f.page.unroute(endpoint);
await f.page
.getByRole('button', { name: 'Discard draft and reload history', exact: true })
.click();
await f.page.getByRole('button', { name: 'View revision 2', exact: true }).waitFor();
await visible(f.page, title.trim());
expect(
await f.page.getByRole('form', { name: 'Revise research entry', exact: true }).count()
).toBe(0);
const history = await f.request(`/api/v2/${path}/${original.id}/revisions`);
expect(history.revisions).toEqual([original.latestRevision, committed.latestRevision]);
if ('hypothesisRevisionId' in committed) {
expect(committed.latestRevision.evidence).toEqual(artifact.latestRevision.evidence);
expect(committed.hypothesisRevisionId).toBe(hypothesis.latestRevision.id);
}
await f.page.reload();
await f.page.getByRole('button', { name: 'View revision 2', exact: true }).waitFor();
expect(posts).toBe(1);
expect(await counts()).toEqual({
runs: 1,
dispatch: 1,
hypotheses: 2,
artifacts: kind === 'artifact' ? 2 : 1,
});
}
expect(await f.request(`/api/v2/runs/${runId}/results`)).toEqual(native);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('single_run_finding_acknowledgement_blocks_duplicates_and_reopens_committed_evidence_browser', async () => {
const f = await fixture(true);
try {

View file

@ -231,6 +231,92 @@ function replyArtifact(value = artifact(), revisions = [value.latestRevision]) {
reply(request(`analysis-artifacts/${value.id}`), { artifact: value });
reply(request(`analysis-artifacts/${value.id}/revisions`), { revisions });
}
function citedFinding(): ResearchArtifact {
const note = artifact();
return {
...note,
kind: 'finding',
hypothesisRevisionId: 'h1-r1',
latestRevision: {
...note.latestRevision,
evidenceState: 'referenced',
source: {
kind: 'experiment/v1',
experimentId: '44444444-4444-4444-8444-444444444444',
previewHash: 'a'.repeat(64),
},
evidence: [
{
runId: '11111111-1111-4111-8111-111111111111',
backtestId: '22222222-2222-4222-8222-222222222222',
strategyVersionId: '33333333-3333-4333-8333-333333333333',
metricsVersion: 'canonical-analytics/v1',
metricPath: 'analytics.metrics.totalReturn',
value: 0.12,
unit: 'fraction',
availability: 'available',
unavailableReason: null,
resultKind: 'canonical',
financialEngine: 'rust',
datasetHash: 'f'.repeat(64),
limitations: [],
},
],
},
};
}
const revisionDraft = {
title: ' Revised research title ',
body: ' Retain the revised interpretation.\n',
criteria: ' Keep untouched holdouts.\n',
};
async function submitRevision(original: ResearchHypothesis | ResearchArtifact) {
const isHypothesis = 'proposition' in original.latestRevision;
await mount(`/research/p1?${isHypothesis ? 'hypothesis' : 'artifact'}=${original.id}`);
await flush(() =>
replyProject(
project(),
isHypothesis ? [original as ResearchHypothesis] : [],
isHypothesis ? [] : [original as ResearchArtifact]
)
);
await flush(() => {
if (isHypothesis) {
replyHypothesis(original as ResearchHypothesis);
} else {
replyArtifact(original as ResearchArtifact);
}
});
await flush(() => click('Edit latest revision'));
await flush(() => {
edit('Revision title', revisionDraft.title);
edit('Revision body', revisionDraft.body);
edit('Revision content origin', 'unknown');
if (isHypothesis) {
edit('Revision validation criteria', revisionDraft.criteria);
}
});
await flush(() => click('Save new revision'));
return {
post: request(
`${isHypothesis ? 'hypotheses' : 'analysis-artifacts'}/${original.id}/revisions`,
'POST'
),
saved: {
...original,
latestRevision: {
...original.latestRevision,
id: `${original.id}-r2`,
ordinal: 2,
title: revisionDraft.title.trim(),
...(isHypothesis
? { proposition: revisionDraft.body.trim(), validationCriteria: revisionDraft.criteria }
: { body: revisionDraft.body }),
contentOrigin: 'unknown' as const,
},
},
};
}
beforeAll(async () => {
for (const [key, value] of Object.entries({
window: browser,
@ -622,6 +708,143 @@ describe('research workspace', () => {
expect(button('Create note').disabled).toBe(true);
expect(host.textContent).toContain('unvalidated narrative');
});
for (const kind of ['hypothesis', 'note', 'finding'] as const) {
const original =
kind === 'hypothesis' ? hypothesis() : kind === 'finding' ? citedFinding() : artifact();
for (const [label, rootChange, revisionChange] of [
['foreign entry', { id: 'other' }, {}],
['foreign project', { projectId: 'p2' }, {}],
['changed owner', { ownerPrincipal: 'service' }, {}],
['old revision ID', {}, { id: original.latestRevision.id }],
['old ordinal', {}, { ordinal: 1 }],
['unexpected ordinal', {}, { ordinal: 3 }],
['changed title', {}, { title: 'Substituted' }],
[
'changed body',
{},
kind === 'hypothesis' ? { proposition: 'Substituted' } : { body: 'Substituted' },
],
['changed content origin', {}, { contentOrigin: 'human' }],
['validated claim', {}, { validationState: 'validated' }],
[
'foreign revision parent',
{},
kind === 'hypothesis' ? { hypothesisId: 'other' } : { artifactId: 'other' },
],
...(kind === 'hypothesis'
? [['changed criteria', {}, { validationCriteria: 'Substituted' }]]
: [
['changed kind', { kind: kind === 'finding' ? 'note' : 'finding' }, {}],
['changed hypothesis link', { hypothesisRevisionId: 'another-revision' }, {}],
]),
] as [string, Record<string, unknown>, Record<string, unknown>][]) {
test(`${kind} revision ${label} acknowledgement preserves and blocks the exact draft`, async () => {
const { post, saved } = await submitRevision(original);
await flush(() =>
reply(post, {
[kind === 'hypothesis' ? 'hypothesis' : 'artifact']: {
...saved,
...rootChange,
latestRevision: { ...saved.latestRevision, ...revisionChange },
},
})
);
expect(host.textContent).toContain('The saved revision response could not be verified.');
expect(field('Revision title').value).toBe(revisionDraft.title);
expect(field('Revision body').value).toBe(revisionDraft.body);
expect(field('Revision content origin').value).toBe('unknown');
if (kind === 'hypothesis') {
expect(field('Revision validation criteria').value).toBe(revisionDraft.criteria);
}
expect(button('Save new revision').disabled).toBe(true);
await flush(() => click('Save new revision'));
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
expect(requests.filter(item => !item.settled)).toHaveLength(0);
});
}
}
for (const [label, change] of [
['missing evidence', { evidence: undefined }],
['empty evidence', { evidence: [] }],
[
'extra evidence',
{
evidence: [
...citedFinding().latestRevision.evidence,
...citedFinding().latestRevision.evidence,
],
},
],
...[
{ runId: '55555555-5555-4555-8555-555555555555' },
{ metricPath: 'analytics.metrics.maxDrawdown' },
{ metricsVersion: 'legacy-display/v1' },
{ strategyVersionId: null },
].map(reference => [
'substituted reference',
{ evidence: [{ ...citedFinding().latestRevision.evidence[0], ...reference }] },
]),
['changed evidence state', { evidenceState: 'none' }],
['missing source', { source: null }],
[
'changed source',
{ source: { ...citedFinding().latestRevision.source, previewHash: 'b'.repeat(64) } },
],
] as [string, Record<string, unknown>][]) {
test(`finding revision ${label} acknowledgement cannot clear the draft`, async () => {
const { post, saved } = await submitRevision(citedFinding());
await flush(() =>
reply(post, {
artifact: { ...saved, latestRevision: { ...saved.latestRevision, ...change } },
})
);
expect(host.textContent).toContain('The saved revision response could not be verified.');
expect(field('Revision body').value).toBe(revisionDraft.body);
expect(button('Save new revision').disabled).toBe(true);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
expect(requests.filter(item => !item.settled)).toHaveLength(0);
});
}
for (const kind of ['hypothesis', 'note', 'finding'] as const) {
test(`verified normalized ${kind} revision clears its draft and reloads saved history`, async () => {
const original =
kind === 'hypothesis' ? hypothesis() : kind === 'finding' ? citedFinding() : artifact();
const { post, saved } = await submitRevision(original);
expect(post.body).toMatchObject({ title: revisionDraft.title.trim() });
await flush(() =>
reply(post, { [kind === 'hypothesis' ? 'hypothesis' : 'artifact']: saved })
);
expect(host.querySelector('[aria-label="Revise research entry"]')).toBeNull();
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
expect(requests.some(item => !item.settled && item.method === 'GET')).toBe(true);
});
}
for (const nullVersion of [false, true]) {
test(`legacy revision accepts ${nullVersion ? 'null' : 'omitted'} strategy version and null-normalized source`, async () => {
const original = citedFinding();
original.latestRevision.source = undefined;
const { strategyVersionId: _version, ...reference } = original.latestRevision.evidence[0]!;
original.latestRevision.evidence = [
{
...reference,
metricsVersion: 'legacy-display/v1',
metricPath: 'metrics.totalReturn',
resultKind: 'legacy',
financialEngine: 'native',
datasetHash: null,
},
];
const { post, saved } = await submitRevision(original);
const revision = saved.latestRevision as typeof original.latestRevision;
revision.source = null;
if (nullVersion) {
revision.evidence[0]!.strategyVersionId = null;
}
await flush(() => reply(post, { artifact: saved }));
expect(host.querySelector('[aria-label="Revise research entry"]')).toBeNull();
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
});
}
test('409 retains revision draft and never silently rebases onto refreshed history', async () => {
await mount('/research/p1?artifact=a1');
await flush(() => replyProject(project(), [], [artifact()]));
@ -798,12 +1021,21 @@ describe('research workspace', () => {
},
],
});
const revisedFinding = {
...finding,
latestRevision: {
...finding.latestRevision,
id: 'a1-r2',
ordinal: 2,
body: 'Updated interpretation, same evidence',
},
};
await flush(() =>
reply(request('analysis-artifacts/a1/revisions', 'POST'), { artifact: finding })
reply(request('analysis-artifacts/a1/revisions', 'POST'), { artifact: revisedFinding })
);
await flush(() => {
replyProject(project(), [linked], [finding]);
replyArtifact(finding);
replyProject(project(), [linked], [revisedFinding]);
replyArtifact(revisedFinding, [finding.latestRevision, revisedFinding.latestRevision]);
});
await flush(() =>
reply(request('hypotheses/h1/revisions'), { revisions: [original, linked.latestRevision] })