fix(research): verify project updates and archive outcomes (RP32)

This commit is contained in:
Boki 2026-10-28 09:52:24 -04:00
parent 233178d4ad
commit f84fa82bba
5 changed files with 670 additions and 46 deletions

View file

@ -2189,6 +2189,219 @@ test('canonical_native_smoke', async () => {
}
});
test('project_and_archive_acknowledgements_preserve_drafts_until_committed_state_is_reloaded_browser', async () => {
const f = await fixture(true);
try {
await f.login();
await createCanonicalInBrowser(f, 'Project archive 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: 'Project archive custody',
})) as { project: ResearchProject };
const { artifact } = (await f.request(
`/api/v2/research-projects/${project.id}/analysis-artifacts`,
'POST',
{
kind: 'finding',
title: 'Retained finding',
body: 'Original 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 analysis_artifacts) AS artifacts,
(SELECT count(*)::int FROM analysis_artifact_revisions) AS revisions`)
).rows[0];
const expectedCounts = { runs: 1, dispatch: 1, artifacts: 1, revisions: 1 };
expect(await counts()).toEqual(expectedCounts);
f.page.on('dialog', event => void event.accept());
await f.page.goto(`${f.origin}/research/${project.id}`);
await f.page.getByRole('button', { name: 'Edit project', exact: true }).click();
const title = ' Revised project custody ',
description = ' Retain the project metadata draft.\n';
await f.page.getByLabel('Project title', { exact: true }).fill(title);
await f.page.getByLabel('Project description', { exact: true }).fill(description);
const projectEndpoint = `**/api/v2/research-projects/${project.id}`;
let metadataPatches = 0;
let committedMetadata: ResearchProject | undefined;
await f.page.route(projectEndpoint, async route => {
if (route.request().method() !== 'PATCH') {
await route.continue();
return;
}
metadataPatches++;
const response = await route.fetch();
expect(response.status()).toBe(200);
const payload = (await response.json()) as { project: ResearchProject };
committedMetadata = structuredClone(payload.project);
payload.project.revision = 1;
await route.fulfill({ response, json: payload });
});
await f.page.getByRole('button', { name: 'Save project', exact: true }).click();
await visible(f.page, 'The saved project update could not be verified.');
expect(await f.page.getByLabel('Project title', { exact: true }).inputValue()).toBe(title);
expect(await f.page.getByLabel('Project description', { exact: true }).inputValue()).toBe(
description
);
expect(
await f.page.getByRole('button', { name: 'Save project', exact: true }).isDisabled()
).toBe(true);
expect(
await f.page.getByRole('button', { name: 'Archive project', exact: true }).isDisabled()
).toBe(true);
await f.page.getByRole('button', { name: 'Refresh project', exact: true }).click();
await visible(f.page, /Project revision 2/);
expect(await f.page.getByLabel('Project title', { exact: true }).inputValue()).toBe(title);
expect(
await f.page.getByRole('button', { name: 'Archive project', exact: true }).isDisabled()
).toBe(true);
expect(metadataPatches).toBe(1);
if (!committedMetadata) {
throw new Error('Expected the ordinary metadata update to commit');
}
expect(committedMetadata.title).toBe(title.trim());
await f.page.unroute(projectEndpoint);
await f.page
.getByRole('button', { name: 'Discard edits and reload project', exact: true })
.click();
await f.page.getByRole('button', { name: 'Edit project', exact: true }).waitFor();
expect((await f.request(`/api/v2/research-projects/${project.id}`)).project).toEqual(
committedMetadata
);
await f.page.goto(`${f.origin}/research/${project.id}?artifact=${artifact.id}`);
await f.page.getByRole('button', { name: 'Edit latest revision', exact: true }).click();
const revisionBody = 'Preserve this unsubmitted interpretation.';
await f.page.getByLabel('Revision body', { exact: true }).fill(revisionBody);
const entryEndpoint = `**/api/v2/analysis-artifacts/${artifact.id}`;
let entryPatches = 0;
let committedArchive: ResearchArtifact | undefined;
await f.page.route(entryEndpoint, async route => {
if (route.request().method() !== 'PATCH') {
await route.continue();
return;
}
entryPatches++;
const response = await route.fetch();
expect(response.status()).toBe(200);
const payload = (await response.json()) as { artifact: ResearchArtifact };
committedArchive = structuredClone(payload.artifact);
payload.artifact.archived = false;
await route.fulfill({ response, json: payload });
});
await f.page.getByRole('button', { name: 'Archive entry', exact: true }).click();
await visible(f.page, 'The archive response could not be verified.');
expect(await f.page.getByLabel('Revision body', { exact: true }).inputValue()).toBe(
revisionBody
);
expect(
await f.page.getByRole('button', { name: 'Save new revision', exact: true }).isDisabled()
).toBe(true);
expect(
await f.page.getByRole('button', { name: 'Archive entry', exact: true }).isDisabled()
).toBe(true);
expect(entryPatches).toBe(1);
if (!committedArchive) {
throw new Error('Expected the ordinary archive write to commit');
}
expect(committedArchive.archived).toBe(true);
expect(committedArchive.latestRevision).toEqual(artifact.latestRevision);
await f.page.unroute(entryEndpoint);
await f.page
.getByRole('button', { name: 'Discard draft and reload archive state', exact: true })
.click();
await f.page.getByRole('button', { name: 'Restore entry', exact: true }).waitFor();
expect((await f.request(`/api/v2/analysis-artifacts/${artifact.id}`)).artifact).toEqual(
committedArchive
);
expect(
(await f.request(`/api/v2/analysis-artifacts/${artifact.id}/revisions`)).revisions
).toEqual([artifact.latestRevision]);
await f.page.getByRole('button', { name: 'Restore entry', exact: true }).click();
await f.page.getByRole('button', { name: 'Archive entry', exact: true }).waitFor();
expect((await f.request(`/api/v2/analysis-artifacts/${artifact.id}`)).artifact.archived).toBe(
false
);
await f.page.getByRole('button', { name: 'New note', exact: true }).click();
const noteBody = 'Preserve the pending child proposal.';
await f.page.getByLabel('Note title', { exact: true }).fill('Pending child draft');
await f.page.getByLabel('Note body', { exact: true }).fill(noteBody);
let projectArchivePatches = 0;
let committedProjectArchive: ResearchProject | undefined;
await f.page.route(projectEndpoint, async route => {
if (route.request().method() !== 'PATCH') {
await route.continue();
return;
}
projectArchivePatches++;
const response = await route.fetch();
expect(response.status()).toBe(200);
const payload = (await response.json()) as { project: ResearchProject };
committedProjectArchive = structuredClone(payload.project);
payload.project.description = 'Substituted acknowledgement only.';
await route.fulfill({ response, json: payload });
});
await f.page.getByRole('button', { name: 'Archive project', exact: true }).click();
await visible(f.page, 'The saved project update could not be verified.');
expect(await f.page.getByLabel('Note body', { exact: true }).inputValue()).toBe(noteBody);
expect(
await f.page.getByRole('button', { name: 'Create note', exact: true }).isDisabled()
).toBe(true);
expect(
await f.page.getByRole('button', { name: 'Archive project', exact: true }).isDisabled()
).toBe(true);
await f.page.getByRole('button', { name: 'Refresh project', exact: true }).click();
await visible(f.page, /Project revision 3/);
expect(await f.page.getByLabel('Note body', { exact: true }).inputValue()).toBe(noteBody);
expect(
await f.page.getByRole('button', { name: 'Create note', exact: true }).isDisabled()
).toBe(true);
expect(projectArchivePatches).toBe(1);
if (!committedProjectArchive) {
throw new Error('Expected the ordinary project archive to commit');
}
expect(committedProjectArchive.archived).toBe(true);
await f.page.unroute(projectEndpoint);
await f.page
.getByRole('button', { name: 'Discard edits and reload project', exact: true })
.click();
await f.page.getByRole('button', { name: 'Restore project', exact: true }).waitFor();
expect(await f.page.getByLabel('Note body', { exact: true }).count()).toBe(0);
expect((await f.request(`/api/v2/research-projects/${project.id}`)).project).toEqual(
committedProjectArchive
);
await f.page.getByRole('button', { name: 'Restore project', exact: true }).click();
await visible(f.page, /Project revision 4/);
await f.page.getByRole('button', { name: 'New note', exact: true }).waitFor();
await f.page.reload();
await visible(f.page, /Project revision 4/);
expect(await counts()).toEqual(expectedCounts);
expect(
(await f.request(`/api/v2/analysis-artifacts/${artifact.id}/revisions`)).revisions
).toEqual([artifact.latestRevision]);
expect(await f.request(`/api/v2/runs/${runId}/results`)).toEqual(native);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('creation_acknowledgements_preserve_proposals_and_reopen_committed_records_browser', async () => {
const f = await fixture(true);
try {

View file

@ -389,6 +389,51 @@ async function submitRevision(original: ResearchHypothesis | ResearchArtifact) {
},
};
}
async function submitProjectEdit() {
await mount();
await flush(() => replyProject());
await flush(() => click('Edit project'));
await flush(() => {
edit('Project title', revisionDraft.title);
edit('Project description', revisionDraft.body);
});
await flush(() => click('Save project'));
return {
patch: request('research-projects/p1', 'PATCH'),
saved: project('p1', {
revision: 2,
title: revisionDraft.title.trim(),
description: revisionDraft.body,
}),
};
}
async function submitEntryArchive(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);
}
});
if (!original.archived) {
await flush(() => click('Edit latest revision'));
await flush(() => {
edit('Revision title', revisionDraft.title);
edit('Revision body', revisionDraft.body);
});
}
await flush(() => click(original.archived ? 'Restore entry' : 'Archive entry'));
return request(`${isHypothesis ? 'hypotheses' : 'analysis-artifacts'}/${original.id}`, 'PATCH');
}
beforeAll(async () => {
for (const [key, value] of Object.entries({
window: browser,
@ -1069,6 +1114,288 @@ describe('research workspace', () => {
expect(field('Revision body').value).toBe('Unsaved conclusion');
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
});
for (const [label, change] of [
['foreign identity', { id: 'p2' }],
['foreign owner', { ownerPrincipal: 'service' }],
['stale revision', { revision: 1 }],
['unexpected revision', { revision: 3 }],
['changed title', { title: 'Substituted' }],
['changed description', { description: 'Substituted' }],
['changed archival', { archived: true }],
] as [string, Partial<ResearchProject>][]) {
test(`project update ${label} acknowledgement preserves the metadata draft`, async () => {
const { patch, saved } = await submitProjectEdit();
await flush(() => reply(patch, { project: { ...saved, ...change } }));
expect(host.textContent).toContain('The saved project update could not be verified.');
expect(field('Project title').value).toBe(revisionDraft.title);
expect(field('Project description').value).toBe(revisionDraft.body);
expect(button('Save project').disabled).toBe(true);
expect(button('Archive project').disabled).toBe(true);
expect(requests.filter(item => !item.settled)).toHaveLength(0);
await flush(() => click('Archive project'));
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
});
}
test('verified normalized project edit reloads the exact next revision', async () => {
const { patch, saved } = await submitProjectEdit();
expect(patch.body).toEqual({
expectedRevision: 1,
title: revisionDraft.title.trim(),
description: revisionDraft.body,
});
await flush(() => reply(patch, { project: saved }));
await flush(() => replyProject(saved));
expect(host.querySelector('[aria-label="Edit research project"]')).toBeNull();
expect(host.textContent).toContain('Project revision 2');
expect(button('Archive project').disabled).toBe(false);
});
test('uncertain project edit survives refresh and discard enters loading before releasing writes', async () => {
const { patch, saved } = await submitProjectEdit();
await flush(() => reply(patch, { error: 'Outcome unknown' }, 500));
expect(button('Archive project').disabled).toBe(true);
await flush(() => click('Refresh project'));
await flush(() => replyProject(saved));
expect(field('Project title').value).toBe(revisionDraft.title);
expect(button('Archive project').disabled).toBe(true);
expect(host.textContent).not.toContain('New hypothesis');
await flush(() => click('Discard edits and reload project'));
expect(button('Archive project').disabled).toBe(true);
expect(host.textContent).toContain('Loading research workspace');
await flush(() => replyProject(saved));
expect(button('Archive project').disabled).toBe(false);
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
});
for (const initialArchive of [false, true]) {
test(`project ${initialArchive ? 'restore' : 'archive'} acknowledgement must match its requested target`, async () => {
const original = project('p1', { archived: initialArchive });
await mount();
await flush(() => replyProject(original));
const action = initialArchive ? 'Restore project' : 'Archive project';
await flush(() => click(action));
const patch = request('research-projects/p1', 'PATCH');
expect(patch.body).toEqual({ expectedRevision: 1, archived: !initialArchive });
await flush(() => reply(patch, { project: { ...original, revision: 2 } }));
expect(host.textContent).toContain('The saved project update could not be verified.');
expect(button(action).disabled).toBe(true);
expect(requests.filter(item => !item.settled)).toHaveLength(0);
});
}
test('uncertain project archive preserves a child draft and freezes child writes until deliberate reload', async () => {
await mount();
await flush(() => replyProject());
await flush(() => click('New note'));
await flush(() => {
edit('Note title', 'Retain child draft');
edit('Note body', revisionDraft.body);
});
await flush(() => click('Archive project'));
await flush(() =>
reply(request('research-projects/p1', 'PATCH'), { error: 'Outcome unknown' }, 500)
);
expect(field('Note body').value).toBe(revisionDraft.body);
expect(button('Create note').disabled).toBe(true);
expect(button('Archive project').disabled).toBe(true);
await flush(() => click('Refresh project'));
await flush(() => replyProject());
expect(button('Create note').disabled).toBe(true);
expect(field('Note body').value).toBe(revisionDraft.body);
await flush(() => click('Discard edits and reload project'));
expect(host.querySelector('[aria-label="Note body"]')).toBeNull();
expect(button('Archive project').disabled).toBe(true);
await flush(() => replyProject(project('p1', { revision: 2, archived: true })));
expect(button('Restore project').disabled).toBe(false);
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
});
for (const kind of ['hypothesis', 'note', 'finding'] as const) {
const original =
kind === 'hypothesis' ? hypothesis() : kind === 'finding' ? citedFinding() : artifact();
for (const [label, rootChange, revisionChange] of [
['identity', { id: 'other' }, {}],
['project', { projectId: 'p2' }, {}],
['owner', { ownerPrincipal: 'service' }, {}],
['archive target', { archived: false }, {}],
[
'revision parent',
{},
kind === 'hypothesis' ? { hypothesisId: 'other' } : { artifactId: 'other' },
],
['validated state', {}, { validationState: 'validated' }],
...(kind === 'hypothesis'
? []
: [
['kind', { kind: kind === 'finding' ? 'note' : 'finding' }, {}],
['hypothesis link', { hypothesisRevisionId: 'other-revision' }, {}],
]),
] as [string, Record<string, unknown>, Record<string, unknown>][]) {
test(`${kind} archive ${label} acknowledgement preserves and blocks the revision draft`, async () => {
const patch = await submitEntryArchive(original);
await flush(() =>
reply(patch, {
[kind === 'hypothesis' ? 'hypothesis' : 'artifact']: {
...original,
archived: true,
...rootChange,
latestRevision: { ...original.latestRevision, ...revisionChange },
},
})
);
expect(host.textContent).toContain('The archive response could not be verified.');
expect(field('Revision title').value).toBe(revisionDraft.title);
expect(field('Revision body').value).toBe(revisionDraft.body);
expect(button('Save new revision').disabled).toBe(true);
expect(button('Archive entry').disabled).toBe(true);
expect(requests.filter(item => !item.settled)).toHaveLength(0);
await flush(() => click('Archive entry'));
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
});
}
}
for (const kind of ['hypothesis', 'artifact'] as const) {
test(`${kind} restore acknowledgement cannot claim an unchanged archive flag`, async () => {
const original =
kind === 'hypothesis'
? hypothesis('h1', { archived: true })
: artifact('a1', { archived: true });
const patch = await submitEntryArchive(original);
await flush(() => reply(patch, { [kind]: original }));
expect(host.textContent).toContain('The archive response could not be verified.');
expect(button('Restore entry').disabled).toBe(true);
expect(requests.filter(item => !item.settled)).toHaveLength(0);
});
for (const archived of [false, true]) {
test(`${kind} ${archived ? 'restore' : 'archive'} accepts a newer concurrent narrative revision`, async () => {
const original =
kind === 'hypothesis' ? hypothesis('h1', { archived }) : artifact('a1', { archived });
const patch = await submitEntryArchive(original);
const saved = {
...original,
archived: !archived,
latestRevision: {
...original.latestRevision,
id: `${original.id}-r2`,
ordinal: 2,
title: 'New concurrent interpretation',
},
};
await flush(() => reply(patch, { [kind]: saved }));
await flush(() => {
replyProject(project());
if (kind === 'hypothesis') {
replyHypothesis(
saved as ResearchHypothesis,
[
original.latestRevision,
saved.latestRevision,
] as ResearchHypothesis['latestRevision'][]
);
} else {
replyArtifact(
saved as ResearchArtifact,
[
original.latestRevision,
saved.latestRevision,
] as ResearchArtifact['latestRevision'][]
);
}
});
expect(host.textContent).toContain('New concurrent interpretation');
expect(button(archived ? 'Archive entry' : 'Restore entry').disabled).toBe(false);
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
});
}
}
test('known entry archive refusal retains an editable draft; uncertain outcome requires loading saved history', async () => {
const patch = await submitEntryArchive(artifact());
await flush(() => reply(patch, { error: 'Not permitted' }, 403));
expect(field('Revision body').value).toBe(revisionDraft.body);
expect(button('Archive entry').disabled).toBe(false);
await flush(() => click('Archive entry'));
await flush(() =>
reply(request('analysis-artifacts/a1', 'PATCH'), { error: 'Outcome unknown' }, 500)
);
expect(button('Save new revision').disabled).toBe(true);
expect(button('Archive entry').disabled).toBe(true);
await flush(() => click('Refresh project'));
await flush(() => replyProject());
expect(field('Revision body').value).toBe(revisionDraft.body);
expect(button('Archive entry').disabled).toBe(true);
await flush(() => click('Discard draft and reload archive state'));
expect(host.textContent).toContain('Loading research entry');
expect(host.querySelector('[aria-label="Revision body"]')).toBeNull();
await flush(() => {
replyProject();
replyArtifact(artifact('a1', { archived: true }));
});
expect(button('Restore entry').disabled).toBe(false);
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(2);
});
test('entry archival can follow a narrative revision conflict without inventing an archive precondition', async () => {
await mount('/research/p1?artifact=a1');
await flush(() => replyProject());
await flush(() => replyArtifact());
await flush(() => click('Edit latest revision'));
await flush(() => edit('Revision body', revisionDraft.body));
await flush(() => click('Save new revision'));
await flush(() =>
reply(request('analysis-artifacts/a1/revisions', 'POST'), { error: 'Revision changed' }, 409)
);
expect(button('Save new revision').disabled).toBe(true);
expect(button('Archive entry').disabled).toBe(false);
await flush(() => click('Archive entry'));
expect(request('analysis-artifacts/a1', 'PATCH').body).toEqual({ archived: true });
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
});
for (const outcome of ['lost', 'malformed', '500'] as const) {
test(`${outcome} project update blocks writes and preserves metadata`, async () => {
const { patch } = await submitProjectEdit();
await flush(() => {
if (outcome === 'lost') {
patch.settled = true;
patch.reject(new Error('Response lost'));
} else {
reply(
patch,
outcome === '500' ? { error: 'Outcome unknown' } : {},
outcome === '500' ? 500 : 200
);
}
});
expect(field('Project description').value).toBe(revisionDraft.body);
expect(button('Save project').disabled).toBe(true);
expect(button('Archive project').disabled).toBe(true);
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
});
test(`${outcome} entry archive blocks writes and preserves the revision draft`, async () => {
const patch = await submitEntryArchive(artifact());
await flush(() => {
if (outcome === 'lost') {
patch.settled = true;
patch.reject(new Error('Response lost'));
} else {
reply(
patch,
outcome === '500' ? { error: 'Outcome unknown' } : {},
outcome === '500' ? 500 : 200
);
}
});
expect(field('Revision body').value).toBe(revisionDraft.body);
expect(button('Save new revision').disabled).toBe(true);
expect(button('Archive entry').disabled).toBe(true);
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
});
}
for (const status of [403, 409]) {
test(`known project ${status} response preserves its existing retry policy`, async () => {
const { patch } = await submitProjectEdit();
await flush(() => reply(patch, { error: 'Refused' }, status));
expect(field('Project title').value).toBe(revisionDraft.title);
expect(button('Save project').disabled).toBe(status === 409);
expect(button('Archive project').disabled).toBe(status === 409);
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
});
}
test('membership refreshes project revision before the next metadata write; archived strategies remain visible', async () => {
await mount();
await flush(() => replyProject());