fix(research): verify creation acknowledgements before leaving drafts (RP31)

This commit is contained in:
Boki 2026-10-28 09:27:39 -04:00
parent b09b2de406
commit 57ba86d035
8 changed files with 552 additions and 22 deletions

View file

@ -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 {

View file

@ -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',

View file

@ -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,

View file

@ -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<ResearchProject>][]) {
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<string, unknown>, Record<string, unknown>][]) {
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)