1734 lines
70 KiB
TypeScript
1734 lines
70 KiB
TypeScript
import {
|
|
afterAll,
|
|
afterEach,
|
|
beforeAll,
|
|
beforeEach,
|
|
describe,
|
|
expect,
|
|
spyOn,
|
|
test,
|
|
} from 'bun:test';
|
|
import { GlobalWindow } from 'happy-dom';
|
|
import { act, createElement } from 'react';
|
|
import type { Root } from 'react-dom/client';
|
|
import type {
|
|
ResearchArtifact,
|
|
ResearchContentOrigin,
|
|
ResearchHypothesis,
|
|
ResearchProject,
|
|
StrategyRecord,
|
|
} from '@stock-bot/types';
|
|
|
|
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
|
const keys = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
|
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
|
let createRoot: typeof import('react-dom/client').createRoot;
|
|
let router: typeof import('react-router-dom');
|
|
let ResearchListPage: typeof import('../../apps/stock/web-app/src/features/research/ResearchListPage').ResearchListPage;
|
|
let ResearchProjectPage: typeof import('../../apps/stock/web-app/src/features/research/ResearchProjectPage').ResearchProjectPage;
|
|
let root: Root | undefined;
|
|
let host: HTMLDivElement;
|
|
let navigate: ReturnType<typeof router.useNavigate>;
|
|
let location = '';
|
|
function deferred<T>() {
|
|
let resolve!: (value: T) => void;
|
|
let reject!: (error: Error) => void;
|
|
const promise = new Promise<T>((yes, no) => {
|
|
resolve = yes;
|
|
reject = no;
|
|
});
|
|
return { promise, resolve, reject };
|
|
}
|
|
type Pending = ReturnType<typeof deferred<Response>> & {
|
|
path: string;
|
|
method: string;
|
|
body: unknown;
|
|
settled: boolean;
|
|
};
|
|
const requests: Pending[] = [];
|
|
function request(path: string, method = 'GET') {
|
|
const found = requests.find(
|
|
item => item.path === `/api/v2/${path}` && item.method === method && !item.settled
|
|
);
|
|
if (!found) {
|
|
throw new Error(
|
|
`Missing ${method} ${path}: ${requests
|
|
.filter(item => !item.settled)
|
|
.map(item => item.path)
|
|
.join(', ')}`
|
|
);
|
|
}
|
|
return found;
|
|
}
|
|
function reply(item: Pending, body: unknown, status = 200) {
|
|
item.settled = true;
|
|
item.resolve(status === 204 ? new Response(null, { status }) : Response.json(body, { status }));
|
|
}
|
|
async function flush(action: () => void = () => {}) {
|
|
await act(async () => {
|
|
action();
|
|
await Promise.resolve();
|
|
});
|
|
}
|
|
function button(label: string) {
|
|
const found = [...host.querySelectorAll('button')].find(
|
|
item => item.textContent?.trim() === label || item.getAttribute('aria-label') === label
|
|
);
|
|
if (!found) {
|
|
throw new Error(`Missing button ${label}: ${host.textContent}`);
|
|
}
|
|
return found;
|
|
}
|
|
function click(label: string) {
|
|
button(label).click();
|
|
}
|
|
function field(label: string) {
|
|
const found = host.querySelector(`[aria-label="${label}"]`) as
|
|
| HTMLInputElement
|
|
| HTMLTextAreaElement
|
|
| HTMLSelectElement
|
|
| null;
|
|
if (!found) {
|
|
throw new Error(`Missing field ${label}`);
|
|
}
|
|
return found;
|
|
}
|
|
function edit(label: string, value: string) {
|
|
const input = field(label);
|
|
const prototype =
|
|
input.tagName === 'SELECT'
|
|
? browser.HTMLSelectElement.prototype
|
|
: input.tagName === 'TEXTAREA'
|
|
? browser.HTMLTextAreaElement.prototype
|
|
: browser.HTMLInputElement.prototype;
|
|
Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value);
|
|
input.dispatchEvent(
|
|
new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', {
|
|
bubbles: true,
|
|
}) as unknown as Event
|
|
);
|
|
}
|
|
function Probe() {
|
|
navigate = router.useNavigate();
|
|
const current = router.useLocation();
|
|
location = current.pathname + current.search;
|
|
return null;
|
|
}
|
|
async function mount(path = '/research/p1') {
|
|
root = createRoot(host);
|
|
await flush(() =>
|
|
root!.render(
|
|
createElement(
|
|
router.MemoryRouter,
|
|
{ initialEntries: [path] },
|
|
createElement(
|
|
router.Routes,
|
|
null,
|
|
createElement(router.Route, {
|
|
path: '/research',
|
|
element: createElement(ResearchListPage),
|
|
}),
|
|
createElement(router.Route, {
|
|
path: '/research/:projectId',
|
|
element: createElement(ResearchProjectPage),
|
|
})
|
|
),
|
|
createElement(Probe)
|
|
)
|
|
)
|
|
);
|
|
}
|
|
const time = '2026-10-23T12:00:00Z';
|
|
const project = (id = 'p1', extra: Partial<ResearchProject> = {}): ResearchProject => ({
|
|
id,
|
|
title: `Project ${id}`,
|
|
description: 'Description',
|
|
revision: 1,
|
|
ownerPrincipal: 'operator',
|
|
updatedBy: 'operator',
|
|
archived: false,
|
|
createdAt: time,
|
|
updatedAt: time,
|
|
...extra,
|
|
});
|
|
const hypothesis = (id = 'h1', extra: Partial<ResearchHypothesis> = {}): ResearchHypothesis => ({
|
|
id,
|
|
projectId: 'p1',
|
|
ownerPrincipal: 'operator',
|
|
updatedBy: 'operator',
|
|
archived: false,
|
|
createdAt: time,
|
|
updatedAt: time,
|
|
latestRevision: {
|
|
id: `${id}-r1`,
|
|
hypothesisId: id,
|
|
ordinal: 1,
|
|
title: 'Momentum hypothesis',
|
|
proposition: '<img src=x onerror=alert(1)>',
|
|
validationCriteria: 'Out of sample',
|
|
validationState: 'unvalidated',
|
|
submittedBy: 'operator',
|
|
contentOrigin: 'ai',
|
|
createdAt: time,
|
|
},
|
|
...extra,
|
|
});
|
|
const artifact = (id = 'a1', extra: Partial<ResearchArtifact> = {}): ResearchArtifact => ({
|
|
id,
|
|
projectId: 'p1',
|
|
hypothesisRevisionId: null,
|
|
kind: 'note',
|
|
ownerPrincipal: 'operator',
|
|
updatedBy: 'operator',
|
|
archived: false,
|
|
createdAt: time,
|
|
updatedAt: time,
|
|
latestRevision: {
|
|
id: `${id}-r1`,
|
|
artifactId: id,
|
|
ordinal: 1,
|
|
title: 'Research note',
|
|
body: '<script>doNotRun()</script>',
|
|
validationState: 'unvalidated',
|
|
evidenceState: 'none',
|
|
evidence: [],
|
|
submittedBy: 'operator',
|
|
contentOrigin: 'human',
|
|
createdAt: time,
|
|
},
|
|
...extra,
|
|
});
|
|
const strategy: StrategyRecord = {
|
|
id: 's1',
|
|
name: 'Trend',
|
|
description: '',
|
|
ownerPrincipal: 'operator',
|
|
updatedBy: 'operator',
|
|
archived: false,
|
|
createdAt: time,
|
|
updatedAt: time,
|
|
};
|
|
function replyProject(
|
|
value = project(),
|
|
hypotheses: ResearchHypothesis[] = [],
|
|
artifacts: ResearchArtifact[] = [],
|
|
strategies: StrategyRecord[] = []
|
|
) {
|
|
reply(request(`research-projects/${value.id}`), { project: value });
|
|
reply(request(`research-projects/${value.id}/strategies`), { strategies });
|
|
reply(request(`research-projects/${value.id}/hypotheses?includeArchived=true`), { hypotheses });
|
|
reply(request(`research-projects/${value.id}/analysis-artifacts?includeArchived=true`), {
|
|
artifacts,
|
|
});
|
|
reply(request('strategies'), {
|
|
strategies: [strategy, { ...strategy, id: 'archived', name: 'Retired', archived: true }],
|
|
});
|
|
}
|
|
function replyHypothesis(value = hypothesis(), revisions = [value.latestRevision]) {
|
|
reply(request(`hypotheses/${value.id}`), { hypothesis: value });
|
|
reply(request(`hypotheses/${value.id}/revisions`), { revisions });
|
|
}
|
|
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',
|
|
};
|
|
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}`);
|
|
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,
|
|
},
|
|
},
|
|
};
|
|
}
|
|
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,
|
|
document: browser.document,
|
|
IS_REACT_ACT_ENVIRONMENT: true,
|
|
})) {
|
|
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
|
}
|
|
({ createRoot } = await import('react-dom/client'));
|
|
router = await import('react-router-dom');
|
|
({ ResearchListPage } = await import(
|
|
'../../apps/stock/web-app/src/features/research/ResearchListPage'
|
|
));
|
|
({ ResearchProjectPage } = await import(
|
|
'../../apps/stock/web-app/src/features/research/ResearchProjectPage'
|
|
));
|
|
});
|
|
beforeEach(() => {
|
|
requests.length = 0;
|
|
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
|
browser.document.body.append(host as never);
|
|
Object.defineProperty(browser, 'confirm', {
|
|
configurable: true,
|
|
writable: true,
|
|
value: () => true,
|
|
});
|
|
browser.fetch = ((url: RequestInfo | URL, init?: RequestInit) => {
|
|
const parsed = new URL(String(url));
|
|
const item: Pending = {
|
|
...deferred<Response>(),
|
|
path: parsed.pathname + parsed.search,
|
|
method: init?.method ?? 'GET',
|
|
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
|
settled: false,
|
|
};
|
|
requests.push(item);
|
|
return item.promise; // Deliberately ignore cancellation to exercise stale-response guards.
|
|
}) as unknown as typeof browser.fetch;
|
|
});
|
|
afterEach(async () => {
|
|
if (root) {
|
|
await flush(() => root!.unmount());
|
|
}
|
|
root = undefined;
|
|
host.remove();
|
|
});
|
|
afterAll(async () => {
|
|
await browser.happyDOM.close();
|
|
for (const key of keys) {
|
|
const descriptor = originals.get(key);
|
|
if (descriptor) {
|
|
Object.defineProperty(globalThis, key, descriptor);
|
|
} else {
|
|
delete (globalThis as Record<string, unknown>)[key];
|
|
}
|
|
}
|
|
});
|
|
|
|
describe('research workspace', () => {
|
|
describe('saved revision download', () => {
|
|
const blobs: Blob[] = [];
|
|
const downloads: string[] = [];
|
|
const revoked: string[] = [];
|
|
let failure: 'url' | 'click' | undefined;
|
|
let restore: () => void;
|
|
const tick = () => new Promise(resolve => setTimeout(resolve, 0));
|
|
beforeEach(() => {
|
|
blobs.length = downloads.length = revoked.length = 0;
|
|
failure = undefined;
|
|
const createUrl = spyOn(URL, 'createObjectURL').mockImplementation(blob => {
|
|
if (failure === 'url') {
|
|
throw new Error('Browser file creation failed');
|
|
}
|
|
blobs.push(blob as Blob);
|
|
return `blob:research-${blobs.length}`;
|
|
});
|
|
const revokeUrl = spyOn(URL, 'revokeObjectURL').mockImplementation(url => revoked.push(url));
|
|
const clickAnchor = spyOn(browser.HTMLAnchorElement.prototype, 'click').mockImplementation(
|
|
() => {
|
|
if (failure === 'click') {
|
|
throw new Error('Browser download failed');
|
|
}
|
|
const anchor = browser.document.querySelector('a[download]');
|
|
if (!(anchor instanceof browser.HTMLAnchorElement)) {
|
|
throw new Error('Missing download anchor');
|
|
}
|
|
downloads.push(anchor.download);
|
|
}
|
|
);
|
|
restore = () => {
|
|
createUrl.mockRestore();
|
|
revokeUrl.mockRestore();
|
|
clickAnchor.mockRestore();
|
|
};
|
|
});
|
|
afterEach(async () => {
|
|
await tick();
|
|
restore();
|
|
});
|
|
|
|
test.each(['hypothesis', 'note', 'finding'] as const)(
|
|
'%s download excludes unsaved edits and issues no requests',
|
|
async kind => {
|
|
const value = kind === 'hypothesis' ? hypothesis() : artifact('a1', { kind });
|
|
await mount(
|
|
`/research/p1?${kind === 'hypothesis' ? 'hypothesis' : 'artifact'}=${value.id}`
|
|
);
|
|
expect(host.textContent).not.toContain('Download saved revision');
|
|
await flush(() => replyProject(project(), [hypothesis()], [artifact()]));
|
|
await flush(() => {
|
|
if ('hypothesisId' in value.latestRevision) {
|
|
replyHypothesis(value as ResearchHypothesis);
|
|
} else {
|
|
replyArtifact(value as ResearchArtifact);
|
|
}
|
|
});
|
|
const original = structuredClone(value.latestRevision);
|
|
await flush(() => click('Edit latest revision'));
|
|
await flush(() => edit('Revision body', 'Unsaved research interpretation'));
|
|
const before = requests.length;
|
|
await flush(() => click('Download saved revision'));
|
|
expect(host.textContent).toContain('Unsaved edits are excluded');
|
|
expect(JSON.parse(await blobs[0]!.text())).toEqual({
|
|
kind: 'research-revision-export/v1',
|
|
projectId: 'p1',
|
|
entry: {
|
|
id: value.id,
|
|
kind,
|
|
...(kind !== 'hypothesis' ? { hypothesisRevisionId: null } : {}),
|
|
},
|
|
revision: original,
|
|
});
|
|
expect(downloads).toEqual([`research-${value.id}-${original.id}.json`]);
|
|
expect(field('Revision body').value).toBe('Unsaved research interpretation');
|
|
expect(value.latestRevision).toEqual(original);
|
|
expect(requests).toHaveLength(before);
|
|
expect(browser.document.querySelector('a[download]')).toBeNull();
|
|
await tick();
|
|
expect(revoked).toEqual(['blob:research-1']);
|
|
await flush(() => click('Save new revision'));
|
|
expect(button('Download saved revision').disabled).toBe(true);
|
|
await flush(() => click('Download saved revision'));
|
|
expect(blobs).toHaveLength(1);
|
|
}
|
|
);
|
|
|
|
test('historical archived finding exports its own source, raw values and unavailable reasons', async () => {
|
|
const original = {
|
|
...artifact().latestRevision,
|
|
title: 'Original interpretation',
|
|
source: {
|
|
kind: 'experiment/v1' as const,
|
|
experimentId: '22222222-2222-4222-8222-222222222222',
|
|
previewHash: 'a'.repeat(64),
|
|
},
|
|
evidenceState: 'referenced' as const,
|
|
evidence: [0.123456789012345, null].map((value, index) => ({
|
|
runId: 'run',
|
|
backtestId: 'backtest',
|
|
strategyVersionId: 'version',
|
|
metricsVersion: 'canonical-analytics/v1' as const,
|
|
metricPath: index ? 'analytics.metrics.sharpeRatio' : 'analytics.metrics.totalReturn',
|
|
value,
|
|
unit: 'fraction' as const,
|
|
availability: index ? ('unavailable' as const) : ('available' as const),
|
|
unavailableReason: index ? 'insufficient-data' : null,
|
|
resultKind: 'canonical' as const,
|
|
financialEngine: 'rust' as const,
|
|
datasetHash: 'b'.repeat(64),
|
|
limitations: [{ code: 'fixture', message: 'Retained limitation' }],
|
|
})),
|
|
};
|
|
const latest = {
|
|
...original,
|
|
id: 'a1-r2',
|
|
ordinal: 2,
|
|
title: 'Latest interpretation',
|
|
source: null,
|
|
};
|
|
const value = artifact('a1', {
|
|
kind: 'finding',
|
|
archived: true,
|
|
hypothesisRevisionId: 'h1-r1',
|
|
latestRevision: latest,
|
|
});
|
|
await mount('/research/p1?artifact=a1&revision=a1-r1');
|
|
await flush(() => replyProject(project('p1', { archived: true }), [hypothesis()], [value]));
|
|
await flush(() => replyArtifact(value, [original, latest]));
|
|
const before = requests.length;
|
|
await flush(() => click('Download saved revision'));
|
|
expect(JSON.parse(await blobs[0]!.text())).toEqual({
|
|
kind: 'research-revision-export/v1',
|
|
projectId: 'p1',
|
|
entry: { id: 'a1', kind: 'finding', hypothesisRevisionId: 'h1-r1' },
|
|
revision: original,
|
|
});
|
|
expect(downloads).toEqual(['research-a1-a1-r1.json']);
|
|
expect(requests).toHaveLength(before);
|
|
expect(value.latestRevision).toEqual(latest);
|
|
});
|
|
|
|
test.each(['url', 'click'] as const)(
|
|
'%s failure retries the saved revision with cleanup',
|
|
async stage => {
|
|
await mount('/research/p1?artifact=a1');
|
|
await flush(() => replyProject());
|
|
await flush(() => replyArtifact());
|
|
failure = stage;
|
|
const before = requests.length;
|
|
await flush(() => click('Download saved revision'));
|
|
expect(host.textContent).toContain(
|
|
stage === 'url' ? 'Browser file creation failed' : 'Browser download failed'
|
|
);
|
|
expect(downloads).toHaveLength(0);
|
|
expect(browser.document.querySelector('a[download]')).toBeNull();
|
|
await tick();
|
|
expect(revoked).toEqual(stage === 'url' ? [] : ['blob:research-1']);
|
|
failure = undefined;
|
|
await flush(() => click('Retry saved revision download'));
|
|
expect(downloads).toHaveLength(1);
|
|
expect(JSON.parse(await blobs.at(-1)!.text()).revision).toEqual(artifact().latestRevision);
|
|
expect(requests).toHaveLength(before);
|
|
await flush(() => click('View revision 1'));
|
|
await flush(() => replyArtifact());
|
|
expect(host.textContent).not.toContain('Retry saved revision download');
|
|
}
|
|
);
|
|
|
|
test('missing or failed history exposes no download action', async () => {
|
|
await mount('/research/p1?artifact=a1&revision=missing');
|
|
await flush(() => replyProject());
|
|
await flush(() => replyArtifact());
|
|
expect(host.textContent).toContain('requested revision does not belong');
|
|
expect(host.textContent).not.toContain('Download saved revision');
|
|
await flush(() => click('Retry research entry'));
|
|
await flush(() => {
|
|
reply(request('analysis-artifacts/a1'), { error: 'Entry unavailable' }, 503);
|
|
reply(request('analysis-artifacts/a1/revisions'), { revisions: [] });
|
|
});
|
|
expect(host.textContent).toContain('Entry unavailable');
|
|
expect(host.textContent).not.toContain('Download saved revision');
|
|
expect(blobs).toHaveLength(0);
|
|
});
|
|
});
|
|
|
|
test('project listing distinguishes loading, error and empty and retries reads', async () => {
|
|
await mount('/research');
|
|
expect(host.textContent).toContain('Loading research projects');
|
|
await flush(() =>
|
|
reply(request('research-projects?includeArchived=false'), { error: 'Read failed' }, 503)
|
|
);
|
|
expect(host.textContent).toContain('Read failed');
|
|
expect(host.textContent).not.toContain('No research projects yet');
|
|
await flush(() => click('Retry projects'));
|
|
await flush(() => reply(request('research-projects?includeArchived=false'), { projects: [] }));
|
|
expect(host.textContent).toContain('No research projects yet');
|
|
});
|
|
test('ambiguous project create freezes draft, prevents duplicate requests, and requires deliberate restart', async () => {
|
|
await mount('/research');
|
|
await flush(() => reply(request('research-projects?includeArchived=false'), { projects: [] }));
|
|
await flush(() => click('New project'));
|
|
await flush(() => edit('Project title', 'Lost response'));
|
|
await flush(() => {
|
|
click('Create project');
|
|
click('Create project');
|
|
});
|
|
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
|
await flush(() => {
|
|
const item = request('research-projects', 'POST');
|
|
item.settled = true;
|
|
item.reject(new Error('Lost'));
|
|
});
|
|
expect(field('Project title').value).toBe('Lost response');
|
|
expect(button('Create project').disabled).toBe(true);
|
|
await flush(() => click('Check saved projects'));
|
|
await flush(() =>
|
|
reply(request('research-projects?includeArchived=true'), { projects: [project()] })
|
|
);
|
|
expect(field('Project title').value).toBe('Lost response');
|
|
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: [] }));
|
|
await flush(() => click('New project'));
|
|
await flush(() => edit('Project title', 'Original'));
|
|
await flush(() => click('Create project'));
|
|
const old = request('research-projects', 'POST');
|
|
await flush(() => navigate('/research/p2'));
|
|
await flush(() => replyProject(project('p2')));
|
|
await flush(() => reply(old, { project: project('p1') }));
|
|
expect(location).toBe('/research/p2');
|
|
expect(host.textContent).toContain('Project p2');
|
|
});
|
|
test('section errors never masquerade as empty records and stale project responses are ignored', async () => {
|
|
await mount();
|
|
const old = requests.slice();
|
|
await flush(() => navigate('/research/p2'));
|
|
await flush(() => {
|
|
const p = project('p2');
|
|
reply(request('research-projects/p2'), { project: p });
|
|
reply(request('research-projects/p2/strategies'), { strategies: [] });
|
|
reply(
|
|
request('research-projects/p2/hypotheses?includeArchived=true'),
|
|
{ error: 'Hypotheses unavailable' },
|
|
500
|
|
);
|
|
reply(request('research-projects/p2/analysis-artifacts?includeArchived=true'), {
|
|
artifacts: [],
|
|
});
|
|
const catalogs = requests.filter(item => item.path === '/api/v2/strategies');
|
|
reply(catalogs[1]!, { strategies: [] });
|
|
});
|
|
await flush(() => {
|
|
for (const item of old) {
|
|
if (item.path.endsWith('/p1')) {
|
|
reply(item, { project: project('p1') });
|
|
} else if (item.path.includes('hypotheses')) {
|
|
reply(item, { hypotheses: [hypothesis()] });
|
|
} else if (item.path.includes('analysis-artifacts')) {
|
|
reply(item, { artifacts: [] });
|
|
} else {
|
|
reply(item, { strategies: [] });
|
|
}
|
|
}
|
|
});
|
|
expect(host.textContent).toContain('Project p2');
|
|
expect(host.textContent).not.toContain('Project p1');
|
|
expect(host.textContent).toContain('Hypotheses unavailable');
|
|
expect(host.textContent).not.toContain('No hypotheses yet');
|
|
});
|
|
test('creates declared AI hypothesis and renders escaped, unvalidated narrative with immutable history', async () => {
|
|
await mount();
|
|
await flush(() => replyProject());
|
|
await flush(() => click('New hypothesis'));
|
|
await flush(() => {
|
|
edit('Hypothesis title', 'Momentum hypothesis');
|
|
edit('Proposition', '<img src=x onerror=alert(1)>');
|
|
edit('Validation criteria', 'Out of sample');
|
|
edit('Declared content origin', 'ai');
|
|
});
|
|
await flush(() => click('Create hypothesis'));
|
|
expect(request('research-projects/p1/hypotheses', 'POST').body).toEqual({
|
|
title: 'Momentum hypothesis',
|
|
proposition: '<img src=x onerror=alert(1)>',
|
|
validationCriteria: 'Out of sample',
|
|
contentOrigin: 'ai',
|
|
});
|
|
await flush(() =>
|
|
reply(request('research-projects/p1/hypotheses', 'POST'), { hypothesis: hypothesis() })
|
|
);
|
|
await flush(() => {
|
|
replyProject(project(), [hypothesis()]);
|
|
replyHypothesis();
|
|
});
|
|
expect(location).toBe('/research/p1?hypothesis=h1');
|
|
expect(host.textContent).toContain('Unvalidated narrative');
|
|
expect(host.textContent).toContain('AI-authored (declared)');
|
|
expect(host.querySelector('img')).toBeNull();
|
|
await flush(() => click('View revision 1'));
|
|
await flush(() => replyHypothesis());
|
|
expect(host.textContent).toContain('Immutable history');
|
|
expect(
|
|
[...host.querySelectorAll('button')].some(item => item.textContent === 'Edit latest revision')
|
|
).toBe(false);
|
|
});
|
|
test('note creation sends no measured claims and preserves an ambiguous draft across record refresh', async () => {
|
|
await mount();
|
|
await flush(() => replyProject());
|
|
await flush(() => click('New note'));
|
|
await flush(() => {
|
|
edit('Note title', 'Observation');
|
|
edit('Note body', 'Needs validation');
|
|
});
|
|
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)
|
|
);
|
|
await flush(() => click('Check saved records'));
|
|
await flush(() => replyProject(project(), [], [artifact()]));
|
|
expect(field('Note body').value).toBe('Needs validation');
|
|
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<string, unknown>, Record<string, unknown>][]) {
|
|
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<string, unknown>][]) {
|
|
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()]));
|
|
await flush(() => replyArtifact());
|
|
await flush(() => click('Edit latest revision'));
|
|
await flush(() => edit('Revision body', 'Unsaved conclusion'));
|
|
await flush(() => click('Save new revision'));
|
|
expect(request('analysis-artifacts/a1/revisions', 'POST').body).toMatchObject({
|
|
expectedRevision: 1,
|
|
body: 'Unsaved conclusion',
|
|
evidence: [],
|
|
});
|
|
await flush(() =>
|
|
reply(request('analysis-artifacts/a1/revisions', 'POST'), { error: 'Revision conflict' }, 409)
|
|
);
|
|
expect(field('Revision body').value).toBe('Unsaved conclusion');
|
|
expect(button('Save new revision').disabled).toBe(true);
|
|
await flush(() => click('Refresh project'));
|
|
await flush(() => replyProject(project(), [], [artifact()]));
|
|
expect(field('Revision body').value).toBe('Unsaved conclusion');
|
|
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
|
});
|
|
for (const [label, change] of [
|
|
['foreign identity', { id: 'p2' }],
|
|
['foreign owner', { ownerPrincipal: 'service' }],
|
|
['stale revision', { revision: 1 }],
|
|
['unexpected revision', { revision: 3 }],
|
|
['changed title', { title: 'Substituted' }],
|
|
['changed description', { description: 'Substituted' }],
|
|
['changed archival', { archived: true }],
|
|
] as [string, Partial<ResearchProject>][]) {
|
|
test(`project update ${label} acknowledgement preserves the metadata draft`, async () => {
|
|
const { patch, saved } = await submitProjectEdit();
|
|
await flush(() => reply(patch, { project: { ...saved, ...change } }));
|
|
expect(host.textContent).toContain('The saved project update could not be verified.');
|
|
expect(field('Project title').value).toBe(revisionDraft.title);
|
|
expect(field('Project description').value).toBe(revisionDraft.body);
|
|
expect(button('Save project').disabled).toBe(true);
|
|
expect(button('Archive project').disabled).toBe(true);
|
|
expect(requests.filter(item => !item.settled)).toHaveLength(0);
|
|
await flush(() => click('Archive project'));
|
|
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
|
|
});
|
|
}
|
|
test('verified normalized project edit reloads the exact next revision', async () => {
|
|
const { patch, saved } = await submitProjectEdit();
|
|
expect(patch.body).toEqual({
|
|
expectedRevision: 1,
|
|
title: revisionDraft.title.trim(),
|
|
description: revisionDraft.body,
|
|
});
|
|
await flush(() => reply(patch, { project: saved }));
|
|
await flush(() => replyProject(saved));
|
|
expect(host.querySelector('[aria-label="Edit research project"]')).toBeNull();
|
|
expect(host.textContent).toContain('Project revision 2');
|
|
expect(button('Archive project').disabled).toBe(false);
|
|
});
|
|
test('uncertain project edit survives refresh and discard enters loading before releasing writes', async () => {
|
|
const { patch, saved } = await submitProjectEdit();
|
|
await flush(() => reply(patch, { error: 'Outcome unknown' }, 500));
|
|
expect(button('Archive project').disabled).toBe(true);
|
|
await flush(() => click('Refresh project'));
|
|
await flush(() => replyProject(saved));
|
|
expect(field('Project title').value).toBe(revisionDraft.title);
|
|
expect(button('Archive project').disabled).toBe(true);
|
|
expect(host.textContent).not.toContain('New hypothesis');
|
|
await flush(() => click('Discard edits and reload project'));
|
|
expect(button('Archive project').disabled).toBe(true);
|
|
expect(host.textContent).toContain('Loading research workspace');
|
|
await flush(() => replyProject(saved));
|
|
expect(button('Archive project').disabled).toBe(false);
|
|
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
|
|
});
|
|
for (const initialArchive of [false, true]) {
|
|
test(`project ${initialArchive ? 'restore' : 'archive'} acknowledgement must match its requested target`, async () => {
|
|
const original = project('p1', { archived: initialArchive });
|
|
await mount();
|
|
await flush(() => replyProject(original));
|
|
const action = initialArchive ? 'Restore project' : 'Archive project';
|
|
await flush(() => click(action));
|
|
const patch = request('research-projects/p1', 'PATCH');
|
|
expect(patch.body).toEqual({ expectedRevision: 1, archived: !initialArchive });
|
|
await flush(() => reply(patch, { project: { ...original, revision: 2 } }));
|
|
expect(host.textContent).toContain('The saved project update could not be verified.');
|
|
expect(button(action).disabled).toBe(true);
|
|
expect(requests.filter(item => !item.settled)).toHaveLength(0);
|
|
});
|
|
}
|
|
test('uncertain project archive preserves a child draft and freezes child writes until deliberate reload', async () => {
|
|
await mount();
|
|
await flush(() => replyProject());
|
|
await flush(() => click('New note'));
|
|
await flush(() => {
|
|
edit('Note title', 'Retain child draft');
|
|
edit('Note body', revisionDraft.body);
|
|
});
|
|
await flush(() => click('Archive project'));
|
|
await flush(() =>
|
|
reply(request('research-projects/p1', 'PATCH'), { error: 'Outcome unknown' }, 500)
|
|
);
|
|
expect(field('Note body').value).toBe(revisionDraft.body);
|
|
expect(button('Create note').disabled).toBe(true);
|
|
expect(button('Archive project').disabled).toBe(true);
|
|
await flush(() => click('Refresh project'));
|
|
await flush(() => replyProject());
|
|
expect(button('Create note').disabled).toBe(true);
|
|
expect(field('Note body').value).toBe(revisionDraft.body);
|
|
await flush(() => click('Discard edits and reload project'));
|
|
expect(host.querySelector('[aria-label="Note body"]')).toBeNull();
|
|
expect(button('Archive project').disabled).toBe(true);
|
|
await flush(() => replyProject(project('p1', { revision: 2, archived: true })));
|
|
expect(button('Restore project').disabled).toBe(false);
|
|
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
|
|
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
|
});
|
|
for (const kind of ['hypothesis', 'note', 'finding'] as const) {
|
|
const original =
|
|
kind === 'hypothesis' ? hypothesis() : kind === 'finding' ? citedFinding() : artifact();
|
|
for (const [label, rootChange, revisionChange] of [
|
|
['identity', { id: 'other' }, {}],
|
|
['project', { projectId: 'p2' }, {}],
|
|
['owner', { ownerPrincipal: 'service' }, {}],
|
|
['archive target', { archived: false }, {}],
|
|
[
|
|
'revision parent',
|
|
{},
|
|
kind === 'hypothesis' ? { hypothesisId: 'other' } : { artifactId: 'other' },
|
|
],
|
|
['validated state', {}, { validationState: 'validated' }],
|
|
...(kind === 'hypothesis'
|
|
? []
|
|
: [
|
|
['kind', { kind: kind === 'finding' ? 'note' : 'finding' }, {}],
|
|
['hypothesis link', { hypothesisRevisionId: 'other-revision' }, {}],
|
|
]),
|
|
] as [string, Record<string, unknown>, Record<string, unknown>][]) {
|
|
test(`${kind} archive ${label} acknowledgement preserves and blocks the revision draft`, async () => {
|
|
const patch = await submitEntryArchive(original);
|
|
await flush(() =>
|
|
reply(patch, {
|
|
[kind === 'hypothesis' ? 'hypothesis' : 'artifact']: {
|
|
...original,
|
|
archived: true,
|
|
...rootChange,
|
|
latestRevision: { ...original.latestRevision, ...revisionChange },
|
|
},
|
|
})
|
|
);
|
|
expect(host.textContent).toContain('The archive response could not be verified.');
|
|
expect(field('Revision title').value).toBe(revisionDraft.title);
|
|
expect(field('Revision body').value).toBe(revisionDraft.body);
|
|
expect(button('Save new revision').disabled).toBe(true);
|
|
expect(button('Archive entry').disabled).toBe(true);
|
|
expect(requests.filter(item => !item.settled)).toHaveLength(0);
|
|
await flush(() => click('Archive entry'));
|
|
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
|
|
});
|
|
}
|
|
}
|
|
for (const kind of ['hypothesis', 'artifact'] as const) {
|
|
test(`${kind} restore acknowledgement cannot claim an unchanged archive flag`, async () => {
|
|
const original =
|
|
kind === 'hypothesis'
|
|
? hypothesis('h1', { archived: true })
|
|
: artifact('a1', { archived: true });
|
|
const patch = await submitEntryArchive(original);
|
|
await flush(() => reply(patch, { [kind]: original }));
|
|
expect(host.textContent).toContain('The archive response could not be verified.');
|
|
expect(button('Restore entry').disabled).toBe(true);
|
|
expect(requests.filter(item => !item.settled)).toHaveLength(0);
|
|
});
|
|
for (const archived of [false, true]) {
|
|
test(`${kind} ${archived ? 'restore' : 'archive'} accepts a newer concurrent narrative revision`, async () => {
|
|
const original =
|
|
kind === 'hypothesis' ? hypothesis('h1', { archived }) : artifact('a1', { archived });
|
|
const patch = await submitEntryArchive(original);
|
|
const saved = {
|
|
...original,
|
|
archived: !archived,
|
|
latestRevision: {
|
|
...original.latestRevision,
|
|
id: `${original.id}-r2`,
|
|
ordinal: 2,
|
|
title: 'New concurrent interpretation',
|
|
},
|
|
};
|
|
await flush(() => reply(patch, { [kind]: saved }));
|
|
await flush(() => {
|
|
replyProject(project());
|
|
if (kind === 'hypothesis') {
|
|
replyHypothesis(
|
|
saved as ResearchHypothesis,
|
|
[
|
|
original.latestRevision,
|
|
saved.latestRevision,
|
|
] as ResearchHypothesis['latestRevision'][]
|
|
);
|
|
} else {
|
|
replyArtifact(
|
|
saved as ResearchArtifact,
|
|
[
|
|
original.latestRevision,
|
|
saved.latestRevision,
|
|
] as ResearchArtifact['latestRevision'][]
|
|
);
|
|
}
|
|
});
|
|
expect(host.textContent).toContain('New concurrent interpretation');
|
|
expect(button(archived ? 'Archive entry' : 'Restore entry').disabled).toBe(false);
|
|
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
|
|
});
|
|
}
|
|
}
|
|
test('known entry archive refusal retains an editable draft; uncertain outcome requires loading saved history', async () => {
|
|
const patch = await submitEntryArchive(artifact());
|
|
await flush(() => reply(patch, { error: 'Not permitted' }, 403));
|
|
expect(field('Revision body').value).toBe(revisionDraft.body);
|
|
expect(button('Archive entry').disabled).toBe(false);
|
|
await flush(() => click('Archive entry'));
|
|
await flush(() =>
|
|
reply(request('analysis-artifacts/a1', 'PATCH'), { error: 'Outcome unknown' }, 500)
|
|
);
|
|
expect(button('Save new revision').disabled).toBe(true);
|
|
expect(button('Archive entry').disabled).toBe(true);
|
|
await flush(() => click('Refresh project'));
|
|
await flush(() => replyProject());
|
|
expect(field('Revision body').value).toBe(revisionDraft.body);
|
|
expect(button('Archive entry').disabled).toBe(true);
|
|
await flush(() => click('Discard draft and reload archive state'));
|
|
expect(host.textContent).toContain('Loading research entry');
|
|
expect(host.querySelector('[aria-label="Revision body"]')).toBeNull();
|
|
await flush(() => {
|
|
replyProject();
|
|
replyArtifact(artifact('a1', { archived: true }));
|
|
});
|
|
expect(button('Restore entry').disabled).toBe(false);
|
|
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(2);
|
|
});
|
|
test('entry archival can follow a narrative revision conflict without inventing an archive precondition', async () => {
|
|
await mount('/research/p1?artifact=a1');
|
|
await flush(() => replyProject());
|
|
await flush(() => replyArtifact());
|
|
await flush(() => click('Edit latest revision'));
|
|
await flush(() => edit('Revision body', revisionDraft.body));
|
|
await flush(() => click('Save new revision'));
|
|
await flush(() =>
|
|
reply(request('analysis-artifacts/a1/revisions', 'POST'), { error: 'Revision changed' }, 409)
|
|
);
|
|
expect(button('Save new revision').disabled).toBe(true);
|
|
expect(button('Archive entry').disabled).toBe(false);
|
|
await flush(() => click('Archive entry'));
|
|
expect(request('analysis-artifacts/a1', 'PATCH').body).toEqual({ archived: true });
|
|
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
|
|
});
|
|
for (const outcome of ['lost', 'malformed', '500'] as const) {
|
|
test(`${outcome} project update blocks writes and preserves metadata`, async () => {
|
|
const { patch } = await submitProjectEdit();
|
|
await flush(() => {
|
|
if (outcome === 'lost') {
|
|
patch.settled = true;
|
|
patch.reject(new Error('Response lost'));
|
|
} else {
|
|
reply(
|
|
patch,
|
|
outcome === '500' ? { error: 'Outcome unknown' } : {},
|
|
outcome === '500' ? 500 : 200
|
|
);
|
|
}
|
|
});
|
|
expect(field('Project description').value).toBe(revisionDraft.body);
|
|
expect(button('Save project').disabled).toBe(true);
|
|
expect(button('Archive project').disabled).toBe(true);
|
|
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
|
|
});
|
|
test(`${outcome} entry archive blocks writes and preserves the revision draft`, async () => {
|
|
const patch = await submitEntryArchive(artifact());
|
|
await flush(() => {
|
|
if (outcome === 'lost') {
|
|
patch.settled = true;
|
|
patch.reject(new Error('Response lost'));
|
|
} else {
|
|
reply(
|
|
patch,
|
|
outcome === '500' ? { error: 'Outcome unknown' } : {},
|
|
outcome === '500' ? 500 : 200
|
|
);
|
|
}
|
|
});
|
|
expect(field('Revision body').value).toBe(revisionDraft.body);
|
|
expect(button('Save new revision').disabled).toBe(true);
|
|
expect(button('Archive entry').disabled).toBe(true);
|
|
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
|
|
});
|
|
}
|
|
for (const status of [403, 409]) {
|
|
test(`known project ${status} response preserves its existing retry policy`, async () => {
|
|
const { patch } = await submitProjectEdit();
|
|
await flush(() => reply(patch, { error: 'Refused' }, status));
|
|
expect(field('Project title').value).toBe(revisionDraft.title);
|
|
expect(button('Save project').disabled).toBe(status === 409);
|
|
expect(button('Archive project').disabled).toBe(status === 409);
|
|
expect(requests.filter(item => item.method === 'PATCH')).toHaveLength(1);
|
|
});
|
|
}
|
|
test('membership refreshes project revision before the next metadata write; archived strategies remain visible', async () => {
|
|
await mount();
|
|
await flush(() => replyProject());
|
|
expect(field('Strategy to link').textContent).not.toContain('Retired');
|
|
await flush(() => edit('Strategy to link', 's1'));
|
|
await flush(() => click('Link strategy'));
|
|
await flush(() => reply(request('research-projects/p1/strategies/s1', 'PUT'), undefined, 204));
|
|
await flush(() =>
|
|
replyProject(project('p1', { revision: 2 }), [], [], [{ ...strategy, archived: true }])
|
|
);
|
|
expect(host.textContent).toContain('Archived strategy');
|
|
await flush(() => click('Edit project'));
|
|
await flush(() => edit('Project description', 'New description'));
|
|
await flush(() => click('Save project'));
|
|
expect(request('research-projects/p1', 'PATCH').body).toMatchObject({
|
|
expectedRevision: 2,
|
|
description: 'New description',
|
|
});
|
|
});
|
|
test('archived project retains entries and history but exposes only project restore', async () => {
|
|
await mount('/research/p1?artifact=a1');
|
|
await flush(() =>
|
|
replyProject(project('p1', { archived: true }), [], [artifact('a1', { archived: true })])
|
|
);
|
|
await flush(() => replyArtifact(artifact('a1', { archived: true })));
|
|
expect(host.textContent).toContain('Research note');
|
|
expect(host.textContent).toContain('Revision history');
|
|
const labels = [...host.querySelectorAll('button')].map(item => item.textContent);
|
|
expect(labels).toContain('Restore project');
|
|
for (const label of [
|
|
'New note',
|
|
'New hypothesis',
|
|
'Restore entry',
|
|
'Archive entry',
|
|
'Edit latest revision',
|
|
'Link strategy',
|
|
]) {
|
|
expect(labels).not.toContain(label);
|
|
}
|
|
await flush(() => click('Restore project'));
|
|
expect(request('research-projects/p1', 'PATCH').body).toEqual({
|
|
expectedRevision: 1,
|
|
archived: false,
|
|
});
|
|
});
|
|
test('cross-project entries and foreign revision IDs fail visibly', async () => {
|
|
await mount('/research/p1?hypothesis=h1&revision=foreign');
|
|
await flush(() => replyProject());
|
|
await flush(() => replyHypothesis());
|
|
expect(host.textContent).toContain('requested revision does not belong');
|
|
await flush(() => navigate('/research/p1?artifact=a1'));
|
|
await flush(() => replyArtifact(artifact('a1', { projectId: 'p2' })));
|
|
expect(host.textContent).toContain('Artifact does not belong to this project');
|
|
expect(host.textContent).not.toContain('<script>doNotRun()');
|
|
});
|
|
test('failed refresh and remote archival retain an uncertain note draft until explicit discard', async () => {
|
|
await mount();
|
|
await flush(() => replyProject());
|
|
await flush(() => click('New note'));
|
|
await flush(() => {
|
|
edit('Note title', 'Retained title');
|
|
edit('Note body', 'Retained body');
|
|
});
|
|
await flush(() => click('Create note'));
|
|
await flush(() =>
|
|
reply(
|
|
request('research-projects/p1/analysis-artifacts', 'POST'),
|
|
{ error: 'Uncertain write' },
|
|
500
|
|
)
|
|
);
|
|
await flush(() => click('Check saved records'));
|
|
await flush(() => {
|
|
reply(request('research-projects/p1'), { error: 'Project refresh unavailable' }, 503);
|
|
reply(request('research-projects/p1/strategies'), { strategies: [] });
|
|
reply(request('research-projects/p1/hypotheses?includeArchived=true'), { hypotheses: [] });
|
|
reply(request('research-projects/p1/analysis-artifacts?includeArchived=true'), {
|
|
artifacts: [],
|
|
});
|
|
reply(request('strategies'), { strategies: [] });
|
|
});
|
|
expect(field('Note title').value).toBe('Retained title');
|
|
expect(field('Note body').value).toBe('Retained body');
|
|
expect(button('Create note').disabled).toBe(true);
|
|
expect(host.textContent).toContain('Project status could not be verified');
|
|
await flush(() => click('Refresh project'));
|
|
await flush(() => replyProject(project('p1', { archived: true })));
|
|
expect(field('Note body').value).toBe('Retained body');
|
|
expect(button('Create note').disabled).toBe(true);
|
|
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
|
});
|
|
test('finding revisions retain exact evidence references and link archived hypothesis history', async () => {
|
|
const original = hypothesis().latestRevision;
|
|
const linked = hypothesis('h1', {
|
|
archived: true,
|
|
latestRevision: { ...original, id: 'h1-r2', ordinal: 2, title: 'Revised hypothesis' },
|
|
});
|
|
const originalNote = artifact().latestRevision;
|
|
const finding = artifact('a1', {
|
|
kind: 'finding',
|
|
hypothesisRevisionId: original.id,
|
|
latestRevision: {
|
|
...originalNote,
|
|
title: 'Finding',
|
|
evidenceState: 'referenced',
|
|
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: 'frozen-dataset',
|
|
limitations: [],
|
|
},
|
|
],
|
|
},
|
|
});
|
|
await mount('/research/p1?artifact=a1');
|
|
await flush(() => replyProject(project(), [linked], [finding]));
|
|
await flush(() => replyArtifact(finding));
|
|
await flush(() =>
|
|
reply(request('hypotheses/h1/revisions'), { revisions: [original, linked.latestRevision] })
|
|
);
|
|
const historyLink = host.querySelector('a[href="/research/p1?hypothesis=h1&revision=h1-r1"]');
|
|
expect(historyLink).not.toBeNull();
|
|
expect(
|
|
host.querySelector(
|
|
'a[href="/backtests/22222222-2222-4222-8222-222222222222/run/11111111-1111-4111-8111-111111111111"]'
|
|
)
|
|
).not.toBeNull();
|
|
await flush(() => click('Edit latest revision'));
|
|
await flush(() => edit('Revision body', 'Updated interpretation, same evidence'));
|
|
await flush(() => click('Save new revision'));
|
|
expect(request('analysis-artifacts/a1/revisions', 'POST').body).toEqual({
|
|
expectedRevision: 1,
|
|
title: 'Finding',
|
|
body: 'Updated interpretation, same evidence',
|
|
contentOrigin: 'human',
|
|
evidence: [
|
|
{
|
|
runId: '11111111-1111-4111-8111-111111111111',
|
|
strategyVersionId: '33333333-3333-4333-8333-333333333333',
|
|
metricsVersion: 'canonical-analytics/v1',
|
|
metricPath: 'analytics.metrics.totalReturn',
|
|
},
|
|
],
|
|
});
|
|
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: revisedFinding })
|
|
);
|
|
await flush(() => {
|
|
replyProject(project(), [linked], [revisedFinding]);
|
|
replyArtifact(revisedFinding, [finding.latestRevision, revisedFinding.latestRevision]);
|
|
});
|
|
await flush(() =>
|
|
reply(request('hypotheses/h1/revisions'), { revisions: [original, linked.latestRevision] })
|
|
);
|
|
await flush(() =>
|
|
(
|
|
host.querySelector(
|
|
'a[href="/research/p1?hypothesis=h1&revision=h1-r1"]'
|
|
) as HTMLAnchorElement
|
|
).click()
|
|
);
|
|
await flush(() => replyHypothesis(linked, [original, linked.latestRevision]));
|
|
expect(host.textContent).toContain('Momentum hypothesis');
|
|
expect(host.textContent).toContain('Immutable history');
|
|
expect(
|
|
[...host.querySelectorAll('button')].some(item => item.textContent === 'Edit latest revision')
|
|
).toBe(false);
|
|
});
|
|
for (const failureFirst of [false, true]) {
|
|
test(`exact hypothesis link survives unrelated history failure (${failureFirst ? 'failure first' : 'match first'})`, async () => {
|
|
const original = hypothesis().latestRevision;
|
|
const linked = hypothesis('h1', {
|
|
latestRevision: { ...original, id: 'h1-r2', ordinal: 2 },
|
|
});
|
|
const finding = artifact('a1', { kind: 'finding', hypothesisRevisionId: original.id });
|
|
await mount('/research/p1?artifact=a1');
|
|
await flush(() => replyProject(project(), [linked, hypothesis('h2')], [finding]));
|
|
await flush(() => replyArtifact(finding));
|
|
const match = () =>
|
|
reply(request('hypotheses/h1/revisions'), {
|
|
revisions: [original, linked.latestRevision],
|
|
});
|
|
const failure = () =>
|
|
reply(request('hypotheses/h2/revisions'), { error: 'Temporary history failure' }, 503);
|
|
await flush(failureFirst ? failure : match);
|
|
await flush(failureFirst ? match : failure);
|
|
expect(
|
|
host.querySelector('a[href="/research/p1?hypothesis=h1&revision=h1-r1"]')
|
|
).not.toBeNull();
|
|
expect(host.textContent).not.toContain('Could not resolve the linked hypothesis history');
|
|
expect(host.textContent).not.toContain('unavailable in the loaded project history');
|
|
});
|
|
}
|
|
test('incomplete hypothesis lookup remains retryable through project refresh', async () => {
|
|
const original = hypothesis().latestRevision;
|
|
const linked = hypothesis('h1', {
|
|
latestRevision: { ...original, id: 'h1-r2', ordinal: 2 },
|
|
});
|
|
const unrelated = hypothesis('h2');
|
|
const finding = artifact('a1', { kind: 'finding', hypothesisRevisionId: original.id });
|
|
await mount('/research/p1?artifact=a1');
|
|
await flush(() => replyProject(project(), [linked, unrelated], [finding]));
|
|
await flush(() => replyArtifact(finding));
|
|
await flush(() => {
|
|
reply(request('hypotheses/h1/revisions'), { error: 'Temporary history failure' }, 503);
|
|
reply(request('hypotheses/h2/revisions'), { revisions: [unrelated.latestRevision] });
|
|
});
|
|
expect(host.textContent).toContain('Could not resolve the linked hypothesis history');
|
|
expect(host.textContent).not.toContain('unavailable in the loaded project history');
|
|
expect(host.querySelector('a[href*="?hypothesis=h1&revision=h1-r1"]')).toBeNull();
|
|
await flush(() => click('Refresh project'));
|
|
await flush(() => replyProject(project(), [linked, unrelated], [finding]));
|
|
await flush(() => {
|
|
reply(request('hypotheses/h1/revisions'), { revisions: [original, linked.latestRevision] });
|
|
reply(request('hypotheses/h2/revisions'), { revisions: [unrelated.latestRevision] });
|
|
});
|
|
expect(host.textContent).not.toContain('Could not resolve the linked hypothesis history');
|
|
expect(
|
|
host.querySelector('a[href="/research/p1?hypothesis=h1&revision=h1-r1"]')
|
|
).not.toBeNull();
|
|
});
|
|
test('fully read hypothesis history distinguishes absence and rejects a foreign revision owner', async () => {
|
|
const finding = artifact('a1', { kind: 'finding', hypothesisRevisionId: 'missing-r1' });
|
|
await mount('/research/p1?artifact=a1');
|
|
await flush(() => replyProject(project(), [hypothesis()], [finding]));
|
|
await flush(() => replyArtifact(finding));
|
|
await flush(() =>
|
|
reply(request('hypotheses/h1/revisions'), {
|
|
revisions: [
|
|
hypothesis().latestRevision,
|
|
{ ...hypothesis('h2').latestRevision, id: 'missing-r1' },
|
|
],
|
|
})
|
|
);
|
|
expect(host.textContent).toContain('unavailable in the loaded project history');
|
|
expect(host.textContent).not.toContain('Could not resolve the linked hypothesis history');
|
|
expect(host.querySelector('a[href*="?hypothesis="]')).toBeNull();
|
|
});
|
|
for (const destination of ['finding', 'project'] as const) {
|
|
test(`late hypothesis resolution cannot attach to a different ${destination}`, async () => {
|
|
const original = hypothesis().latestRevision;
|
|
const linked = hypothesis('h1', {
|
|
latestRevision: { ...original, id: 'h1-r2', ordinal: 2 },
|
|
});
|
|
const finding = artifact('a1', { kind: 'finding', hypothesisRevisionId: original.id });
|
|
await mount('/research/p1?artifact=a1');
|
|
await flush(() => replyProject(project(), [linked, hypothesis('h2')], [finding]));
|
|
await flush(() => replyArtifact(finding));
|
|
const previousMatch = request('hypotheses/h1/revisions');
|
|
const previousFailure = request('hypotheses/h2/revisions');
|
|
const nextProjectId = destination === 'project' ? 'p2' : 'p1';
|
|
const next = artifact('a2', { projectId: nextProjectId, kind: 'finding' });
|
|
await flush(() => navigate(`/research/${nextProjectId}?artifact=a2`));
|
|
if (destination === 'project') {
|
|
await flush(() => replyProject(project('p2'), [], [next]));
|
|
}
|
|
await flush(() => replyArtifact(next));
|
|
await flush(() => {
|
|
reply(previousMatch, { revisions: [original, linked.latestRevision] });
|
|
reply(previousFailure, { error: 'Temporary history failure' }, 503);
|
|
});
|
|
expect(location).toBe(`/research/${nextProjectId}?artifact=a2`);
|
|
expect(host.querySelector('a[href*="?hypothesis="]')).toBeNull();
|
|
expect(host.textContent).not.toContain('Linked hypothesis revision:');
|
|
expect(host.textContent).not.toContain('Could not resolve the linked hypothesis history');
|
|
});
|
|
}
|
|
test('late entry read and late revision success cannot overwrite a newly selected entry', async () => {
|
|
await mount('/research/p1?hypothesis=h1');
|
|
await flush(() => replyProject());
|
|
const oldRead = request('hypotheses/h1');
|
|
const oldHistory = request('hypotheses/h1/revisions');
|
|
await flush(() => navigate('/research/p1?artifact=a1'));
|
|
await flush(() => replyArtifact());
|
|
await flush(() => {
|
|
reply(oldRead, { hypothesis: hypothesis() });
|
|
reply(oldHistory, { revisions: [hypothesis().latestRevision] });
|
|
});
|
|
expect(host.textContent).not.toContain('Momentum hypothesis');
|
|
await flush(() => click('Edit latest revision'));
|
|
await flush(() => edit('Revision body', 'Pending revision'));
|
|
await flush(() => click('Save new revision'));
|
|
const oldSave = request('analysis-artifacts/a1/revisions', 'POST');
|
|
await flush(() => navigate('/research/p1?hypothesis=h2'));
|
|
await flush(() => replyHypothesis(hypothesis('h2')));
|
|
const before = requests.length;
|
|
await flush(() => reply(oldSave, { artifact: artifact() }));
|
|
expect(location).toBe('/research/p1?hypothesis=h2');
|
|
expect(requests).toHaveLength(before);
|
|
});
|
|
test('discarding a draft by reopening the same entry reloads it and owned navigation respects refusal', async () => {
|
|
await mount('/research/p1?artifact=a1');
|
|
await flush(() => replyProject(project(), [], [artifact()]));
|
|
await flush(() => replyArtifact());
|
|
await flush(() => click('Edit latest revision'));
|
|
await flush(() => edit('Revision body', 'Discard me'));
|
|
Object.defineProperty(browser, 'confirm', {
|
|
configurable: true,
|
|
writable: true,
|
|
value: () => false,
|
|
});
|
|
await flush(() => (host.querySelector('a[href="/research"]') as HTMLAnchorElement).click());
|
|
expect(location).toBe('/research/p1?artifact=a1');
|
|
expect(field('Revision body').value).toBe('Discard me');
|
|
await flush(() => click('View latest revision'));
|
|
expect(field('Revision body').value).toBe('Discard me');
|
|
Object.defineProperty(browser, 'confirm', {
|
|
configurable: true,
|
|
writable: true,
|
|
value: () => true,
|
|
});
|
|
await flush(() => click('View latest revision'));
|
|
await flush(() => replyArtifact());
|
|
expect(host.querySelector('[aria-label="Revision body"]')).toBeNull();
|
|
expect(host.textContent).not.toContain('Discard me');
|
|
});
|
|
});
|