diff --git a/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx b/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx index 917ae900..5f8e4468 100644 --- a/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx +++ b/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx @@ -3,7 +3,7 @@ import { Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'rec import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research'; import type { CanonicalMetrics } from '@stock-bot/types'; import { actionClass } from '@/features/strategies/components/StrategyParameterForm'; -import { downloadJsonText } from '../services/downloadJsonText'; +import { downloadJsonText } from '@/utils/downloadJsonText'; import { DatasetDownload } from './DatasetDownload'; const tableClass = 'w-full text-sm text-left border-collapse'; diff --git a/apps/stock/web-app/src/features/backtest/components/DatasetDownload.tsx b/apps/stock/web-app/src/features/backtest/components/DatasetDownload.tsx index b89ad180..b45657e3 100644 --- a/apps/stock/web-app/src/features/backtest/components/DatasetDownload.tsx +++ b/apps/stock/web-app/src/features/backtest/components/DatasetDownload.tsx @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from 'react'; import { actionClass } from '@/features/strategies/components/StrategyParameterForm'; +import { downloadJsonText } from '@/utils/downloadJsonText'; import { backtestApiV2 } from '../services/backtestApiV2'; -import { downloadJsonText } from '../services/downloadJsonText'; /** Changing the dataset discards pending transport state before another download is possible. */ export function DatasetDownload({ hash }: { hash: string }) { diff --git a/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx b/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx index faa0a557..a8c9ede0 100644 --- a/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx +++ b/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx @@ -9,6 +9,7 @@ import type { ResearchHypothesisRevision, } from '@stock-bot/types'; import { Card } from '@/components/ui/Card'; +import { downloadJsonText } from '@/utils/downloadJsonText'; import { actionClass, fieldClass } from '../../strategies/components/StrategyParameterForm'; import { confirmDiscard, useUnsavedWarning } from '../../strategies/components/useUnsavedWarning'; import { researchApi, ResearchApiError } from '../services/researchApi'; @@ -129,6 +130,7 @@ export function ResearchEntry({ const [saving, setSaving] = useState(false); const [error, setError] = useState(''); const [blocked, setBlocked] = useState(false); + const [downloadError, setDownloadError] = useState(''); useUnsavedWarning(editing); useEffect(() => { onDirty(editing); @@ -145,6 +147,7 @@ export function ResearchEntry({ const controller = new AbortController(); setLoading(true); setLoadError(''); + setDownloadError(''); setEntry(null); const load = async (): Promise => { if (kind === 'hypothesis') { @@ -205,6 +208,32 @@ export function ResearchEntry({ const revision = revisionId ? entry?.revisions.find(item => item.id === revisionId) : entry?.entity.latestRevision; + const download = () => { + if (loading || saving || !entry || !revision) { + return; + } + setDownloadError(''); + try { + const record = { + kind: 'research-revision-export/v1', + projectId, + entry: + entry.kind === 'hypothesis' + ? { id: entry.entity.id, kind: 'hypothesis' } + : { + id: entry.entity.id, + kind: entry.entity.kind, + hypothesisRevisionId: entry.entity.hypothesisRevisionId, + }, + revision, + }; + downloadJsonText(JSON.stringify(record), `research-${entry.entity.id}-${revision.id}.json`); + } catch (cause) { + setDownloadError( + cause instanceof Error ? cause.message : 'Could not download saved revision' + ); + } + }; const readonly = archived || Boolean(writeBlocked) || entry?.entity.archived || Boolean(revisionId); const beginEdit = () => { @@ -338,6 +367,21 @@ export function ResearchEntry({

Revision {revision.ordinal} · {revision.createdAt} · {revision.id}

+
+ + {editing && ( +

+ Downloads the saved revision displayed above. Unsaved edits are excluded. +

+ )} + {downloadError && ( +

+ {downloadError} +

+ )} +
{revisionId &&

Immutable history: this revision is read-only.

} {writeBlocked && (

diff --git a/apps/stock/web-app/src/features/backtest/services/downloadJsonText.ts b/apps/stock/web-app/src/utils/downloadJsonText.ts similarity index 100% rename from apps/stock/web-app/src/features/backtest/services/downloadJsonText.ts rename to apps/stock/web-app/src/utils/downloadJsonText.ts diff --git a/docs/guide/backtest-walkthrough.md b/docs/guide/backtest-walkthrough.md index a384754f..f8e3aabd 100644 --- a/docs/guide/backtest-walkthrough.md +++ b/docs/guide/backtest-walkthrough.md @@ -154,6 +154,19 @@ the normal preview and confirmation steps. 4. Run **cost sensitivity** on the selected configuration and compare ordinary experiments with compatible inputs. Save findings with explicit run/report references. 5. Reopen those saved IDs to inspect or reproduce the work. The browser is the normal research interface; authorized AI clients use the same backend capabilities with separate grants and budgets. +Open a hypothesis, note or finding and choose **Download saved revision** to take its +narrative and citations into local analysis. When viewing history, the file contains that +exact older revision. While editing, it exports the saved version and leaves your draft +untouched. Archived entries can still be downloaded. + +The file `research--.json` has `kind: "research-revision-export/v1"`, +`projectId`, an `entry` identity/kind (including an artifact's linked hypothesis-revision +ID), and the complete saved `revision`. Authorship, source/report hashes, raw cited values, +unavailable reasons and limitations are preserved. Downloading uses the loaded record and +makes no additional API request. A local failure offers **Retry saved revision download**. +Pair it with the separate run-result and dataset files above for notebook or AI analysis. +The file is an analysis record; replay uses the retained execution path. + Useful entry points are [ResearchProjectPage](../../apps/stock/web-app/src/features/research/ResearchProjectPage.tsx), [ExperimentDetailPage](../../apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx), [ChronologicalValidationDetailPage](../../apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage.tsx), and [WalkForwardDetailPage](../../apps/stock/web-app/src/features/experiments/WalkForwardDetailPage.tsx). The [AI research-cycle example](../../scripts/examples/research-cycle.ts) submits prepared candidate packages, bounded searches, held-out validation and cost studies, then creates evidence-linked findings. It records request intents and receipts for recovery. It does not independently generate code, supply a model SDK or activate trading; AI-written findings remain distinguishable from validated results. diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts index 359dd34e..b31aec2b 100644 --- a/test/e2e/workbench.test.ts +++ b/test/e2e/workbench.test.ts @@ -36,7 +36,9 @@ import type { HistoricalDatasetInputV2, HistoricalDatasetV2, ResearchArtifact, + ResearchArtifactRevision, ResearchFindingSource, + ResearchHypothesisRevision, } from '@stock-bot/types'; import { createDatasetV2, @@ -94,6 +96,55 @@ async function downloadDatasetInBrowser( expect(validateDatasetV2(JSON.parse(readFileSync(path, 'utf8')))).toEqual(expected); } +async function downloadResearchRevisionInBrowser( + f: Awaited>, + projectId: string, + entry: { + id: string; + kind: 'hypothesis' | 'note' | 'finding'; + hypothesisRevisionId?: string | null; + }, + revision: ResearchArtifactRevision | ResearchHypothesisRevision +) { + const counts = async () => + ( + await f.pool.query(`SELECT + (SELECT count(*)::int FROM runs) AS runs, + (SELECT count(*)::int FROM backtest_dispatch) AS dispatch, + (SELECT count(*)::int FROM analysis_artifact_revisions) AS artifacts, + (SELECT count(*)::int FROM research_hypothesis_revisions) AS hypotheses`) + ).rows[0]; + const before = await counts(); + const requests: string[] = []; + const record = (request: Request) => { + if (new URL(request.url()).pathname.startsWith('/api/')) { + requests.push(request.url()); + } + }; + f.page.on('request', record); + try { + const downloading = f.page.waitForEvent('download'); + await f.page.getByRole('button', { name: 'Download saved revision', exact: true }).click(); + const download = await downloading; + expect(download.suggestedFilename()).toBe(`research-${entry.id}-${revision.id}.json`); + expect(await download.failure()).toBeNull(); + const path = await download.path(); + if (!path) { + throw new Error('Expected a downloaded research revision file'); + } + expect(JSON.parse(readFileSync(path, 'utf8'))).toEqual({ + kind: 'research-revision-export/v1', + projectId, + entry, + revision, + }); + expect(requests).toEqual([]); + expect(await counts()).toEqual(before); + } finally { + f.page.off('request', record); + } +} + test('operator_provisions_bounded_agent_views_usage_and_revokes_without_corrupting_accepted_work_browser', async () => { const f = await fixture(true); try { @@ -3725,6 +3776,14 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_ await f.page.getByRole('button', { name: 'View revision 1', exact: true }).click(); await visible(f.page, 'Costs and losses require further validation.'); await visible(f.page, 'Immutable history: this revision is read-only.'); + await downloadResearchRevisionInBrowser( + f, + project.id, + { id: artifact.id, kind: 'finding', hypothesisRevisionId: hypothesis.latestRevision.id }, + history.revisions.find( + (item: ResearchArtifactRevision) => item.id === artifact.latestRevision.id + )! + ); // Move the cited hypothesis forward so the exact link requires history resolution. await f.request(`/api/v2/hypotheses/${hypothesis.id}/revisions`, 'POST', { expectedRevision: 1, @@ -3755,6 +3814,12 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_ await f.page.unroute(unrelatedHistoryPath); await visible(f.page, 'A hypothesis, not validated alpha.'); await visible(f.page, /AI-authored \(declared\).*Unvalidated narrative/); + await downloadResearchRevisionInBrowser( + f, + project.id, + { id: hypothesis.id, kind: 'hypothesis' }, + hypothesis.latestRevision + ); await f.page.getByRole('button', { name: 'Archive project', exact: true }).click(); await visible(f.page, 'Archived project: research entries are read-only.'); expect(await f.page.getByRole('button', { name: 'New note', exact: true }).count()).toBe(0); diff --git a/test/integration/research-workspace-ui.test.tsx b/test/integration/research-workspace-ui.test.tsx index 1658a628..ab18863c 100644 --- a/test/integration/research-workspace-ui.test.tsx +++ b/test/integration/research-workspace-ui.test.tsx @@ -1,4 +1,13 @@ -import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; +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'; @@ -281,6 +290,192 @@ afterAll(async () => { }); 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');