diff --git a/apps/stock/web-api/src/services/backtest-result.ts b/apps/stock/web-api/src/services/backtest-result.ts index b828ead0..b0bf1211 100644 --- a/apps/stock/web-api/src/services/backtest-result.ts +++ b/apps/stock/web-api/src/services/backtest-result.ts @@ -1,5 +1,5 @@ import { BACKTEST_DEFAULTS } from '@stock-bot/stock-config/backtest'; -import type { BacktestRunResult, BacktestRunTrade } from '@stock-bot/types'; +import type { BacktestRunProvenance, BacktestRunResult, BacktestRunTrade } from '@stock-bot/types'; type StoredTrade = Omit & Partial>; @@ -32,11 +32,65 @@ export interface StoredBacktestResult { }; } -/** Read-only compatibility conversion. Stored rows and metric units are never rewritten. */ +function resultProvenance(row: StoredBacktestResult): BacktestRunProvenance { + const limitations = [ + { + code: 'unversioned-execution', + message: + 'Engine build, financial semantics version and strategy artifact were not recorded. Current terminal-equity and fee-funding fixes do not certify this saved run.', + }, + { + code: 'same-bar-execution', + message: + 'Existing simulators can observe a completed bar and fill at its close. These results do not establish next-event execution or freedom from look-ahead bias.', + }, + { + code: 'funding-policy', + message: + 'Native and TypeScript engines have different funding checks; short and reducing-order financing is not a canonical cash or margin model.', + }, + { + code: 'strategy-attribution', + message: + 'Positions and cost basis are aggregated by symbol. Shared-asset strategy ownership and P&L attribution are not independently reconciled.', + }, + ]; + if (!row.configuration) { + limitations.push({ + code: 'missing-configuration', + message: + 'No frozen run configuration was saved. The compatibility config may use the current mutable definition and defaults; it is not evidence of historical inputs.', + }); + } + if (row.engine === 'typescript') { + limitations.push({ + code: 'exposure-convention', + message: + 'TypeScript exposure sums closed-trade durations, so overlapping positions can be counted twice and open positions omitted. It is not portfolio exposure time.', + }); + } else { + limitations.push({ + code: 'unavailable-risk-metrics', + message: + 'Native exposure and VaR include placeholders, which are shown as unavailable. For unknown engines, zero exposure cannot be distinguished from a placeholder. Native daily-return grouping and Sharpe/Sortino conventions need correction; stored computed statistics are retained but are not comparable across engines. Unknown-engine historical metric conventions cannot be verified.', + }); + } + return { + configurationSource: row.configuration ? 'stored-snapshot' : 'legacy-definition-fallback', + datasetHash: row.configuration?.dataset?.hash ?? null, + // Neither the stored engine name nor a mutable strategy name identifies a build/artifact. + engineVersion: null, + economicsVersion: null, + strategyArtifactHash: null, + limitations, + }; +} + +/** Read-only compatibility conversion. Stored rows are never rewritten. */ export function mapStoredBacktestResult(row: StoredBacktestResult): BacktestRunResult { const legacy = !row.configuration; const metrics = { ...row.metrics }; - const analytics = { ...row.analytics, exposureTime: row.analytics?.exposureTime ?? 0 }; + const analytics = { ...row.analytics, exposureTime: row.analytics?.exposureTime ?? null }; const trades = row.trades.map(trade => { const timestamp = trade.timestamp ?? trade.entryDate; const price = trade.price ?? trade.entryPrice; @@ -63,7 +117,9 @@ export function mapStoredBacktestResult(row: StoredBacktestResult): BacktestRunR metrics.totalTrades = trades.length; metrics.profitableTrades = trades.filter(trade => (trade.pnl ?? 0) > 0).length; } - analytics.exposureTime /= 100; + if (analytics.exposureTime !== null) { + analytics.exposureTime /= 100; + } analytics.drawdownSeries = analytics.drawdownSeries?.map(point => ({ ...point, value: point.value / 100, @@ -78,12 +134,21 @@ export function mapStoredBacktestResult(row: StoredBacktestResult): BacktestRunR ); } } + if (row.engine !== 'typescript' && analytics.exposureTime === 0) { + // Native writes placeholder exposure. Unknown-engine historical zero cannot be + // distinguished from that placeholder; retain nonzero stored legacy evidence. + analytics.exposureTime = null; + } + if (row.engine !== 'typescript' && analytics.riskMetrics?.value_at_risk_95 === 0) { + analytics.riskMetrics = { ...analytics.riskMetrics, value_at_risk_95: null }; + } return { runId: row.run_id, backtestId: row.backtest_id, status: row.run_status ?? 'completed', completedAt: row.completed_at.toISOString(), engine: row.engine ?? 'legacy', + provenance: resultProvenance(row), ...(legacy ? { legacy: true } : {}), config: row.configuration ?? { parameters: row.backtest_config ?? {}, diff --git a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx index 9dda14dc..496d5b47 100644 --- a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx +++ b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx @@ -331,7 +331,8 @@ export function BacktestDetailPageV2() { )}

- {backtest?.strategy || ''} • {backtest?.symbols.join(', ') || ''} + Current definition: {backtest?.strategy || ''} •{' '} + {backtest?.symbols.join(', ') || ''}

diff --git a/apps/stock/web-app/src/features/backtest/components/BacktestPlayback.tsx b/apps/stock/web-app/src/features/backtest/components/BacktestPlayback.tsx index 216d569d..8c07642b 100644 --- a/apps/stock/web-app/src/features/backtest/components/BacktestPlayback.tsx +++ b/apps/stock/web-app/src/features/backtest/components/BacktestPlayback.tsx @@ -5,6 +5,7 @@ import type { Position } from '../types/backtest.types'; import { BacktestChart } from './BacktestChart'; import { CompactPerformanceMetrics } from './CompactPerformanceMetrics'; import { PositionsSummary } from './PositionsSummary'; +import { ResultProvenance } from './ResultProvenance'; interface BacktestPlaybackProps { result: RunResult | null; @@ -68,6 +69,10 @@ export const BacktestPlayback = memo(function BacktestPlayback({ +
+ +
+ {/* Performance Metrics and Positions - Fixed height section */}
diff --git a/apps/stock/web-app/src/features/backtest/components/CompactPerformanceMetrics.tsx b/apps/stock/web-app/src/features/backtest/components/CompactPerformanceMetrics.tsx index 7c1e2cba..b4c618d3 100644 --- a/apps/stock/web-app/src/features/backtest/components/CompactPerformanceMetrics.tsx +++ b/apps/stock/web-app/src/features/backtest/components/CompactPerformanceMetrics.tsx @@ -7,6 +7,7 @@ interface ExtendedMetrics { maxDrawdown?: number | null; winRate?: number | null; totalProfit?: number | null; + totalPnl?: number | null; profitFactor?: number | null; totalTrades?: number | null; avgWin?: number | null; @@ -55,10 +56,13 @@ export function CompactPerformanceMetrics({ result, isLoading }: CompactPerforma ...metrics, }; - // Calculate totalProfit if not provided + // Never infer a historical cash amount from a mutable legacy definition's capital. const totalProfit = allMetrics.totalProfit ?? - (typeof allMetrics.totalReturn === 'number' && typeof result.config?.initialCapital === 'number' + allMetrics.totalPnl ?? + (result.provenance?.configurationSource === 'stored-snapshot' && + typeof allMetrics.totalReturn === 'number' && + typeof result.config?.initialCapital === 'number' ? allMetrics.totalReturn * result.config.initialCapital : undefined); diff --git a/apps/stock/web-app/src/features/backtest/components/ResultProvenance.tsx b/apps/stock/web-app/src/features/backtest/components/ResultProvenance.tsx new file mode 100644 index 00000000..d8e42dd2 --- /dev/null +++ b/apps/stock/web-app/src/features/backtest/components/ResultProvenance.tsx @@ -0,0 +1,89 @@ +import type { BacktestRunResult } from '@stock-bot/types'; + +/** Display saved evidence only; the mutable definition remains a separate settings view. */ +export function ResultProvenance({ result }: { result: BacktestRunResult }) { + const provenance = result.provenance; + const config = provenance?.configurationSource === 'stored-snapshot' ? result.config : null; + + return ( +
+
+

Saved run evidence

+ Research only · Unverified economics +
+

+ Completion is not financial validation. Do not use this result alone as evidence for + promotion to paper or live trading. +

+

+ Known limitations: same-bar execution, funding constraints, strategy attribution and metric + conventions. +

+
+ + Configuration, provenance and simulation limitations + +
+
+
+
Run
+
{result.runId}
+
+
+
Recorded engine
+
{result.engine === 'legacy' ? 'Unknown' : result.engine}
+
+
+
Engine build
+
{provenance?.engineVersion ?? 'Unknown — not recorded'}
+
+
+
Financial semantics version
+
{provenance?.economicsVersion ?? 'Unknown — not recorded'}
+
+
+
Strategy artifact
+
{provenance?.strategyArtifactHash ?? 'Unknown — not recorded'}
+
+
+
Dataset hash
+
{provenance?.datasetHash ?? 'Unknown — not recorded'}
+
+
+ {config ? ( +
+

Stored run configuration

+

+ Exact saved snapshot, including parameters and data policy when recorded. This is + not the current editable definition. +

+
+                {JSON.stringify(config, null, 2)}
+              
+
+ ) : ( +

+ Stored run configuration: Unknown. Current strategy settings and defaults are not + historical evidence. +

+ )} + {provenance ? ( +
    + {provenance.limitations.map(limitation => ( +
  • {limitation.message}
  • + ))} +
+ ) : ( +

+ Provenance metadata is unavailable from this API. Execution timing, funding, strategy + attribution and metric conventions are unverified. +

+ )} +
+
+
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/types/backtest.types.ts b/apps/stock/web-app/src/features/backtest/types/backtest.types.ts index 6e4f4b8b..8f589efa 100644 --- a/apps/stock/web-app/src/features/backtest/types/backtest.types.ts +++ b/apps/stock/web-app/src/features/backtest/types/backtest.types.ts @@ -78,7 +78,7 @@ export interface BacktestResult { positions: Position[]; trades: Trade[]; performanceData: PerformanceDataPoint[]; - analytics?: { exposureTime?: number }; + analytics?: { exposureTime?: number | null }; } export interface OrderBookLevel { diff --git a/libs/core/types/src/backtest-run.ts b/libs/core/types/src/backtest-run.ts index a8cce989..6f7d17e7 100644 --- a/libs/core/types/src/backtest-run.ts +++ b/libs/core/types/src/backtest-run.ts @@ -57,6 +57,17 @@ export interface BacktestRunTrade { duration?: number; } +/** Read-only evidence from saved results, not a certification of economic correctness. */ +export interface BacktestRunProvenance { + /** Legacy config remains a compatibility display fallback, never historical evidence. */ + configurationSource: 'stored-snapshot' | 'legacy-definition-fallback'; + datasetHash: string | null; + engineVersion: string | null; + economicsVersion: string | null; + strategyArtifactHash: string | null; + limitations: { code: string; message: string }[]; +} + export interface BacktestRunResult { runId: string; backtestId: string; @@ -65,6 +76,8 @@ export interface BacktestRunResult { legacy?: boolean; status: 'completed' | 'cancelled'; completedAt: string; + /** Optional for older API clients/results. Missing provenance must display as unknown. */ + provenance?: BacktestRunProvenance; config: BacktestRunConfiguration; metrics: BacktestRunMetrics; equity: { date: string; value: number }[]; @@ -83,7 +96,8 @@ export interface BacktestRunResult { }[]; /** Returns, drawdowns, and exposure use fractions here as well. */ analytics: { - exposureTime: number; + /** Null when unavailable or a known placeholder; genuine measured zero remains zero. */ + exposureTime: number | null; drawdownSeries?: { timestamp: number; value: number }[]; dailyReturns?: number[]; monthlyReturns?: Record; diff --git a/libs/core/types/src/index.ts b/libs/core/types/src/index.ts index 391bddcf..29a0d6a7 100644 --- a/libs/core/types/src/index.ts +++ b/libs/core/types/src/index.ts @@ -47,6 +47,7 @@ export type { BacktestResults } from './backtesting'; export type { BacktestRunConfiguration, BacktestRunMetrics, + BacktestRunProvenance, BacktestRunTrade, BacktestRunResult, } from './backtest-run'; diff --git a/test/integration/analytics-ui.test.tsx b/test/integration/analytics-ui.test.tsx index d5b58b8d..1f795443 100644 --- a/test/integration/analytics-ui.test.tsx +++ b/test/integration/analytics-ui.test.tsx @@ -72,7 +72,7 @@ test('compact metrics preserve null ratios and render a genuine zero profit', () dataFrequency: '1d', parameters: {}, }, - metrics, + metrics: { ...metrics, totalProfit: 0 }, equity: [], ohlcData: {}, positions: [], @@ -88,3 +88,34 @@ test('compact metrics preserve null ratios and render a genuine zero profit', () expect(rendered).toContain('$0.00'); expect(rendered).not.toMatch(/Infinity|NaN/); }); + +test('null_metrics: detailed exposure is unavailable rather than a measured zero', () => { + const rendered = text( + renderToStaticMarkup( + createElement(BacktestMetrics, { + isLoading: false, + result: { + id: 'fixture', + config: { + name: 'fixture', + startDate: new Date('2024-01-01'), + endDate: new Date('2024-02-01'), + initialCapital: 1000, + symbols: ['A.US'], + strategy: 'sma', + speedMultiplier: 0, + commission: 0, + slippage: 0, + }, + metrics, + positions: [], + trades: [], + performanceData: [], + analytics: { exposureTime: null }, + }, + }) + ) + ); + expect(rendered).toContain('Exposure TimeN/A'); + expect(rendered).not.toContain('Exposure Time0.0%'); +}); diff --git a/test/integration/backtest-result-mapping.test.ts b/test/integration/backtest-result-mapping.test.ts index c1c0dd64..f8d69bc7 100644 --- a/test/integration/backtest-result-mapping.test.ts +++ b/test/integration/backtest-result-mapping.test.ts @@ -157,7 +157,7 @@ describe('pure stored backtest result conversion', () => { expect(row).toEqual(before); }); - test('legacy explicit zero fees and absent optional analytics keep their existing defaults', () => { + test('legacy explicit zero fees remain compatibility defaults, missing analytics are unknown', () => { const row = fixture(); row.backtest_config = { name: 'Legacy', @@ -176,10 +176,108 @@ describe('pure stored backtest result conversion', () => { dataFrequency: '1h', parameters: row.backtest_config, }, - analytics: { exposureTime: 0 }, + analytics: { exposureTime: null }, }); }); + test('legacy_missing_provenance: mutable definition fallback is explicitly not saved evidence', () => { + const row = fixture(); + row.backtest_config = { name: 'Changed later', commission: 0.25 }; + const result = mapStoredBacktestResult(row); + expect(result.config.name).toBe('Changed later'); // Old consumers keep their display fallback. + expect(result.provenance).toMatchObject({ + configurationSource: 'legacy-definition-fallback', + datasetHash: null, + engineVersion: null, + economicsVersion: null, + strategyArtifactHash: null, + }); + expect(result.provenance?.limitations.map(item => item.code)).toContain( + 'missing-configuration' + ); + expect(result.provenance?.limitations.map(item => item.code)).toContain( + 'unversioned-execution' + ); + }); + + test('frozen_config_not_mutable_definition: all stored inputs and dataset identity survive definition edits', () => { + const row = fixture(); + row.engine = 'typescript'; + row.configuration = { + name: 'Frozen strategy', + strategy: 'saved-strategy', + symbols: ['B.US'], + startDate: '2023-01-01', + endDate: '2023-02-01', + initialCapital: 1000, + commission: 0.0007, + slippage: 0.0002, + dataFrequency: '1m', + parameters: { lookback: 14 }, + dataset: { + version: 1, + hash: 'a'.repeat(64), + instruments: [{ id: 'B.US', symbol: 'B', exchange: 'US' }], + startDate: '2023-01-01', + endDate: '2023-02-01', + interval: '1m', + policy: { adjustment: 'raw', timestamp: 'utc-instant' }, + volumePolicy: 'reported', + qualityPolicy: 'reject-invalid-no-interpolation', + sources: [], + barCount: 10, + }, + }; + const first = mapStoredBacktestResult(row); + row.strategy = 'changed-strategy'; + row.symbols = ['C.US']; + row.initial_capital = 999999; + row.backtest_config = { commission: 0.9, slippage: 0.9, dataFrequency: '1d' }; + const reopened = mapStoredBacktestResult(row); + expect(reopened.config).toEqual(first.config); + expect(reopened.provenance).toEqual(first.provenance); + expect(reopened.provenance).toMatchObject({ + configurationSource: 'stored-snapshot', + datasetHash: 'a'.repeat(64), + engineVersion: null, + economicsVersion: null, + strategyArtifactHash: null, + }); + expect(reopened.provenance?.limitations.map(item => item.code)).not.toContain( + 'missing-configuration' + ); + }); + + test('null_metrics: known placeholders are unavailable without discarding computed statistics or mutating storage', () => { + const row = fixture(); + row.engine = 'native'; + row.metrics.sharpeRatio = 1.2; + row.metrics.sortinoRatio = 1.4; + row.analytics = { + exposureTime: 0, + riskMetrics: { value_at_risk_95: 0, volatility: 0.12, downside_deviation: 0.08 }, + }; + const before = structuredClone(row); + const result = mapStoredBacktestResult(row); + expect(result.analytics.exposureTime).toBeNull(); + expect(result.analytics.riskMetrics).toEqual({ + value_at_risk_95: null, + volatility: 0.12, + downside_deviation: 0.08, + }); + expect(result.metrics.sharpeRatio).toBe(1.2); + expect(result.metrics.sortinoRatio).toBe(1.4); + expect(row).toEqual(before); + row.engine = 'typescript'; + row.analytics = { exposureTime: 0, riskMetrics: { var95: 0 } }; + expect(mapStoredBacktestResult(row).analytics).toEqual({ + exposureTime: 0, + riskMetrics: { var95: 0 }, + }); + row.engine = 'legacy'; + expect(mapStoredBacktestResult(row).analytics.exposureTime).toBeNull(); + }); + test('malformed trade identities fail instead of fabricating an execution time or price', () => { const row = fixture(); delete row.trades[0]!.entryDate; diff --git a/test/integration/backtest-result-provenance.test.tsx b/test/integration/backtest-result-provenance.test.tsx new file mode 100644 index 00000000..5da95940 --- /dev/null +++ b/test/integration/backtest-result-provenance.test.tsx @@ -0,0 +1,119 @@ +import { expect, test } from 'bun:test'; +import { createElement } from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import type { BacktestRunResult } from '@stock-bot/types'; +import { mapStoredBacktestResult } from '../../apps/stock/web-api/src/services/backtest-result'; +import { CompactPerformanceMetrics } from '../../apps/stock/web-app/src/features/backtest/components/CompactPerformanceMetrics'; +import { ResultProvenance } from '../../apps/stock/web-app/src/features/backtest/components/ResultProvenance'; + +function result(): BacktestRunResult { + return mapStoredBacktestResult({ + run_id: 'saved-run', + backtest_id: 'definition', + completed_at: new Date('2024-02-01'), + strategy: 'MUTABLE_STRATEGY', + symbols: ['CHANGED.US'], + initial_capital: 999999, + start_date: new Date('2020-01-01'), + end_date: new Date('2020-02-01'), + backtest_config: { name: 'MUTABLE_NAME', commission: 0.9 }, + metrics: { + totalReturn: 10, + sharpeRatio: 1, + maxDrawdown: 0.1, + winRate: 50, + totalTrades: 2, + profitFactor: 1.5, + avgWin: 1, + avgLoss: -1, + }, + trades: [], + equity_curve: [], + ohlc_data: {}, + positions: [], + execution_time: 2, + }); +} +const text = (html: string) => html.replace(/<[^>]*>/g, ''); +const panel = (saved: BacktestRunResult) => + text(renderToStaticMarkup(createElement(ResultProvenance, { result: saved }))); +const metrics = (saved: BacktestRunResult) => + text( + renderToStaticMarkup( + createElement(CompactPerformanceMetrics, { result: saved, isLoading: false }) + ) + ); + +test('legacy_missing_provenance: panel never substitutes current settings for historical evidence', () => { + const saved = result(); + const rendered = panel(saved); + expect(rendered).toContain('Stored run configuration: Unknown'); + expect(rendered).toContain('Dataset hashUnknown'); + expect(rendered).toContain('Engine buildUnknown'); + expect(rendered).toContain('Strategy artifactUnknown'); + expect(rendered).not.toContain('MUTABLE_STRATEGY'); + expect(rendered).not.toContain('MUTABLE_NAME'); + expect(rendered).not.toContain('999999'); + expect(metrics(saved)).toContain('Total Profit-'); + saved.metrics.totalPnl = 123; + expect(metrics(saved)).toContain('Total Profit$123.00'); +}); + +test('frozen_config_not_mutable_definition: exact snapshot renders and permits capital-derived profit', () => { + const saved = result(); + saved.config = { + name: 'Stored strategy', + strategy: 'saved-strategy', + symbols: ['A.US'], + startDate: '2024-01-01', + endDate: '2024-02-01', + initialCapital: 1000, + commission: 0.0007, + slippage: 0, + dataFrequency: '1m', + parameters: { lookback: 42 }, + }; + saved.provenance!.configurationSource = 'stored-snapshot'; + saved.provenance!.datasetHash = 'a'.repeat(64); + const rendered = panel(saved); + expect(rendered).toContain('Stored run configuration'); + expect(rendered).toContain('saved-strategy'); + expect(rendered).toContain('lookback'); + expect(rendered).toContain('42'); + expect(rendered).toContain('0.0007'); + expect(rendered).toContain('a'.repeat(64)); + expect(rendered).not.toContain('MUTABLE_STRATEGY'); + expect(metrics(saved)).toContain('Total Profit$100.00'); +}); + +test('limitation_badge: engine name never establishes version or financial validation', () => { + const saved = result(); + saved.engine = 'native'; + const rendered = panel(saved); + expect(rendered).toContain('Research only · Unverified economics'); + expect(rendered).toContain('Recorded enginenative'); + expect(rendered).toContain('Engine buildUnknown'); + expect(rendered).toContain('same-bar execution'); + expect(rendered).toContain('funding constraints'); + expect(rendered).toContain('strategy attribution'); + expect(rendered).toContain( + 'Current terminal-equity and fee-funding fixes do not certify this saved run' + ); +}); + +test('old API without provenance remains readable but cannot invent historical inputs', () => { + const saved = result(); + delete saved.provenance; + expect(panel(saved)).toContain('Provenance metadata is unavailable from this API'); + expect(panel(saved)).toContain('Stored run configuration: Unknown'); + expect(metrics(saved)).toContain('Total Profit-'); +}); + +test('null_metrics: missing exposure is unavailable, genuine recorded zeros remain visible', () => { + const saved = result(); + expect(metrics(saved)).toContain('Exposure-'); + saved.analytics.exposureTime = 0; + saved.metrics.totalProfit = 0; + expect(metrics(saved)).toContain('Total Profit$0.00'); + expect(metrics(saved)).toContain('Exposure0.0%'); +}); diff --git a/test/integration/backtest-run-controls.test.tsx b/test/integration/backtest-run-controls.test.tsx index e6646029..f87bae42 100644 --- a/test/integration/backtest-run-controls.test.tsx +++ b/test/integration/backtest-run-controls.test.tsx @@ -537,20 +537,37 @@ describe('actual detail page result states', () => { status === 'failed' ? 'Run failed: Fixture failure' : 'Run cancelled' ); expect(host.textContent).not.toContain('No trades executed'); + expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull(); expect(requests.some(item => item.path.endsWith('/results'))).toBe(false); }); } test('completed missing results differ from successful zero trades and retry uses saved results', async () => { await mountPage('completed'); expect(host.textContent).toContain('Loading run data'); + expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull(); await flush(() => click('Trades')); await flush(() => reply(request('/api/v2/runs/A/results'), { error: 'Not found' }, 404)); expect(host.textContent).toContain('saved results are unavailable'); expect(host.textContent).not.toContain('No trades executed'); + expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull(); await flush(() => click('Retry results')); await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed'))); await flush(() => reply(request('/api/v2/runs/A/results'), results('A'))); expect(host.textContent).toContain('No trades executed in this backtest.'); expect(host.textContent).not.toContain('saved results are unavailable'); }); + + test('limitation_badge: completed detail shows unknown legacy provenance beside performance', async () => { + await mountPage('completed'); + await flush(() => reply(request('/api/v2/runs/A/results'), results('A'))); + const evidence = host.querySelector('[aria-label="Result provenance and limitations"]'); + expect(evidence).not.toBeNull(); + expect(evidence!.textContent).toContain('Research only · Unverified economics'); + const details = evidence!.querySelector('details')!; + await flush(() => details.querySelector('summary')!.click()); + expect(details.open).toBe(true); + expect(evidence!.textContent).toContain('Stored run configuration: Unknown'); + expect(evidence!.textContent).toContain('Provenance metadata is unavailable from this API'); + expect(host.textContent).toContain('Performance'); + }); });