feat(research): add workspace and evidence-linked finding UI

This commit is contained in:
Boki 2026-10-24 01:26:07 -04:00
parent ee45257507
commit e3bd708838
21 changed files with 4566 additions and 1379 deletions

View file

@ -2,6 +2,7 @@ import { ArrowLeftIcon, PlusIcon } from '@heroicons/react/24/outline';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { isCanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
import { SaveFindingDialog } from '@/features/research/components/SaveFindingDialog';
import {
catalogExecutionReason,
supportedLegacyStrategy,
@ -34,6 +35,7 @@ export function BacktestDetailPageV2() {
const navigate = useNavigate();
const [activeTab, setActiveTab] = useState('details');
const [showNewRun, setShowNewRun] = useState(false);
const [showFinding, setShowFinding] = useState(false);
const [showArchiveDialog, setShowArchiveDialog] = useState(false);
const [showCanonicalSetup, setShowCanonicalSetup] = useState(false);
const navigationGeneration = useRef(0);
@ -62,6 +64,17 @@ export function BacktestDetailPageV2() {
refreshRun,
} = useBacktestV2();
const archived = Boolean(backtest?.archivedAt);
const findingResult =
!isLoading &&
currentRun?.status === 'completed' &&
currentRun.id === runId &&
currentRun.backtestId === id &&
runResults?.status === 'completed' &&
runResults.runId === runId &&
runResults.backtestId === id &&
backtest?.id === id
? runResults
: null;
const catalog = Boolean(backtest?.strategyVersionId) || backtest?.strategy === 'catalog';
const unsupportedLegacy = Boolean(
backtest && !catalog && !supportedLegacyStrategy(backtest.strategy)
@ -87,6 +100,7 @@ export function BacktestDetailPageV2() {
setShowNewRun(false);
setShowArchiveDialog(false);
setShowCanonicalSetup(false);
setShowFinding(false);
return () => {
navigationGeneration.current++;
};
@ -469,6 +483,21 @@ export function BacktestDetailPageV2() {
</div>
{/* Run Controls */}
{currentRun && (
<button
type="button"
disabled={!findingResult}
title={
findingResult
? 'Cite saved run measurements'
: 'A completed run with available saved results is required'
}
onClick={() => setShowFinding(true)}
className="px-3 py-2 text-sm text-primary-500 border border-border rounded-md disabled:opacity-50"
>
Save finding
</button>
)}
{backtest && (
<button
type="button"
@ -577,6 +606,13 @@ export function BacktestDetailPageV2() {
{currentRun && <RunDataset dataset={currentRun.dataset} />}
<div className="min-h-0 flex-1 overflow-y-auto">{renderTabContent()}</div>
</div>
{showFinding && findingResult && (
<SaveFindingDialog
key={findingResult.runId}
result={findingResult}
onClose={() => setShowFinding(false)}
/>
)}
{showArchiveDialog && backtest && (
<ArchiveBacktestDialog
key={backtest.id}

View file

@ -0,0 +1,234 @@
import { useEffect, useRef, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import type { ResearchProject } from '@stock-bot/types';
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';
export function ResearchListPage() {
const navigate = useNavigate();
const mounted = useRef(false);
const pending = useRef(false);
const [projects, setProjects] = useState<ResearchProject[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [refresh, setRefresh] = useState(0);
const [archived, setArchived] = useState(false);
const [creating, setCreating] = useState(false);
const [open, setOpen] = useState(false);
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [saveError, setSaveError] = useState('');
const [uncertain, setUncertain] = useState(false);
const dirty = open && Boolean(title || description);
useUnsavedWarning(dirty);
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
useEffect(() => {
let current = true;
const controller = new AbortController();
setLoading(true);
setError('');
void researchApi
.listProjects(archived, controller.signal)
.then(result => {
if (current) {
setProjects(result.projects);
}
})
.catch(cause => {
if (current) {
setError(cause instanceof Error ? cause.message : 'Could not load projects');
}
})
.finally(() => {
if (current) {
setLoading(false);
}
});
return () => {
current = false;
controller.abort();
};
}, [archived, refresh]);
const create = async (event: React.FormEvent) => {
event.preventDefault();
if (pending.current || uncertain || !title.trim()) {
return;
}
pending.current = true;
setCreating(true);
setSaveError('');
try {
const { project } = await researchApi.createProject({ title, description });
if (mounted.current) {
navigate(`/research/${project.id}`);
}
} catch (cause) {
if (mounted.current) {
setSaveError(cause instanceof Error ? cause.message : 'Could not create project');
setUncertain(!(cause instanceof ResearchApiError) || cause.ambiguous);
}
} finally {
pending.current = false;
if (mounted.current) {
setCreating(false);
}
}
};
return (
<div className="space-y-5 text-text-primary">
<div className="flex items-center justify-between">
<h1 className="text-lg font-bold">Research</h1>
<button className={actionClass} onClick={() => setOpen(true)}>
New project
</button>
</div>
<p className="text-sm text-text-secondary">
Organize hypotheses, strategies and findings with links to the exact backtests supporting
them.
</p>
{open && (
<Card className="p-4">
<form
className="space-y-3"
aria-label="Create research project"
onSubmit={event => void create(event)}
>
<label className="block">
Project title
<input
aria-label="Project title"
className={fieldClass}
value={title}
onChange={event => setTitle(event.target.value)}
disabled={creating || uncertain}
required
/>
</label>
<label className="block">
Project description
<textarea
aria-label="Project description"
className={fieldClass}
value={description}
onChange={event => setDescription(event.target.value)}
disabled={creating || uncertain}
/>
</label>
{saveError && (
<p role="alert" className="text-error">
{saveError}
</p>
)}
{uncertain && (
<div role="status">
<p>
The request may have saved. Check saved records before creating another project.
</p>
<button
type="button"
className={actionClass}
onClick={() => {
setArchived(true);
setRefresh(value => value + 1);
}}
>
Check saved projects
</button>{' '}
<button
type="button"
className={actionClass}
onClick={() => {
setUncertain(false);
setSaveError('');
}}
>
Start new request
</button>
</div>
)}
<button
type="submit"
className={actionClass}
disabled={creating || uncertain || !title.trim()}
>
{creating ? 'Creating project...' : 'Create project'}
</button>{' '}
<button
type="button"
className={actionClass}
disabled={creating}
onClick={() => {
if (confirmDiscard(dirty)) {
setOpen(false);
setTitle('');
setDescription('');
setSaveError('');
setUncertain(false);
}
}}
>
Discard project draft
</button>
</form>
</Card>
)}
<label className="flex gap-2">
<input
type="checkbox"
checked={archived}
onChange={event => setArchived(event.target.checked)}
/>
Show archived projects
</label>
{loading && <p role="status">Loading research projects...</p>}
{error && (
<div>
<p role="alert" className="text-error">
{error}
</p>
<button className={actionClass} onClick={() => setRefresh(value => value + 1)}>
Retry projects
</button>
</div>
)}
{!loading && !error && !projects.length && (
<p role="status">No research projects yet. Create a project to begin.</p>
)}
{!loading && !error && (
<ul className="space-y-3">
{projects.map(project => (
<li key={project.id}>
<Card className="p-4">
<Link
className="text-primary-500 font-medium"
to={`/research/${project.id}`}
onClick={event => {
if (!confirmDiscard(dirty)) {
event.preventDefault();
}
}}
>
{project.title}
</Link>
{project.archived && <span className="ml-2 text-xs">Archived</span>}
<p className="whitespace-pre-wrap text-sm text-text-secondary">
{project.description || 'No description yet.'}
</p>
<p className="text-xs text-text-muted">
Owner: {project.ownerPrincipal} · Updated {project.updatedAt}
</p>
</Card>
</li>
))}
</ul>
)}
</div>
);
}

View file

@ -0,0 +1,632 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { Link, useParams, useSearchParams } from 'react-router-dom';
import type {
ResearchArtifact,
ResearchHypothesis,
ResearchProject,
StrategyRecord,
} from '@stock-bot/types';
import { Card } from '@/components/ui/Card';
import { actionClass, fieldClass } from '../strategies/components/StrategyParameterForm';
import { confirmDiscard, useUnsavedWarning } from '../strategies/components/useUnsavedWarning';
import { strategyApi } from '../strategies/services/strategyApi';
import { CreateResearchEntry } from './components/CreateResearchEntry';
import { ResearchEntry } from './components/ResearchEntry';
import { researchApi, ResearchApiError } from './services/researchApi';
type Section = 'project' | 'strategies' | 'hypotheses' | 'artifacts' | 'catalog';
const initialErrors: Record<Section, string> = {
project: '',
strategies: '',
hypotheses: '',
artifacts: '',
catalog: '',
};
export function ResearchProjectPage() {
const { projectId } = useParams();
return projectId ? (
<ProjectWorkspace key={projectId} projectId={projectId} />
) : (
<p role="alert">Missing research project.</p>
);
}
function ProjectWorkspace({ projectId }: { projectId: string }) {
const [params, setParams] = useSearchParams();
const mounted = useRef(false);
const pending = useRef(false);
const [project, setProject] = useState<ResearchProject | null>(null);
const [strategies, setStrategies] = useState<StrategyRecord[]>([]);
const [catalog, setCatalog] = useState<StrategyRecord[]>([]);
const [hypotheses, setHypotheses] = useState<ResearchHypothesis[]>([]);
const [artifacts, setArtifacts] = useState<ResearchArtifact[]>([]);
const [errors, setErrors] = useState(initialErrors);
const [loading, setLoading] = useState(true);
const [refresh, setRefresh] = useState(0);
const [selectionEpoch, setSelectionEpoch] = useState(0);
const [showArchived, setShowArchived] = useState(false);
const [editing, setEditing] = useState<{
title: string;
description: string;
expectedRevision: number;
} | null>(null);
const [creator, setCreator] = useState<'hypothesis' | 'note' | null>(null);
const [createDirty, setCreateDirty] = useState(false);
const [entryDirty, setEntryDirty] = useState(false);
const [strategyId, setStrategyId] = useState('');
const [saving, setSaving] = useState(false);
const [mutationError, setMutationError] = useState('');
const [conflict, setConflict] = useState(false);
const dirty = Boolean(editing) || createDirty || entryDirty;
useUnsavedWarning(dirty);
const reload = useCallback(() => setRefresh(value => value + 1), []);
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
useEffect(() => {
let current = true;
const controller = new AbortController();
setLoading(true);
setErrors(initialErrors);
const failed = (section: Section, cause: unknown) => {
if (current) {
setErrors(previous => ({
...previous,
[section]: cause instanceof Error ? cause.message : `Could not load ${section}`,
}));
}
};
void Promise.allSettled([
researchApi
.getProject(projectId, controller.signal)
.then(({ project: value }) => {
if (value.id !== projectId) {
throw new Error('The response belongs to another project.');
}
if (current) {
setProject(value);
}
})
.catch(cause => failed('project', cause)),
researchApi
.listStrategies(projectId, controller.signal)
.then(({ strategies: value }) => {
if (current) {
setStrategies(value);
}
})
.catch(cause => failed('strategies', cause)),
researchApi
.listHypotheses(projectId, true, controller.signal)
.then(({ hypotheses: value }) => {
if (value.some(item => item.projectId !== projectId)) {
throw new Error('Hypotheses belong to another project.');
}
if (current) {
setHypotheses(value);
}
})
.catch(cause => failed('hypotheses', cause)),
researchApi
.listArtifacts(projectId, true, controller.signal)
.then(({ artifacts: value }) => {
if (value.some(item => item.projectId !== projectId)) {
throw new Error('Research entries belong to another project.');
}
if (current) {
setArtifacts(value);
}
})
.catch(cause => failed('artifacts', cause)),
strategyApi
.list(controller.signal)
.then(({ strategies: value }) => {
if (current) {
setCatalog(value);
}
})
.catch(cause => failed('catalog', cause)),
]).finally(() => {
if (current) {
setLoading(false);
}
});
return () => {
current = false;
controller.abort();
};
}, [projectId, refresh]);
const select = (kind: 'hypothesis' | 'artifact', id: string, revisionId?: string | null) => {
if (!confirmDiscard(dirty)) {
return;
}
setEditing(null);
setCreator(null);
setCreateDirty(false);
setEntryDirty(false);
if (params.get(kind) === id && params.get('revision') === (revisionId ?? null)) {
setSelectionEpoch(value => value + 1);
}
setParams({ [kind]: id, ...(revisionId ? { revision: revisionId } : {}) });
};
const mutateProject = async (archived?: boolean) => {
if (
!project ||
loading ||
pending.current ||
errors.project ||
(archived === undefined && (!editing || conflict))
) {
return;
}
if (
archived !== undefined &&
(!confirmDiscard(dirty) ||
!window.confirm(`${archived ? 'Archive' : 'Restore'} this project?`))
) {
return;
}
pending.current = true;
setSaving(true);
setMutationError('');
try {
const body =
archived === undefined ? editing : { expectedRevision: project.revision, archived };
if (!body) {
return;
}
const { project: updated } = await researchApi.updateProject(projectId, body);
if (mounted.current) {
setProject(updated);
setEditing(null);
setConflict(false);
if (archived !== undefined) {
setCreator(null);
setCreateDirty(false);
setEntryDirty(false);
setSelectionEpoch(value => value + 1);
}
reload();
}
} catch (cause) {
if (mounted.current) {
setMutationError(cause instanceof Error ? cause.message : 'Could not update project');
setConflict(
!(cause instanceof ResearchApiError) || cause.status === 409 || cause.ambiguous
);
}
} finally {
pending.current = false;
if (mounted.current) {
setSaving(false);
}
}
};
const membership = async (id: string, remove: boolean) => {
if (
!project ||
project.archived ||
loading ||
saving ||
pending.current ||
editing ||
errors.project ||
errors.strategies
) {
return;
}
pending.current = true;
setSaving(true);
setMutationError('');
try {
if (remove) {
await researchApi.unlinkStrategy(projectId, id);
} else {
await researchApi.linkStrategy(projectId, id);
}
if (mounted.current) {
setStrategyId('');
reload();
}
} catch (cause) {
if (mounted.current) {
setMutationError(
cause instanceof Error ? cause.message : 'Could not update linked strategies'
);
reload();
}
} finally {
pending.current = false;
if (mounted.current) {
setSaving(false);
}
}
};
const hypothesisId = params.get('hypothesis');
const artifactId = params.get('artifact');
const selection =
hypothesisId && !artifactId
? { kind: 'hypothesis' as const, id: hypothesisId }
: artifactId && !hypothesisId
? { kind: 'artifact' as const, id: artifactId }
: null;
const visibleHypotheses = hypotheses.filter(
item => showArchived || project?.archived || !item.archived
);
const visibleArtifacts = artifacts.filter(
item => showArchived || project?.archived || !item.archived
);
const canWrite = project && !project.archived && !errors.project && !loading && !saving;
const sectionError = (section: Section) =>
errors[section] && (
<div>
<p role="alert" className="text-error">
{section}: {errors[section]}
</p>
<button className={actionClass} onClick={reload}>
Retry {section}
</button>
</div>
);
return (
<div
className="space-y-5 text-text-primary"
onClickCapture={event => {
if ((event.target as HTMLElement).closest('a') && !confirmDiscard(dirty)) {
event.preventDefault();
event.stopPropagation();
}
}}
>
<div className="flex flex-wrap gap-4">
<Link className="text-primary-500" to="/research">
Research projects
</Link>
<Link className="text-primary-500" to="/backtests">
Backtesting workbench
</Link>
<button className={actionClass} onClick={reload} disabled={saving}>
Refresh project
</button>
</div>
{loading && <p role="status">Loading research workspace...</p>}
{sectionError('project')}
{project && (
<>
<Card className="p-4 space-y-3">
<h1 className="text-lg font-bold">{project.title}</h1>
<p className="whitespace-pre-wrap text-text-secondary">
{project.description || 'No description yet.'}
</p>
<p className="text-xs text-text-muted">
Project revision {project.revision} · Owner: {project.ownerPrincipal} · Updated{' '}
{project.updatedAt}
</p>
{project.archived && (
<p role="status">
Archived project. Records, history and evidence remain available; restore the
project to make changes.
</p>
)}
{!editing && canWrite && (
<button
className={actionClass}
onClick={() => {
if (confirmDiscard(dirty)) {
setCreator(null);
setCreateDirty(false);
setParams({});
setEditing({
title: project.title,
description: project.description,
expectedRevision: project.revision,
});
setConflict(false);
setMutationError('');
}
}}
>
Edit project
</button>
)}{' '}
<button
className={actionClass}
disabled={saving || loading || Boolean(errors.project)}
onClick={() => void mutateProject(!project.archived)}
>
{project.archived ? 'Restore project' : 'Archive project'}
</button>
{editing && !project.archived && (
<form
aria-label="Edit research project"
className="space-y-3"
onSubmit={event => {
event.preventDefault();
void mutateProject();
}}
>
<label className="block">
Project title
<input
aria-label="Project title"
className={fieldClass}
value={editing.title}
onChange={event => setEditing({ ...editing, title: event.target.value })}
disabled={saving || conflict}
required
/>
</label>
<label className="block">
Project description
<textarea
aria-label="Project description"
className={fieldClass}
value={editing.description}
onChange={event => setEditing({ ...editing, description: event.target.value })}
disabled={saving || conflict}
/>
</label>
<button
type="submit"
className={actionClass}
disabled={!canWrite || conflict || !editing.title.trim()}
>
Save project
</button>{' '}
<button
type="button"
className={actionClass}
disabled={saving}
onClick={() => {
if (confirmDiscard(true)) {
setEditing(null);
setMutationError('');
setConflict(false);
}
}}
>
Discard project edits
</button>
</form>
)}
{mutationError && (
<p role="alert" className="text-error">
{mutationError}
</p>
)}
{conflict && (
<div role="status">
<p>
Review the saved project before another update. Your draft has been preserved.
</p>
<button
className={actionClass}
disabled={saving}
onClick={() => {
if (confirmDiscard(Boolean(editing))) {
setEditing(null);
setConflict(false);
setMutationError('');
reload();
}
}}
>
Discard edits and reload project
</button>
</div>
)}
</Card>
<Card className="p-4 space-y-3">
<h2 className="font-semibold">Linked strategies</h2>
{sectionError('strategies')}
{!loading && !errors.strategies && !strategies.length && (
<p>
No strategies linked. Link a strategy, then choose an immutable version for a
backtest.
</p>
)}
{!errors.strategies && (
<ul className="space-y-2">
{strategies.map(strategy => (
<li key={strategy.id} className="flex flex-wrap gap-3 items-center">
<Link className="text-primary-500" to={`/strategies/${strategy.id}`}>
{strategy.name}
</Link>
{strategy.archived && <span className="text-xs">Archived strategy</span>}
{canWrite && (
<button
className={actionClass}
disabled={Boolean(editing)}
onClick={() => void membership(strategy.id, true)}
aria-label={`Unlink ${strategy.name}`}
>
Unlink
</button>
)}
</li>
))}
</ul>
)}
{sectionError('catalog')}
{canWrite && !errors.catalog && !errors.strategies && (
<div className="flex flex-wrap gap-2">
<label>
Strategy to link
<select
className={fieldClass}
aria-label="Strategy to link"
value={strategyId}
disabled={Boolean(editing)}
onChange={event => setStrategyId(event.target.value)}
>
<option value="">Select strategy</option>
{catalog
.filter(
item => !item.archived && !strategies.some(link => link.id === item.id)
)
.map(item => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</label>
<button
className={actionClass}
disabled={!strategyId || Boolean(editing)}
onClick={() => void membership(strategyId, false)}
>
Link strategy
</button>
</div>
)}
<Link className="text-primary-500 text-sm" to="/strategies">
Browse strategy catalog
</Link>
</Card>
<label className="flex gap-2">
<input
type="checkbox"
checked={showArchived}
onChange={event => setShowArchived(event.target.checked)}
/>
Show archived research entries
</label>
<div className="grid gap-4 lg:grid-cols-2">
<Card className="p-4 space-y-3">
<h2 className="font-semibold">Hypotheses</h2>
{sectionError('hypotheses')}
{canWrite && (
<button
className={actionClass}
onClick={() => {
if (confirmDiscard(dirty)) {
setEditing(null);
setCreator('hypothesis');
setParams({});
}
}}
>
New hypothesis
</button>
)}
{!loading && !errors.hypotheses && !visibleHypotheses.length && (
<p>No hypotheses yet.</p>
)}
{!errors.hypotheses && (
<ul className="space-y-2">
{visibleHypotheses.map(item => (
<li key={item.id}>
<button
className="text-primary-500"
onClick={() => select('hypothesis', item.id)}
>
{item.latestRevision.title}
</button>
{item.archived && <span className="ml-2 text-xs">Archived</span>}
<p className="text-xs">
Unvalidated · Revision {item.latestRevision.ordinal} · Declared{' '}
{item.latestRevision.contentOrigin}
</p>
</li>
))}
</ul>
)}
</Card>
<Card className="p-4 space-y-3">
<h2 className="font-semibold">Notes and findings</h2>
{sectionError('artifacts')}
{canWrite && (
<button
className={actionClass}
onClick={() => {
if (confirmDiscard(dirty)) {
setEditing(null);
setCreator('note');
setParams({});
}
}}
>
New note
</button>
)}
<p className="text-sm text-text-secondary">
Save findings from a completed backtest result to attach exact evidence.
</p>
{!loading && !errors.artifacts && !visibleArtifacts.length && (
<p>No notes or findings yet.</p>
)}
{!errors.artifacts && (
<ul className="space-y-2">
{visibleArtifacts.map(item => (
<li key={item.id}>
<button
className="text-primary-500"
onClick={() => select('artifact', item.id)}
>
{item.latestRevision.title}
</button>
{item.archived && <span className="ml-2 text-xs">Archived</span>}
<p className="text-xs">
{item.kind} · Unvalidated · Revision {item.latestRevision.ordinal}
</p>
</li>
))}
</ul>
)}
</Card>
</div>
{creator && (
<CreateResearchEntry
key={creator}
projectId={projectId}
kind={creator}
writeBlocked={
project.archived
? 'Archived project.'
: loading
? 'Refreshing project.'
: errors.project
? 'Project status could not be verified.'
: ''
}
onDirty={setCreateDirty}
onClose={() => setCreator(null)}
onRefresh={reload}
onCreated={id => {
setCreator(null);
setCreateDirty(false);
setParams({ [creator === 'hypothesis' ? 'hypothesis' : 'artifact']: id });
reload();
}}
/>
)}
{hypothesisId && artifactId && <p role="alert">Select one research entry at a time.</p>}
{selection && (
<ResearchEntry
key={`${selection.kind}:${selection.id}:${params.get('revision') ?? 'latest'}:${selectionEpoch}`}
projectId={projectId}
id={selection.id}
kind={selection.kind}
revisionId={params.get('revision')}
archived={project.archived}
writeBlocked={
loading
? 'Refreshing project.'
: errors.project
? 'Project status could not be verified.'
: ''
}
hypotheses={hypotheses}
onDirty={setEntryDirty}
onRefresh={reload}
onSelectRevision={id => select(selection.kind, selection.id, id)}
/>
)}
</>
)}
</div>
);
}

View file

@ -0,0 +1,207 @@
import { useEffect, useRef, useState } from 'react';
import type { ResearchContentOrigin } from '@stock-bot/types';
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';
interface Props {
projectId: string;
kind: 'hypothesis' | 'note';
writeBlocked: string;
onCreated: (id: string) => void;
onRefresh: () => void;
onClose: () => void;
onDirty: (dirty: boolean) => void;
}
export function CreateResearchEntry({
projectId,
kind,
writeBlocked,
onCreated,
onRefresh,
onClose,
onDirty,
}: Props) {
const mounted = useRef(false);
const pending = useRef(false);
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const [criteria, setCriteria] = useState('');
const [origin, setOrigin] = useState<ResearchContentOrigin>('human');
const [saving, setSaving] = useState(false);
const [uncertain, setUncertain] = useState(false);
const [error, setError] = useState('');
const dirty = Boolean(title || body || criteria || origin !== 'human');
useUnsavedWarning(dirty);
useEffect(() => {
onDirty(dirty);
}, [dirty, onDirty]);
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
onDirty(false);
};
}, [onDirty]);
const submit = async (event: React.FormEvent) => {
event.preventDefault();
if (
pending.current ||
writeBlocked ||
uncertain ||
!title.trim() ||
(kind === 'hypothesis' && !body.trim())
) {
return;
}
pending.current = true;
setSaving(true);
setError('');
try {
const id =
kind === 'hypothesis'
? (
await researchApi.createHypothesis(projectId, {
title,
proposition: body,
validationCriteria: criteria,
contentOrigin: origin,
})
).hypothesis.id
: (
await researchApi.createArtifact(projectId, {
kind: 'note',
title,
body,
contentOrigin: origin,
})
).artifact.id;
if (mounted.current) {
onCreated(id);
}
} catch (cause) {
if (mounted.current) {
setError(cause instanceof Error ? cause.message : 'Could not save research entry');
setUncertain(!(cause instanceof ResearchApiError) || cause.ambiguous);
}
} finally {
pending.current = false;
if (mounted.current) {
setSaving(false);
}
}
};
return (
<Card className="p-4">
<form
aria-label={`Create ${kind}`}
className="space-y-3"
onSubmit={event => void submit(event)}
>
<h2 className="font-semibold">New {kind}</h2>
<label className="block">
Title
<input
className={fieldClass}
aria-label={`${kind === 'hypothesis' ? 'Hypothesis' : 'Note'} title`}
value={title}
onChange={event => setTitle(event.target.value)}
required
disabled={saving || uncertain || Boolean(writeBlocked)}
/>
</label>
<label className="block">
{kind === 'hypothesis' ? 'Proposition' : 'Body'}
<textarea
className={fieldClass}
aria-label={kind === 'hypothesis' ? 'Proposition' : 'Note body'}
value={body}
onChange={event => setBody(event.target.value)}
required={kind === 'hypothesis'}
disabled={saving || uncertain || Boolean(writeBlocked)}
/>
</label>
{kind === 'hypothesis' && (
<label className="block">
Validation criteria
<textarea
className={fieldClass}
aria-label="Validation criteria"
value={criteria}
onChange={event => setCriteria(event.target.value)}
disabled={saving || uncertain || Boolean(writeBlocked)}
/>
</label>
)}
<label className="block">
Declared content origin
<select
className={fieldClass}
aria-label="Declared content origin"
value={origin}
onChange={event => setOrigin(event.target.value as ResearchContentOrigin)}
disabled={saving || uncertain || Boolean(writeBlocked)}
>
<option value="human">Human</option>
<option value="ai">AI</option>
<option value="unknown">Unknown</option>
</select>
</label>
<p className="text-sm text-text-secondary">
This is unvalidated narrative. A note or hypothesis does not establish performance
evidence.
</p>
{writeBlocked && <p role="status">{writeBlocked} Your draft is retained.</p>}
{error && (
<p role="alert" className="text-error">
{error}
</p>
)}
{uncertain && (
<div role="status">
<p>The request may have saved. Check saved records before creating another entry.</p>
<button type="button" className={actionClass} onClick={onRefresh}>
Check saved records
</button>{' '}
<button
type="button"
className={actionClass}
onClick={() => {
setUncertain(false);
setError('');
}}
>
Start new request
</button>
</div>
)}
<button
className={actionClass}
type="submit"
disabled={
saving ||
uncertain ||
Boolean(writeBlocked) ||
!title.trim() ||
(kind === 'hypothesis' && !body.trim())
}
>
{saving ? 'Saving...' : `Create ${kind}`}
</button>{' '}
<button
className={actionClass}
type="button"
disabled={saving}
onClick={() => {
if (confirmDiscard(dirty)) {
onClose();
}
}}
>
Discard entry draft
</button>
</form>
</Card>
);
}

View file

@ -0,0 +1,513 @@
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { reviseResearchArtifactSchema } from '@stock-bot/stock-config/research';
import type {
ResearchArtifact,
ResearchArtifactRevision,
ResearchContentOrigin,
ResearchHypothesis,
ResearchHypothesisRevision,
} from '@stock-bot/types';
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 {
evidenceReferences,
ResearchAuthorshipBadge,
ResearchEvidenceList,
} from './ResearchEvidence';
type Entry =
| { kind: 'hypothesis'; entity: ResearchHypothesis; revisions: ResearchHypothesisRevision[] }
| { kind: 'artifact'; entity: ResearchArtifact; revisions: ResearchArtifactRevision[] };
interface Props {
projectId: string;
id: string;
kind: 'hypothesis' | 'artifact';
revisionId: string | null;
archived: boolean;
writeBlocked: string;
hypotheses: ResearchHypothesis[];
onSelectRevision: (id: string | null) => void;
onRefresh: () => void;
onDirty: (dirty: boolean) => void;
}
function HypothesisReference({
projectId,
revisionId,
hypotheses,
}: {
projectId: string;
revisionId: string;
hypotheses: ResearchHypothesis[];
}) {
const [hypothesisId, setHypothesisId] = useState<string | null>(null);
const [error, setError] = useState('');
useEffect(() => {
let current = true;
const controller = new AbortController();
setHypothesisId(null);
setError('');
const candidates = hypotheses.filter(item => item.projectId === projectId);
const known = candidates.find(item => item.latestRevision.id === revisionId);
if (known) {
setHypothesisId(known.id);
} else {
void Promise.all(
candidates.map(async item => {
const { revisions } = await researchApi.hypothesisRevisions(item.id, controller.signal);
return revisions.some(
revision => revision.id === revisionId && revision.hypothesisId === item.id
)
? item.id
: null;
})
)
.then(ids => {
if (current) {
const found = ids.find(Boolean) ?? null;
setHypothesisId(found);
if (!found) {
setError(
'The linked hypothesis revision is unavailable in the loaded project history.'
);
}
}
})
.catch(() => {
if (current) {
setError(
'Could not resolve the linked hypothesis history. Refresh the project to try again.'
);
}
});
}
return () => {
current = false;
controller.abort();
};
}, [hypotheses, projectId, revisionId]);
return (
<div className="text-sm">
<p>
Linked hypothesis revision: <code>{revisionId}</code>
</p>
{hypothesisId && (
<Link
className="text-primary-500"
to={`/research/${projectId}?hypothesis=${hypothesisId}&revision=${revisionId}`}
>
Open exact hypothesis revision
</Link>
)}
{error && <p role="alert">{error}</p>}
</div>
);
}
export function ResearchEntry({
projectId,
id,
kind,
revisionId,
archived,
writeBlocked,
hypotheses,
onSelectRevision,
onRefresh,
onDirty,
}: Props) {
const mounted = useRef(false);
const pending = useRef(false);
const [entry, setEntry] = useState<Entry | null>(null);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState('');
const [reload, setReload] = useState(0);
const [editing, setEditing] = useState(false);
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const [criteria, setCriteria] = useState('');
const [origin, setOrigin] = useState<ResearchContentOrigin>('human');
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
const [blocked, setBlocked] = useState(false);
useUnsavedWarning(editing);
useEffect(() => {
onDirty(editing);
}, [editing, onDirty]);
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
onDirty(false);
};
}, [onDirty]);
useEffect(() => {
let current = true;
const controller = new AbortController();
setLoading(true);
setLoadError('');
setEntry(null);
const load = async (): Promise<Entry> => {
if (kind === 'hypothesis') {
const [{ hypothesis }, { revisions }] = await Promise.all([
researchApi.getHypothesis(id, controller.signal),
researchApi.hypothesisRevisions(id, controller.signal),
]);
if (
hypothesis.id !== id ||
hypothesis.projectId !== projectId ||
hypothesis.latestRevision.hypothesisId !== id ||
revisions.some(item => item.hypothesisId !== id)
) {
throw new Error(
'Hypothesis does not belong to this project or its history is inconsistent.'
);
}
return { kind, entity: hypothesis, revisions };
}
const [{ artifact }, { revisions }] = await Promise.all([
researchApi.getArtifact(id, controller.signal),
researchApi.artifactRevisions(id, controller.signal),
]);
if (
artifact.id !== id ||
artifact.projectId !== projectId ||
artifact.latestRevision.artifactId !== id ||
revisions.some(item => item.artifactId !== id)
) {
throw new Error('Artifact does not belong to this project or its history is inconsistent.');
}
return { kind, entity: artifact, revisions };
};
void load()
.then(result => {
if (revisionId && !result.revisions.some(item => item.id === revisionId)) {
throw new Error('The requested revision does not belong to this research entry.');
}
if (current) {
setEntry(result);
}
})
.catch(cause => {
if (current) {
setLoadError(cause instanceof Error ? cause.message : 'Could not load research entry');
}
})
.finally(() => {
if (current) {
setLoading(false);
}
});
return () => {
current = false;
controller.abort();
};
}, [id, kind, projectId, revisionId, reload]);
const revision = revisionId
? entry?.revisions.find(item => item.id === revisionId)
: entry?.entity.latestRevision;
const readonly =
archived || Boolean(writeBlocked) || entry?.entity.archived || Boolean(revisionId);
const beginEdit = () => {
if (!revision || readonly) {
return;
}
setTitle(revision.title);
setBody('proposition' in revision ? revision.proposition : revision.body);
setCriteria('validationCriteria' in revision ? revision.validationCriteria : '');
setOrigin(revision.contentOrigin);
setError('');
setBlocked(false);
setEditing(true);
};
const save = async (event: React.FormEvent) => {
event.preventDefault();
if (
!entry ||
!revision ||
pending.current ||
readonly ||
blocked ||
!title.trim() ||
(kind === 'hypothesis' && !body.trim())
) {
return;
}
pending.current = true;
setSaving(true);
setError('');
try {
if (entry.kind === 'hypothesis') {
await researchApi.reviseHypothesis(id, {
expectedRevision: entry.entity.latestRevision.ordinal,
title,
proposition: body,
validationCriteria: criteria,
contentOrigin: origin,
});
} else {
await researchApi.reviseArtifact(
id,
reviseResearchArtifactSchema.parse({
expectedRevision: entry.entity.latestRevision.ordinal,
title,
body,
contentOrigin: origin,
evidence: evidenceReferences(entry.entity.latestRevision.evidence),
})
);
}
if (mounted.current) {
setEditing(false);
setReload(value => value + 1);
onRefresh();
}
} catch (cause) {
if (mounted.current) {
setError(cause instanceof Error ? cause.message : 'Could not save revision');
setBlocked(!(cause instanceof ResearchApiError) || cause.status === 409 || cause.ambiguous);
}
} finally {
pending.current = false;
if (mounted.current) {
setSaving(false);
}
}
};
const archive = async () => {
if (
!entry ||
archived ||
Boolean(writeBlocked) ||
pending.current ||
!confirmDiscard(editing) ||
!window.confirm(`${entry.entity.archived ? 'Restore' : 'Archive'} this research entry?`)
) {
return;
}
pending.current = true;
setSaving(true);
setError('');
try {
if (kind === 'hypothesis') {
await researchApi.archiveHypothesis(id, !entry.entity.archived);
} else {
await researchApi.archiveArtifact(id, !entry.entity.archived);
}
if (mounted.current) {
setEditing(false);
setReload(value => value + 1);
onRefresh();
}
} catch (cause) {
if (mounted.current) {
setError(cause instanceof Error ? cause.message : 'Could not update archive state');
}
} finally {
pending.current = false;
if (mounted.current) {
setSaving(false);
}
}
};
return (
<Card className="p-4 space-y-4">
{loading && <p role="status">Loading research entry and revision history...</p>}
{loadError && (
<div>
<p role="alert" className="text-error">
{loadError}
</p>
<button className={actionClass} onClick={() => setReload(value => value + 1)}>
Retry research entry
</button>
</div>
)}
{!loading && entry && revision && (
<>
<div className="flex flex-wrap justify-between gap-2">
<h2 className="font-semibold">{revision.title}</h2>
<span>
{entry.kind === 'hypothesis' ? 'Hypothesis' : entry.entity.kind}{' '}
{entry.entity.archived ? '· Archived' : ''}
</span>
</div>
<ResearchAuthorshipBadge authorship={revision} />
<p className="text-xs text-text-secondary">
Revision {revision.ordinal} · {revision.createdAt} · {revision.id}
</p>
{revisionId && <p role="status">Immutable history: this revision is read-only.</p>}
{writeBlocked && (
<p role="status">
{writeBlocked} Research entries are read-only until the project can be verified.
</p>
)}
{archived && <p role="status">Archived project: research entries are read-only.</p>}
<p className="whitespace-pre-wrap">
{'proposition' in revision ? revision.proposition : revision.body}
</p>
{'validationCriteria' in revision && (
<div>
<h3 className="text-sm font-semibold">Validation criteria</h3>
<p className="whitespace-pre-wrap">
{revision.validationCriteria || 'No criteria recorded.'}
</p>
</div>
)}
{'evidence' in revision && <ResearchEvidenceList evidence={revision.evidence} />}
{entry.kind === 'artifact' && entry.entity.hypothesisRevisionId && (
<HypothesisReference
projectId={projectId}
hypotheses={hypotheses}
revisionId={entry.entity.hypothesisRevisionId}
/>
)}
<div className="flex gap-2 flex-wrap">
{!readonly && !editing && (
<button className={actionClass} onClick={beginEdit} disabled={saving}>
Edit latest revision
</button>
)}
{!archived && !writeBlocked && (
<button className={actionClass} onClick={() => void archive()} disabled={saving}>
{entry.entity.archived ? 'Restore entry' : 'Archive entry'}
</button>
)}
</div>
{error && (
<p role="alert" className="text-error">
{error}
</p>
)}
{editing && !readonly && (
<form
aria-label="Revise research entry"
className="space-y-3"
onSubmit={event => void save(event)}
>
<label className="block">
Revision title
<input
aria-label="Revision title"
className={fieldClass}
value={title}
onChange={event => setTitle(event.target.value)}
disabled={saving || blocked}
required
/>
</label>
<label className="block">
{kind === 'hypothesis' ? 'Proposition' : 'Body'}
<textarea
aria-label="Revision body"
className={fieldClass}
value={body}
onChange={event => setBody(event.target.value)}
disabled={saving || blocked}
required={kind === 'hypothesis'}
/>
</label>
{kind === 'hypothesis' && (
<label className="block">
Validation criteria
<textarea
aria-label="Revision validation criteria"
className={fieldClass}
value={criteria}
onChange={event => setCriteria(event.target.value)}
disabled={saving || blocked}
/>
</label>
)}
<label className="block">
Declared content origin
<select
aria-label="Revision content origin"
className={fieldClass}
value={origin}
onChange={event => setOrigin(event.target.value as ResearchContentOrigin)}
disabled={saving || blocked}
>
<option value="human">Human</option>
<option value="ai">AI</option>
<option value="unknown">Unknown</option>
</select>
</label>
{blocked && (
<div role="status">
<p>
The draft is preserved. Reload and review saved history before starting another
revision; this request will not be retried.
</p>
<button
className={actionClass}
type="button"
onClick={() => {
if (confirmDiscard(true)) {
setEditing(false);
setBlocked(false);
setError('');
setReload(value => value + 1);
onRefresh();
}
}}
>
Discard draft and reload history
</button>
</div>
)}
<button
className={actionClass}
type="submit"
disabled={
saving || blocked || !title.trim() || (kind === 'hypothesis' && !body.trim())
}
>
{saving ? 'Saving revision...' : 'Save new revision'}
</button>{' '}
<button
className={actionClass}
type="button"
disabled={saving}
onClick={() => {
if (confirmDiscard(true)) {
setEditing(false);
setError('');
}
}}
>
Discard revision draft
</button>
</form>
)}
<div>
<h3 className="font-semibold text-sm">Revision history</h3>
<button
className={actionClass}
disabled={saving}
onClick={() => onSelectRevision(null)}
>
View latest revision
</button>
<ul className="space-y-2 mt-2">
{entry.revisions.map(item => (
<li key={item.id} className="text-sm">
<button
className="text-primary-500"
disabled={saving}
onClick={() => onSelectRevision(item.id)}
>
View revision {item.ordinal}
</button>{' '}
· {item.createdAt} · Submitted by {item.submittedBy} · Declared{' '}
{item.contentOrigin}
</li>
))}
</ul>
</div>
</>
)}
</Card>
);
}

View file

@ -0,0 +1,102 @@
import { Link } from 'react-router-dom';
import type {
ResearchAuthorship,
ResearchEvidence,
ResearchEvidenceReference,
} from '@stock-bot/types';
export function ResearchAuthorshipBadge({ authorship }: { authorship: ResearchAuthorship }) {
const origin =
authorship.contentOrigin === 'ai'
? 'AI-authored (declared)'
: authorship.contentOrigin === 'human'
? 'Human-authored (declared)'
: 'Origin unknown';
return (
<p className="text-xs text-text-secondary">
{origin} · Submitted by {authorship.submittedBy} · Unvalidated narrative
</p>
);
}
export function evidenceReferences(evidence: ResearchEvidence[]): ResearchEvidenceReference[] {
return evidence.map(({ runId, metricsVersion, metricPath, strategyVersionId }) => ({
runId,
metricsVersion,
metricPath,
...(strategyVersionId ? { strategyVersionId } : {}),
}));
}
export function researchMetricLabel(path: string): string {
const name = path.split('.').at(-1) ?? path;
return name.replace(/([A-Z])/g, ' $1').replace(/^./, letter => letter.toUpperCase());
}
export function formatResearchEvidence(evidence: ResearchEvidence): string {
if (evidence.value === null) {
return `Unavailable — ${(evidence.unavailableReason ?? 'not reported').replace(/-/g, ' ')}`;
}
const value =
evidence.unit === 'fraction'
? new Intl.NumberFormat(undefined, { style: 'percent', maximumSignificantDigits: 12 }).format(
evidence.value
)
: String(evidence.value);
return evidence.unit === 'currency' ? `${value} (account currency)` : value;
}
/** Display server-resolved measurements; the browser never recomputes cited results. */
export function ResearchEvidenceList({ evidence }: { evidence: ResearchEvidence[] }) {
if (!evidence.length) {
return <p className="text-sm text-text-secondary">No measured evidence attached.</p>;
}
return (
<section aria-label="Referenced measurements" className="space-y-3">
<h3 className="font-medium">Referenced measurements</h3>
<p className="text-sm text-text-secondary">
These measurements support review. They do not validate the narrative.
</p>
{evidence.map(item => (
<div
key={`${item.runId}:${item.metricsVersion}:${item.metricPath}`}
className="rounded border border-border p-3 space-y-2 break-words"
>
<p>
<span className="font-medium">{researchMetricLabel(item.metricPath)}: </span>
{formatResearchEvidence(item)}
</p>
<p className="text-xs text-text-secondary">
{item.metricsVersion} · {item.metricPath} · Unit: {item.unit} ·{' '}
{item.resultKind === 'legacy'
? 'Legacy · Unverified economics'
: 'Canonical Rust result'}
{' · '}Engine: {item.financialEngine}
</p>
<div className="flex flex-wrap gap-3 text-sm text-primary-500">
<Link
to={`/backtests/${encodeURIComponent(item.backtestId)}/run/${encodeURIComponent(item.runId)}`}
>
Open cited run
</Link>
{item.strategyVersionId && (
<Link to={`/strategies/versions/${encodeURIComponent(item.strategyVersionId)}`}>
Open cited strategy version
</Link>
)}
</div>
<p className="text-xs text-text-secondary break-all">
Raw value: {item.value === null ? 'Unavailable' : String(item.value)} · Run:{' '}
{item.runId} · Dataset: {item.datasetHash ?? 'Unknown'}
</p>
{!!item.limitations.length && (
<details>
<summary className="cursor-pointer text-sm">Evidence limitations</summary>
<ul className="list-disc pl-5 text-sm text-text-secondary">
{item.limitations.map((limit, index) => (
<li key={`${limit.code}:${index}`}>{limit.message}</li>
))}
</ul>
</details>
)}
</div>
))}
</section>
);
}

View file

@ -0,0 +1,493 @@
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 {
ResearchArtifact,
ResearchContentOrigin,
ResearchHypothesis,
ResearchProject,
} from '@stock-bot/types';
import { Button } from '@/components/ui/Button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/Dialog';
import { fieldClass } from '@/features/strategies/components/StrategyParameterForm';
import {
confirmDiscard,
useUnsavedWarning,
} from '@/features/strategies/components/useUnsavedWarning';
import { researchApi, ResearchApiError, type ArtifactInput } from '../services/researchApi';
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} />;
}
function FindingDraft({ result, onClose }: { result: ResearchRunResult; onClose: () => void }) {
const canonical = isCanonicalRunResult(result);
const metricPaths = canonical ? canonicalResearchMetricPaths : legacyResearchMetricPaths;
const [projects, setProjects] = useState<ResearchProject[]>([]);
const [projectsLoading, setProjectsLoading] = useState(true);
const [projectsError, setProjectsError] = useState('');
const [reloadProjects, setReloadProjects] = useState(0);
const [projectId, setProjectId] = useState('');
const [project, setProject] = useState<ResearchProject | null>(null);
const [hypotheses, setHypotheses] = useState<ResearchHypothesis[]>([]);
const [hypothesisRevisionId, setHypothesisRevisionId] = useState('');
const [destinationLoading, setDestinationLoading] = useState(false);
const [destinationError, setDestinationError] = useState('');
const [reloadDestination, setReloadDestination] = useState(0);
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const [contentOrigin, setContentOrigin] = useState<ResearchContentOrigin>('human');
const [selectedMetrics, setSelectedMetrics] = useState<string[]>([metricPaths[0]]);
const [pending, setPending] = useState(false);
const [ambiguous, setAmbiguous] = useState(false);
const [error, setError] = useState('');
const [saved, setSaved] = useState<ResearchArtifact | null>(null);
const alive = useRef(false);
const submission = useRef(false);
const destinationGeneration = useRef(0);
const currentProjectId = useRef(projectId);
currentProjectId.current = projectId;
const dirty =
!saved &&
Boolean(
title ||
body ||
projectId ||
contentOrigin !== 'human' ||
selectedMetrics.length !== 1 ||
selectedMetrics[0] !== metricPaths[0]
);
useUnsavedWarning(dirty);
useEffect(() => {
alive.current = true;
return () => {
alive.current = false;
};
}, []);
useEffect(() => {
const controller = new AbortController();
let current = true;
setProjectsLoading(true);
setProjectsError('');
void researchApi.listProjects(false, controller.signal).then(
({ projects: items }) => {
if (current) {
setProjects(items.filter(item => !item.archived));
setProjectsLoading(false);
}
},
cause => {
if (current) {
setProjectsError(
cause instanceof Error ? cause.message : 'Projects could not be loaded.'
);
setProjectsLoading(false);
}
}
);
return () => {
current = false;
controller.abort();
};
}, [reloadProjects]);
useEffect(() => {
const controller = new AbortController();
const generation = ++destinationGeneration.current;
const current = () =>
!controller.signal.aborted &&
generation === destinationGeneration.current &&
currentProjectId.current === projectId;
setProject(null);
setHypotheses([]);
setHypothesisRevisionId('');
setDestinationError('');
setDestinationLoading(Boolean(projectId));
if (projectId) {
void Promise.all([
researchApi.getProject(projectId, controller.signal),
researchApi.listHypotheses(projectId, false, controller.signal),
]).then(
([{ project: destination }, { hypotheses: items }]) => {
if (!current()) {
return;
}
if (destination.id !== projectId) {
setDestinationError('The project response did not match the selected destination.');
} else {
setProject(destination);
setHypotheses(items.filter(item => item.projectId === projectId && !item.archived));
}
setDestinationLoading(false);
},
cause => {
if (current()) {
setDestinationError(
cause instanceof Error ? cause.message : 'The destination could not be loaded.'
);
setDestinationLoading(false);
}
}
);
}
return () => controller.abort();
}, [projectId, reloadDestination]);
const blocked = pending || ambiguous;
const destinationActive = project?.id === projectId && !project.archived;
const close = () => {
if (!submission.current && !pending && confirmDiscard(dirty)) {
onClose();
}
};
async function save() {
if (
submission.current ||
ambiguous ||
saved ||
!destinationActive ||
destinationLoading ||
!title.trim() ||
!selectedMetrics.length ||
result.status !== 'completed'
) {
return;
}
const chosenHypothesis = hypotheses.find(
item => item.latestRevision.id === hypothesisRevisionId
);
if (hypothesisRevisionId && !chosenHypothesis) {
setError('Select an active hypothesis from this project.');
return;
}
const input: ArtifactInput = {
kind: 'finding',
title: title.trim(),
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,
})),
};
submission.current = true;
setPending(true);
setError('');
let posted = false;
try {
const { project: destination } = await researchApi.getProject(projectId);
if (!alive.current) {
return;
}
if (destination.id !== projectId || destination.archived) {
setProject(destination.id === projectId ? destination : null);
throw new Error(
'The destination project is archived or unavailable. Choose an active project.'
);
}
if (chosenHypothesis) {
const { hypothesis } = await researchApi.getHypothesis(chosenHypothesis.id);
if (!alive.current) {
return;
}
if (
hypothesis.id !== chosenHypothesis.id ||
hypothesis.projectId !== projectId ||
hypothesis.archived
) {
throw new Error(
'The selected hypothesis is archived or unavailable. Refresh the destination and choose again.'
);
}
}
posted = true;
const { artifact } = await researchApi.createArtifact(projectId, input);
if (!alive.current) {
return;
}
if (
!artifact?.id ||
artifact.projectId !== projectId ||
artifact.hypothesisRevisionId !== input.hypothesisRevisionId ||
artifact.kind !== 'finding'
) {
throw new ResearchApiError('The saved finding response could not be verified.', null);
}
setSaved(artifact);
} catch (cause) {
if (alive.current) {
setError(cause instanceof Error ? cause.message : 'The finding could not be saved.');
setAmbiguous(posted && (!(cause instanceof ResearchApiError) || cause.ambiguous));
}
} finally {
if (alive.current) {
submission.current = false;
setPending(false);
}
}
}
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)]">
<section role="dialog" aria-modal="true" aria-label="Save finding" className="space-y-4">
<DialogHeader>
<DialogTitle>Save finding</DialogTitle>
</DialogHeader>
<p className="text-sm break-all">
Run: {result.runId} ·{' '}
{canonical ? 'Canonical Rust result' : 'Legacy · Unverified economics'}
</p>
{!canonical && (
<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 && (
<ul className="list-disc pl-5 text-sm text-text-secondary">
{limitations.map((limit, index) => (
<li key={index}>{limit}</li>
))}
</ul>
)}
{saved ? (
<>
<p role="status">Finding saved. Its narrative remains unvalidated.</p>
<Link
className="text-primary-500 underline"
to={`/research/${encodeURIComponent(saved.projectId)}?artifact=${encodeURIComponent(saved.id)}`}
>
Open saved finding
</Link>
<ResearchEvidenceList evidence={saved.latestRevision.evidence} />
</>
) : (
<>
{projectsLoading && <p role="status">Loading projects...</p>}
{projectsError && (
<div role="alert">
{projectsError}{' '}
<Button variant="outline" onClick={() => setReloadProjects(value => value + 1)}>
Retry projects
</Button>
</div>
)}
{!projectsLoading && !projectsError && !projects.length && (
<p>
No active research projects.{' '}
<Link
className="text-primary-500 underline"
to="/research"
onClick={event => {
if (!confirmDiscard(dirty)) {
event.preventDefault();
}
}}
>
Create a project
</Link>{' '}
to save findings.
</p>
)}
<label className="block text-sm">
Project
<select
aria-label="Finding project"
className={fieldClass}
disabled={blocked || projectsLoading}
value={projectId}
onChange={event => {
setProjectId(event.target.value);
setHypothesisRevisionId('');
}}
>
<option value="">Select an active project</option>
{projects.map(item => (
<option key={item.id} value={item.id}>
{item.title}
</option>
))}
</select>
</label>
{destinationLoading && <p role="status">Checking destination...</p>}
{destinationError && <p role="alert">{destinationError}</p>}
{project?.archived && (
<p role="alert">This destination project is archived. Choose an active project.</p>
)}
{projectId && (
<Button
variant="outline"
disabled={blocked || destinationLoading}
onClick={() => setReloadDestination(value => value + 1)}
>
Refresh destination
</Button>
)}
<label className="block text-sm">
Hypothesis (optional)
<select
aria-label="Finding hypothesis"
className={fieldClass}
disabled={blocked || !destinationActive || destinationLoading}
value={hypothesisRevisionId}
onChange={event => setHypothesisRevisionId(event.target.value)}
>
<option value="">No hypothesis</option>
{hypotheses.map(item => (
<option key={item.id} value={item.latestRevision.id}>
{item.latestRevision.title} · revision {item.latestRevision.ordinal}
</option>
))}
</select>
</label>
<label className="block text-sm">
Title
<input
aria-label="Finding title"
className={fieldClass}
disabled={blocked}
value={title}
onChange={event => setTitle(event.target.value)}
/>
</label>
<label className="block text-sm">
Finding
<textarea
aria-label="Finding body"
className={fieldClass}
disabled={blocked}
value={body}
onChange={event => setBody(event.target.value)}
/>
</label>
<label className="block text-sm">
Declared content origin
<select
aria-label="Finding content origin"
className={fieldClass}
disabled={blocked}
value={contentOrigin}
onChange={event => setContentOrigin(event.target.value as ResearchContentOrigin)}
>
<option value="human">Human-authored</option>
<option value="ai">AI-authored</option>
<option value="unknown">Unknown</option>
</select>
</label>
<p className="text-sm text-text-secondary">
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
);
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>
{error && <p role="alert">{error}</p>}
{ambiguous && (
<div role="alert" className="space-y-2">
<p>
Check saved records before creating another. The previous request may already
have saved this finding.
</p>
<a
className="text-primary-500 underline block"
href={`/research/${encodeURIComponent(projectId)}`}
target="_blank"
rel="noopener noreferrer"
>
Check saved records
</a>
<Button
variant="outline"
onClick={() => {
if (
window.confirm(
'The previous request may have saved this finding. Start a new request only after checking saved records. Continue?'
)
) {
setAmbiguous(false);
setError('');
}
}}
>
Start new request
</Button>
</div>
)}
<Button
disabled={
blocked ||
!destinationActive ||
destinationLoading ||
!title.trim() ||
!selectedMetrics.length ||
result.status !== 'completed'
}
onClick={() => void save()}
>
{pending ? 'Saving finding...' : 'Save finding'}
</Button>
</>
)}
<Button variant="outline" disabled={pending} onClick={close}>
Close
</Button>
</section>
</DialogContent>
</Dialog>
);
}

View file

@ -0,0 +1,2 @@
export { ResearchListPage } from './ResearchListPage';
export { ResearchProjectPage } from './ResearchProjectPage';

View file

@ -0,0 +1,228 @@
import type { z } from 'zod';
import type {
createResearchArtifactSchema,
createResearchHypothesisSchema,
createResearchProjectSchema,
reviseResearchArtifactSchema,
reviseResearchHypothesisSchema,
updateResearchProjectSchema,
} from '@stock-bot/stock-config/research';
import type {
ResearchArtifact,
ResearchArtifactRevision,
ResearchHypothesis,
ResearchHypothesisRevision,
ResearchProject,
StrategyRecord,
} from '@stock-bot/types';
import { API_BASE_URL, apiFetch } from '@/lib/api';
export type ProjectInput = z.input<typeof createResearchProjectSchema>;
export type ProjectUpdate = z.input<typeof updateResearchProjectSchema>;
export type HypothesisInput = z.input<typeof createResearchHypothesisSchema>;
export type HypothesisRevisionInput = z.input<typeof reviseResearchHypothesisSchema>;
export type ArtifactInput = z.input<typeof createResearchArtifactSchema>;
export type ArtifactRevisionInput = z.input<typeof reviseResearchArtifactSchema>;
export class ResearchApiError extends Error {
constructor(
message: string,
public readonly status: number | null
) {
super(message);
}
/** Mutations may have committed before a failed or unreadable response. */
get ambiguous() {
return this.status === null || this.status >= 500;
}
}
type ResponseField =
| 'project'
| 'projects'
| 'strategies'
| 'hypothesis'
| 'hypotheses'
| 'artifact'
| 'artifacts'
| 'revisions';
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 validEnvelope(body: unknown, field: ResponseField): boolean {
if (!record(body)) {
return false;
}
const validItem = (item: unknown): boolean => {
if (!identified(item)) {
return false;
}
if (field === 'project' || field === 'projects') {
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 true;
};
const value = body[field];
return ['project', 'hypothesis', 'artifact'].includes(field)
? validItem(value)
: Array.isArray(value) && value.every(validItem);
}
async function request<T>(
path: string,
init: RequestInit,
field: ResponseField | null
): Promise<T> {
let response;
try {
response = await apiFetch(`${API_BASE_URL}/api/v2/${path}`, init);
} catch (cause) {
if (init?.signal?.aborted) {
throw cause;
}
throw new ResearchApiError(
'The research request response was lost. Check saved records before submitting again.',
null
);
}
const body = response.status === 204 ? undefined : await response.json().catch(() => undefined);
if (!response.ok) {
throw new ResearchApiError(
typeof body?.error === 'string' ? body.error : `Research request failed (${response.status})`,
response.status
);
}
if (field === null ? response.status !== 204 : !validEnvelope(body, field)) {
throw new ResearchApiError(
'The research response could not be read. Check saved records before submitting again.',
null
);
}
return body as T;
}
const id = encodeURIComponent;
const json = (method: string, body: unknown): RequestInit => ({
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
export const researchApi = {
listProjects: (includeArchived = false, signal?: AbortSignal) =>
request<{ projects: ResearchProject[] }>(
`research-projects?includeArchived=${includeArchived}`,
{ signal },
'projects'
),
createProject: (body: ProjectInput) =>
request<{ project: ResearchProject }>('research-projects', json('POST', body), 'project'),
getProject: (projectId: string, signal?: AbortSignal) =>
request<{ project: ResearchProject }>(
`research-projects/${id(projectId)}`,
{ signal },
'project'
),
updateProject: (projectId: string, body: ProjectUpdate) =>
request<{ project: ResearchProject }>(
`research-projects/${id(projectId)}`,
json('PATCH', body),
'project'
),
listStrategies: (projectId: string, signal?: AbortSignal) =>
request<{ strategies: StrategyRecord[] }>(
`research-projects/${id(projectId)}/strategies`,
{
signal,
},
'strategies'
),
linkStrategy: (projectId: string, strategyId: string) =>
request<void>(
`research-projects/${id(projectId)}/strategies/${id(strategyId)}`,
{
method: 'PUT',
},
null
),
unlinkStrategy: (projectId: string, strategyId: string) =>
request<void>(
`research-projects/${id(projectId)}/strategies/${id(strategyId)}`,
{
method: 'DELETE',
},
null
),
listHypotheses: (projectId: string, includeArchived = false, signal?: AbortSignal) =>
request<{ hypotheses: ResearchHypothesis[] }>(
`research-projects/${id(projectId)}/hypotheses?includeArchived=${includeArchived}`,
{ signal },
'hypotheses'
),
createHypothesis: (projectId: string, body: HypothesisInput) =>
request<{ hypothesis: ResearchHypothesis }>(
`research-projects/${id(projectId)}/hypotheses`,
json('POST', body),
'hypothesis'
),
getHypothesis: (hypothesisId: string, signal?: AbortSignal) =>
request<{ hypothesis: ResearchHypothesis }>(
`hypotheses/${id(hypothesisId)}`,
{ signal },
'hypothesis'
),
hypothesisRevisions: (hypothesisId: string, signal?: AbortSignal) =>
request<{ revisions: ResearchHypothesisRevision[] }>(
`hypotheses/${id(hypothesisId)}/revisions`,
{ signal },
'revisions'
),
reviseHypothesis: (hypothesisId: string, body: HypothesisRevisionInput) =>
request<{ hypothesis: ResearchHypothesis }>(
`hypotheses/${id(hypothesisId)}/revisions`,
json('POST', body),
'hypothesis'
),
archiveHypothesis: (hypothesisId: string, archived: boolean) =>
request<{ hypothesis: ResearchHypothesis }>(
`hypotheses/${id(hypothesisId)}`,
json('PATCH', { archived }),
'hypothesis'
),
listArtifacts: (projectId: string, includeArchived = false, signal?: AbortSignal) =>
request<{ artifacts: ResearchArtifact[] }>(
`research-projects/${id(projectId)}/analysis-artifacts?includeArchived=${includeArchived}`,
{ signal },
'artifacts'
),
createArtifact: (projectId: string, body: ArtifactInput) =>
request<{ artifact: ResearchArtifact }>(
`research-projects/${id(projectId)}/analysis-artifacts`,
json('POST', body),
'artifact'
),
getArtifact: (artifactId: string, signal?: AbortSignal) =>
request<{ artifact: ResearchArtifact }>(
`analysis-artifacts/${id(artifactId)}`,
{ signal },
'artifact'
),
artifactRevisions: (artifactId: string, signal?: AbortSignal) =>
request<{ revisions: ResearchArtifactRevision[] }>(
`analysis-artifacts/${id(artifactId)}/revisions`,
{ signal },
'revisions'
),
reviseArtifact: (artifactId: string, body: ArtifactRevisionInput) =>
request<{ artifact: ResearchArtifact }>(
`analysis-artifacts/${id(artifactId)}/revisions`,
json('POST', body),
'artifact'
),
archiveArtifact: (artifactId: string, archived: boolean) =>
request<{ artifact: ResearchArtifact }>(
`analysis-artifacts/${id(artifactId)}`,
json('PATCH', { archived }),
'artifact'
),
};