feat(research): retain exact experiment and report citations in findings
This commit is contained in:
parent
46a4f13acd
commit
06039d17ba
36 changed files with 4170 additions and 253 deletions
|
|
@ -2,8 +2,11 @@ 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/components/findingSources';
|
||||
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
|
||||
import { ExperimentCounts } from './components/ExperimentCounts';
|
||||
import { RegimeEvidenceUnavailable } from './components/RegimeEvidenceUnavailable';
|
||||
import { SourceFindingAction } from './components/SourceFindingAction';
|
||||
import { ValidationEvidence } from './components/ValidationEvidence';
|
||||
import {
|
||||
chronologicalValidationDurableApi,
|
||||
|
|
@ -24,6 +27,7 @@ type Intent =
|
|||
key: string;
|
||||
};
|
||||
function ValidationDetail({ validationId }: { validationId: string }) {
|
||||
const [findingDirty, setFindingDirty] = useState(false);
|
||||
const alive = useRef(false),
|
||||
pending = useRef(false),
|
||||
reading = useRef(true),
|
||||
|
|
@ -195,6 +199,22 @@ function ValidationDetail({ validationId }: { validationId: string }) {
|
|||
<div
|
||||
className="h-full overflow-auto p-1 space-y-4"
|
||||
onClickCapture={event => {
|
||||
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 &&
|
||||
|
|
@ -270,6 +290,15 @@ function ValidationDetail({ validationId }: { validationId: string }) {
|
|||
)}
|
||||
{validation && (
|
||||
<>
|
||||
<RegimeEvidenceUnavailable />
|
||||
{!validation.report && (
|
||||
<SourceFindingAction
|
||||
source={null}
|
||||
disabled
|
||||
onDirtyChange={setFindingDirty}
|
||||
unavailable="Save the complete report before linking its evidence to a research finding."
|
||||
/>
|
||||
)}
|
||||
<p className="font-semibold">
|
||||
{validation.report
|
||||
? 'Execution complete · report saved'
|
||||
|
|
@ -481,6 +510,13 @@ function ValidationDetail({ validationId }: { validationId: string }) {
|
|||
{validation.report && (
|
||||
<section aria-label="Saved validation report" className="space-y-3">
|
||||
<h2 className="font-semibold">Saved validation report</h2>
|
||||
<SourceFindingAction
|
||||
key={validation.report.reportHash}
|
||||
source={chronologicalFindingSource(validation)}
|
||||
disabled={loading || busy || Boolean(intent)}
|
||||
onDirtyChange={setFindingDirty}
|
||||
unavailable="A sealed report is required to cite this source."
|
||||
/>
|
||||
<p className="break-all text-xs">
|
||||
Report {validation.report.id} · {validation.report.reportHash} ·{' '}
|
||||
{validation.report.createdAt} · {validation.report.principal}
|
||||
|
|
|
|||
|
|
@ -2,10 +2,13 @@ import { useCallback, useEffect, useRef, useState } from 'react';
|
|||
import { Link, useParams } from 'react-router-dom';
|
||||
import type { ExperimentTrial } from '@stock-bot/stock-config/experiments';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { experimentFindingSource } from '@/features/research/components/findingSources';
|
||||
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
|
||||
import { ExperimentCounts } from './components/ExperimentCounts';
|
||||
import { ExperimentInputs } from './components/ExperimentInputs';
|
||||
import { ExperimentTrialRecovery } from './components/ExperimentTrialRecovery';
|
||||
import { RegimeEvidenceUnavailable } from './components/RegimeEvidenceUnavailable';
|
||||
import { SourceFindingAction } from './components/SourceFindingAction';
|
||||
import { metricText } from './components/trialMetricText';
|
||||
import {
|
||||
experimentApi,
|
||||
|
|
@ -17,6 +20,7 @@ export function ExperimentDetailPage() {
|
|||
return <ExperimentDetailView key={experimentId} experimentId={experimentId} />;
|
||||
}
|
||||
function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
||||
const [findingDirty, setFindingDirty] = useState(false);
|
||||
const alive = useRef(false);
|
||||
const pending = useRef(false);
|
||||
const reading = useRef(true);
|
||||
|
|
@ -135,6 +139,22 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
<div
|
||||
className="h-full overflow-auto space-y-5 p-1"
|
||||
onClickCapture={event => {
|
||||
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') &&
|
||||
retryIntents.length > 0 &&
|
||||
|
|
@ -181,6 +201,14 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
{experiment && (
|
||||
<>
|
||||
<ExperimentCounts experiment={experiment} />
|
||||
<RegimeEvidenceUnavailable />
|
||||
<SourceFindingAction
|
||||
key={`experiment:${experiment.id}:${experiment.previewHash}`}
|
||||
source={experimentFindingSource(experiment)}
|
||||
disabled={loading || mutating || retryIntents.length > 0}
|
||||
onDirtyChange={setFindingDirty}
|
||||
unavailable="Only explicitly standalone experiments can be cited here. Use the saved chronological or walk-forward report for validation evidence."
|
||||
/>
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<Link
|
||||
className="text-primary-500 text-sm"
|
||||
|
|
|
|||
|
|
@ -2,7 +2,10 @@ import { useEffect, useRef, useState } from 'react';
|
|||
import { Link, useParams } from 'react-router-dom';
|
||||
import type { WalkForwardReceipt } from '@stock-bot/stock-config/walk-forward';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { walkForwardFindingSource } from '@/features/research/components/findingSources';
|
||||
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
|
||||
import { RegimeEvidenceUnavailable } from './components/RegimeEvidenceUnavailable';
|
||||
import { SourceFindingAction } from './components/SourceFindingAction';
|
||||
import { ValidationEvidence } from './components/ValidationEvidence';
|
||||
import {
|
||||
walkForwardApi,
|
||||
|
|
@ -16,6 +19,7 @@ export function WalkForwardDetailPage() {
|
|||
}
|
||||
type Intent = { id: string; body: { previewHash: string }; key: string };
|
||||
function WalkForwardDetail({ walkForwardId }: { walkForwardId: string }) {
|
||||
const [findingDirty, setFindingDirty] = useState(false);
|
||||
const alive = useRef(false),
|
||||
pending = useRef(false),
|
||||
reading = useRef(true),
|
||||
|
|
@ -170,6 +174,22 @@ function WalkForwardDetail({ walkForwardId }: { walkForwardId: string }) {
|
|||
<div
|
||||
className="h-full overflow-auto p-1 space-y-4"
|
||||
onClickCapture={event => {
|
||||
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 &&
|
||||
|
|
@ -239,6 +259,15 @@ function WalkForwardDetail({ walkForwardId }: { walkForwardId: string }) {
|
|||
)}
|
||||
{value && (
|
||||
<>
|
||||
<RegimeEvidenceUnavailable />
|
||||
{!value.report && (
|
||||
<SourceFindingAction
|
||||
source={null}
|
||||
disabled
|
||||
onDirtyChange={setFindingDirty}
|
||||
unavailable="Save the complete report before linking its evidence to a research finding."
|
||||
/>
|
||||
)}
|
||||
<p className="font-semibold">
|
||||
{value.report
|
||||
? 'Execution complete · walk-forward report saved'
|
||||
|
|
@ -348,6 +377,13 @@ function WalkForwardDetail({ walkForwardId }: { walkForwardId: string }) {
|
|||
{value.report && (
|
||||
<section aria-label="Saved walk-forward report" className="space-y-3">
|
||||
<h2 className="font-semibold">Saved walk-forward report</h2>
|
||||
<SourceFindingAction
|
||||
key={value.report.reportHash}
|
||||
source={walkForwardFindingSource(value)}
|
||||
disabled={loading || busy || Boolean(intent)}
|
||||
onDirtyChange={setFindingDirty}
|
||||
unavailable="A sealed report is required to cite this source."
|
||||
/>
|
||||
<p className="break-all">
|
||||
Report {value.report.id} · {value.report.createdAt} · Hash {value.report.reportHash}
|
||||
</p>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,15 @@
|
|||
export function RegimeEvidenceUnavailable() {
|
||||
return (
|
||||
<section aria-label="Regime evidence" className="text-sm space-y-1">
|
||||
<h2 className="font-semibold">Regime evidence unavailable</h2>
|
||||
<p>
|
||||
No versioned as-of regime annotations were retained for these results. Regime sample counts,
|
||||
unclassified samples and window coverage are unavailable.
|
||||
</p>
|
||||
<p>
|
||||
Strategy names, parameters and current market classifications do not establish historical
|
||||
regime evidence.
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import type { FindingDraftSource } from '@/features/research/components/findingSources';
|
||||
import { SaveSourceFindingDialog } from '@/features/research/components/SaveFindingDialog';
|
||||
|
||||
export function SourceFindingAction({
|
||||
source,
|
||||
unavailable,
|
||||
disabled,
|
||||
onDirtyChange,
|
||||
}: {
|
||||
source: FindingDraftSource | null;
|
||||
unavailable: string;
|
||||
disabled?: boolean;
|
||||
onDirtyChange: (dirty: boolean) => void;
|
||||
}) {
|
||||
const [snapshot, setSnapshot] = useState<FindingDraftSource | null>(null);
|
||||
const eligible = source?.runs.some(run => run.metrics.length);
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled || !eligible}
|
||||
onClick={() => {
|
||||
if (source && eligible) {
|
||||
setSnapshot(structuredClone(source));
|
||||
}
|
||||
}}
|
||||
>
|
||||
Save research finding
|
||||
</Button>
|
||||
{!eligible && (
|
||||
<p className="text-sm">
|
||||
{source
|
||||
? 'No completed, comparable measurements are available to cite yet.'
|
||||
: unavailable}
|
||||
</p>
|
||||
)}
|
||||
{snapshot && (
|
||||
<SaveSourceFindingDialog
|
||||
source={snapshot}
|
||||
onClose={() => setSnapshot(null)}
|
||||
onDirtyChange={onDirtyChange}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -144,7 +144,11 @@ const trial = candidate.extend({
|
|||
unavailable: z.record(z.string()).nullable(),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const detail = summary.extend({ preview, trials: z.array(trial).max(MAX_EXPERIMENT_TRIALS) });
|
||||
const detail = summary.extend({
|
||||
standalone: z.boolean().optional(),
|
||||
preview,
|
||||
trials: z.array(trial).max(MAX_EXPERIMENT_TRIALS),
|
||||
});
|
||||
const retryReceipt = z.object({
|
||||
id: z.string().uuid(),
|
||||
experimentId: z.string().uuid(),
|
||||
|
|
@ -219,6 +223,7 @@ const costPreview = preview
|
|||
.strict();
|
||||
const costDetail = summary.extend({
|
||||
kind: z.literal('cost-sensitivity'),
|
||||
standalone: z.boolean().optional(),
|
||||
preview: z.unknown(),
|
||||
trials: z.array(trial.extend({ costs: costScenarioSchema })).max(MAX_EXPERIMENT_TRIALS),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -0,0 +1,49 @@
|
|||
import { Link } from 'react-router-dom';
|
||||
import type { ResearchFindingSource } from '@stock-bot/types';
|
||||
|
||||
export function FindingSource({
|
||||
source,
|
||||
link = true,
|
||||
}: {
|
||||
source?: ResearchFindingSource | null;
|
||||
link?: boolean;
|
||||
}) {
|
||||
if (!source) {
|
||||
return null;
|
||||
}
|
||||
const identity =
|
||||
source.kind === 'experiment/v1'
|
||||
? source.experimentId
|
||||
: source.kind === 'chronological-report/v1'
|
||||
? source.validationId
|
||||
: source.walkForwardId;
|
||||
const href =
|
||||
source.kind === 'experiment/v1'
|
||||
? `/experiments/${identity}`
|
||||
: source.kind === 'chronological-report/v1'
|
||||
? `/experiments/validation/${identity}`
|
||||
: `/experiments/walk-forward/${identity}`;
|
||||
return (
|
||||
<section aria-label="Finding source" className="space-y-1 break-all text-sm">
|
||||
<h3 className="font-medium">Exact evidence source</h3>
|
||||
<p>
|
||||
{source.kind} · {identity}
|
||||
</p>
|
||||
<p>Preview hash: {source.previewHash}</p>
|
||||
{'reportId' in source && (
|
||||
<p>
|
||||
Report: {source.reportId} · Report hash: {source.reportHash}
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Selected contributing evidence; the source does not validate this narrative or endorse the
|
||||
whole experiment or report.
|
||||
</p>
|
||||
{link && (
|
||||
<Link className="text-primary-500 underline" to={href}>
|
||||
Open cited source
|
||||
</Link>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -12,6 +12,7 @@ import { Card } from '@/components/ui/Card';
|
|||
import { actionClass, fieldClass } from '../../strategies/components/StrategyParameterForm';
|
||||
import { confirmDiscard, useUnsavedWarning } from '../../strategies/components/useUnsavedWarning';
|
||||
import { researchApi, ResearchApiError } from '../services/researchApi';
|
||||
import { FindingSource } from './FindingSource';
|
||||
import {
|
||||
evidenceReferences,
|
||||
ResearchAuthorshipBadge,
|
||||
|
|
@ -255,6 +256,9 @@ export function ResearchEntry({
|
|||
body,
|
||||
contentOrigin: origin,
|
||||
evidence: evidenceReferences(entry.entity.latestRevision.evidence),
|
||||
...(entry.entity.latestRevision.source !== undefined
|
||||
? { source: entry.entity.latestRevision.source }
|
||||
: {}),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
|
@ -355,7 +359,12 @@ export function ResearchEntry({
|
|||
</p>
|
||||
</div>
|
||||
)}
|
||||
{'evidence' in revision && <ResearchEvidenceList evidence={revision.evidence} />}
|
||||
{'evidence' in revision && (
|
||||
<>
|
||||
<FindingSource source={revision.source} />
|
||||
<ResearchEvidenceList evidence={revision.evidence} />
|
||||
</>
|
||||
)}
|
||||
{entry.kind === 'artifact' && entry.entity.hypothesisRevisionId && (
|
||||
<HypothesisReference
|
||||
projectId={projectId}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,7 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import {
|
||||
isCanonicalRunResult,
|
||||
type ResearchRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
canonicalResearchMetricPaths,
|
||||
legacyResearchMetricPaths,
|
||||
} from '@stock-bot/stock-config/research';
|
||||
import type { ResearchRunResult } from '@stock-bot/stock-config/canonical-research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import type {
|
||||
ResearchArtifact,
|
||||
ResearchContentOrigin,
|
||||
|
|
@ -22,16 +16,49 @@ import {
|
|||
useUnsavedWarning,
|
||||
} from '@/features/strategies/components/useUnsavedWarning';
|
||||
import { researchApi, ResearchApiError, type ArtifactInput } from '../services/researchApi';
|
||||
import { FindingSource } from './FindingSource';
|
||||
import {
|
||||
findingMetricKey,
|
||||
singleRunFindingSource,
|
||||
type FindingDraftSource,
|
||||
} from './findingSources';
|
||||
import { ResearchEvidenceList, researchMetricLabel } from './ResearchEvidence';
|
||||
|
||||
/** Remount even when a caller replaces the result without keying its dialog. */
|
||||
export function SaveFindingDialog(props: { result: ResearchRunResult; onClose: () => void }) {
|
||||
return <FindingDraft key={`${props.result.backtestId}:${props.result.runId}`} {...props} />;
|
||||
/** Preserve the original single-run API and initial total-return selection. */
|
||||
export function SaveFindingDialog({
|
||||
result,
|
||||
onClose,
|
||||
}: {
|
||||
result: ResearchRunResult;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
return (
|
||||
<FindingDraft
|
||||
key={`${result.backtestId}:${result.runId}`}
|
||||
source={singleRunFindingSource(result)}
|
||||
onClose={onClose}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose: () => void }) {
|
||||
const canonical = isCanonicalRunResult(result);
|
||||
const metricPaths = canonical ? canonicalResearchMetricPaths : legacyResearchMetricPaths;
|
||||
export function SaveSourceFindingDialog(props: {
|
||||
source: FindingDraftSource;
|
||||
onClose: () => void;
|
||||
onDirtyChange?: (dirty: boolean) => void;
|
||||
}) {
|
||||
return <FindingDraft key={props.source.key} {...props} />;
|
||||
}
|
||||
function FindingDraft({
|
||||
source: incoming,
|
||||
onClose,
|
||||
onDirtyChange,
|
||||
}: {
|
||||
source: FindingDraftSource;
|
||||
onClose: () => void;
|
||||
onDirtyChange?: (dirty: boolean) => void;
|
||||
}) {
|
||||
// Retain the exact open-time source and choices through background page refreshes.
|
||||
const [source] = useState(() => structuredClone(incoming));
|
||||
const metrics = source.runs.flatMap(run => run.metrics);
|
||||
const [projects, setProjects] = useState<ResearchProject[]>([]);
|
||||
const [projectsLoading, setProjectsLoading] = useState(true);
|
||||
const [projectsError, setProjectsError] = useState('');
|
||||
|
|
@ -46,7 +73,7 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose:
|
|||
const [title, setTitle] = useState('');
|
||||
const [body, setBody] = useState('');
|
||||
const [contentOrigin, setContentOrigin] = useState<ResearchContentOrigin>('human');
|
||||
const [selectedMetrics, setSelectedMetrics] = useState<string[]>([metricPaths[0]]);
|
||||
const [selectedMetrics, setSelectedMetrics] = useState<string[]>(source.initialSelection);
|
||||
const [pending, setPending] = useState(false);
|
||||
const [ambiguous, setAmbiguous] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
|
@ -63,10 +90,14 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose:
|
|||
body ||
|
||||
projectId ||
|
||||
contentOrigin !== 'human' ||
|
||||
selectedMetrics.length !== 1 ||
|
||||
selectedMetrics[0] !== metricPaths[0]
|
||||
selectedMetrics.length !== source.initialSelection.length ||
|
||||
selectedMetrics.some((key, index) => key !== source.initialSelection[index])
|
||||
);
|
||||
useUnsavedWarning(dirty);
|
||||
useEffect(() => {
|
||||
onDirtyChange?.(dirty || pending || ambiguous);
|
||||
}, [dirty, pending, ambiguous, onDirtyChange]);
|
||||
useEffect(() => () => onDirtyChange?.(false), [onDirtyChange]);
|
||||
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
|
|
@ -159,7 +190,7 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose:
|
|||
destinationLoading ||
|
||||
!title.trim() ||
|
||||
!selectedMetrics.length ||
|
||||
result.status !== 'completed'
|
||||
!metrics.length
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -176,22 +207,10 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose:
|
|||
body,
|
||||
contentOrigin,
|
||||
hypothesisRevisionId: hypothesisRevisionId || null,
|
||||
evidence: canonical
|
||||
? canonicalResearchMetricPaths
|
||||
.filter(path => selectedMetrics.includes(path))
|
||||
.map(metricPath => ({
|
||||
runId: result.runId,
|
||||
metricsVersion: 'canonical-analytics/v1' as const,
|
||||
strategyVersionId: result.request.strategy.versionId,
|
||||
metricPath,
|
||||
}))
|
||||
: legacyResearchMetricPaths
|
||||
.filter(path => selectedMetrics.includes(path))
|
||||
.map(metricPath => ({
|
||||
runId: result.runId,
|
||||
metricsVersion: 'legacy-display/v1' as const,
|
||||
metricPath,
|
||||
})),
|
||||
evidence: metrics
|
||||
.filter(metric => selectedMetrics.includes(findingMetricKey(metric.reference)))
|
||||
.map(metric => metric.reference),
|
||||
...(source.context ? { source: source.context } : {}),
|
||||
};
|
||||
submission.current = true;
|
||||
setPending(true);
|
||||
|
|
@ -232,7 +251,20 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose:
|
|||
!artifact?.id ||
|
||||
artifact.projectId !== projectId ||
|
||||
artifact.hypothesisRevisionId !== input.hypothesisRevisionId ||
|
||||
artifact.kind !== 'finding'
|
||||
artifact.kind !== 'finding' ||
|
||||
(source.context !== null &&
|
||||
(canonicalStrategyJson(artifact.latestRevision.source ?? null) !==
|
||||
canonicalStrategyJson(source.context) ||
|
||||
canonicalStrategyJson(
|
||||
artifact.latestRevision.evidence.map(
|
||||
({ runId, metricsVersion, metricPath, strategyVersionId }) => ({
|
||||
runId,
|
||||
metricsVersion,
|
||||
metricPath,
|
||||
strategyVersionId,
|
||||
})
|
||||
)
|
||||
) !== canonicalStrategyJson(input.evidence)))
|
||||
) {
|
||||
throw new ResearchApiError('The saved finding response could not be verified.', null);
|
||||
}
|
||||
|
|
@ -249,9 +281,6 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose:
|
|||
}
|
||||
}
|
||||
}
|
||||
const limitations = canonical
|
||||
? [...result.financial.limitations, ...result.financial.modelLimitations]
|
||||
: (result.provenance?.limitations.map(item => item.message) ?? []);
|
||||
return (
|
||||
<Dialog open onOpenChange={open => !open && close()}>
|
||||
<DialogContent className="max-w-2xl w-[min(42rem,95vw)]">
|
||||
|
|
@ -260,22 +289,23 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose:
|
|||
<DialogTitle>Save finding</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm break-all">
|
||||
Run: {result.runId} ·{' '}
|
||||
{canonical ? 'Canonical Rust result' : 'Legacy · Unverified economics'}
|
||||
{source.label} ·{' '}
|
||||
{source.legacy ? 'Legacy · Unverified economics' : 'Canonical Rust result'}
|
||||
</p>
|
||||
{!canonical && (
|
||||
{source.legacy && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
Legacy display measurements are exploratory evidence; financial correctness and
|
||||
historical engine versions are not certified.
|
||||
</p>
|
||||
)}
|
||||
{limitations.length > 0 && (
|
||||
{source.limitations.length > 0 && (
|
||||
<ul className="list-disc pl-5 text-sm text-text-secondary">
|
||||
{limitations.map((limit, index) => (
|
||||
{source.limitations.map((limit, index) => (
|
||||
<li key={index}>{limit}</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<FindingSource source={source.context} link={Boolean(saved)} />
|
||||
{saved ? (
|
||||
<>
|
||||
<p role="status">Finding saved. Its narrative remains unvalidated.</p>
|
||||
|
|
@ -404,38 +434,61 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose:
|
|||
A finding is an unvalidated narrative with references to saved measurements. Values
|
||||
are resolved by the server.
|
||||
</p>
|
||||
<fieldset disabled={blocked} className="grid gap-2 sm:grid-cols-2">
|
||||
<legend className="mb-2 text-sm font-medium">Referenced measurements</legend>
|
||||
{metricPaths.map(path => {
|
||||
const value = path
|
||||
.split('.')
|
||||
.reduce<unknown>(
|
||||
(item, key) =>
|
||||
item && typeof item === 'object'
|
||||
? (item as Record<string, unknown>)[key]
|
||||
: undefined,
|
||||
result
|
||||
{source.context && (
|
||||
<p className="text-sm">
|
||||
Choose contributing runs and measurements explicitly. Unselected and unavailable
|
||||
outcomes remain visible.
|
||||
</p>
|
||||
)}
|
||||
{source.runs.map(run => (
|
||||
<fieldset
|
||||
key={run.key}
|
||||
aria-label={source.context ? run.label : undefined}
|
||||
disabled={blocked}
|
||||
className="grid gap-2 sm:grid-cols-2"
|
||||
>
|
||||
<legend className="mb-2 text-sm font-medium">
|
||||
{source.context ? `${run.label} · ${run.status}` : 'Referenced measurements'}
|
||||
</legend>
|
||||
{run.diagnostic && <p className="text-sm sm:col-span-2">{run.diagnostic}</p>}
|
||||
{!run.metrics.length && (
|
||||
<p className="text-sm sm:col-span-2">
|
||||
No selectable measurements. A completed, comparable saved result is required.
|
||||
</p>
|
||||
)}
|
||||
{run.metrics.map(metric => {
|
||||
const key = findingMetricKey(metric.reference);
|
||||
const label = researchMetricLabel(metric.reference.metricPath);
|
||||
return (
|
||||
<label key={key} className="text-sm flex gap-2 items-start">
|
||||
<input
|
||||
type="checkbox"
|
||||
data-run-id={metric.reference.runId}
|
||||
data-metric-path={metric.reference.metricPath}
|
||||
aria-label={source.context ? `${run.label}: ${label}` : label}
|
||||
checked={selectedMetrics.includes(key)}
|
||||
onChange={event =>
|
||||
setSelectedMetrics(previous =>
|
||||
event.target.checked
|
||||
? [...previous, key]
|
||||
: previous.filter(item => item !== key)
|
||||
)
|
||||
}
|
||||
/>
|
||||
{label}
|
||||
{source.context
|
||||
? ` (${metric.reference.metricPath.endsWith('sharpeRatio') ? 'ratio' : 'fraction'})`
|
||||
: ''}
|
||||
{metric.value === null
|
||||
? ` · Unavailable${source.context && metric.unavailableReason ? `: ${metric.unavailableReason}` : ''}`
|
||||
: source.context
|
||||
? ` · ${String(metric.value)}`
|
||||
: ''}
|
||||
</label>
|
||||
);
|
||||
return (
|
||||
<label key={path} className="text-sm flex gap-2 items-start">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={researchMetricLabel(path)}
|
||||
checked={selectedMetrics.includes(path)}
|
||||
onChange={event =>
|
||||
setSelectedMetrics(previous =>
|
||||
event.target.checked
|
||||
? [...previous, path]
|
||||
: previous.filter(item => item !== path)
|
||||
)
|
||||
}
|
||||
/>
|
||||
{researchMetricLabel(path)}
|
||||
{value === null || value === undefined ? ' · Unavailable' : ''}
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</fieldset>
|
||||
})}
|
||||
</fieldset>
|
||||
))}
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{ambiguous && (
|
||||
<div role="alert" className="space-y-2">
|
||||
|
|
@ -475,7 +528,7 @@ function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose:
|
|||
destinationLoading ||
|
||||
!title.trim() ||
|
||||
!selectedMetrics.length ||
|
||||
result.status !== 'completed'
|
||||
!metrics.length
|
||||
}
|
||||
onClick={() => void save()}
|
||||
>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,215 @@
|
|||
import {
|
||||
isCanonicalRunResult,
|
||||
type ResearchRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type { ValidationResultEvidence } from '@stock-bot/stock-config/chronological-validation';
|
||||
import {
|
||||
canonicalResearchMetricPaths,
|
||||
legacyResearchMetricPaths,
|
||||
} from '@stock-bot/stock-config/research';
|
||||
import type { ResearchFindingSource } from '@stock-bot/types';
|
||||
import type { ValidationDetailView } from '@/features/experiments/services/chronologicalValidationDurableApi';
|
||||
import type { WorkbenchExperimentDetailView } from '@/features/experiments/services/experimentApi';
|
||||
import type { WalkForwardDetailView } from '@/features/experiments/services/walkForwardApi';
|
||||
import type { ArtifactInput } from '../services/researchApi';
|
||||
|
||||
type Reference = NonNullable<ArtifactInput['evidence']>[number];
|
||||
export interface FindingMetricChoice {
|
||||
reference: Reference;
|
||||
value: number | null;
|
||||
unavailableReason?: string | null;
|
||||
}
|
||||
export interface FindingRunChoice {
|
||||
key: string;
|
||||
label: string;
|
||||
status: string;
|
||||
diagnostic: string | null;
|
||||
metrics: FindingMetricChoice[];
|
||||
}
|
||||
export interface FindingDraftSource {
|
||||
key: string;
|
||||
label: string;
|
||||
context: ResearchFindingSource | null;
|
||||
legacy: boolean;
|
||||
limitations: string[];
|
||||
runs: FindingRunChoice[];
|
||||
initialSelection: string[];
|
||||
}
|
||||
export const findingMetricKey = (reference: Reference) =>
|
||||
`${reference.runId}:${reference.metricsVersion}:${reference.metricPath}`;
|
||||
const sourceMetrics = ['totalReturn', 'maxDrawdown', 'sharpeRatio'] as const;
|
||||
function choices(
|
||||
runId: string,
|
||||
strategyVersionId: string,
|
||||
metrics: Record<(typeof sourceMetrics)[number], number | null>,
|
||||
unavailable: Record<string, string>
|
||||
): FindingMetricChoice[] {
|
||||
return sourceMetrics.map(key => ({
|
||||
reference: {
|
||||
runId,
|
||||
strategyVersionId,
|
||||
metricsVersion: 'canonical-analytics/v1',
|
||||
metricPath: `analytics.metrics.${key}`,
|
||||
},
|
||||
value: metrics[key],
|
||||
unavailableReason: unavailable[key],
|
||||
}));
|
||||
}
|
||||
export function singleRunFindingSource(result: ResearchRunResult): FindingDraftSource {
|
||||
const canonical = isCanonicalRunResult(result);
|
||||
const references: Reference[] = canonical
|
||||
? canonicalResearchMetricPaths.map(metricPath => ({
|
||||
runId: result.runId,
|
||||
metricsVersion: 'canonical-analytics/v1',
|
||||
strategyVersionId: result.request.strategy.versionId,
|
||||
metricPath,
|
||||
}))
|
||||
: legacyResearchMetricPaths.map(metricPath => ({
|
||||
runId: result.runId,
|
||||
metricsVersion: 'legacy-display/v1',
|
||||
metricPath,
|
||||
}));
|
||||
const metrics =
|
||||
result.status === 'completed'
|
||||
? references.map(reference => {
|
||||
const value = reference.metricPath
|
||||
.split('.')
|
||||
.reduce<unknown>(
|
||||
(item, key) =>
|
||||
item && typeof item === 'object'
|
||||
? (item as Record<string, unknown>)[key]
|
||||
: undefined,
|
||||
result
|
||||
);
|
||||
return { reference, value: typeof value === 'number' ? value : null };
|
||||
})
|
||||
: [];
|
||||
return {
|
||||
key: `${result.backtestId}:${result.runId}`,
|
||||
label: `Run: ${result.runId}`,
|
||||
context: null,
|
||||
legacy: !canonical,
|
||||
limitations: canonical
|
||||
? [...result.financial.limitations, ...result.financial.modelLimitations]
|
||||
: (result.provenance?.limitations.map(item => item.message) ?? []),
|
||||
runs: [{ key: result.runId, label: 'Run', status: result.status, diagnostic: null, metrics }],
|
||||
initialSelection: metrics[0] ? [findingMetricKey(metrics[0].reference)] : [],
|
||||
};
|
||||
}
|
||||
function source(
|
||||
context: ResearchFindingSource,
|
||||
label: string,
|
||||
runs: FindingRunChoice[],
|
||||
limitations: string[]
|
||||
): FindingDraftSource {
|
||||
return {
|
||||
key: JSON.stringify(context),
|
||||
label,
|
||||
context,
|
||||
legacy: false,
|
||||
runs,
|
||||
limitations,
|
||||
initialSelection: [],
|
||||
};
|
||||
}
|
||||
export function experimentFindingSource(
|
||||
value: WorkbenchExperimentDetailView
|
||||
): FindingDraftSource | null {
|
||||
if (value.standalone !== true) {
|
||||
return null;
|
||||
}
|
||||
return source(
|
||||
{ kind: 'experiment/v1', experimentId: value.id, previewHash: value.previewHash },
|
||||
value.name,
|
||||
value.trials.map(trial => ({
|
||||
key: trial.trialKey,
|
||||
label:
|
||||
value.kind === 'cost-sensitivity'
|
||||
? trial.index === 0
|
||||
? 'Baseline'
|
||||
: `Scenario ${trial.index}`
|
||||
: `Trial ${trial.index + 1}`,
|
||||
status:
|
||||
trial.status === 'completed' && !trial.comparable
|
||||
? 'completed · incomparable'
|
||||
: trial.status,
|
||||
diagnostic: trial.error ?? trial.diagnostic,
|
||||
metrics:
|
||||
trial.status === 'completed' &&
|
||||
trial.comparable &&
|
||||
trial.runId &&
|
||||
trial.metrics &&
|
||||
trial.unavailable
|
||||
? choices(trial.runId, value.strategyVersionId, trial.metrics, trial.unavailable)
|
||||
: [],
|
||||
})),
|
||||
[
|
||||
'Selected contributing measurements do not endorse the whole experiment or establish out-of-sample validity.',
|
||||
]
|
||||
);
|
||||
}
|
||||
function reportRun(
|
||||
item: ValidationResultEvidence,
|
||||
strategyVersionId: string,
|
||||
prefix = ''
|
||||
): FindingRunChoice {
|
||||
return {
|
||||
key: `${prefix}${item.phase}:${item.runId}`,
|
||||
label: `${prefix}${item.phase} candidate ${item.sourceCandidateIndex + 1}`,
|
||||
status: 'completed',
|
||||
diagnostic: null,
|
||||
metrics: choices(item.runId, strategyVersionId, item.metrics, item.unavailable),
|
||||
};
|
||||
}
|
||||
export function chronologicalFindingSource(value: ValidationDetailView): FindingDraftSource | null {
|
||||
const report = value.report;
|
||||
if (!report) {
|
||||
return null;
|
||||
}
|
||||
return source(
|
||||
{
|
||||
kind: 'chronological-report/v1',
|
||||
validationId: value.id,
|
||||
previewHash: value.previewHash,
|
||||
reportId: report.id,
|
||||
reportHash: report.reportHash,
|
||||
},
|
||||
value.name,
|
||||
[...report.training, report.validation, report.test].map(item =>
|
||||
reportRun(item, value.preview.source.request.strategy.versionId)
|
||||
),
|
||||
[
|
||||
...report.limitations,
|
||||
'Selected contributing measurements do not endorse the whole report. Training, validation and test remain distinct reset accounts.',
|
||||
]
|
||||
);
|
||||
}
|
||||
export function walkForwardFindingSource(value: WalkForwardDetailView): FindingDraftSource | null {
|
||||
const report = value.report;
|
||||
if (!report) {
|
||||
return null;
|
||||
}
|
||||
return source(
|
||||
{
|
||||
kind: 'walk-forward-report/v1',
|
||||
walkForwardId: value.id,
|
||||
previewHash: value.previewHash,
|
||||
reportId: report.id,
|
||||
reportHash: report.reportHash,
|
||||
},
|
||||
value.name,
|
||||
report.segments.flatMap(segment =>
|
||||
[segment.validation, segment.test].map(item =>
|
||||
reportRun(
|
||||
item,
|
||||
value.preview.source.request.strategy.versionId,
|
||||
`Window ${segment.index + 1} `
|
||||
)
|
||||
)
|
||||
),
|
||||
[
|
||||
...report.limitations,
|
||||
'Selected contributing measurements do not endorse the whole report. Windows are independent reset segments, not continuous portfolio equity.',
|
||||
]
|
||||
);
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import type { z } from 'zod';
|
||||
import { researchFindingSourceSchema } from '@stock-bot/stock-config/research';
|
||||
import type {
|
||||
createResearchArtifactSchema,
|
||||
createResearchHypothesisSchema,
|
||||
|
|
@ -49,6 +50,17 @@ const record = (value: unknown): value is Record<string, unknown> =>
|
|||
typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
const identified = (value: unknown): value is Record<string, unknown> =>
|
||||
record(value) && typeof value.id === 'string' && value.id.length > 0;
|
||||
function validSource(value: Record<string, unknown>): boolean {
|
||||
if (value.source === undefined || value.source === null) {
|
||||
return true;
|
||||
}
|
||||
const parsed = researchFindingSourceSchema.safeParse(value.source);
|
||||
if (!parsed.success) {
|
||||
return false;
|
||||
}
|
||||
value.source = parsed.data;
|
||||
return true;
|
||||
}
|
||||
function validEnvelope(body: unknown, field: ResponseField): boolean {
|
||||
if (!record(body)) {
|
||||
return false;
|
||||
|
|
@ -61,9 +73,13 @@ function validEnvelope(body: unknown, field: ResponseField): boolean {
|
|||
return typeof item.title === 'string' && Number.isInteger(item.revision);
|
||||
}
|
||||
if (['hypothesis', 'hypotheses', 'artifact', 'artifacts'].includes(field)) {
|
||||
return typeof item.projectId === 'string' && identified(item.latestRevision);
|
||||
return (
|
||||
typeof item.projectId === 'string' &&
|
||||
identified(item.latestRevision) &&
|
||||
validSource(item.latestRevision)
|
||||
);
|
||||
}
|
||||
return true;
|
||||
return validSource(item);
|
||||
};
|
||||
const value = body[field];
|
||||
return ['project', 'hypothesis', 'artifact'].includes(field)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue