import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test'; import { GlobalWindow } from 'happy-dom'; import { createElement } from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import type { IServiceContainer } from '@stock-bot/services'; import type { ResearchArtifact, ResearchAuthorship, ResearchHypothesis, StrategyVersionSummary, } from '@stock-bot/types'; import { backtestResponseSchema, researchArtifactResponseSchema, researchHypothesisResponseSchema, researchProjectResponseSchema, runResponseSchema, strategyVersionResponseSchema, type RunResponse, } from '../../apps/stock/config/src/contracts/product-responses'; import { builtinCatalogDescriptors } from '../../apps/stock/config/src/contracts/strategy'; import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes'; import { createStrategyRoutes } from '../../apps/stock/web-api/src/routes/strategies.routes'; import { mapBacktest, mapRun } from '../../apps/stock/web-api/src/services/backtests/mapping'; import { RunControlsCompact } from '../../apps/stock/web-app/src/features/backtest/components/RunControlsCompact'; const browser = new GlobalWindow({ url: 'http://localhost:5173' }); const original = Object.getOwnPropertyDescriptor(globalThis, 'window'); let backtest: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'); let research: typeof import('../../apps/stock/web-app/src/features/research/services/researchApi'); let strategies: typeof import('../../apps/stock/web-app/src/features/strategies/services/strategyApi'); beforeAll(async () => { Object.defineProperty(globalThis, 'window', { value: browser, configurable: true }); backtest = await import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'); research = await import('../../apps/stock/web-app/src/features/research/services/researchApi'); strategies = await import( '../../apps/stock/web-app/src/features/strategies/services/strategyApi' ); }); beforeEach(() => { Object.defineProperty(globalThis, 'window', { value: browser, configurable: true }); }); afterAll(() => { if (original) { Object.defineProperty(globalThis, 'window', original); } else { Reflect.deleteProperty(globalThis, 'window'); } browser.happyDOM.abort(); }); const now = new Date('2026-10-28T14:32:00Z'); const backtestId = '11111111-1111-4111-8111-111111111111'; const runId = '22222222-2222-4222-8222-222222222222'; const row = { id: backtestId, name: 'Saved research', strategy: 'sma_crossover', symbols: ['AAPL.US'], start_date: now, end_date: new Date('2026-10-29'), initial_capital: '10000', config: {}, created_at: now, updated_at: now, archived_at: null, }; const run = () => mapRun({ id: runId, backtest_id: backtestId, run_number: 1, status: 'running', speed_multiplier: null, error: null, started_at: now, completed_at: null, paused_at: null, progress: '12.5', current_simulation_date: now, created_at: now, updated_at: now, cancel_requested: false, attempt_number: 1, }); function respond(body: unknown, status = 200) { const fetch = mock(async (_input: unknown, _init?: RequestInit) => status === 204 ? new Response(null, { status }) : Response.json(body, { status }) ); browser.fetch = fetch as unknown as typeof browser.fetch; return fetch; } test('historical templates with SQL-null configuration remain readable without rewriting them', async () => { const mapped = mapBacktest({ ...row, config: null }); const wire = JSON.parse(JSON.stringify(mapped)); expect(backtestResponseSchema.parse(wire).config).toBeNull(); respond(mapped); expect((await backtest.backtestApiV2.getBacktest(backtestId)).config).toBeNull(); }); test('real server backtest/run mappings survive JSON serialization and display the server clock field', async () => { const mapped = mapBacktest(row); respond(mapped); const saved = await backtest.backtestApiV2.getBacktest(backtestId); expect(saved).toEqual(backtestResponseSchema.parse(await Response.json(mapped).json())); expect(saved.initialCapital).toBe(10000); expect(saved.startDate).toBe(now.toISOString()); expect(saved.archivedAt).toBeNull(); respond(run()); const savedRun = await backtest.backtestApiV2.getRun(runId); expect(savedRun.currentDate).toBe(now.toISOString()); expect(savedRun.progress).toBe(12.5); expect(savedRun.completedAt).toBeNull(); expect(savedRun.dataset?.state).toBe('unknown'); const noop = () => {}; const html = renderToStaticMarkup( createElement(RunControlsCompact, { run: savedRun, cancelRequested: false, onCancel: noop, onRerun: noop, }) ); expect(html).toContain('Running'); expect(html).toContain('13%'); }); test('existing optional fields remain optional without accepting malformed rendered fields', async () => { const legacy: RunResponse = { id: 'old-run', backtestId: 'old-template', runNumber: 1, status: 'completed', speedMultiplier: null, progress: 100, createdAt: '2024-01-01', updatedAt: '2024-01-01', }; expect(runResponseSchema.parse(legacy)).toEqual(legacy); const serialized = await Response.json(mapBacktest(row)).json(); for (const bad of [ { ...serialized, symbols: 'AAPL' }, { ...serialized, initialCapital: '10000' }, { ...serialized, config: [] }, ]) { respond(bad); await expect(backtest.backtestApiV2.getBacktest(backtestId)).rejects.toThrow( 'could not be verified' ); } for (const bad of [ { ...legacy, progress: '100' }, { ...legacy, runNumber: null }, { ...legacy, currentDate: 'not a date' }, ]) { respond(bad); await expect(backtest.backtestApiV2.getRun('old-run')).rejects.toThrow('could not be verified'); } }); test('strategy and research records roundtrip from actual routes through browser clients', async () => { const databaseRow = { ...row, title: 'Research project', description: 'Unvalidated narrative', revision: 1, owner_principal: 'operator', updated_by: 'operator', }; const container = { postgres: { query: async () => ({ rows: [databaseRow] }) }, logger: { error: () => {} }, } as unknown as IServiceContainer; const researchRoutes = createResearchRoutes(container); browser.fetch = ((input: unknown, init?: RequestInit) => researchRoutes.request(String(input), init)) as unknown as typeof browser.fetch; const projects = await research.researchApi.listProjects(); expect(projects.projects).toEqual([ researchProjectResponseSchema.parse({ id: backtestId, title: databaseRow.title, description: databaseRow.description, revision: 1, ownerPrincipal: 'operator', updatedBy: 'operator', archived: false, createdAt: now.toISOString(), updatedAt: now.toISOString(), }), ]); const catalogRoutes = createStrategyRoutes(container); browser.fetch = ((input: unknown, init?: RequestInit) => catalogRoutes.request(String(input), init)) as unknown as typeof browser.fetch; const catalog = await strategies.strategyApi.list(); expect(catalog.strategies[0]).toMatchObject({ id: backtestId, name: row.name, archived: false }); expect(catalog.strategies[0]?.createdAt).toBe(now.toISOString()); }); const authorship: ResearchAuthorship & { createdAt: string } = { submittedBy: 'operator', contentOrigin: 'human', createdAt: now.toISOString(), }; const record: Omit = { id: 'record', projectId: 'project', ownerPrincipal: 'operator', updatedBy: 'operator', archived: false, createdAt: now.toISOString(), updatedAt: now.toISOString(), }; const hypothesis: ResearchHypothesis = { ...record, latestRevision: { ...authorship, id: 'revision', hypothesisId: 'record', ordinal: 1, title: 'Hypothesis', proposition: 'Testable claim', validationCriteria: '', validationState: 'unvalidated', }, }; const artifact: ResearchArtifact = { ...record, kind: 'note', hypothesisRevisionId: null, latestRevision: { ...authorship, id: 'revision', artifactId: 'record', ordinal: 1, title: 'Notes', body: '', validationState: 'unvalidated', evidenceState: 'none', evidence: [], }, }; test('research parsers validate nested rendered fields and revision ownership, preserving legacy source omission', async () => { expect(researchHypothesisResponseSchema.parse(hypothesis)).toEqual(hypothesis); expect(researchArtifactResponseSchema.parse(artifact)).toEqual(artifact); for (const malformed of [ { ...artifact, latestRevision: { ...artifact.latestRevision, evidence: null } }, { ...artifact, latestRevision: { ...artifact.latestRevision, contentOrigin: 'verified' } }, { ...artifact, latestRevision: { ...artifact.latestRevision, artifactId: 'another' } }, { ...artifact, latestRevision: { ...artifact.latestRevision, source: {} } }, ]) { respond({ artifact: malformed }, 201); await expect( research.researchApi.createArtifact('project', { kind: 'note', title: 'Notes', body: '' }) ).rejects.toMatchObject({ ambiguous: true, status: null }); } respond({ projects: [{ id: 'project', title: 'Partial', revision: 1 }] }); await expect(research.researchApi.listProjects()).rejects.toBeInstanceOf( research.ResearchApiError ); }); test('catalog schema reuses retained parameter and package shapes without requiring a new execution declaration', async () => { const builtin = builtinCatalogDescriptors[0]!; const version: StrategyVersionSummary = { id: 'version', strategyId: 'family', ordinal: 1, parentVersionId: null, createdBy: 'operator', origin: 'builtin', createdAt: now.toISOString(), package: { version: 1, program: builtin.program, parameterSchema: builtin.parameterSchema, artifact: { format: 'esm-bundle/v1', entryExport: builtin.entryExport, sha256: 'a'.repeat(64), }, dependencyLock: { format: 'bun-lock/v1', sha256: 'b'.repeat(64) }, source: { revision: 'c'.repeat(40), dirty: false }, build: { tool: 'bun', version: '1.2.17', target: 'browser' }, }, reviewStatus: 'approved', runnable: false, reason: 'Explicit policy required', }; const parsed: StrategyVersionSummary = strategyVersionResponseSchema.parse(version); expect(parsed).toEqual(version); respond({ versions: [version] }); const catalog: { versions: StrategyVersionSummary[] } = await strategies.strategyApi.versions('family'); expect(catalog).toEqual({ versions: [version] }); respond({ versions: [{ ...version, package: { ...version.package, parameterSchema: {} } }] }); await expect(strategies.strategyApi.versions('family')).rejects.toThrow('could not be verified'); }); test('reproduction receipts preserve identity, status, idempotency key and no automatic write retry', async () => { const originalRunId = '33333333-3333-4333-8333-333333333333'; const accepted = { ...run(), originalRunId }; const fetch = respond(accepted, 202); const value = await backtest.backtestApiV2.reproduceRun(originalRunId, 'retained-key'); expect(value.id).toBe(runId); expect(fetch).toHaveBeenCalledTimes(1); expect(fetch.mock.calls[0]?.[1]).toMatchObject({ credentials: 'include', headers: { 'Idempotency-Key': 'retained-key' }, }); for (const [body, status] of [ [{ ...accepted, originalRunId: runId }, 202], [accepted, 200], [{ id: runId }, 202], ] as const) { const calls = respond(body, status); await expect( backtest.backtestApiV2.reproduceRun(originalRunId, 'retained-key') ).rejects.toMatchObject({ ambiguous: true, status: null }); expect(calls).toHaveBeenCalledTimes(1); } respond({ error: 'Review revoked' }, 409); await expect( backtest.backtestApiV2.reproduceRun(originalRunId, 'retained-key') ).rejects.toMatchObject({ ambiguous: false, status: 409, message: 'Review revoked' }); }); test('204 acknowledgements are accepted only where intended; cancellations remain acknowledged 202 writes', async () => { respond(null, 204); await expect(research.researchApi.linkStrategy('project', 'strategy')).resolves.toBeUndefined(); respond(null, 204); await expect(backtest.backtestApiV2.deleteBacktest(backtestId)).resolves.toBeUndefined(); respond({ message: 'Cancellation requested' }, 202); await expect(backtest.backtestApiV2.cancelRun(runId)).resolves.toBeUndefined(); const calls = respond({}, 202); await expect(backtest.backtestApiV2.cancelRun(runId)).rejects.toThrow('could not be verified'); expect(calls).toHaveBeenCalledTimes(1); respond({}, 200); await expect(research.researchApi.linkStrategy('project', 'strategy')).rejects.toMatchObject({ ambiguous: true, }); }); test('all shared transports preserve abort causes and classify lost research writes as ambiguous without retries', async () => { const controller = new AbortController(); controller.abort(); const cause = new DOMException('Cancelled', 'AbortError'); const fetch = mock(async () => { throw cause; }); browser.fetch = fetch as unknown as typeof browser.fetch; await expect(backtest.backtestApiV2.getRun(runId, controller.signal)).rejects.toBe(cause); await expect(strategies.strategyApi.list(controller.signal)).rejects.toBe(cause); await expect(research.researchApi.listProjects(false, controller.signal)).rejects.toBe(cause); await expect( research.researchApi.createProject({ title: 'Potentially saved' }) ).rejects.toMatchObject({ ambiguous: true, status: null }); expect(fetch).toHaveBeenCalledTimes(4); });