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 a8c9ede0..df1f39bf 100644 --- a/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx +++ b/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx @@ -1,6 +1,10 @@ import { useEffect, useRef, useState } from 'react'; import { Link } from 'react-router-dom'; -import { reviseResearchArtifactSchema } from '@stock-bot/stock-config/research'; +import { + reviseResearchArtifactSchema, + reviseResearchHypothesisSchema, +} from '@stock-bot/stock-config/research'; +import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; import type { ResearchArtifact, ResearchArtifactRevision, @@ -265,28 +269,58 @@ export function ResearchEntry({ setSaving(true); setError(''); try { + let saved: ResearchHypothesis | ResearchArtifact; + let matches: boolean; if (entry.kind === 'hypothesis') { - await researchApi.reviseHypothesis(id, { + const input = reviseResearchHypothesisSchema.parse({ expectedRevision: entry.entity.latestRevision.ordinal, title, proposition: body, validationCriteria: criteria, contentOrigin: origin, }); + ({ hypothesis: saved } = await researchApi.reviseHypothesis(id, input)); + matches = + saved.latestRevision.hypothesisId === id && + saved.latestRevision.title === input.title && + saved.latestRevision.proposition === input.proposition && + saved.latestRevision.validationCriteria === input.validationCriteria; } else { - await researchApi.reviseArtifact( - id, - reviseResearchArtifactSchema.parse({ - expectedRevision: entry.entity.latestRevision.ordinal, - title, - body, - contentOrigin: origin, - evidence: evidenceReferences(entry.entity.latestRevision.evidence), - ...(entry.entity.latestRevision.source !== undefined - ? { source: entry.entity.latestRevision.source } - : {}), - }) - ); + const input = reviseResearchArtifactSchema.parse({ + expectedRevision: entry.entity.latestRevision.ordinal, + title, + body, + contentOrigin: origin, + evidence: evidenceReferences(entry.entity.latestRevision.evidence), + ...(entry.entity.latestRevision.source !== undefined + ? { source: entry.entity.latestRevision.source } + : {}), + }); + ({ artifact: saved } = await researchApi.reviseArtifact(id, input)); + matches = + saved.kind === entry.entity.kind && + saved.hypothesisRevisionId === entry.entity.hypothesisRevisionId && + saved.latestRevision.artifactId === id && + saved.latestRevision.title === input.title && + saved.latestRevision.body === input.body && + saved.latestRevision.evidenceState === (input.evidence.length ? 'referenced' : 'none') && + Array.isArray(saved.latestRevision.evidence) && + canonicalStrategyJson(evidenceReferences(saved.latestRevision.evidence)) === + canonicalStrategyJson(input.evidence) && + canonicalStrategyJson(saved.latestRevision.source ?? null) === + canonicalStrategyJson(entry.entity.latestRevision.source ?? null); + } + if ( + !matches || + saved.id !== id || + saved.projectId !== projectId || + saved.ownerPrincipal !== entry.entity.ownerPrincipal || + saved.latestRevision.id === entry.entity.latestRevision.id || + saved.latestRevision.ordinal !== entry.entity.latestRevision.ordinal + 1 || + saved.latestRevision.contentOrigin !== origin || + saved.latestRevision.validationState !== 'unvalidated' + ) { + throw new ResearchApiError('The saved revision response could not be verified.', null); } if (mounted.current) { setEditing(false); diff --git a/docs/development/backlog/dependencies.mmd b/docs/development/backlog/dependencies.mmd index 9508764e..2d7a9e07 100644 --- a/docs/development/backlog/dependencies.mmd +++ b/docs/development/backlog/dependencies.mmd @@ -358,4 +358,3 @@ flowchart TD R04 --> RP30 RP24 --> RP30 - RP29 --> RP30 diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 8568d818..6a1e88f0 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -3614,7 +3614,7 @@ "priority": "P1", "severity": "High", "status": "in_progress", - "dependencies": ["R04", "RP24", "RP29"], + "dependencies": ["R04", "RP24"], "decision_dependencies": [], "task_file": "backlog/tasks/RP30.md", "complexity": "M", diff --git a/docs/development/backlog/tasks/RP30.md b/docs/development/backlog/tasks/RP30.md index 59a089ac..c8cbc8ab 100644 --- a/docs/development/backlog/tasks/RP30.md +++ b/docs/development/backlog/tasks/RP30.md @@ -1,6 +1,6 @@ # RP30 — Verify saved research revisions before clearing drafts -Parent E12. Priority P1 / High draft-custody defect. Complexity M. Dependencies R04, RP24, RP29. Owner continuation authorizes implementation and commits. All seven conditional tasks remain deferred. +Parent E12. Priority P1 / High draft-custody defect. Complexity M. Dependencies R04, RP24. Owner continuation authorizes implementation and commits. All seven conditional tasks remain deferred. Verified baseline: `ResearchEntry.save` awaits `researchApi.reviseHypothesis` or `reviseArtifact` but ignores the returned record, immediately clears editing and reloads. The transport checks only a broad envelope/record ID. A stale, foreign or altered successful acknowledgement therefore discards the draft. The existing finding-create dialog already verifies its source/reference acknowledgement; the revision form already preserves uncertain drafts and prevents automatic replay for transport failures/conflicts. diff --git a/docs/guide/backtest-walkthrough.md b/docs/guide/backtest-walkthrough.md index f8e3aabd..70661105 100644 --- a/docs/guide/backtest-walkthrough.md +++ b/docs/guide/backtest-walkthrough.md @@ -154,6 +154,12 @@ the normal preview and confirmation steps. 4. Run **cost sensitivity** on the selected configuration and compare ordinary experiments with compatible inputs. Save findings with explicit run/report references. 5. Reopen those saved IDs to inspect or reproduce the work. The browser is the normal research interface; authorized AI clients use the same backend capabilities with separate grants and budgets. +When editing a saved hypothesis, note or finding, **Save new revision** clears the draft +only after the returned revision matches its entry, submitted text and retained citations. +An unverifiable acknowledgement may follow a committed write: the form preserves and +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. + 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 b31aec2b..9498edb0 100644 --- a/test/e2e/workbench.test.ts +++ b/test/e2e/workbench.test.ts @@ -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 { diff --git a/test/integration/research-workspace-ui.test.tsx b/test/integration/research-workspace-ui.test.tsx index ab18863c..b9c71004 100644 --- a/test/integration/research-workspace-ui.test.tsx +++ b/test/integration/research-workspace-ui.test.tsx @@ -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, Record][]) { + 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][]) { + 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] })