From f84fa82bba64dc0551ad1756c1b2179fc0f2845d Mon Sep 17 00:00:00 2001 From: Boki Date: Wed, 28 Oct 2026 09:52:24 -0400 Subject: [PATCH] fix(research): verify project updates and archive outcomes (RP32) --- .../features/research/ResearchProjectPage.tsx | 83 +++-- .../research/components/ResearchEntry.tsx | 86 ++++- docs/guide/backtest-walkthrough.md | 7 + test/e2e/workbench.test.ts | 213 ++++++++++++ .../research-workspace-ui.test.tsx | 327 ++++++++++++++++++ 5 files changed, 670 insertions(+), 46 deletions(-) diff --git a/apps/stock/web-app/src/features/research/ResearchProjectPage.tsx b/apps/stock/web-app/src/features/research/ResearchProjectPage.tsx index 04931006..bd2618b7 100644 --- a/apps/stock/web-app/src/features/research/ResearchProjectPage.tsx +++ b/apps/stock/web-app/src/features/research/ResearchProjectPage.tsx @@ -1,5 +1,6 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import { Link, useParams, useSearchParams } from 'react-router-dom'; +import { updateResearchProjectSchema } from '@stock-bot/stock-config/research'; import type { ResearchArtifact, ResearchHypothesis, @@ -157,7 +158,8 @@ function ProjectWorkspace({ projectId }: { projectId: string }) { loading || pending.current || errors.project || - (archived === undefined && (!editing || conflict)) + conflict || + (archived === undefined && !editing) ) { return; } @@ -177,7 +179,18 @@ function ProjectWorkspace({ projectId }: { projectId: string }) { if (!body) { return; } - const { project: updated } = await researchApi.updateProject(projectId, body); + const input = updateResearchProjectSchema.parse(body); + const { project: updated } = await researchApi.updateProject(projectId, input); + if ( + updated.id !== projectId || + updated.ownerPrincipal !== project.ownerPrincipal || + updated.revision !== input.expectedRevision + 1 || + updated.title !== (input.title ?? project.title) || + updated.description !== (input.description ?? project.description) || + updated.archived !== (input.archived ?? project.archived) + ) { + throw new ResearchApiError('The saved project update could not be verified.', null); + } if (mounted.current) { setProject(updated); setEditing(null); @@ -213,7 +226,8 @@ function ProjectWorkspace({ projectId }: { projectId: string }) { pending.current || editing || errors.project || - errors.strategies + errors.strategies || + conflict ) { return; } @@ -244,6 +258,20 @@ function ProjectWorkspace({ projectId }: { projectId: string }) { } } }; + const discardAndReloadProject = () => { + if (saving || !confirmDiscard(dirty)) { + return; + } + setLoading(true); + setEditing(null); + setCreator(null); + setCreateDirty(false); + setEntryDirty(false); + setSelectionEpoch(value => value + 1); + setConflict(false); + setMutationError(''); + reload(); + }; const hypothesisId = params.get('hypothesis'); const artifactId = params.get('artifact'); const selection = @@ -258,7 +286,17 @@ function ProjectWorkspace({ projectId }: { projectId: string }) { const visibleArtifacts = artifacts.filter( item => showArchived || project?.archived || !item.archived ); - const canWrite = project && !project.archived && !errors.project && !loading && !saving; + const canWrite = + project && !project.archived && !errors.project && !loading && !saving && !conflict; + const projectWriteBlocked = conflict + ? 'Review the saved project before another update.' + : saving + ? 'Updating project.' + : loading + ? 'Refreshing project.' + : errors.project + ? 'Project status could not be verified.' + : ''; const sectionError = (section: Section) => errors[section] && (
@@ -333,7 +371,7 @@ function ProjectWorkspace({ projectId }: { projectId: string }) { )}{' '}
@@ -583,15 +612,7 @@ function ProjectWorkspace({ projectId }: { projectId: string }) { key={creator} projectId={projectId} kind={creator} - writeBlocked={ - project.archived - ? 'Archived project.' - : loading - ? 'Refreshing project.' - : errors.project - ? 'Project status could not be verified.' - : '' - } + writeBlocked={project.archived ? 'Archived project.' : projectWriteBlocked} onDirty={setCreateDirty} onClose={() => setCreator(null)} onRefresh={reload} @@ -612,13 +633,7 @@ function ProjectWorkspace({ projectId }: { projectId: string }) { kind={selection.kind} revisionId={params.get('revision')} archived={project.archived} - writeBlocked={ - loading - ? 'Refreshing project.' - : errors.project - ? 'Project status could not be verified.' - : '' - } + writeBlocked={projectWriteBlocked} hypotheses={hypotheses} onDirty={setEntryDirty} onRefresh={reload} diff --git a/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx b/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx index df1f39bf..692e3644 100644 --- a/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx +++ b/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx @@ -134,6 +134,7 @@ export function ResearchEntry({ const [saving, setSaving] = useState(false); const [error, setError] = useState(''); const [blocked, setBlocked] = useState(false); + const [archiveUncertain, setArchiveUncertain] = useState(false); const [downloadError, setDownloadError] = useState(''); useUnsavedWarning(editing); useEffect(() => { @@ -241,7 +242,7 @@ export function ResearchEntry({ const readonly = archived || Boolean(writeBlocked) || entry?.entity.archived || Boolean(revisionId); const beginEdit = () => { - if (!revision || readonly) { + if (!revision || readonly || archiveUncertain) { return; } setTitle(revision.title); @@ -260,6 +261,7 @@ export function ResearchEntry({ pending.current || readonly || blocked || + archiveUncertain || !title.trim() || (kind === 'hypothesis' && !body.trim()) ) { @@ -345,6 +347,7 @@ export function ResearchEntry({ archived || Boolean(writeBlocked) || pending.current || + archiveUncertain || !confirmDiscard(editing) || !window.confirm(`${entry.entity.archived ? 'Restore' : 'Archive'} this research entry?`) ) { @@ -354,10 +357,29 @@ export function ResearchEntry({ setSaving(true); setError(''); try { - if (kind === 'hypothesis') { - await researchApi.archiveHypothesis(id, !entry.entity.archived); + const targetArchived = !entry.entity.archived; + let saved: ResearchHypothesis | ResearchArtifact; + let matches: boolean; + if (entry.kind === 'hypothesis') { + ({ hypothesis: saved } = await researchApi.archiveHypothesis(id, targetArchived)); + matches = saved.latestRevision.hypothesisId === id; } else { - await researchApi.archiveArtifact(id, !entry.entity.archived); + ({ artifact: saved } = await researchApi.archiveArtifact(id, targetArchived)); + matches = + saved.latestRevision.artifactId === id && + saved.kind === entry.entity.kind && + saved.hypothesisRevisionId === entry.entity.hypothesisRevisionId; + } + // Archive has no narrative revision precondition. A concurrent edit may be newer. + if ( + !matches || + saved.id !== id || + saved.projectId !== projectId || + saved.ownerPrincipal !== entry.entity.ownerPrincipal || + saved.archived !== targetArchived || + saved.latestRevision.validationState !== 'unvalidated' + ) { + throw new ResearchApiError('The archive response could not be verified.', null); } if (mounted.current) { setEditing(false); @@ -367,6 +389,7 @@ export function ResearchEntry({ } catch (cause) { if (mounted.current) { setError(cause instanceof Error ? cause.message : 'Could not update archive state'); + setArchiveUncertain(!(cause instanceof ResearchApiError) || cause.ambiguous); } } finally { pending.current = false; @@ -449,12 +472,20 @@ export function ResearchEntry({ )}
{!readonly && !editing && ( - )} {!archived && !writeBlocked && ( - )} @@ -464,7 +495,33 @@ export function ResearchEntry({ {error}

)} - {editing && !readonly && ( + {archiveUncertain && ( +
+

+ The archive request may have saved. Your draft is preserved. Reload saved history + before another write; this request will not be retried. +

+ +
+ )} + {editing && !archived && !entry.entity.archived && !revisionId && (
setTitle(event.target.value)} - disabled={saving || blocked} + disabled={saving || blocked || archiveUncertain || Boolean(writeBlocked)} required /> @@ -488,7 +545,7 @@ export function ResearchEntry({ className={fieldClass} value={body} onChange={event => setBody(event.target.value)} - disabled={saving || blocked} + disabled={saving || blocked || archiveUncertain || Boolean(writeBlocked)} required={kind === 'hypothesis'} /> @@ -500,7 +557,7 @@ export function ResearchEntry({ className={fieldClass} value={criteria} onChange={event => setCriteria(event.target.value)} - disabled={saving || blocked} + disabled={saving || blocked || archiveUncertain || Boolean(writeBlocked)} /> )} @@ -511,7 +568,7 @@ export function ResearchEntry({ className={fieldClass} value={origin} onChange={event => setOrigin(event.target.value as ResearchContentOrigin)} - disabled={saving || blocked} + disabled={saving || blocked || archiveUncertain || Boolean(writeBlocked)} > @@ -545,7 +602,12 @@ export function ResearchEntry({ className={actionClass} type="submit" disabled={ - saving || blocked || !title.trim() || (kind === 'hypothesis' && !body.trim()) + saving || + blocked || + archiveUncertain || + Boolean(writeBlocked) || + !title.trim() || + (kind === 'hypothesis' && !body.trim()) } > {saving ? 'Saving revision...' : 'Save new revision'} diff --git a/docs/guide/backtest-walkthrough.md b/docs/guide/backtest-walkthrough.md index ab81ae98..15446fe8 100644 --- a/docs/guide/backtest-walkthrough.md +++ b/docs/guide/backtest-walkthrough.md @@ -166,6 +166,13 @@ An unverifiable acknowledgement may follow a committed write: the form preserves blocks the draft without retrying. Review it, then deliberately choose **Discard draft and reload history** to inspect the saved revisions before deciding whether another edit is needed. +Project edits and archive/restore actions also verify their acknowledgement. An uncertain +project update blocks further project and child writes; an uncertain entry archive blocks +entry writes. Refreshing lists preserves that block and any draft. Use **Discard edits and +reload project** or **Discard draft and reload archive state** to deliberately discard drafts +and read the committed state before continuing. Entry archival may return a newer narrative +revision from a concurrent editor; it does not append a narrative revision itself. + Open a hypothesis, note or finding and choose **Download saved revision** to take its narrative and citations into local analysis. When viewing history, the file contains that exact older revision. While editing, it exports the saved version and leaves your draft diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts index 03b69811..63de6aa0 100644 --- a/test/e2e/workbench.test.ts +++ b/test/e2e/workbench.test.ts @@ -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 { diff --git a/test/integration/research-workspace-ui.test.tsx b/test/integration/research-workspace-ui.test.tsx index 67b259a9..0dc95616 100644 --- a/test/integration/research-workspace-ui.test.tsx +++ b/test/integration/research-workspace-ui.test.tsx @@ -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][]) { + 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, Record][]) { + 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());