import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; import { GlobalWindow } from 'happy-dom'; import { act, createElement, type ReactElement } from 'react'; import type { Root } from 'react-dom/client'; import type { CanonicalRunResult, ResearchRunResult, } from '@stock-bot/stock-config/canonical-research'; import type { BacktestRunResult, ResearchArtifact, ResearchEvidenceReference, ResearchHypothesis, ResearchProject, } from '@stock-bot/types'; import type { Backtest, Run, } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'; const browser = new GlobalWindow({ url: 'http://localhost:5173' }); const keys = ['window', 'document', 'Event', 'ResizeObserver', '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 SaveFindingDialog: typeof import('../../apps/stock/web-app/src/features/research/components/SaveFindingDialog').SaveFindingDialog; let BacktestDetailPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2').BacktestDetailPageV2; let root: Root | undefined; let host: HTMLDivElement; let navigate: ReturnType; let closed: number; function deferred() { let resolve!: (value: T) => void; let reject!: (reason: Error) => void; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; } type Pending = ReturnType> & { path: string; method: string; body: unknown; settled: boolean; signal?: AbortSignal | null; }; const requests: Pending[] = []; function request(path: string, method = 'GET') { const value = requests.find( item => !item.settled && item.path === path && item.method === method ); if (!value) { throw new Error( `Missing ${method} ${path}; requests ${requests.map(item => `${item.method} ${item.path} ${item.settled}`).join(',')}` ); } return value; } function reply(item: Pending, body: unknown, status = 200) { item.settled = true; item.resolve(Response.json(body, { status })); } async function flush(action: () => void = () => {}) { await act(async () => { action(); await Promise.resolve(); }); } function button(label: string) { const item = [...host.querySelectorAll('button')].find( item => item.textContent?.trim() === label ); if (!item) { throw new Error(`Missing ${label}: ${host.textContent}`); } return item; } function field(label: string) { const item = host.querySelector(`[aria-label="${label}"]`) as | HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | null; if (!item) { throw new Error(`Missing field ${label}`); } return item; } 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(); return null; } const project = (id = 'p1', archived = false): ResearchProject => ({ id, archived, title: `Project ${id}`, description: '', revision: 1, ownerPrincipal: 'operator', updatedBy: 'operator', createdAt: '2026-10-23', updatedAt: '2026-10-23', }); const hypothesis = (id = 'h1', projectId = 'p1', archived = false): ResearchHypothesis => ({ id, projectId, archived, ownerPrincipal: 'operator', updatedBy: 'operator', createdAt: '2026-10-23', updatedAt: '2026-10-23', latestRevision: { id: `${id}-revision`, hypothesisId: id, ordinal: 2, title: `Hypothesis ${id}`, proposition: 'Candidate', validationCriteria: '', validationState: 'unvalidated', contentOrigin: 'human', submittedBy: 'operator', createdAt: '2026-10-23', }, }); const artifact = (hypothesisRevisionId: string | null = null): ResearchArtifact => ({ id: 'saved-finding', projectId: 'p1', hypothesisRevisionId, kind: 'finding', archived: false, ownerPrincipal: 'operator', updatedBy: 'operator', createdAt: '2026-10-23', updatedAt: '2026-10-23', latestRevision: { id: 'a-revision', artifactId: 'saved-finding', ordinal: 1, title: 'Finding', body: 'Narrative', validationState: 'unvalidated', evidenceState: 'referenced', evidence: [], submittedBy: 'operator', contentOrigin: 'human', createdAt: '2026-10-23', }, }); function acceptedFinding(hypothesisRevisionId: string | null = null): ResearchArtifact { const saved = artifact(hypothesisRevisionId); 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, backtestId: 'definition', value: reference.metricPath.endsWith('sharpeRatio') ? null : 0.23, unit: 'fraction', availability: reference.metricPath.endsWith('sharpeRatio') ? 'unavailable' : 'available', unavailableReason: reference.metricPath.endsWith('sharpeRatio') ? 'insufficient-data' : null, resultKind: reference.metricsVersion === 'canonical-analytics/v1' ? 'canonical' : 'legacy', financialEngine: reference.metricsVersion === 'canonical-analytics/v1' ? 'rust' : 'typescript', datasetHash: 'a'.repeat(64), limitations: [], })); return saved; } function legacy(runId = 'run'): BacktestRunResult { return { runId, backtestId: 'definition', engine: 'typescript', status: 'completed', completedAt: '2026-10-23', config: { name: 'Historical config', strategy: 'sma', symbols: ['A.US'], startDate: '2024-01-01', endDate: '2024-02-01', initialCapital: 1000, commission: 0, slippage: 0, dataFrequency: '1d', parameters: {}, }, metrics: { totalReturn: 0.23, sharpeRatio: null, maxDrawdown: -0.05, winRate: 0, totalTrades: 0, profitFactor: null, avgWin: 0, avgLoss: 0, }, equity: [], ohlcData: {}, trades: [], positions: [], analytics: { exposureTime: null }, executionTime: 1, }; } /** Only fields read by the citation picker; the financial report itself is not simulated here. */ function canonical(): CanonicalRunResult { return { kind: 'canonical-result/v1', runId: 'run', backtestId: 'definition', status: 'completed', financialEngine: 'rust', request: { strategy: { versionId: 'frozen-version' } }, financial: { limitations: ['Only retained exchange sessions'], modelLimitations: ['No market impact'], }, analytics: { metrics: { totalReturn: 0.23, sharpeRatio: null }, fillCount: 3 }, } as unknown as CanonicalRunResult; } const definition: Backtest = { id: 'definition', name: 'Mutable template', strategy: 'sma', symbols: ['A.US'], startDate: '2024-01-01', endDate: '2024-02-01', initialCapital: 1000, config: {}, createdAt: '2024-01-01', updatedAt: '2024-01-01', archivedAt: null, }; const run = (id = 'run', status: Run['status'] = 'completed'): Run => ({ id, backtestId: 'definition', status, runNumber: 1, speedMultiplier: null, progress: 100, createdAt: '2026-10-23', updatedAt: '2026-10-23', }); async function render(element: ReactElement, initial = '/') { if (!root) { root = createRoot(host); } await flush(() => root!.render( createElement( router.MemoryRouter, { initialEntries: [initial] }, element, createElement(Probe) ) ) ); } async function mountDialog(result: ResearchRunResult = canonical()) { await render( createElement(SaveFindingDialog, { result, onClose: () => { closed++; }, }) ); await flush(() => reply(request('/api/v2/research-projects?includeArchived=false'), { projects: [project(), project('p2'), project('archived', true)], }) ); } async function destination(id = 'p1', items = [hypothesis()]) { await flush(() => edit('Finding project', id)); await flush(() => { reply(request(`/api/v2/research-projects/${id}`), { project: project(id) }); reply(request(`/api/v2/research-projects/${id}/hypotheses?includeArchived=false`), { hypotheses: items, }); }); } async function draft() { await destination(); await flush(() => { edit('Finding title', 'Exact finding'); edit('Finding body', 'Keep this narrative'); }); } async function preflight() { await flush(() => button('Save finding').click()); await flush(() => reply(request('/api/v2/research-projects/p1'), { project: project() })); } const post = () => request('/api/v2/research-projects/p1/analysis-artifacts', 'POST'); beforeAll(async () => { for (const [key, value] of Object.entries({ window: browser, document: browser.document, Event: browser.Event, ResizeObserver: browser.ResizeObserver, 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'); ({ SaveFindingDialog } = await import( '../../apps/stock/web-app/src/features/research/components/SaveFindingDialog' )); ({ BacktestDetailPageV2 } = await import( '../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2' )); }); beforeEach(() => { requests.length = 0; closed = 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 = ((input: RequestInfo | URL, init?: RequestInit) => { const url = new URL(String(input)); const item: Pending = { ...deferred(), path: url.pathname + url.search, method: init?.method ?? 'GET', body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined, signal: init?.signal, settled: false, }; requests.push(item); return item.promise; // Deliberately ignore abort: identity fences must handle late replies. }) 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 { Reflect.deleteProperty(globalThis, key); } } }); describe('saved-result finding', () => { test('canonical citations use the frozen strategy version and immutable hypothesis revision, never metric copies', async () => { await mountDialog(); await draft(); expect(host.textContent).toContain('No market impact'); expect(host.textContent).toContain('Sharpe Ratio · Unavailable'); expect(field('Finding project').textContent).not.toContain('Project archived'); await flush(() => { edit('Finding hypothesis', 'h1-revision'); edit('Finding content origin', 'ai'); (field('Sharpe Ratio') as HTMLInputElement).click(); }); await preflight(); await flush(() => reply(request('/api/v2/hypotheses/h1'), { hypothesis: hypothesis() })); expect(post().body).toEqual({ kind: 'finding', title: 'Exact finding', body: 'Keep this narrative', contentOrigin: 'ai', hypothesisRevisionId: 'h1-revision', evidence: [ { runId: 'run', metricsVersion: 'canonical-analytics/v1', metricPath: 'analytics.metrics.totalReturn', strategyVersionId: 'frozen-version', }, { runId: 'run', metricsVersion: 'canonical-analytics/v1', metricPath: 'analytics.metrics.sharpeRatio', strategyVersionId: 'frozen-version', }, ], }); await flush(() => reply(post(), { artifact: acceptedFinding('h1-revision') }, 201)); expect(host.querySelector('a')?.getAttribute('href')).toBe( '/research/p1?artifact=saved-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', 'extra', 'foreign-run', 'foreign-version', 'missing-version', 'foreign-metric', 'legacy-metric', 'foreign-source', ] as const)('%s evidence acknowledgement freezes the single-run finding draft', async failure => { await mountDialog(); await draft(); await preflight(); const saved = acceptedFinding(); const reference = saved.latestRevision.evidence[0]!; switch (failure) { case 'empty': saved.latestRevision.evidence = []; break; case 'missing': delete (saved.latestRevision as Partial).evidence; break; case 'extra': saved.latestRevision.evidence.push({ ...reference, metricPath: 'analytics.fillCount' }); break; case 'foreign-run': reference.runId = 'another-run'; break; case 'foreign-version': reference.strategyVersionId = 'another-version'; break; case 'missing-version': reference.strategyVersionId = null; break; case 'foreign-metric': reference.metricPath = 'analytics.metrics.maxDrawdown'; break; case 'legacy-metric': reference.metricsVersion = 'legacy-display/v1'; reference.metricPath = 'metrics.totalReturn'; break; case 'foreign-source': saved.latestRevision.source = { kind: 'experiment/v1', experimentId: '22222222-2222-4222-8222-222222222222', previewHash: 'a'.repeat(64), }; break; } await flush(() => reply(post(), { artifact: saved }, 201)); expect(host.textContent).toContain('saved finding response could not be verified'); expect(host.textContent).toContain('Check saved records before creating another'); expect(host.textContent).not.toContain('Finding saved.'); expect(host.textContent).not.toContain('Open saved finding'); expect(field('Finding title').value).toBe('Exact finding'); expect(field('Finding body').value).toBe('Keep this narrative'); expect(field('Finding title').disabled).toBe(true); expect(button('Save finding').disabled).toBe(true); await flush(() => button('Save finding').click()); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); }); test.each(['omitted', 'null'] as const)( 'matching canonical evidence accepts %s aggregate source', async source => { await mountDialog(); await draft(); await preflight(); const saved = acceptedFinding(); if (source === 'omitted') { delete saved.latestRevision.source; } await flush(() => reply(post(), { artifact: saved }, 201)); expect(host.textContent).toContain('Finding saved.'); expect(host.querySelector('a')?.getAttribute('href')).toContain('artifact=saved-finding'); } ); test.each(['omitted', 'null'] as const)( 'legacy citations accept %s version without inferring one', async version => { await mountDialog(legacy()); await draft(); await preflight(); expect(host.textContent).toContain('Legacy · Unverified economics'); expect(post().body).toEqual({ kind: 'finding', title: 'Exact finding', body: 'Keep this narrative', contentOrigin: 'human', hypothesisRevisionId: null, evidence: [ { runId: 'run', metricsVersion: 'legacy-display/v1', metricPath: 'metrics.totalReturn' }, ], }); const saved = acceptedFinding(); if (version === 'null') { saved.latestRevision.evidence[0]!.strategyVersionId = null; } await flush(() => reply(post(), { artifact: saved }, 201)); expect(host.textContent).toContain('Finding saved.'); expect(host.textContent).toContain('Legacy · Unverified economics'); expect(host.querySelector('a[href*="/strategies/versions/"]')).toBeNull(); } ); test('late project and hypothesis responses cannot overwrite the current destination', async () => { await mountDialog(); await flush(() => edit('Finding project', 'p1')); const oldProject = request('/api/v2/research-projects/p1'); const oldHypotheses = request('/api/v2/research-projects/p1/hypotheses?includeArchived=false'); await destination('p2', [ hypothesis('h2', 'p2'), hypothesis('foreign', 'p1'), hypothesis('archived', 'p2', true), ]); await flush(() => edit('Finding hypothesis', 'h2-revision')); await flush(() => { reply(oldProject, { project: project('p1') }); reply(oldHypotheses, { hypotheses: [hypothesis()] }); }); expect(oldProject.signal?.aborted).toBe(true); expect(field('Finding project').value).toBe('p2'); expect(field('Finding hypothesis').value).toBe('h2-revision'); expect(field('Finding hypothesis').textContent).not.toContain('Hypothesis h1'); expect(field('Finding hypothesis').textContent).not.toContain('foreign'); expect(field('Finding hypothesis').textContent).not.toContain('archived'); await destination(); expect(field('Finding hypothesis').value).toBe(''); }); for (const status of [422, 409, 401]) { test(`${status} preserves the finding draft and never retries automatically`, async () => { await mountDialog(); await draft(); await preflight(); await flush(() => reply( post(), { error: status === 422 ? 'Saved evidence is incomplete' : 'Destination write rejected' }, status ) ); expect(field('Finding title').value).toBe('Exact finding'); expect(field('Finding body').value).toBe('Keep this narrative'); expect(host.querySelector('[role="alert"]')?.textContent).toContain( status === 422 ? 'incomplete' : 'rejected' ); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); expect(button('Save finding').disabled).toBe(false); }); } test('archived destination found during preflight denies any POST', async () => { await mountDialog(); await draft(); await flush(() => button('Save finding').click()); await flush(() => reply(request('/api/v2/research-projects/p1'), { project: project('p1', true) }) ); expect(button('Save finding').disabled).toBe(true); expect(host.textContent).toContain('destination project is archived'); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); expect(field('Finding title').value).toBe('Exact finding'); }); test('archived selected hypothesis cannot be cited by a new request', async () => { await mountDialog(); await draft(); await flush(() => edit('Finding hypothesis', 'h1-revision')); await preflight(); await flush(() => reply(request('/api/v2/hypotheses/h1'), { hypothesis: hypothesis('h1', 'p1', true) }) ); expect(host.textContent).toContain('selected hypothesis is archived'); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); }); for (const response of ['lost', '500', 'malformed'] as const) { test(`${response} create outcome freezes draft until explicit new request`, async () => { await mountDialog(); await draft(); await flush(() => { button('Save finding').click(); button('Save finding').click(); button('Close').click(); }); expect(closed).toBe(0); expect(requests.filter(item => item.path === '/api/v2/research-projects/p1')).toHaveLength(2); await flush(() => reply(request('/api/v2/research-projects/p1'), { project: project() })); const pending = post(); await flush(() => { if (response === 'lost') { pending.settled = true; pending.reject(new Error('Response lost')); } else if (response === '500') { reply(pending, { error: 'Server interrupted' }, 500); } else { reply(pending, {}, 201); } }); expect(host.textContent).toContain('Check saved records before creating another'); expect(button('Save finding').disabled).toBe(true); expect(field('Finding title').disabled).toBe(true); expect(field('Finding title').value).toBe('Exact finding'); expect(host.querySelector('a[target="_blank"]')?.getAttribute('href')).toBe('/research/p1'); await flush(() => button('Save finding').click()); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); await flush(() => button('Start new request').click()); expect(field('Finding title').disabled).toBe(false); expect(button('Save finding').disabled).toBe(false); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); }); } test('changing result identity resets draft and rejects a late create success', async () => { await mountDialog(); await draft(); await preflight(); const pending = post(); await render( createElement(SaveFindingDialog, { result: legacy('next-run'), onClose: () => { closed++; }, }) ); await flush(() => reply(pending, { artifact: artifact() }, 201)); expect(host.textContent).toContain('Run: next-run'); expect(field('Finding title').value).toBe(''); expect(field('Finding project').value).toBe(''); expect(host.textContent).not.toContain('Open saved finding'); }); test('changed result ignores late projects and unsaved close requires confirmation', async () => { await render( createElement(SaveFindingDialog, { result: legacy(), onClose: () => { closed++; }, }) ); const oldList = request('/api/v2/research-projects?includeArchived=false'); await render( createElement(SaveFindingDialog, { result: legacy('next-run'), onClose: () => { closed++; }, }) ); await flush(() => reply(oldList, { projects: [project('old')] })); expect(field('Finding project').textContent).not.toContain('Project old'); await flush(() => edit('Finding title', 'Keep draft')); Object.defineProperty(browser, 'confirm', { configurable: true, writable: true, value: () => false, }); await flush(() => button('Close').click()); expect(closed).toBe(0); Object.defineProperty(browser, 'confirm', { configurable: true, writable: true, value: () => true, }); await flush(() => button('Close').click()); expect(closed).toBe(1); }); test('project load failure is distinct from empty projects and can be retried', async () => { await render(createElement(SaveFindingDialog, { result: legacy(), onClose: () => {} })); await flush(() => reply( request('/api/v2/research-projects?includeArchived=false'), { error: 'Unavailable projects' }, 503 ) ); expect(host.textContent).toContain('Unavailable projects'); expect(host.textContent).not.toContain('No active research projects'); await flush(() => button('Retry projects').click()); await flush(() => reply(request('/api/v2/research-projects?includeArchived=false'), { projects: [] }) ); expect(host.textContent).toContain('No active research projects'); }); }); async function mountPage(status: Run['status'] = 'completed') { await render( createElement( router.Routes, null, createElement(router.Route, { path: '/backtests/:id/run/:runId', element: createElement(BacktestDetailPageV2), }) ), '/backtests/definition/run/run' ); await flush(() => { reply(request('/api/v2/backtests/definition'), { ...definition, archivedAt: '2026-10-23' }); reply(request('/api/v2/backtests/definition/runs'), []); reply(request('/api/v2/runs/run'), run('run', status)); }); } describe('backtest finding entry point', () => { test('archived backtest permits completed matching results and run navigation closes the dialog', async () => { await mountPage(); expect(button('Save finding').disabled).toBe(true); await flush(() => reply(request('/api/v2/runs/run/results'), legacy())); expect(button('Save finding').disabled).toBe(false); await flush(() => button('Save finding').click()); expect(host.querySelector('[role="dialog"]')).not.toBeNull(); const pending = request('/api/v2/research-projects?includeArchived=false'); await flush(() => navigate('/backtests/definition/run/next-run')); expect(host.querySelector('[role="dialog"]')).toBeNull(); await flush(() => reply(pending, { projects: [project()] })); expect(host.querySelector('[role="dialog"]')).toBeNull(); }); for (const source of ['missing', 'wrong-parent', 'wrong-run', 'cancelled'] as const) { test(`${source} results cannot open finding creation`, async () => { await mountPage(); await flush(() => reply( request('/api/v2/runs/run/results'), source === 'missing' ? { error: 'Missing results' } : { ...legacy(), ...(source === 'wrong-parent' ? { backtestId: 'foreign' } : source === 'wrong-run' ? { runId: 'foreign' } : { status: 'cancelled' }), }, source === 'missing' ? 404 : 200 ) ); expect(button('Save finding').disabled).toBe(true); await flush(() => button('Save finding').click()); expect(host.querySelector('[role="dialog"]')).toBeNull(); }); } test('failed runs have no usable evidence action', async () => { await mountPage('failed'); expect(button('Save finding').disabled).toBe(true); expect(requests.some(item => item.path.endsWith('/results'))).toBe(false); }); });