import { useEffect, useRef, useState } from 'react'; import { Link, useParams } from 'react-router-dom'; import type { ChronologicalValidationActionReceipt } from '@stock-bot/stock-config/chronological-validation'; import { Button } from '@/components/ui/Button'; import { chronologicalFindingSource } from '@/features/research/services/findingSources'; import { useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { ExperimentCounts } from './components/ExperimentCounts'; import { RegimeEvidenceUnavailable } from './components/RegimeEvidenceUnavailable'; import { SourceFindingAction } from './components/SourceFindingAction'; import { ValidationEvidence } from './components/ValidationEvidence'; import { chronologicalValidationDurableApi, ValidationApiError, type ValidationDetailView, } from './services/chronologicalValidationDurableApi'; export function ChronologicalValidationDetailPage() { const { validationId = '' } = useParams<{ validationId: string }>(); return ; } type Intent = | { id: string; operation: 'select'; body: { previewHash: string }; key: string } | { id: string; operation: 'finalize'; body: { previewHash: string; selectionHash: string }; key: string; }; function ValidationDetail({ validationId }: { validationId: string }) { const [findingDirty, setFindingDirty] = useState(false); const alive = useRef(false), pending = useRef(false), reading = useRef(true), generation = useRef(0), read = useRef(null); const captured = useRef(null); const [intent, setIntent] = useState(null); const [validation, setValidation] = useState(null); const [loading, setLoading] = useState(true), [busy, setBusy] = useState(false), [reload, setReload] = useState(0); const [readError, setReadError] = useState(''), [actionError, setActionError] = useState(''); const [ambiguous, setAmbiguous] = useState(false), [receipt, setReceipt] = useState(null); useUnsavedWarning(Boolean(intent)); useEffect(() => { alive.current = true; return () => { alive.current = false; generation.current++; read.current?.abort(); }; }, []); useEffect(() => { if (pending.current) { return; } let current = true; const revision = ++generation.current, controller = new AbortController(); read.current = controller; reading.current = true; setLoading(true); setReadError(''); void chronologicalValidationDurableApi .get(validationId, controller.signal) .then(value => { if (current && revision === generation.current) { setValidation(value); } }) .catch(cause => { if (current && revision === generation.current) { setReadError(cause instanceof Error ? cause.message : 'Could not load validation'); } }) .finally(() => { if (current && revision === generation.current) { reading.current = false; setLoading(false); } }); return () => { current = false; controller.abort(); }; }, [validationId, reload]); const begin = () => { if (pending.current || reading.current) { return false; } pending.current = true; generation.current++; read.current?.abort(); setLoading(false); setBusy(true); setActionError(''); return true; }; const finish = () => { pending.current = false; if (alive.current) { setBusy(false); } }; const advance = async (operation: 'select' | 'finalize') => { if (pending.current || reading.current || loading || !validation) { return; } if (!captured.current) { if ( !validation.actions[operation].available || (operation === 'finalize' && !validation.selection) ) { return; } captured.current = operation === 'select' ? { id: validationId, operation, body: { previewHash: validation.previewHash }, key: crypto.randomUUID(), } : { id: validationId, operation, body: { previewHash: validation.previewHash, selectionHash: validation.selection?.selectionHash ?? '', }, key: crypto.randomUUID(), }; setIntent(captured.current); setReceipt(null); } const original = captured.current; if (!begin()) { return; } try { const result = await chronologicalValidationDurableApi.advance( original.id, original.operation, original.body, original.key ); if (alive.current) { captured.current = null; setIntent(null); setAmbiguous(false); setReceipt(result.receipt); setValidation(result.validation); } } catch (cause) { if (alive.current) { setActionError(cause instanceof Error ? cause.message : 'Could not advance validation'); setAmbiguous(!(cause instanceof ValidationApiError) || cause.ambiguous); } } finally { finish(); } }; const cancel = async () => { if (loading || !validation || !begin()) { return; } try { const value = await chronologicalValidationDurableApi.cancel(validationId); if (alive.current) { setValidation(value); } } catch (cause) { if (alive.current) { setActionError( `${cause instanceof Error ? cause.message : 'Cancellation failed'}. Refresh to verify cancellation or retry the request.` ); } } finally { finish(); } }; const discard = () => { if ( pending.current || !window.confirm( 'Discard this action request? It may already have succeeded. Refresh the saved validation before preparing another action.' ) ) { return; } captured.current = null; setIntent(null); setActionError(''); setAmbiguous(false); }; return (
{ const findingLink = (event.target as HTMLElement).closest('a'); if ( findingLink && (!findingLink.target || findingLink.target === '_self') && findingDirty && !event.ctrlKey && !event.metaKey && !event.shiftKey && !window.confirm( 'Leave this finding draft? The previous request may already have saved if its response was lost. Inspect saved records before submitting again.' ) ) { event.preventDefault(); event.stopPropagation(); return; } if ( (event.target as HTMLElement).closest('a') && captured.current && !event.ctrlKey && !event.metaKey && !event.shiftKey && !window.confirm( 'Leave this unconfirmed validation action? Its exact body and key will be discarded. You can inspect evidence in another tab.' ) ) { event.preventDefault(); event.stopPropagation(); } }} > All experiments

{validation?.name ?? 'Chronological validation'}

{loading &&

Loading validation...

} {readError && (

{readError} {validation && ' Showing the last loaded state.'}

)} {actionError && (

{actionError}

)} {intent && (

{ambiguous ? 'Action acceptance is unconfirmed. ' : ''}This request still targets{' '} {intent.operation === 'select' ? 'selection and holdout admission' : 'report finalization'}{' '} with its exact saved body and key.

{' '}
)} {receipt && (

{receipt.operation === 'select-and-admit-holdouts' ? 'Selection and holdout admission accepted.' : 'Report finalization accepted.'}{' '} Receipt {receipt.id} · {receipt.createdAt}

)} {validation && ( <> {!validation.report && ( )}

{validation.report ? 'Execution complete · report saved' : validation.selection ? 'Fixed selection saved · validation and test admitted' : 'Training candidates admitted · selection not yet frozen'}

{validation.trainingCandidateCount} training candidates; one validation run and one test run after selection. Each phase resets initial capital and positions. No combined portfolio equity curve is produced.

{validation.cancelRequested && (

Cancellation requested. Completed evidence remains retained; active work may still finish.

)} {!intent && (
{!validation.selection && ( )} {validation.selection && !validation.report && ( )}
)} {!validation.selection && validation.actions.select.reason && (

{validation.actions.select.reason}

)} {validation.selection && !validation.report && validation.actions.finalize.reason && (

{validation.actions.finalize.reason}

)} {!validation.cancelRequested && !validation.report && ( )}

Frozen chronological recipe

Train selection maximizes total return; ties use the original candidate index. Every candidate is required. Validation is diagnostic only; test is holdout only. Neither retunes the fixed selection.

Initial capital (USD):{' '} {validation.preview.source.request.policy.matching.risk.ledger.initialCapital} · Owner budget: {validation.preview.source.request.strategy.selection.ownerBudget} · Seed:{' '} {validation.preview.source.request.strategy.selection.seed}

Selection uses training results only in this workflow. These dates may have been examined in other research.

{validation.preview.partitions.map(part => (

{part.phase} window

Warmup: {new Date(part.dataset.bounds.warmupStart).toISOString()}

Trading: {new Date(part.dataset.bounds.tradeStart).toISOString()} —{' '} {new Date(part.dataset.bounds.tradeEnd).toISOString()} (end exclusive)

Dataset: {part.dataset.hash}

Admitted / required warmup: {part.counts.admittedWarmup} / {part.requiredWarmup}

{part.warnings.map((warning, index) => (

{warning}

))}
))}
Exact retained recipe and policies
                {JSON.stringify(
                  {
                    previewHash: validation.previewHash,
                    input: validation.preview.input,
                    policy: validation.preview.policy,
                    sourceDataset: validation.preview.source.request.datasetHash,
                    strategyVersion: validation.preview.source.request.strategy.versionId,
                    sourceReview: validation.preview.source.request.strategy.reviewId,
                    artifactHash:
                      validation.preview.source.request.strategy.package.artifact.sha256,
                    build: validation.preview.source.request.build,
                    financialPolicy: validation.preview.source.request.policy,
                    analyticsPolicy: validation.preview.source.request.analyticsPolicy,
                  },
                  null,
                  2
                )}
              

Phase outcomes

{validation.phases.map(phase => (

{phase.phase}

{phase.status === 'not-admitted' && (

Not admitted. No {phase.phase} run exists before the fixed selection is saved.

)} {phase.status === 'missing' && (

Expected {phase.phase} experiment is missing. Report finalization is blocked.

)} {phase.experiment && ( <>
    {phase.experiment.trials.map(trial => (
  • Candidate{' '} {phase.phase === 'train' ? trial.index + 1 : (validation.selection?.winner.index ?? 0) + 1}{' '} · {trial.status} · {trial.progress}% ·{' '} {trial.comparable ? 'Comparable' : trial.status === 'completed' ? 'Incomparable' : 'Not evaluated'}
    {JSON.stringify(trial.parameters)}
    {trial.error &&

    {trial.error}

    } {trial.diagnostic &&

    {trial.diagnostic}

    }

    Total return (fraction):{' '} {trial.metrics?.totalReturn === null || trial.metrics?.totalReturn === undefined ? `Unavailable${trial.unavailable?.totalReturn ? `: ${trial.unavailable.totalReturn}` : ''}` : String(trial.metrics.totalReturn)}

    {trial.runId && ( Open {phase.phase} run {trial.index + 1} )}
  • ))}
)} {phase.experimentId && ( Open {phase.phase} experiment )}
))}
{validation.selection && (

Fixed training selection

Selected training candidate {validation.selection.winner.index + 1}

                {JSON.stringify(validation.selection.winner.parameters, null, 2)}
              

Selection {validation.selection.id} · {validation.selection.selectionHash} ·{' '} {validation.selection.createdAt} · {validation.selection.principal}

Holdout admission approval: {validation.selection.reviewId}

)} {validation.selection && ( )} {validation.report && (

Saved validation report

Report {validation.report.id} · {validation.report.reportHash} ·{' '} {validation.report.createdAt} · {validation.report.principal}

Independent reset accounts. No return compounding, portfolio stitching or OOS parameter ranking is applied.

{validation.report.limitations.map((value, index) => (

{value}

))}
)} )}
); }