+ );
+}
+
const metricFields: { key: keyof CanonicalMetrics; label: string; percentage?: boolean }[] = [
{ key: 'totalReturn', label: 'Total return', percentage: true },
{ key: 'cagr', label: 'CAGR', percentage: true },
@@ -147,6 +173,7 @@ export function CanonicalResults({
+ Immutable configuration and reporting policy
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 ae380c53..b89ad180 100644
--- a/apps/stock/web-app/src/features/backtest/components/DatasetDownload.tsx
+++ b/apps/stock/web-app/src/features/backtest/components/DatasetDownload.tsx
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { actionClass } from '@/features/strategies/components/StrategyParameterForm';
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 }) {
@@ -35,18 +36,7 @@ function Download({ hash }: { hash: string }) {
if (!current()) {
return;
}
- const url = URL.createObjectURL(new Blob([text], { type: 'application/json' }));
- const anchor = document.createElement('a');
- try {
- anchor.href = url;
- anchor.download = `dataset-${hash}.json`;
- document.body.append(anchor);
- anchor.click();
- } finally {
- anchor.remove();
- // Allow the browser to consume the click before releasing the URL, even after unmount.
- setTimeout(() => URL.revokeObjectURL(url), 0);
- }
+ downloadJsonText(text, `dataset-${hash}.json`);
} catch (cause) {
if (current()) {
setError(cause instanceof Error ? cause.message : 'Could not download retained dataset');
diff --git a/apps/stock/web-app/src/features/backtest/services/downloadJsonText.ts b/apps/stock/web-app/src/features/backtest/services/downloadJsonText.ts
new file mode 100644
index 00000000..ba6a3821
--- /dev/null
+++ b/apps/stock/web-app/src/features/backtest/services/downloadJsonText.ts
@@ -0,0 +1,15 @@
+/** Save inert JSON text and release the browser URL after it consumes the click. */
+export function downloadJsonText(text: string, filename: string): void {
+ const url = URL.createObjectURL(new Blob([text], { type: 'application/json' }));
+ let anchor: HTMLAnchorElement | undefined;
+ try {
+ anchor = document.createElement('a');
+ anchor.href = url;
+ anchor.download = filename;
+ document.body.append(anchor);
+ anchor.click();
+ } finally {
+ setTimeout(() => URL.revokeObjectURL(url), 0);
+ anchor?.remove();
+ }
+}
diff --git a/docs/development/backlog/tasks/RP08.md b/docs/development/backlog/tasks/RP08.md
index 430af072..af8e96b6 100644
--- a/docs/development/backlog/tasks/RP08.md
+++ b/docs/development/backlog/tasks/RP08.md
@@ -11,3 +11,5 @@ Ownership: one frontend agent owns the result action, minimal shared download he
Acceptance/tests: a downloaded file deep-equals the displayed canonical API result, including decimal amounts, null reasons and full original provenance. Distinct run IDs produce the corresponding filenames and contents; failed Blob/click work creates no success and releases resources. Downloading does not fetch, save settings, create runs or mutate the result. Preserve RP07 cancellation/raw-text semantics. Chromium reopens an original native run after changing its editable template, downloads the result and compares the complete JSON with that original API response; run/dispatch counts remain unchanged. Existing run-selection tests remain the identity gate; do not add a competing result validator or async loader.
Gates: focused result/download UI tests, authored-test/application types, strict lint, production build, root full repository check and Chromium workbench. Document that the JSON is analysis evidence, not a standalone replay archive: dataset bars and engine binaries are separate, and retained strategy JavaScript is data, not automatically executed. No candidate approval, research execution, paper/live activation or performance work.
+
+Accepted October 27, 2026. Independent review and implementer checks passed 64 focused tests / 457 assertions. Root full repository check passed, including 1,320 integration and 150 Rust tests. Final Chromium suite passed all 21 scenarios / 726 assertions, comparing the actual downloaded result with its original API response after template changes and checking no extra API requests/writes. The repeated archive-fixture shutdown failure was addressed by returning its WebSocket upgrade synchronously; HTTP handling and teardown checks remain unchanged, with authored types and full browser suite passing. [Evidence](../../real-data-research.md) records the initial failure and final gates; [usage](../../../guide/backtest-walkthrough.md#take-the-result-into-a-notebook-or-local-ai-workflow) covers local inspection and replay limitations.
diff --git a/docs/development/real-data-research.md b/docs/development/real-data-research.md
index fc0784ff..d9ecc15a 100644
--- a/docs/development/real-data-research.md
+++ b/docs/development/real-data-research.md
@@ -154,3 +154,21 @@ Root validation:
- Chromium: all 21 workbench scenarios passed with 721 assertions. Actual downloaded files from a verified selection and a reopened native result validate in full. The latter's template is deliberately changed to a distinct retained dataset first; export still delivers the original run dataset and leaves the replacement settings, one run and one dispatch unchanged. The fills-only view exposes no download action.
Logs: `/tmp/stock-bot-rp07-root-check.log`, `/tmp/stock-bot-rp07-postgres.log`, `/tmp/stock-bot-rp07-browser.log`, `/tmp/stock-bot-rp07-root-test-types.log`, `/tmp/stock-bot-rp07-api-independent.log` and `/tmp/stock-bot-rp07-ui-independent.log`. Tests use disposable PostgreSQL/Redis fixtures; no development research runs or paper/live operations were performed. Export retains the existing eligible single-asset/single-series gate. Performance, monitoring and conditional replay extraction remain deferred.
+
+## RP08 — Original run result download
+
+Owner continuation authorized a small companion to the dataset download; planning commit `dd1545b9` records the scope. The full canonical result view now offers **Download run result**, saving its already loaded `CanonicalRunResult` as `run-.json`. It serializes the entire original object, preserving decimal strings, null metric reasons, financial views, analytics and admitted request/build provenance. There is no new API, request on click, financial calculation or upload format.
+
+The existing results service validates stored financial content and request/analytics identity; the existing monitoring hook binds it to the selected run/backtest. The new action reuses that ownership instead of introducing another loader or validator. A private per-run component owns local error/retry state. A 15-line JSON-text download helper is shared with RP07, preserving its raw text, cancellation and resource cleanup behavior. Legacy and fills-only views remain unchanged.
+
+Independent reviewer `/root/find_research_followup` accepted the implementation and root browser test: 64 focused UI tests / 457 assertions passed independently and in the implementer worktree. The existing canonical report fixture verifies complete JSON equality, unchanged input, distinct run filenames/contents, zero extra requests, error reset and URL/click failure retry with cleanup. No duplicate financial fixture or download framework was added. Review corrected two guide details: orders are under `financial.view`, and the button says **Retry run result download**. [Usage](../guide/backtest-walkthrough.md#take-the-result-into-a-notebook-or-local-ai-workflow) explains local inspection and the separate dataset/runtime requirements for replay.
+
+Root validation:
+
+- `CARGO_BUILD_JOBS=2 bun run check`: passed — 134 tooling, 43 utility, 44 calculation, 1,320 integration and 150 Rust tests. Existing 14 conditional integration skips / 4 ignored Rust measurements remain. Build, types, contracts, strict lint and secret audit passed.
+- Authored Chromium-test typecheck and formatting/diff checks passed. Implementer application/authored-test types, focused strict lint and production build also passed.
+- Final Chromium suite: all 21 scenarios passed with 726 assertions. An actual result file deep-equals the original API response after the editable template changes dataset. Downloading issues zero additional API requests and leaves the replacement settings, run and dispatch counts unchanged. The existing dataset download also passes through the shared helper.
+
+The first full browser invocation passed 20 scenarios but failed the archive scenario during fixture shutdown (`pendingWebSockets=1`, no tracked sockets). All archive application assertions completed; the shutdown failure repeated in isolation. The fixture now returns WebSocket upgrades synchronously while keeping ordinary HTTP handling asynchronous. The focused archive test and then the complete suite passed; original cleanup deadlines/errors remain enforced. No timing probes or timeout increases were retained, and the production server wrapper was not changed. This is observed fixture validation, not a claim that a Bun internals defect has been proven or a production reliability issue fixed.
+
+Logs: `/tmp/stock-bot-rp08-root-check.log`, `/tmp/stock-bot-rp08-root-test-types-final.log`, `/tmp/stock-bot-rp08-browser.log` (initial failure), `/tmp/stock-bot-rp08-browser-archive-sync.log`, `/tmp/stock-bot-rp08-browser-final.log` and `/tmp/stock-bot-rp08-independent.log`. Browser tests use disposable PostgreSQL/Redis fixtures. No development research runs, paper/live operations or deferred optimization were activated.
diff --git a/docs/guide/backtest-walkthrough.md b/docs/guide/backtest-walkthrough.md
index ddfc5dc7..eeabfdd3 100644
--- a/docs/guide/backtest-walkthrough.md
+++ b/docs/guide/backtest-walkthrough.md
@@ -90,6 +90,42 @@ Rust returns financial facts, including orders, fills, positions and valuation.
`BacktestRunner` validates the result and commits it through [`PostgresBacktestRunRepository`](../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts). Completion notifications follow persistence. The browser's [CanonicalResults](../../apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx) and [ResultProvenance](../../apps/stock/web-app/src/features/backtest/components/ResultProvenance.tsx) render this saved record. Reloading the page reads the same run; it does not rerun the simulation. WebSocket updates help refresh the display, but the database owns status and results.
+### Take the result into a notebook or local AI workflow
+
+Open a completed canonical run and choose **Download run result**. The file,
+`run-.json`, contains the complete result already displayed, including the original
+request. Changing the backtest's editable settings does not change an earlier run's file.
+Downloading makes no additional API request and neither saves settings nor submits a run.
+
+Useful fields for exploration:
+
+| Field | Contents |
+| --- | --- |
+| `request` | Original dataset hash, strategy package/parameters, execution policy and engine/build identity. |
+| `financial.projection` | Native fills and terminal valuation. |
+| `financial.view` | Native orders, account and strategy-owned position views. |
+| `financial.reporting` | Evaluation bounds, session samples and reporting policy. |
+| `analytics` | Metrics, unavailable-value reasons and statistical assumptions. |
+
+For a quick inspection with Bun:
+
+```ts
+const result = await Bun.file('/path/to/run-.json').json();
+console.log(result.runId, result.request.datasetHash);
+console.table(result.financial.projection.fills);
+console.log(result.financial.projection.valuation, result.analytics.unavailable);
+```
+
+Financial decimal strings and null metric values remain unchanged; chart rounding is not
+exported. Keep null reasons when comparing runs instead of treating missing metrics as zero.
+Pair the result with its [retained dataset download](../backtest-datasets.md#downloading-a-retained-snapshot-for-local-exploration)
+to explore observations and outcomes in VS Code, notebooks or local AI tools.
+
+This is an analysis record, not a self-contained replay archive or an upload format. Bars
+and engine binaries are separate; use **Reproduce original run** for the existing retained
+execution path. The JSON includes the retained strategy JavaScript as text and never executes
+it during download or JSON inspection. A local download failure offers **Retry run result download**.
+
## 6. Retry, cancel and reproduce are different operations
| Operation | What to expect |
diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts
index d070cdb5..8ae1e2a3 100644
--- a/test/e2e/workbench.test.ts
+++ b/test/e2e/workbench.test.ts
@@ -1930,6 +1930,9 @@ test('canonical_native_smoke', async () => {
expect(
await f.page.getByRole('button', { name: 'Download retained dataset', exact: true }).count()
).toBe(0);
+ expect(
+ await f.page.getByRole('button', { name: 'Download run result', exact: true }).count()
+ ).toBe(0);
// The editable template moves to a different retained source; this run's
// export must still resolve its immutable original request hash.
const replacement = canonicalSmaFixture(['A'], { volume: 2000 }).dataset;
@@ -1943,6 +1946,25 @@ test('canonical_native_smoke', async () => {
await f.page.getByText('Immutable configuration and reporting policy', { exact: true }).click();
await visible(f.page, result.request.datasetHash);
await downloadDatasetInBrowser(f, dataset);
+ const exportRequests: string[] = [];
+ const recordExportRequest = (request: Request) => {
+ if (new URL(request.url()).pathname.startsWith('/api/')) {
+ exportRequests.push(request.url());
+ }
+ };
+ f.page.on('request', recordExportRequest);
+ const downloadingResult = f.page.waitForEvent('download');
+ await f.page.getByRole('button', { name: 'Download run result', exact: true }).click();
+ const downloadedResult = await downloadingResult;
+ expect(downloadedResult.suggestedFilename()).toBe(`run-${runId}.json`);
+ expect(await downloadedResult.failure()).toBeNull();
+ const resultPath = await downloadedResult.path();
+ if (!resultPath) {
+ throw new Error('Expected a downloaded canonical result file');
+ }
+ expect(JSON.parse(readFileSync(resultPath, 'utf8'))).toEqual(result);
+ f.page.off('request', recordExportRequest);
+ expect(exportRequests).toEqual([]);
expect((await f.request(`/api/v2/backtests/${id}`)).config.datasetHash).toBe(
replacement.manifest.hash
);
diff --git a/test/integration/canonical-workbench.test.tsx b/test/integration/canonical-workbench.test.tsx
index dc2b6fec..6d9289fa 100644
--- a/test/integration/canonical-workbench.test.tsx
+++ b/test/integration/canonical-workbench.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, type ReactElement } from 'react';
import type { Root } from 'react-dom/client';
@@ -755,6 +764,119 @@ describe('canonical research workbench', () => {
expect(requests).toHaveLength(1);
});
+ describe('canonical run result download', () => {
+ const blobs: Blob[] = [];
+ const downloads: { href: string; filename: 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:run-${blobs.length}`;
+ });
+ const revokeUrl = spyOn(URL, 'revokeObjectURL').mockImplementation(url => {
+ revoked.push(url);
+ });
+ const anchorClick = 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('Download anchor was not attached');
+ }
+ downloads.push({ href: anchor.href, filename: anchor.download });
+ }
+ );
+ restore = () => {
+ createUrl.mockRestore();
+ revokeUrl.mockRestore();
+ anchorClick.mockRestore();
+ };
+ });
+ afterEach(async () => {
+ await tick();
+ restore();
+ });
+
+ test('saves the complete original result without rounding, mutation or another request', async () => {
+ const value = report();
+ const before = structuredClone(value);
+ await mount(createElement(CanonicalResults, { result: value }));
+ expect(downloads).toHaveLength(0);
+ await flush(() => click('Download run result'));
+ expect(downloads).toEqual([{ href: 'blob:run-1', filename: 'run-run.json' }]);
+ expect(blobs[0]!.type.split(';')[0]).toBe('application/json');
+ expect(JSON.parse(await blobs[0]!.text())).toEqual(before);
+ expect(value).toEqual(before);
+ expect(browser.document.querySelector('a[download]')).toBeNull();
+ await tick();
+ expect(revoked).toEqual(['blob:run-1']);
+
+ const other = report();
+ other.runId = other.request.runId = 'another-run';
+ other.request.name = 'Other retained inputs';
+ await flush(() => root!.render(createElement(CanonicalResults, { result: other })));
+ await flush(() => click('Download run result'));
+ expect(downloads[1]!.filename).toBe('run-another-run.json');
+ expect(JSON.parse(await blobs[1]!.text())).toEqual(other);
+ expect(requests).toHaveLength(0);
+ await flush(() =>
+ root!.render(createElement(CanonicalResults, { result: other, fillsOnly: true }))
+ );
+ expect(host.textContent).not.toContain('Download run result');
+ expect(host.textContent).not.toContain('Retry run result download');
+ });
+
+ for (const stage of ['url', 'click'] as const) {
+ test(`reports ${stage} failure inline and retries the unchanged result with cleanup`, async () => {
+ const value = report();
+ await mount(createElement(CanonicalResults, { result: value }));
+ failure = stage;
+ await flush(() => click('Download run result'));
+ expect(host.querySelector('[role="alert"]')?.textContent).toBe(
+ 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:run-1']);
+ failure = undefined;
+ await flush(() => click('Retry run result download'));
+ expect(host.querySelector('[role="alert"]')).toBeNull();
+ expect(downloads).toHaveLength(1);
+ expect(JSON.parse(await blobs.at(-1)!.text())).toEqual(value);
+ expect(requests).toHaveLength(0);
+ await tick();
+ expect(revoked).toEqual(blobs.map((_, index) => `blob:run-${index + 1}`));
+ });
+ }
+
+ test('a different displayed run clears the earlier local download error', async () => {
+ await mount(createElement(CanonicalResults, { result: report() }));
+ failure = 'click';
+ await flush(() => click('Download run result'));
+ expect(host.querySelector('[role="alert"]')?.textContent).toBe('Browser download failed');
+ const other = report();
+ other.runId = other.request.runId = 'next-run';
+ await flush(() => root!.render(createElement(CanonicalResults, { result: other })));
+ expect(host.querySelector('[role="alert"]')).toBeNull();
+ failure = undefined;
+ await flush(() => click('Download run result'));
+ expect(downloads[0]!.filename).toBe('run-next-run.json');
+ expect(JSON.parse(await blobs.at(-1)!.text())).toEqual(other);
+ expect(requests).toHaveLength(0);
+ });
+ });
+
test('explains a partial-session evaluation horizon alongside the unchanged retained CAGR', async () => {
const value = report();
value.financial.reporting.tradeStart = Date.parse('2024-10-01T14:30:00Z');