diff --git a/apps/stock/web-app/src/features/research/ResearchListPage.tsx b/apps/stock/web-app/src/features/research/ResearchListPage.tsx index 3a7f26ce..6d667451 100644 --- a/apps/stock/web-app/src/features/research/ResearchListPage.tsx +++ b/apps/stock/web-app/src/features/research/ResearchListPage.tsx @@ -1,5 +1,6 @@ import { useEffect, useRef, useState } from 'react'; import { Link, useNavigate } from 'react-router-dom'; +import { createResearchProjectSchema } from '@stock-bot/stock-config/research'; import type { ResearchProject } from '@stock-bot/types'; import { Card } from '@/components/ui/Card'; import { actionClass, fieldClass } from '../strategies/components/StrategyParameterForm'; @@ -65,7 +66,16 @@ export function ResearchListPage() { setCreating(true); setSaveError(''); try { - const { project } = await researchApi.createProject({ title, description }); + const input = createResearchProjectSchema.parse({ title, description }); + const { project } = await researchApi.createProject(input); + if ( + project.title !== input.title || + project.description !== input.description || + project.revision !== 1 || + project.archived !== false + ) { + throw new ResearchApiError('The saved project response could not be verified.', null); + } if (mounted.current) { navigate(`/research/${project.id}`); } diff --git a/apps/stock/web-app/src/features/research/components/CreateResearchEntry.tsx b/apps/stock/web-app/src/features/research/components/CreateResearchEntry.tsx index e5de8728..a955a87c 100644 --- a/apps/stock/web-app/src/features/research/components/CreateResearchEntry.tsx +++ b/apps/stock/web-app/src/features/research/components/CreateResearchEntry.tsx @@ -1,5 +1,9 @@ import { useEffect, useRef, useState } from 'react'; -import type { ResearchContentOrigin } from '@stock-bot/types'; +import { + createResearchArtifactSchema, + createResearchHypothesisSchema, +} from '@stock-bot/stock-config/research'; +import type { ResearchArtifact, ResearchContentOrigin, ResearchHypothesis } from '@stock-bot/types'; import { Card } from '@/components/ui/Card'; import { actionClass, fieldClass } from '../../strategies/components/StrategyParameterForm'; import { confirmDiscard, useUnsavedWarning } from '../../strategies/components/useUnsavedWarning'; @@ -59,26 +63,55 @@ export function CreateResearchEntry({ setSaving(true); setError(''); try { - const id = - kind === 'hypothesis' - ? ( - await researchApi.createHypothesis(projectId, { - title, - proposition: body, - validationCriteria: criteria, - contentOrigin: origin, - }) - ).hypothesis.id - : ( - await researchApi.createArtifact(projectId, { - kind: 'note', - title, - body, - contentOrigin: origin, - }) - ).artifact.id; + let saved: ResearchHypothesis | ResearchArtifact; + let matches: boolean; + if (kind === 'hypothesis') { + const input = createResearchHypothesisSchema.parse({ + title, + proposition: body, + validationCriteria: criteria, + contentOrigin: origin, + }); + ({ hypothesis: saved } = await researchApi.createHypothesis(projectId, input)); + matches = + saved.latestRevision.hypothesisId === saved.id && + saved.latestRevision.title === input.title && + saved.latestRevision.proposition === input.proposition && + saved.latestRevision.validationCriteria === input.validationCriteria; + } else { + const input = createResearchArtifactSchema.parse({ + kind: 'note', + title, + body, + contentOrigin: origin, + }); + ({ artifact: saved } = await researchApi.createArtifact(projectId, input)); + matches = + saved.kind === 'note' && + saved.hypothesisRevisionId === null && + saved.latestRevision.artifactId === saved.id && + saved.latestRevision.title === input.title && + saved.latestRevision.body === input.body && + (saved.latestRevision.source ?? null) === null && + saved.latestRevision.evidenceState === 'none' && + Array.isArray(saved.latestRevision.evidence) && + saved.latestRevision.evidence.length === 0; + } + if ( + !matches || + saved.projectId !== projectId || + saved.archived !== false || + saved.latestRevision.ordinal !== 1 || + saved.latestRevision.contentOrigin !== origin || + saved.latestRevision.validationState !== 'unvalidated' + ) { + throw new ResearchApiError( + 'The saved research entry response could not be verified.', + null + ); + } if (mounted.current) { - onCreated(id); + onCreated(saved.id); } } catch (cause) { if (mounted.current) { diff --git a/apps/stock/web-app/src/features/research/components/SaveFindingDialog.tsx b/apps/stock/web-app/src/features/research/components/SaveFindingDialog.tsx index 9be645c2..c97f524b 100644 --- a/apps/stock/web-app/src/features/research/components/SaveFindingDialog.tsx +++ b/apps/stock/web-app/src/features/research/components/SaveFindingDialog.tsx @@ -262,6 +262,14 @@ function FindingDraft({ artifact.projectId !== projectId || artifact.hypothesisRevisionId !== input.hypothesisRevisionId || artifact.kind !== 'finding' || + artifact.archived !== false || + artifact.latestRevision.artifactId !== artifact.id || + artifact.latestRevision.ordinal !== 1 || + artifact.latestRevision.title !== input.title || + artifact.latestRevision.body !== input.body || + artifact.latestRevision.contentOrigin !== input.contentOrigin || + artifact.latestRevision.validationState !== 'unvalidated' || + artifact.latestRevision.evidenceState !== 'referenced' || canonicalStrategyJson(artifact.latestRevision.source ?? null) !== canonicalStrategyJson(source.context) || !Array.isArray(artifact.latestRevision.evidence) || diff --git a/docs/guide/backtest-walkthrough.md b/docs/guide/backtest-walkthrough.md index 70661105..ab81ae98 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. +Project, hypothesis, note and finding creation also verifies the returned content before +opening a saved record or showing success. If that acknowledgement cannot be verified, +the original draft stays blocked. Use **Check saved projects** or **Check saved records** +to review what committed; checking does not resubmit. Start a new request only after that +review, or deliberately discard the draft and open the existing record. + 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 diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts index 9498edb0..03b69811 100644 --- a/test/e2e/workbench.test.ts +++ b/test/e2e/workbench.test.ts @@ -40,6 +40,7 @@ import type { ResearchFindingSource, ResearchHypothesis, ResearchHypothesisRevision, + ResearchProject, } from '@stock-bot/types'; import { createDatasetV2, @@ -2188,6 +2189,228 @@ test('canonical_native_smoke', async () => { } }); +test('creation_acknowledgements_preserve_proposals_and_reopen_committed_records_browser', async () => { + const f = await fixture(true); + try { + await f.login(); + await createCanonicalInBrowser(f, 'Creation 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; + f.page.on('dialog', event => void event.accept()); + await f.page.goto(`${f.origin}/research`); + await f.page.getByRole('button', { name: 'New project', exact: true }).click(); + const projectTitle = ' Research creation custody '; + const projectDescription = ' Preserve this project draft.\n'; + await f.page.getByLabel('Project title', { exact: true }).fill(projectTitle); + await f.page.getByLabel('Project description', { exact: true }).fill(projectDescription); + let projectPosts = 0; + let committedProject: ResearchProject | undefined; + const projectEndpoint = '**/api/v2/research-projects'; + await f.page.route(projectEndpoint, async route => { + if (route.request().method() !== 'POST') { + await route.continue(); + return; + } + projectPosts++; + const response = await route.fetch(); + expect(response.status()).toBe(201); + const payload = (await response.json()) as { project: ResearchProject }; + committedProject = structuredClone(payload.project); + payload.project.description = 'Substituted acknowledgement only.'; + await route.fulfill({ response, json: payload }); + }); + await f.page.getByRole('button', { name: 'Create project', exact: true }).click(); + await visible(f.page, 'The saved project response could not be verified.'); + expect(await f.page.getByLabel('Project title', { exact: true }).inputValue()).toBe( + projectTitle + ); + expect(await f.page.getByLabel('Project description', { exact: true }).inputValue()).toBe( + projectDescription + ); + expect( + await f.page.getByRole('button', { name: 'Create project', exact: true }).isDisabled() + ).toBe(true); + expect(f.page.url()).toBe(`${f.origin}/research`); + await f.page.getByRole('button', { name: 'Check saved projects', exact: true }).click(); + await f.page.getByRole('link', { name: projectTitle.trim(), exact: true }).waitFor(); + expect(await f.page.getByLabel('Project title', { exact: true }).inputValue()).toBe( + projectTitle + ); + expect(projectPosts).toBe(1); + if (!committedProject) { + throw new Error('Expected the ordinary project write to commit'); + } + const project = committedProject; + expect((await f.request(`/api/v2/research-projects/${project.id}`)).project).toEqual(project); + await f.page.unroute(projectEndpoint); + await f.page.getByRole('button', { name: 'Discard project draft', exact: true }).click(); + await f.page.getByRole('link', { name: projectTitle.trim(), exact: true }).click(); + await f.page.waitForURL(`${f.origin}/research/${project.id}`); + let savedHypothesis: ResearchHypothesis | undefined; + for (const kind of ['hypothesis', 'note'] as const) { + await f.page.getByRole('button', { name: `New ${kind}`, exact: true }).click(); + const title = ` Original ${kind} proposal `; + const body = ` Preserve this ${kind} proposal.\n`; + await f.page + .getByLabel(kind === 'hypothesis' ? 'Hypothesis title' : 'Note title', { exact: true }) + .fill(title); + await f.page + .getByLabel(kind === 'hypothesis' ? 'Proposition' : 'Note body', { exact: true }) + .fill(body); + await f.page.getByLabel('Declared content origin', { exact: true }).selectOption('ai'); + if (kind === 'hypothesis') { + await f.page + .getByLabel('Validation criteria', { exact: true }) + .fill('Untouched validation required.'); + } + const path = kind === 'hypothesis' ? 'hypotheses' : 'analysis-artifacts'; + const endpoint = `**/api/v2/research-projects/${project.id}/${path}`; + 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; + }; + if (kind === 'hypothesis') { + committed = structuredClone(payload.hypothesis); + savedHypothesis = structuredClone(payload.hypothesis); + payload.hypothesis.latestRevision.proposition = 'Substituted acknowledgement only.'; + } else { + committed = structuredClone(payload.artifact); + payload.artifact.latestRevision.body = 'Substituted acknowledgement only.'; + } + await route.fulfill({ response, json: payload }); + }); + await f.page.getByRole('button', { name: `Create ${kind}`, exact: true }).click(); + await visible(f.page, 'The saved research entry response could not be verified.'); + expect( + await f.page + .getByLabel(kind === 'hypothesis' ? 'Hypothesis title' : 'Note title', { exact: true }) + .inputValue() + ).toBe(title); + expect( + await f.page + .getByLabel(kind === 'hypothesis' ? 'Proposition' : 'Note body', { exact: true }) + .inputValue() + ).toBe(body); + expect(await f.page.getByLabel('Declared content origin', { exact: true }).inputValue()).toBe( + 'ai' + ); + expect( + await f.page.getByRole('button', { name: `Create ${kind}`, exact: true }).isDisabled() + ).toBe(true); + await f.page.getByRole('button', { name: 'Check saved records', exact: true }).click(); + await f.page.getByRole('button', { name: title.trim(), exact: true }).waitFor(); + expect( + await f.page.getByRole('button', { name: `Create ${kind}`, exact: true }).isDisabled() + ).toBe(true); + expect(posts).toBe(1); + if (!committed) { + throw new Error('Expected the ordinary narrative write to commit'); + } + const reopened = await f.request(`/api/v2/${path}/${committed.id}`); + expect(reopened[kind === 'hypothesis' ? 'hypothesis' : 'artifact']).toEqual(committed); + await f.page.unroute(endpoint); + await f.page.getByRole('button', { name: 'Discard entry draft', exact: true }).click(); + await f.page.getByRole('button', { name: title.trim(), exact: true }).click(); + await f.page.getByRole('button', { name: 'Edit latest revision', exact: true }).waitFor(); + const history = await f.request(`/api/v2/${path}/${committed.id}/revisions`); + expect(history.revisions).toEqual([committed.latestRevision]); + } + if (!savedHypothesis) { + throw new Error('Expected the original hypothesis revision'); + } + await f.page.goto(`${f.origin}/backtests/${native.backtestId}/run/${runId}`); + await f.page.getByRole('button', { name: 'Save finding', exact: true }).click(); + const dialog = f.page.getByRole('dialog', { name: 'Save finding', exact: true }); + await dialog.getByLabel('Finding project', { exact: true }).selectOption(project.id); + await dialog + .getByLabel('Finding hypothesis', { exact: true }) + .selectOption(savedHypothesis.latestRevision.id); + await dialog.getByLabel('Finding title', { exact: true }).fill('Original finding narrative'); + await dialog.getByLabel('Finding body', { exact: true }).fill('Preserve the finding proposal.'); + const findingEndpoint = `**/api/v2/research-projects/${project.id}/analysis-artifacts`; + let findingPosts = 0; + let committedFinding: ResearchArtifact | undefined; + await f.page.route(findingEndpoint, async route => { + if (route.request().method() !== 'POST') { + await route.continue(); + return; + } + findingPosts++; + const response = await route.fetch(); + expect(response.status()).toBe(201); + const payload = (await response.json()) as { artifact: ResearchArtifact }; + committedFinding = structuredClone(payload.artifact); + payload.artifact.latestRevision.body = 'Substituted narrative; original citations retained.'; + await route.fulfill({ response, json: payload }); + }); + await dialog.getByRole('button', { name: 'Save finding', exact: true }).click(); + await visible(f.page, 'The saved finding response could not be verified.'); + expect(await dialog.getByLabel('Finding body', { exact: true }).inputValue()).toBe( + 'Preserve the finding proposal.' + ); + expect( + await dialog.getByRole('button', { name: 'Save finding', exact: true }).isDisabled() + ).toBe(true); + expect( + await dialog.getByRole('link', { name: 'Open saved finding', exact: true }).count() + ).toBe(0); + expect(findingPosts).toBe(1); + if (!committedFinding) { + throw new Error('Expected the original finding write to commit'); + } + expect(committedFinding.latestRevision.evidence).toHaveLength(1); + expect(committedFinding.hypothesisRevisionId).toBe(savedHypothesis.latestRevision.id); + expect(committedFinding.latestRevision.evidence[0]!.value).toBe( + native.analytics.metrics.totalReturn + ); + await f.page.unroute(findingEndpoint); + await dialog.getByRole('button', { name: 'Close', exact: true }).click(); + await f.page.goto(`${f.origin}/research/${project.id}?artifact=${committedFinding.id}`); + await f.page.getByRole('button', { name: 'Edit latest revision', exact: true }).waitFor(); + expect((await f.request(`/api/v2/analysis-artifacts/${committedFinding.id}`)).artifact).toEqual( + committedFinding + ); + await f.page.reload(); + await f.page.getByRole('button', { name: 'Edit latest revision', exact: true }).waitFor(); + expect( + ( + 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_projects) AS projects, + (SELECT count(*)::int FROM research_hypotheses) AS hypotheses, + (SELECT count(*)::int FROM research_hypothesis_revisions) AS hypothesis_revisions, + (SELECT count(*)::int FROM analysis_artifacts) AS artifacts, + (SELECT count(*)::int FROM analysis_artifact_revisions) AS artifact_revisions`) + ).rows[0] + ).toEqual({ + runs: 1, + dispatch: 1, + projects: 1, + hypotheses: 1, + hypothesis_revisions: 1, + artifacts: 2, + artifact_revisions: 2, + }); + expect(await f.request(`/api/v2/runs/${runId}/results`)).toEqual(native); + expect(f.unexpectedNetwork).toEqual([]); + } finally { + await f.close(); + } +}); + test('revision_acknowledgements_preserve_drafts_and_reopen_exact_committed_history_browser', async () => { const f = await fixture(true); try { diff --git a/test/integration/research-finding-ui.test.tsx b/test/integration/research-finding-ui.test.tsx index cf9aded9..1dd9ef69 100644 --- a/test/integration/research-finding-ui.test.tsx +++ b/test/integration/research-finding-ui.test.tsx @@ -164,7 +164,15 @@ const artifact = (hypothesisRevisionId: string | null = null): ResearchArtifact }); function acceptedFinding(hypothesisRevisionId: string | null = null): ResearchArtifact { const saved = artifact(hypothesisRevisionId); - const input = post().body as { evidence: ResearchEvidenceReference[] }; + const input = post().body as { + title: string; + body: string; + contentOrigin: 'human' | 'ai' | 'unknown'; + evidence: ResearchEvidenceReference[]; + }; + saved.latestRevision.title = input.title; + saved.latestRevision.body = input.body; + saved.latestRevision.contentOrigin = input.contentOrigin; saved.latestRevision.source = null; saved.latestRevision.evidence = input.evidence.map(reference => ({ ...reference, @@ -411,6 +419,43 @@ describe('saved-result finding', () => { expect(host.textContent).toContain('narrative remains unvalidated'); expect(closed).toBe(0); }); + test.each([ + ['title', { title: 'Substituted narrative' }], + ['body', { body: 'Substituted narrative' }], + ['origin', { contentOrigin: 'unknown' }], + ['parent', { artifactId: 'different-entry' }], + ['noninitial ordinal', { ordinal: 2 }], + ['validated state', { validationState: 'validated' }], + ['evidence state', { evidenceState: 'none' }], + ] as const)('%s narrative acknowledgement freezes the finding draft', async (_label, change) => { + await mountDialog(); + await draft(); + await preflight(); + const saved = acceptedFinding(); + await flush(() => + reply( + post(), + { artifact: { ...saved, latestRevision: { ...saved.latestRevision, ...change } } }, + 201 + ) + ); + expect(host.textContent).toContain('saved finding response could not be verified'); + expect(host.textContent).not.toContain('Finding saved.'); + expect(field('Finding title').value).toBe('Exact finding'); + expect(field('Finding body').value).toBe('Keep this narrative'); + expect(button('Save finding').disabled).toBe(true); + expect(host.querySelector('a[href*="artifact=saved-finding"]')).toBeNull(); + await flush(() => button('Save finding').click()); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + }); + test('archived creation acknowledgement cannot claim a saved finding', async () => { + await mountDialog(); + await draft(); + await preflight(); + await flush(() => reply(post(), { artifact: { ...acceptedFinding(), archived: true } }, 201)); + expect(host.textContent).toContain('saved finding response could not be verified'); + expect(button('Save finding').disabled).toBe(true); + }); test.each([ 'empty', 'missing', diff --git a/test/integration/research-source-ui.test.tsx b/test/integration/research-source-ui.test.tsx index 731f850b..e6ff55d3 100644 --- a/test/integration/research-source-ui.test.tsx +++ b/test/integration/research-source-ui.test.tsx @@ -759,6 +759,9 @@ function sourceFor(value = standalone()) { } function savedArtifact(body: ArtifactInput): ResearchArtifact { const value = artifact(); + value.latestRevision.title = body.title; + value.latestRevision.body = body.body; + value.latestRevision.contentOrigin = body.contentOrigin ?? 'human'; value.latestRevision.source = body.source ?? null; value.latestRevision.evidence = (body.evidence ?? []).map(reference => ({ ...reference, diff --git a/test/integration/research-workspace-ui.test.tsx b/test/integration/research-workspace-ui.test.tsx index b9c71004..67b259a9 100644 --- a/test/integration/research-workspace-ui.test.tsx +++ b/test/integration/research-workspace-ui.test.tsx @@ -13,6 +13,7 @@ import { act, createElement } from 'react'; import type { Root } from 'react-dom/client'; import type { ResearchArtifact, + ResearchContentOrigin, ResearchHypothesis, ResearchProject, StrategyRecord, @@ -270,6 +271,77 @@ const revisionDraft = { body: ' Retain the revised interpretation.\n', criteria: ' Keep untouched holdouts.\n', }; +const creationDraft = { + title: ' New research title ', + body: ' Preserve this new proposal.\n', + criteria: ' Keep untouched validation.\n', +}; +async function submitCreation( + kind: 'project' | 'hypothesis' | 'note', + origin: ResearchContentOrigin = 'ai', + body = creationDraft.body +) { + await mount(kind === 'project' ? '/research' : '/research/p1'); + await flush(() => { + if (kind === 'project') { + reply(request('research-projects?includeArchived=false'), { projects: [] }); + } else { + replyProject(); + } + }); + await flush(() => click(`New ${kind}`)); + await flush(() => { + edit( + kind === 'project' + ? 'Project title' + : kind === 'hypothesis' + ? 'Hypothesis title' + : 'Note title', + creationDraft.title + ); + edit( + kind === 'project' + ? 'Project description' + : kind === 'hypothesis' + ? 'Proposition' + : 'Note body', + body + ); + if (kind !== 'project') { + edit('Declared content origin', origin); + } + if (kind === 'hypothesis') { + edit('Validation criteria', creationDraft.criteria); + } + }); + await flush(() => click(`Create ${kind}`)); + const path = + kind === 'project' + ? 'research-projects' + : `research-projects/p1/${kind === 'hypothesis' ? 'hypotheses' : 'analysis-artifacts'}`; + const saved = + kind === 'project' + ? project('p1', { title: creationDraft.title.trim(), description: body }) + : kind === 'hypothesis' + ? hypothesis('h1', { + latestRevision: { + ...hypothesis().latestRevision, + title: creationDraft.title.trim(), + proposition: body.trim(), + validationCriteria: creationDraft.criteria, + contentOrigin: origin, + }, + }) + : artifact('a1', { + latestRevision: { + ...artifact().latestRevision, + title: creationDraft.title.trim(), + body, + contentOrigin: origin, + }, + }); + return { post: request(path, 'POST'), saved }; +} async function submitRevision(original: ResearchHypothesis | ResearchArtifact) { const isHypothesis = 'proposition' in original.latestRevision; await mount(`/research/p1?${isHypothesis ? 'hypothesis' : 'artifact'}=${original.id}`); @@ -599,6 +671,134 @@ describe('research workspace', () => { await flush(() => click('Start new request')); expect(button('Create project').disabled).toBe(false); }); + for (const [label, change] of [ + ['title', { title: 'Different project' }], + ['description', { description: 'Different description' }], + ['noninitial revision', { revision: 2 }], + ['archival', { archived: true }], + ] as [string, Partial][]) { + test(`project creation ${label} acknowledgement retains the draft without navigation`, async () => { + const { post, saved } = await submitCreation('project'); + await flush(() => reply(post, { project: { ...saved, ...change } }, 201)); + expect(host.textContent).toContain('The saved project response could not be verified.'); + expect(field('Project title').value).toBe(creationDraft.title); + expect(field('Project description').value).toBe(creationDraft.body); + expect(button('Create project').disabled).toBe(true); + expect(location).toBe('/research'); + await flush(() => click('Create project')); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + expect(requests.filter(item => !item.settled)).toHaveLength(0); + }); + } + for (const kind of ['hypothesis', 'note'] as const) { + for (const [label, rootChange, revisionChange] of [ + ['project', { projectId: 'p2' }, {}], + ['archival', { archived: true }, {}], + ['parent', {}, kind === 'hypothesis' ? { hypothesisId: 'other' } : { artifactId: 'other' }], + ['noninitial ordinal', {}, { ordinal: 2 }], + ['title', {}, { title: 'Different title' }], + [ + 'body', + {}, + kind === 'hypothesis' ? { proposition: 'Different proposal' } : { body: 'Different note' }, + ], + ['origin', {}, { contentOrigin: 'human' }], + ['validated state', {}, { validationState: 'validated' }], + ...(kind === 'hypothesis' + ? [['criteria', {}, { validationCriteria: 'Different criteria' }]] + : [ + ['kind', { kind: 'finding' }, {}], + ['hypothesis link', { hypothesisRevisionId: 'unselected' }, {}], + [ + 'source', + {}, + { + source: { + kind: 'experiment/v1', + experimentId: '11111111-1111-4111-8111-111111111111', + previewHash: 'a'.repeat(64), + }, + }, + ], + ['evidence', {}, { evidence: [{}] }], + ['evidence state', {}, { evidenceState: 'referenced' }], + ]), + ] as [string, Record, Record][]) { + test(`${kind} creation ${label} acknowledgement retains and blocks the proposal`, async () => { + const { post, saved } = await submitCreation(kind); + if (!('latestRevision' in saved)) { + throw new Error('Expected a narrative fixture'); + } + await flush(() => + reply( + post, + { + [kind === 'hypothesis' ? 'hypothesis' : 'artifact']: { + ...saved, + ...rootChange, + latestRevision: { ...saved.latestRevision, ...revisionChange }, + }, + }, + 201 + ) + ); + expect(host.textContent).toContain( + 'The saved research entry response could not be verified.' + ); + expect(field(kind === 'hypothesis' ? 'Hypothesis title' : 'Note title').value).toBe( + creationDraft.title + ); + expect(field(kind === 'hypothesis' ? 'Proposition' : 'Note body').value).toBe( + creationDraft.body + ); + expect(field('Declared content origin').value).toBe('ai'); + if (kind === 'hypothesis') { + expect(field('Validation criteria').value).toBe(creationDraft.criteria); + } + expect(button(`Create ${kind}`).disabled).toBe(true); + expect(location).toBe('/research/p1'); + await flush(() => click(`Create ${kind}`)); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + expect(requests.filter(item => !item.settled)).toHaveLength(0); + await flush(() => click('Check saved records')); + await flush(() => replyProject()); + expect(field(kind === 'hypothesis' ? 'Proposition' : 'Note body').value).toBe( + creationDraft.body + ); + expect(button(`Create ${kind}`).disabled).toBe(true); + }); + } + } + for (const kind of ['project', 'hypothesis', 'note'] as const) { + const origins: ResearchContentOrigin[] = + kind === 'project' ? ['human'] : ['human', 'ai', 'unknown']; + for (const origin of origins) { + test(`normalized ${kind} creation with ${origin} origin opens the accepted record`, async () => { + const { post, saved } = await submitCreation( + kind, + origin, + kind === 'note' ? '' : creationDraft.body + ); + expect(post.body).toMatchObject({ title: creationDraft.title.trim() }); + await flush(() => + reply( + post, + { + [kind === 'project' ? 'project' : kind === 'hypothesis' ? 'hypothesis' : 'artifact']: + saved, + }, + 201 + ) + ); + expect(location).toBe( + kind === 'project' + ? '/research/p1' + : `/research/p1?${kind === 'hypothesis' ? 'hypothesis=h1' : 'artifact=a1'}` + ); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + }); + } + } test('late create success cannot navigate away from a newer project', async () => { await mount('/research'); await flush(() => reply(request('research-projects?includeArchived=false'), { projects: [] })); @@ -695,9 +895,11 @@ describe('research workspace', () => { await flush(() => click('Create note')); expect(request('research-projects/p1/analysis-artifacts', 'POST').body).toEqual({ kind: 'note', + hypothesisRevisionId: null, title: 'Observation', body: 'Needs validation', contentOrigin: 'human', + evidence: [], }); await flush(() => reply(request('research-projects/p1/analysis-artifacts', 'POST'), { error: 'Uncertain' }, 500)