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 { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research'; import type { ChronologicalValidationDetail, ChronologicalValidationPreview, ValidationResultEvidence, } from '@stock-bot/stock-config/chronological-validation'; import { costSensitivityInputSchema, type CostSensitivityDetail, type CostSensitivityPreview, } from '@stock-bot/stock-config/cost-sensitivity'; import type { ExperimentDetail, ExperimentPreview, ExperimentTrial, } from '@stock-bot/stock-config/experiments'; import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy'; import { walkForwardPolicy, type WalkForwardDetail, type WalkForwardPreview, } from '@stock-bot/stock-config/walk-forward'; import type { ResearchArtifact, ResearchFindingSource, ResearchHypothesis, ResearchProject, } from '@stock-bot/types'; import { buildExperimentPreview } from '../../apps/stock/web-api/src/services/experiment-input'; import { prepareChronologicalValidation } from '../../apps/stock/web-api/src/services/validation-preview'; import type { FindingDraftSource } from '../../apps/stock/web-app/src/features/research/components/findingSources'; import type { ArtifactInput } from '../../apps/stock/web-app/src/features/research/services/researchApi'; import { nativeReplayFixture } from '../fixtures/native-replay'; import { walkForwardDataset } from '../fixtures/walk-forward'; 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 SaveSourceFindingDialog: typeof import('../../apps/stock/web-app/src/features/research/components/SaveFindingDialog').SaveSourceFindingDialog; let ResearchEntry: typeof import('../../apps/stock/web-app/src/features/research/components/ResearchEntry').ResearchEntry; let researchApi: typeof import('../../apps/stock/web-app/src/features/research/services/researchApi').researchApi; let sources: typeof import('../../apps/stock/web-app/src/features/research/components/findingSources'); let ExperimentDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments/ExperimentDetailPage').ExperimentDetailPage; let ChronologicalValidationDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage').ChronologicalValidationDetailPage; let WalkForwardDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments/WalkForwardDetailPage').WalkForwardDetailPage; let parseExperiment: typeof import('../../apps/stock/web-app/src/features/experiments/services/experimentApi').parseWorkbenchExperimentDetail; let parseValidation: typeof import('../../apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi').parseValidationDetail; let parseWalk: typeof import('../../apps/stock/web-app/src/features/experiments/services/walkForwardApi').parseWalkForwardDetail; 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', }, }); 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 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 }); } ({ parseWorkbenchExperimentDetail: parseExperiment } = await import( '../../apps/stock/web-app/src/features/experiments/services/experimentApi' )); ({ parseValidationDetail: parseValidation } = await import( '../../apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi' )); ({ parseWalkForwardDetail: parseWalk } = await import( '../../apps/stock/web-app/src/features/experiments/services/walkForwardApi' )); ({ createRoot } = await import('react-dom/client')); router = await import('react-router-dom'); ({ SaveSourceFindingDialog } = await import( '../../apps/stock/web-app/src/features/research/components/SaveFindingDialog' )); ({ ResearchEntry } = await import( '../../apps/stock/web-app/src/features/research/components/ResearchEntry' )); ({ researchApi } = await import( '../../apps/stock/web-app/src/features/research/services/researchApi' )); sources = await import( '../../apps/stock/web-app/src/features/research/components/findingSources' ); ({ ExperimentDetailPage } = await import( '../../apps/stock/web-app/src/features/experiments/ExperimentDetailPage' )); ({ ChronologicalValidationDetailPage } = await import( '../../apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage' )); ({ WalkForwardDetailPage } = await import( '../../apps/stock/web-app/src/features/experiments/WalkForwardDetailPage' )); }); 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); } } }); const backtestId = '11111111-1111-4111-8111-111111111111'; const versionId = '55555555-5555-4555-8555-555555555555'; const seriesId = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee'; function sourcePreview(count = 2, parent = backtestId): ExperimentPreview { const owner = `strategy:${versionId}`; const { config } = nativeReplayFixture(72, 1, [owner]); const { dataset } = walkForwardDataset(); const previewId = '00000000-0000-4000-8000-000000000001'; config.matching.risk.ledger.sessionId = previewId; config.matching.risk.ledger.accountId = `research:${previewId}`; const builtin = builtinCatalogDescriptors[0]!; const candidates = Array.from({ length: count }, (_, index) => ({ index, trialKey: String(index + 1).padStart(64, '0'), parameters: { fastPeriod: index + 2, slowPeriod: 4 }, })); const source: ExperimentPreview = { version: 'research-experiment-preview/v1', previewHash: 'e'.repeat(64), input: { backtestId: parent, name: 'Trend study', grid: { fastPeriod: candidates.map(item => item.parameters.fastPeriod) }, }, dataset: dataset.manifest, candidates, request: canonicalRunRequestSchema.parse({ kind: 'canonical-research/v1', runId: previewId, backtestId: parent, name: 'Frozen template name', strategy: { familyId: '66666666-6666-4666-8666-666666666666', versionId, origin: 'builtin', reviewId: '88888888-8888-4888-8888-888888888888', package: { version: 1, program: builtin.program, parameterSchema: builtin.parameterSchema, artifact: { format: 'esm-bundle/v1', entryExport: builtin.entryExport, content: 'Never execute fixture code', sha256: 'a'.repeat(64), }, dependencyLock: { format: 'bun-lock/v1', content: 'Retained lock', sha256: 'b'.repeat(64), }, source: { revision: 'c'.repeat(40), dirty: false }, build: { tool: 'bun', version: '1.2.17', target: 'browser' }, }, selection: { strategyId: builtin.program.strategyId, strategyVersion: builtin.program.strategyVersion, ownerId: owner, seed: 17, instrumentId: 'X0.US', seriesId: 'X0.US:1m', ownerBudget: '100', parameters: { fastPeriod: 2, slowPeriod: 4 }, }, }, datasetHash: dataset.manifest.hash, policy: config, analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null }, build: { version: 1, workerSha256: 'a'.repeat(64), engineWrapperSha256: 'b'.repeat(64), engineBinarySha256: 'c'.repeat(64), dependencyLockSha256: 'd'.repeat(64), runtime: 'bun', runtimeVersion: '1.2.17', platform: 'linux', arch: 'x64', }, modelArtifacts: [], }), }; return buildExperimentPreview(source.input, source.request, source.dataset); } function metrics(): NonNullable { return { totalReturn: 0, cagr: null, maxDrawdown: 0, exposureTime: 0, volatility: null, downsideDeviation: null, sharpeRatio: null, sortinoRatio: null, var95: null, cvar95: null, var99: null, alpha: null, beta: null, informationRatio: null, roundTripCount: null, winRate: null, profitFactor: null, avgWin: null, avgLoss: null, }; } function prepared(): WalkForwardPreview { const source = sourcePreview(), fixture = walkForwardDataset(); const input = { ...source.input, windows: fixture.windows }; return { version: 'walk-forward-preview/v1', execution: 'preview-only', previewHash: 'f'.repeat(64), input, source, policy: walkForwardPolicy, windows: input.windows.map((recipe, index) => { const windowSource = buildExperimentPreview( { ...source.input, name: `${input.name} · window ${index + 1}` }, source.request, source.dataset ); return { index, preview: prepareChronologicalValidation( { ...windowSource.input, recipe }, windowSource, fixture.dataset ).preview, }; }), counts: { windows: 2, trainingRuns: 4, holdoutRuns: 4, totalRuns: 8, maxRuns: 100 }, }; } const id = (number: number) => `99999999-9999-4999-8999-${String(number).padStart(12, '0')}`; function memberDocument( preview: ChronologicalValidationPreview, index: number, sealed: boolean ): ChronologicalValidationDetail { const base = 100 * (index + 1), winner = preview.source.candidates[1]!; const phaseIds = { train: id(base), validation: id(base + 1), test: id(base + 2) }; const experiments = preview.partitions.map((part, phaseIndex): ExperimentDetail => { const candidates = phaseIndex === 0 ? preview.source.candidates : [{ ...winner, index: 0 }], request = structuredClone(part.request); if (phaseIndex !== 0) { request.strategy.selection.parameters = winner.parameters as never; } const input = { ...preview.source.input, name: `${preview.input.name} · ${part.phase}`, grid: phaseIndex === 0 ? preview.input.grid : {}, }; const childPreview: ExperimentPreview = { version: 'research-experiment-preview/v1', previewHash: String(phaseIndex + 1).repeat(64), input, request, dataset: part.dataset, candidates, }; const trials: ExperimentTrial[] = candidates.map((candidate, trialIndex) => ({ ...candidate, runId: id(base + 10 + phaseIndex * 10 + trialIndex), attemptNumber: sealed ? 1 : 0, retryCount: 0, status: sealed ? 'completed' : 'pending', progress: sealed ? 100 : 0, cancelRequested: false, error: null, comparable: sealed, diagnostic: null, metrics: sealed ? { ...metrics(), totalReturn: phaseIndex === 0 && trialIndex === 0 ? -0.1 : 0 } : null, unavailable: sealed ? { sharpeRatio: 'insufficient-periods' } : null, limitations: ['Reviewed fixture limitation.'], })); return { id: phaseIds[part.phase], name: input.name, backtestId, createdAt: '2026-10-24T10:00:00Z', cancelRequested: false, trialCount: trials.length, counts: { pending: sealed ? 0 : trials.length, running: 0, paused: 0, completed: sealed ? trials.length : 0, failed: 0, cancelled: 0, }, datasetHash: part.dataset.hash, strategyVersionId: versionId, previewHash: childPreview.previewHash, preview: childPreview, trials, }; }); const evidence = (phaseIndex: number, trialIndex: number): ValidationResultEvidence => { const experiment = experiments[phaseIndex]!, trial = experiment.trials[trialIndex]!; return { phase: preview.partitions[phaseIndex]!.phase, experimentId: experiment.id, runId: trial.runId!, sourceCandidateIndex: phaseIndex === 0 ? trialIndex : 1, trialKey: trial.trialKey, parameters: trial.parameters, datasetHash: experiment.datasetHash, requestHash: 'b'.repeat(64), economicHash: 'c'.repeat(64), metrics: trial.metrics!, unavailable: trial.unavailable!, completePeriodCount: 1, periodicSampleCount: 1, fillCount: 0, limitations: trial.limitations, }; }; const selection = sealed ? { version: 'chronological-validation-selection/v1' as const, id: id(base + 3), validationId: phaseIds.train, previewHash: preview.previewHash, selectionHash: 'd'.repeat(64), createdAt: '2026-10-24T11:00:00Z', principal: 'operator' as const, reviewId: preview.source.request.strategy.reviewId, winner, training: experiments[0]!.trials.map((_, i) => evidence(0, i)), holdoutExperimentIds: { validation: phaseIds.validation, test: phaseIds.test }, } : null; return { id: phaseIds.train, name: preview.input.name, backtestId, createdAt: experiments[0]!.createdAt, cancelRequested: false, previewHash: preview.previewHash, trainingCandidateCount: 2, stage: sealed ? 'reported' : 'training', preview, phases: preview.partitions.map((part, i) => ({ phase: part.phase, status: i === 0 || sealed ? 'admitted' : 'not-admitted', experimentId: i === 0 || sealed ? experiments[i]!.id : null, experiment: i === 0 || sealed ? experiments[i]! : null, })) as ChronologicalValidationDetail['phases'], selection, report: sealed ? { version: 'chronological-validation-report/v1', id: id(base + 4), validationId: phaseIds.train, previewHash: preview.previewHash, selectionHash: selection!.selectionHash, reportHash: 'e'.repeat(64), createdAt: '2026-10-24T12:00:00Z', principal: 'operator', reset: 'initial-capital-empty-positions', training: selection!.training, validation: evidence(1, 0), test: evidence(2, 0), limitations: ['Independent reset accounts.'], } : null, actions: { select: { available: false, reason: sealed ? null : 'Every training candidate must complete.', }, finalize: { available: false, reason: sealed ? null : 'Waiting for holdout evidence.' }, }, }; } function walkDocument(stage: 'training' | 'ready' | 'reported' = 'training'): WalkForwardDetail { const preview = prepared(), members = preview.windows.map(item => memberDocument(item.preview, item.index, stage !== 'training') ); return { id: seriesId, backtestId, name: preview.input.name, previewHash: preview.previewHash, createdAt: '2026-10-24T10:00:00Z', cancelRequested: false, windowCount: 2, reportedWindowCount: stage === 'training' ? 0 : 2, trainingRunCount: 4, plannedRunCount: 8, stage: stage === 'reported' ? 'reported' : 'windows', preview, windows: members.map((validation, index) => ({ index, validationId: validation.id, status: 'admitted', validation, })), report: stage === 'reported' ? { version: 'walk-forward-report/v1', id: id(999), walkForwardId: seriesId, previewHash: preview.previewHash, reportHash: 'a'.repeat(64), createdAt: '2026-10-24T13:00:00Z', principal: 'operator', reset: 'initial-capital-empty-positions', segments: members.map((member, index) => ({ index, validationId: member.id, previewHash: member.previewHash, selectionHash: member.report!.selectionHash, reportId: member.report!.id, reportHash: member.report!.reportHash, validation: member.report!.validation, test: member.report!.test, })), limitations: ['No compounding or averaged metrics.'], } : null, actions: { finalize: { available: stage === 'ready', reason: stage === 'training' ? 'Every window requires a complete immutable report.' : null, }, }, }; } function costPreview(): CostSensitivityPreview { const source = sourcePreview(1); source.input.grid = {}; const input = costSensitivityInputSchema.parse({ backtestId, name: source.input.name, scenarios: [{ feeRate: '0.01', slippageRate: '0.02' }], }); return { version: 'cost-sensitivity-preview/v1', previewHash: 'b'.repeat(64), input, source, request: structuredClone(source.request), dataset: structuredClone(source.dataset), candidates: [ { feeRate: source.request.policy.matching.risk.feeRate, slippageRate: source.request.policy.matching.slippageRate, }, ...input.scenarios, ].map((costs, index) => ({ index, trialKey: String(index + 11).padStart(64, '0'), parameters: { ...source.request.strategy.selection.parameters }, costs, })), }; } function standalone( cost = false, statuses: ExperimentTrial['status'][] = ['completed', 'completed'] ): ExperimentDetail | CostSensitivityDetail { const base = sourcePreview(Math.min(statuses.length, 2)); const preview = cost ? costPreview() : statuses.length > 2 ? buildExperimentPreview( { ...base.input, grid: { slowPeriod: statuses.map((_, index) => index + 20) } }, base.request, base.dataset ) : base; const trials = preview.candidates.map((candidate, index) => ({ ...structuredClone(candidate), runId: statuses[index] === 'missing' ? null : id(index + 700), attemptNumber: 0, retryCount: 0, status: statuses[index]!, progress: statuses[index] === 'completed' ? 100 : 0, cancelRequested: false, comparable: statuses[index] === 'completed', error: statuses[index] === 'failed' ? 'Recorded trial failed' : null, diagnostic: statuses[index] === 'missing' ? 'Expected run missing' : null, metrics: statuses[index] === 'completed' ? metrics() : null, unavailable: statuses[index] === 'completed' ? { sharpeRatio: 'insufficient-periods' } : null, limitations: [], })); return { id: id(777), backtestId, kind: cost ? 'cost-sensitivity' : 'parameters', standalone: true, name: preview.input.name, previewHash: preview.previewHash, datasetHash: preview.request.datasetHash, strategyVersionId: versionId, createdAt: '2026-10-24T14:00:00Z', cancelRequested: false, trialCount: trials.length, counts: { pending: 0, running: 0, paused: 0, completed: 0, failed: 0, cancelled: 0, ...Object.fromEntries( ['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'].map(status => [ status, trials.filter(item => item.status === status).length, ]) ), }, preview, trials, } as ExperimentDetail | CostSensitivityDetail; } async function mountSource(source: FindingDraftSource) { await render( createElement(SaveSourceFindingDialog, { source, onClose: () => { closed++; }, }) ); await flush(() => reply(request('/api/v2/research-projects?includeArchived=false'), { projects: [project(), project('p2')], }) ); } function sourceFor(value = standalone()) { return sources.experimentFindingSource(parseExperiment(value))!; } function savedArtifact(body: ArtifactInput): ResearchArtifact { const value = artifact(); value.latestRevision.source = body.source ?? null; value.latestRevision.evidence = (body.evidence ?? []).map(reference => ({ ...reference, backtestId, value: reference.metricPath.endsWith('sharpeRatio') ? null : 0, unit: 'fraction', availability: reference.metricPath.endsWith('sharpeRatio') ? 'unavailable' : 'available', unavailableReason: reference.metricPath.endsWith('sharpeRatio') ? 'insufficient-periods' : null, resultKind: 'canonical', financialEngine: 'rust', datasetHash: 'a'.repeat(64), limitations: [], })); return value; } function metric(runId: string, metricPath = 'analytics.metrics.totalReturn') { const input = host.querySelector( `input[data-run-id="${runId}"][data-metric-path="${metricPath}"]` ); if (!input) { throw new Error(`Missing ${runId} ${metricPath}`); } return input; } function link(label: string) { const item = [...host.querySelectorAll('a')].find(item => item.textContent?.trim() === label); if (!item) { throw new Error(`Missing ${label}`); } return item; } async function showPage( kind: 'experiment' | 'chrono' | 'walk', value: | ExperimentDetail | CostSensitivityDetail | ChronologicalValidationDetail | WalkForwardDetail ) { const path = kind === 'experiment' ? '/experiments' : kind === 'chrono' ? '/experiments/validation' : '/experiments/walk-forward'; const parameter = kind === 'experiment' ? 'experimentId' : kind === 'chrono' ? 'validationId' : 'walkForwardId'; const page = kind === 'experiment' ? ExperimentDetailPage : kind === 'chrono' ? ChronologicalValidationDetailPage : WalkForwardDetailPage; await render( createElement( router.Routes, null, createElement(router.Route, { path: `${path}/:${parameter}`, element: createElement(page) }) ), `${path}/${value.id}` ); await flush(() => reply(request(`/api/v2${path}/${value.id}`), { [kind === 'experiment' ? 'experiment' : kind === 'chrono' ? 'validation' : 'walkForward']: value, }) ); } describe('source-linked finding selection', () => { test.each([false, true])( 'parameter/cost=%s offers exactly three metrics per eligible run and submits references only', async cost => { const value = standalone(cost); const source = sourceFor(value); await mountSource(source); await draft(); expect(host.querySelectorAll('input[type="checkbox"]')).toHaveLength(6); expect(host.querySelectorAll('input:checked')).toHaveLength(0); expect(button('Save finding').disabled).toBe(true); expect(host.textContent).toContain('insufficient-periods'); expect(host.textContent).toContain('Sharpe Ratio (ratio) · Unavailable'); expect(host.textContent).toContain('Total Return (fraction) · 0'); await flush(() => { metric(id(700)).click(); metric(id(701), 'analytics.metrics.sharpeRatio').click(); }); await preflight(); const body = post().body as ArtifactInput; expect(body.source).toEqual(source.context); expect(body.evidence).toEqual([ { runId: id(700), strategyVersionId: versionId, metricsVersion: 'canonical-analytics/v1', metricPath: 'analytics.metrics.totalReturn', }, { runId: id(701), strategyVersionId: versionId, metricsVersion: 'canonical-analytics/v1', metricPath: 'analytics.metrics.sharpeRatio', }, ]); expect(JSON.stringify(body)).not.toContain('value'); await flush(() => reply(post(), { artifact: savedArtifact(body) }, 201)); expect(host.textContent).toContain('Finding saved. Its narrative remains unvalidated.'); expect(link('Open cited source').getAttribute('href')).toBe(`/experiments/${value.id}`); expect(link('Open saved finding').getAttribute('href')).toContain('?artifact=saved-finding'); } ); test('all original noneligible outcomes remain visible without selectable metrics', async () => { const value = standalone(false, [ 'completed', 'pending', 'running', 'paused', 'failed', 'cancelled', 'missing', 'completed', ]); const bad = value.trials[7]!; bad.comparable = false; bad.diagnostic = 'Result identity mismatch'; await mountSource(sourceFor(value)); expect(host.querySelectorAll('fieldset')).toHaveLength(8); expect(host.querySelectorAll('input[type="checkbox"]')).toHaveLength(3); for (const text of [ 'pending', 'running', 'paused', 'failed', 'cancelled', 'missing', 'incomparable', 'Recorded trial failed', 'Result identity mismatch', ]) { expect(host.textContent).toContain(text); } }); test('chronological choices include every training candidate followed by validation/test; series only published segments', async () => { const series = walkDocument('reported'); const member = series.windows[0]!.validation!; const chronological = sources.chronologicalFindingSource(parseValidation(member))!; expect(chronological.runs.map(run => run.label)).toEqual([ 'train candidate 1', 'train candidate 2', 'validation candidate 2', 'test candidate 2', ]); expect(chronological.context).toEqual({ kind: 'chronological-report/v1', validationId: member.id, previewHash: member.previewHash, reportId: member.report!.id, reportHash: member.report!.reportHash, }); const source = sources.walkForwardFindingSource(parseWalk(series))!; expect(source.runs.map(run => run.label)).toEqual([ 'Window 1 validation candidate 2', 'Window 1 test candidate 2', 'Window 2 validation candidate 2', 'Window 2 test candidate 2', ]); await mountSource(source); await draft(); await flush(() => { metric(series.report!.segments[0]!.validation.runId).click(); metric(series.report!.segments[1]!.test.runId, 'analytics.metrics.sharpeRatio').click(); }); await preflight(); const body = post().body as ArtifactInput; expect(body.source).toEqual(source.context); expect(body.evidence?.map(item => item.runId)).toEqual([ series.report!.segments[0]!.validation.runId, series.report!.segments[1]!.test.runId, ]); await flush(() => reply(post(), { artifact: savedArtifact(body) }, 201)); expect(link('Open cited source').getAttribute('href')).toBe( `/experiments/walk-forward/${series.id}` ); }); test('same source refresh cannot alter open-time metrics or selectable run set', async () => { const first = sourceFor(); await mountSource(first); await draft(); await flush(() => metric(id(700)).click()); const changed = structuredClone(first); changed.runs[0]!.metrics[0]!.value = 99; changed.runs[1]!.metrics = []; await render( createElement(SaveSourceFindingDialog, { source: changed, onClose: () => { closed++; }, }) ); expect(host.textContent).not.toContain('Total Return (fraction) · 99'); expect(host.querySelectorAll('input[type="checkbox"]')).toHaveLength(6); expect(field('Finding title').value).toBe('Exact finding'); await preflight(); expect((post().body as ArtifactInput).evidence?.[0]?.runId).toBe(id(700)); }); test('source identity changes reset the form and ignore late accepted results', async () => { await mountSource(sourceFor()); await draft(); await flush(() => metric(id(700)).click()); await preflight(); const old = post(); const changed = sourceFor(); changed.context = { kind: 'experiment/v1', experimentId: id(888), previewHash: 'c'.repeat(64) }; changed.key = JSON.stringify(changed.context); await render( createElement(SaveSourceFindingDialog, { source: changed, onClose: () => { closed++; }, }) ); await flush(() => reply(old, { artifact: savedArtifact(old.body as ArtifactInput) }, 201)); expect(field('Finding title').value).toBe(''); expect(host.textContent).not.toContain('Finding saved.'); expect(host.textContent).toContain(id(888)); }); test.each(['network', 'malformed', 'foreign-source', 'foreign-evidence'] as const)( '%s accepted response ambiguity freezes exactly one submission until explicit inspection', async failure => { await mountSource(sourceFor()); await draft(); await flush(() => metric(id(700)).click()); await preflight(); const current = post(); await flush(() => { if (failure === 'network') { current.settled = true; current.reject(new Error('Lost response')); return; } if (failure === 'malformed') { reply(current, { artifact: { id: 'bad' } }, 201); return; } const saved = savedArtifact(current.body as ArtifactInput); if (failure === 'foreign-source') { saved.latestRevision.source = { kind: 'experiment/v1', experimentId: id(888), previewHash: 'd'.repeat(64), }; } else { saved.latestRevision.evidence[0]!.runId = id(999); } reply(current, { artifact: saved }, 201); }); expect(host.textContent).toContain('previous request may already'); expect(button('Save finding').disabled).toBe(true); expect(field('Finding title').value).toBe('Exact finding'); expect(link('Check saved records').target).toBe('_blank'); await flush(() => button('Save finding').click()); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); } ); test('new source with no selectable metrics stays disabled and preserves actual statuses', async () => { await mountSource(sourceFor(standalone(false, ['failed', 'missing']))); await draft(); expect(button('Save finding').disabled).toBe(true); expect(host.querySelectorAll('input[type="checkbox"]')).toHaveLength(0); }); }); describe('workbench source actions and unavailable regimes', () => { test.each([false, true])( 'standalone cost=%s stays readable without research API until action opens', async cost => { const value = standalone(cost); await showPage('experiment', value); expect(host.textContent).toContain('Regime evidence unavailable'); expect(host.textContent).toContain('window coverage are unavailable'); expect(requests).toHaveLength(1); expect(button('Save research finding').disabled).toBe(false); await flush(() => button('Save research finding').click()); expect(request('/api/v2/research-projects?includeArchived=false')).toBeDefined(); await flush(() => reply( request('/api/v2/research-projects?includeArchived=false'), { error: 'Research API unavailable' }, 503 ) ); expect(host.textContent).toContain('Research API unavailable'); expect(button('Retry projects')).toBeDefined(); expect(requests.some(item => item.path.includes('/analytics/'))).toBe(false); } ); test.each([undefined, false])( 'absent/phase standalone=%s fails closed despite eligible trials', async flag => { const value = standalone(); value.standalone = flag; await showPage('experiment', value); expect(button('Save research finding').disabled).toBe(true); expect(host.textContent).toContain('explicitly standalone'); expect(requests).toHaveLength(1); } ); test('page refresh retains an active finding snapshot and owned navigation refuses discard', async () => { const value = standalone(); await showPage('experiment', value); await flush(() => button('Save research finding').click()); await flush(() => reply(request('/api/v2/research-projects?includeArchived=false'), { projects: [project()] }) ); await draft(); await flush(() => metric(id(700)).click()); const changed = structuredClone(value); changed.trials[0]!.metrics!.totalReturn = 99; await flush(() => button('Refresh experiment').click()); await flush(() => reply(request(`/api/v2/experiments/${value.id}`), { experiment: changed })); const dialog = host.querySelector('[aria-label="Save finding"]')!; expect(dialog.textContent).not.toContain('Total Return (fraction) · 99'); expect(field('Finding title').value).toBe('Exact finding'); let prompts = 0; Object.defineProperty(browser, 'confirm', { configurable: true, value: () => { prompts++; return false; }, }); await flush(() => link('All experiments').click()); expect(prompts).toBe(1); expect(field('Finding title').value).toBe('Exact finding'); }); test.each(['chrono', 'walk'] as const)( '%s without sealed report displays unavailable action without research reads', async kind => { const series = walkDocument('training'); const value = kind === 'walk' ? series : series.windows[0]!.validation!; await showPage(kind, value); expect(button('Save research finding').disabled).toBe(true); expect(host.textContent).toContain('Save the complete report'); expect(host.textContent).toContain('Regime evidence unavailable'); expect(requests).toHaveLength(1); } ); test.each(['chrono', 'walk'] as const)( '%s sealed report opens original evidence choices with exact source', async kind => { const series = walkDocument('reported'); const value = kind === 'walk' ? series : series.windows[0]!.validation!; await showPage(kind, value); expect(button('Save research finding').disabled).toBe(false); await flush(() => button('Save research finding').click()); expect(host.querySelectorAll('input[type="checkbox"]')).toHaveLength(12); expect(host.querySelector('[aria-label="Finding source"]')!.textContent).toContain( value.report!.reportHash ); expect( requests.some(item => item.method === 'POST' || item.path.includes('/analytics/')) ).toBe(false); } ); }); const noop = () => {}; async function entry( value: ResearchArtifact, revisionId: string | null = null, revisions = [value.latestRevision] ) { await render( createElement(ResearchEntry, { projectId: 'p1', id: value.id, kind: 'artifact', revisionId, archived: false, writeBlocked: '', hypotheses: [], onSelectRevision: noop, onRefresh: noop, onDirty: noop, }) ); await flush(() => { reply(request(`/api/v2/analysis-artifacts/${value.id}`), { artifact: value }); reply(request(`/api/v2/analysis-artifacts/${value.id}/revisions`), { revisions }); }); } describe('finding navigation and destination safety', () => { test('ambiguous page finding can inspect saved records in another tab without discarding the draft', async () => { const value = standalone(); await showPage('experiment', value); await flush(() => button('Save research finding').click()); await flush(() => reply(request('/api/v2/research-projects?includeArchived=false'), { projects: [project()] }) ); await draft(); await flush(() => metric(id(700)).click()); await preflight(); const pending = post(); await flush(() => { pending.settled = true; pending.reject(new Error('Response lost')); }); let prompts = 0; Object.defineProperty(browser, 'confirm', { configurable: true, value: () => { prompts++; return false; }, }); const event = new browser.MouseEvent('click', { bubbles: true, cancelable: true }); await flush(() => link('Check saved records').dispatchEvent(event as unknown as Event)); expect(prompts).toBe(0); expect(event.defaultPrevented).toBe(false); expect(field('Finding title').value).toBe('Exact finding'); expect(metric(id(700)).checked).toBe(true); expect(button('Save finding').disabled).toBe(true); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); }); test('unsaved close refusal preserves source choices and accepted close invokes caller once', async () => { await mountSource(sourceFor()); await draft(); await flush(() => metric(id(700)).click()); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); await flush(() => button('Close').click()); expect(closed).toBe(0); expect(metric(id(700)).checked).toBe(true); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true }); await flush(() => button('Close').click()); expect(closed).toBe(1); }); test('route replacement drops old source dialog and late accepted mutation cannot show success', async () => { const value = standalone(); await showPage('experiment', value); await flush(() => button('Save research finding').click()); await flush(() => reply(request('/api/v2/research-projects?includeArchived=false'), { projects: [project()] }) ); await draft(); await flush(() => metric(id(700)).click()); await preflight(); const old = post(); await flush(() => navigate(`/experiments/${id(888)}`)); const next = structuredClone(value); next.id = id(888); await flush(() => reply(request(`/api/v2/experiments/${id(888)}`), { experiment: next })); await flush(() => reply(old, { artifact: savedArtifact(old.body as ArtifactInput) }, 201)); expect(host.querySelector('[aria-label="Save finding"]')).toBeNull(); expect(host.textContent).not.toContain('Finding saved.'); }); test('archived destination preflight sends no POST and retains selected evidence', async () => { await mountSource(sourceFor()); await draft(); await flush(() => metric(id(700)).click()); await flush(() => { button('Save finding').click(); button('Save finding').click(); }); await flush(() => reply(request('/api/v2/research-projects/p1'), { project: project('p1', true) }) ); expect(host.textContent).toContain('archived'); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); expect(metric(id(700)).checked).toBe(true); expect(field('Finding title').value).toBe('Exact finding'); }); }); describe('source-linked historical research revisions', () => { test('selected historical revision displays its own source and exact report link, not latest', async () => { const value = artifact(); value.latestRevision.ordinal = 2; value.latestRevision.source = { kind: 'experiment/v1', experimentId: id(777), previewHash: 'e'.repeat(64), }; const old = { ...structuredClone(value.latestRevision), id: 'old-revision', ordinal: 1, source: { kind: 'chronological-report/v1' as const, validationId: id(100), previewHash: 'a'.repeat(64), reportId: id(104), reportHash: 'b'.repeat(64), }, }; await entry(value, old.id, [old, value.latestRevision]); expect(link('Open cited source').getAttribute('href')).toBe( `/experiments/validation/${id(100)}` ); expect(host.querySelector('[aria-label="Finding source"]')!.textContent).toContain(id(104)); expect(host.querySelector('[aria-label="Finding source"]')!.textContent).not.toContain(id(777)); }); test('narrative revision forwards source and existing metric references unchanged', async () => { const body: ArtifactInput = { kind: 'finding', title: 'Old', body: 'Old', evidence: [ { runId: id(700), strategyVersionId: versionId, metricsVersion: 'canonical-analytics/v1', metricPath: 'analytics.metrics.totalReturn', }, ], source: sourceFor().context, }; const value = savedArtifact(body); await entry(value); await flush(() => button('Edit latest revision').click()); await flush(() => button('Save new revision').click()); const pending = request(`/api/v2/analysis-artifacts/${value.id}/revisions`, 'POST'); expect((pending.body as ArtifactInput).source ?? null).toEqual(body.source ?? null); expect((pending.body as ArtifactInput).evidence ?? []).toEqual(body.evidence ?? []); }); test.each(['extra', 'bad-id', 'bad-hash', 'unknown-kind'] as const)( 'new source decoder rejects %s on latest and history envelopes', async problem => { const source: Record = { kind: 'experiment/v1', experimentId: id(777), previewHash: 'a'.repeat(64), }; if (problem === 'extra') { source.extra = true; } if (problem === 'bad-id') { source.experimentId = 'bad'; } if (problem === 'bad-hash') { source.previewHash = 'bad'; } if (problem === 'unknown-kind') { source.kind = 'unsupported'; } const value = artifact(); value.latestRevision.source = source as ResearchFindingSource; const load = researchApi.getArtifact(value.id); reply(request(`/api/v2/analysis-artifacts/${value.id}`), { artifact: value }); await expect(load).rejects.toThrow('could not be read'); const history = researchApi.artifactRevisions(value.id); reply(request(`/api/v2/analysis-artifacts/${value.id}/revisions`), { revisions: [value.latestRevision], }); await expect(history).rejects.toThrow('could not be read'); } ); });