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

@ -5,6 +5,7 @@ import { DashboardPage } from '@/features/dashboard';
import { ExchangesPage } from '@/features/exchanges';
import { MonitoringPage } from '@/features/monitoring';
import { PipelinePage } from '@/features/pipeline';
import { ResearchListPage, ResearchProjectPage } from '@/features/research';
import { StrategyDetailPage, StrategyListPage, StrategyVersionPage } from '@/features/strategies';
import { SymbolDetailPage, SymbolsPage } from '@/features/symbols';
import { AuthGate } from './AuthGate';
@ -43,6 +44,10 @@ export function App() {
<Route path="run/:runId" element={<BacktestDetailPageV2 />} />
</Route>
</Route>
<Route path="research">
<Route index element={<ResearchListPage />} />
<Route path=":projectId" element={<ResearchProjectPage />} />
</Route>
<Route
path="settings"
element={<div className="p-4">Settings Page - Coming Soon</div>}

View file

@ -10,8 +10,13 @@ export function Layout() {
// Determine title from current route
const getTitle = () => {
const path = location.pathname.replace('/', '');
if (!path || path === 'dashboard') {return 'Dashboard';}
if (path === 'research' || path.startsWith('research/')) {
return 'Research';
}
if (!path || path === 'dashboard') {
return 'Dashboard';
}
// Handle nested routes
if (path.includes('/')) {
const parts = path.split('/');
@ -20,7 +25,7 @@ export function Layout() {
return parts[1].charAt(0).toUpperCase() + parts[1].slice(1);
}
}
return path.charAt(0).toUpperCase() + path.slice(1);
};

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'
),
};

View file

@ -1,15 +1,15 @@
import {
BeakerIcon,
BuildingLibraryIcon,
ChartBarIcon,
ChartPieIcon,
CircleStackIcon,
CogIcon,
CurrencyDollarIcon,
DocumentTextIcon,
HomeIcon,
PresentationChartLineIcon,
ServerStackIcon,
BeakerIcon,
CurrencyDollarIcon,
} from '@heroicons/react/24/outline';
export interface NavigationItem {
@ -33,6 +33,7 @@ export const navigation: NavigationItem[] = [
{ name: 'Strategies', href: '/strategies', icon: DocumentTextIcon },
{ name: 'Analytics', href: '/analytics', icon: PresentationChartLineIcon },
{ name: 'Backtests', href: '/backtests', icon: BeakerIcon },
{ name: 'Research', href: '/research', icon: BeakerIcon },
{
name: 'System',
icon: ServerStackIcon,

View file

@ -1,8 +1,8 @@
# Revised development roadmap
Baseline `b7aeca4` · execution 2026-10-23 · **R10 committed; R02 catalog/setup validated and awaiting acceptance/commit**
Baseline `b7aeca4` · execution 2026-10-24 · **R03 committed; R04 workspace validated and awaiting acceptance/commit**
Authorization update: the owner requested “commit and continue”. R10 is committed as `8cca0ee`; R02 is authorized under ADR-006. Performance work remains paused. New R02 commits, pushes, PRs and trading/default-engine operations remain outside this continuation’s scope.
Authorization update: the owner requested “commit and continue”. R03 is committed as `ee45257`; R04 is implemented under ADR-006. Performance work remains paused. New R04 commits, pushes, PRs and trading/default-engine operations remain outside this continuation’s scope.
## Strategy and review outcome
@ -553,3 +553,18 @@ Exact source hashes, commands and review dispositions are recorded in `manifest.
R03's [implemented API contract](backlog/tasks/R03.md#implemented-contract--2026-10-23) documents revision inputs, archive/error behavior and evidence limitations. Initial metadata POSTs use ordinary creation semantics, so clients must handle ambiguous responses without blind retries. No R03 commit, push, PR, new simulator, performance work or trading/default activation.
**Next after acceptance/commit: R04 — research workspace and save-findings UI**, consuming these same APIs. R05's remaining source preparation and wider cutover are still tracked; R06/S06 gates remain intact.
## Twenty-fifth-wave handoff — 2026-10-24
R03 is accepted and committed as `ee45257`. R04 is independently reviewed and `validated_uncommitted`. Seventeen implementation/test files add the web research workspace while retaining existing APIs, persistence and financial semantics. Two UI agents worked in isolated worktrees under `/tmp/stock-bot-wave25.X7zzoe/`; root owned shared browser contracts, navigation, evidence display and browser integration.
- **Workspace:** Create/edit/archive projects, link catalog strategies, create hypotheses and notes, and view or revise immutable narratives. History URLs retain exact revision IDs. Archived projects remain readable. Declared AI/human authorship is separate from authenticated submitter, and prose stays unvalidated.
- **Findings:** Completed matching results offer a project/hypothesis/metric selector. Only reference identities are submitted; R03 resolves actual measurements. Display includes raw values, units, unavailable reasons, financial engine, dataset and exact run/version links. Existing findings keep their references when prose changes; legacy evidence remains qualified.
- **Failure behavior:** Duplicate clicks, late navigation responses, lost save responses, malformed success envelopes and stale revision conflicts have focused coverage. Ambiguous creation freezes the draft until explicit review/new request. Review caught and fixed draft loss during failed project refresh and same-entry discard behavior.
- **Validation:** Build/types/contracts/secrets, **628 integration**, **150 Rust** (4 manual ignored), 93 tooling, 43 utility and 44 calculation tests passed. Two new curly-rule lint issues were fixed and final source/test lint passed. Final focused UI/client tests: **38 / 207 assertions**. Strict changed-test types and formatting/diff checks passed. Real Chromium/PostgreSQL/Redis: **9 workflows / 184 assertions**. The expanded canonical browser fixture covers project → linked strategy → retained run → exact finding → revision/reload/archive → unchanged original result, preserving the expected two fills, `9969.30000000` equity and `0.70000000` fees.
The initial sandbox check stalled on native-worker IPC; permitted checks passed. Browser development caught a fixture endpoint allowlist omission and a test that read history before the revision response committed; both were corrected, and the final full suite passed without retries. The full standalone SQL suite was not rerun because backend/schema sources are unchanged; real browser fixtures exercise the existing research API and database. The release addon matches the previous wave and checkout release library. Exact hashes, commands, review and cleanup are recorded in `manifest.json` → `twenty_fifth_wave_validation`.
No backend financial authority, second evidence store or creation-receipt framework was added. Initial metadata creation still cannot guarantee exactly-once semantics across an ambiguous response; the UI makes this explicit. No performance work, new-wave commit, push, PR, candidate execution, default/multi-asset activation or trading operation occurred.
**Recommended next product slice: R12 original-run reproduction**, limited to already-retained inputs and a supported installed build. The current manifest still blocks R12 on full R05. Before implementation, record its narrower component prerequisite and pin lineage/admission/current-approval rules; migration 19 presently binds ordinary admission to current template settings, so snapshot copying alone is insufficient. Keep R05 incomplete, R06/S06 gated, and historical build provisioning/source preparation outside that slice.

View file

@ -1,6 +1,6 @@
# Canonical development backlog
**First twenty-three waves committed; R03 is validated and uncommitted.** The initial R05 slice is accepted as `618fb9e`; broader R05 remains in progress. R03 adds research projects, revisioned hypotheses/notes/findings and exact retained metric citations through the shared API. R04 supplies the workspace UI next. Performance work remains paused. See [current handoff](../ROADMAP.md#twenty-fourth-wave-handoff--2026-10-23) and manifest execution scope.
**First twenty-four waves committed; R04 is validated and uncommitted.** R03 is accepted as `ee45257`. The workspace now connects projects, revisioned narratives, linked strategies and exact saved-run findings through the existing APIs. Broader R05 remains in progress. Performance work remains paused. See [current handoff](../ROADMAP.md#twenty-fifth-wave-handoff--2026-10-24) and manifest execution scope.
## One source of truth
@ -74,8 +74,8 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
| --- | --- | --- | --- | --- |
| [R01 Persist immutable strategy versions and parameter schemas](tasks/R01.md) | P1 / done | O01, ADR-006 | — | Full-stack research product / M |
| [R02 Deliver strategy catalog and version-aware backtest setup](tasks/R02.md) | P1 / done | R01, W03, ADR-006 | W04 | Full-stack research product / M |
| [R03 Add projects, hypotheses and evidence-linked findings APIs](tasks/R03.md) | P1 / review | R01, R10, ADR-006 | — | Full-stack research product / M |
| [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / blocked | R03, W02, ADR-006 | W04 | Full-stack research product / M |
| [R03 Add projects, hypotheses and evidence-linked findings APIs](tasks/R03.md) | P1 / done | R01, R10, ADR-006 | — | Full-stack research product / M |
| [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / review | R03, W02, ADR-006 | W04 | Full-stack research product / M |
| [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / in_progress | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M |
| [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / blocked | R05, ADR-006 | — | Full-stack research product / M |
| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / blocked | R06, ADR-006 | W04 | Full-stack research product / M |
@ -118,4 +118,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation.
The first twenty-one waves are committed, including R10 (`8cca0ee`). **R02 catalog and versioned setup is validated and awaiting acceptance/commit; performance work remains deferred by the owner.** ADR-006 is approved; R03/R05 prerequisites are integrated but those tasks are outside this wave. R05 is next: verified retained-artifact execution through the existing canonical runtime and durable runner. The multi-asset mark-policy gate still blocks default activation. No default/paper activation, push or PR is included in this continuation.
R03 is committed; R04 awaits acceptance/commit after independent review and full integration/browser checks. R12 original-run reproduction is the recommended next product slice, but its current manifest dependency on full R05 remains blocked. Before execution, explicitly scope it to retained, single-asset, same-installed-build inputs and pin guarded reproduction admission without weakening current authorization. R05 source preparation and broader cutover remain incomplete; R06/S06 are not unblocked. Performance and multi-asset/default/paper activation remain excluded.

File diff suppressed because it is too large Load diff

View file

@ -6,8 +6,8 @@ Scheduling source of truth: [manifest entry R04](../manifest.json). No task is a
## Evidence and root cause
- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211).
- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107).
- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; The existing strategy catalog, immutable versions and retained canonical single-asset run path are integrated; this task adds the research workspace around them. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211).
- **WEB-04 — Historical finding, partially resolved by R01/R05:** Retained canonical runs now bind immutable strategy and engine inputs. Legacy projections can still use mutable definition fallbacks; the workspace must preserve each result kind and its evidence limitations. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107).
## Intended behavior and implementation scope
@ -23,10 +23,10 @@ No general workflow framework, browser IDE, multi-tenant identity platform or se
- apps/stock/web-app/src/features/research/ (new)
- apps/stock/web-app/src/app/App.tsx
- apps/stock/web-app/src/lib/constants/navigation.ts
- apps/stock/web-app/src/lib/constants.ts
- apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx
Write locks: web-research, web-backtest-detail. One agent owns this change. Lock names do not override actual overlapping files.
Write locks: web-research, web-backtest-detail. Root coordinates separate workspace and save-finding UI owners; actual file assignments are recorded in the manifest. Lock names do not override actual overlapping files.
## Dependencies and blockers
@ -66,3 +66,17 @@ Keep migrations additive and previous results readable. Do not add a switch that
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Implemented surface — 2026-10-24
- `/research` lists and creates projects; `/research/:projectId` edits metadata, links catalog strategies, and creates or browses hypotheses, notes and findings. Query selectors `hypothesis`/`artifact` plus optional immutable `revision` identify the displayed narrative.
- Revisions append with `expectedRevision`. A conflict preserves the draft and requires deliberate history review. Historical revisions and archived projects remain readable. Child writes are blocked when project authority cannot be verified.
- Completed matching backtest results offer **Save finding**. Choose an active project, optional exact hypothesis revision, declared content origin and allowlisted measurements. The browser sends reference identities only; R03 resolves values from retained results. Canonical strategy versions come from the original request; legacy results retain their qualifications.
- Evidence displays raw and formatted values, units, unavailable reasons, actual financial engine, dataset identity and exact run/version links. Declared AI/human origin is separate from authenticated submitter; citations never validate the narrative.
- Pending mutations reject duplicate clicks. Lost, malformed or server-error creation responses freeze the draft; users check saved records before explicitly starting another request. Reads and mutation callbacks reject obsolete navigation responses.
- Existing Card/Dialog, strategy parameter form styles, navigation, authentication and APIs are reused. No backend, database, financial or execution contract changed.
The browser acceptance extends the existing retained canonical execution fixture through project creation, an AI-labelled hypothesis, linked strategy selection, backtest setup/run, exact finding, revision history, reload and archived-project reading. It retains the hand-derived two-fill/equity/fee assertions and verifies that original results stay unchanged. Focused DOM tests exercise failure/empty/loading states, conflicts, unavailable evidence, ambiguous saves, archive races and stale replies.
Current integration state and exact checks are in `manifest.json` → `twenty_fifth_wave_validation`; this section does not independently change scheduling status. UI origins are declared labels, not authenticated AI identities; agent credentials/execution, experiment management and automated validation remain separate tasks.

View file

@ -414,6 +414,9 @@ export async function fixture(browser: Browser, native = false) {
!pathname.startsWith('/api/v2/datasets') &&
!pathname.startsWith('/api/v2/strategies') &&
!pathname.startsWith('/api/v2/strategy-versions') &&
!pathname.startsWith('/api/v2/research-projects') &&
!pathname.startsWith('/api/v2/hypotheses/') &&
!pathname.startsWith('/api/v2/analysis-artifacts/') &&
pathname !== '/api/auth/session') ||
/\/(pause|resume|speed)$/.test(pathname)
) {

View file

@ -709,7 +709,7 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
}
});
test('browser_approved_canonical_strategy_setup_run_and_reopen', async () => {
test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_reopen', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());
try {
@ -719,7 +719,51 @@ test('browser_approved_canonical_strategy_setup_run_and_reopen', async () => {
const selected = seeded.find(item => item.package.program.strategyId === 'sma_crossover')!;
expect(selected.reviewStatus).toBe('pending');
await f.login();
await f.page.goto(`${f.origin}/strategies/${selected.strategyId}/versions/${selected.id}`);
await f.page.getByRole('link', { name: 'Research', exact: true }).click();
await visible(f.page, 'No research projects yet. Create a project to begin.');
await f.page.getByRole('button', { name: 'New project', exact: true }).click();
await f.page.getByLabel('Project title', { exact: true }).fill('Trend research');
await f.page.getByLabel('Project description', { exact: true }).fill('Retained SMA evidence');
const creatingProject = f.page.waitForResponse(
response =>
response.request().method() === 'POST' && response.url().endsWith('/research-projects')
);
await f.page.getByRole('button', { name: 'Create project', exact: true }).click();
const projectResponse = await creatingProject;
expect(projectResponse.status()).toBe(201);
const { project } = await projectResponse.json();
await f.page.waitForURL(`${f.origin}/research/${project.id}`);
await f.page.getByRole('button', { name: 'New hypothesis', exact: true }).click();
await f.page.getByLabel('Hypothesis title', { exact: true }).fill('AI trend hypothesis');
await f.page
.getByLabel('Proposition', { exact: true })
.fill('A hypothesis, not validated alpha.');
await f.page
.getByLabel('Validation criteria', { exact: true })
.fill('Out-of-sample evidence required.');
await f.page.getByLabel('Declared content origin', { exact: true }).selectOption('ai');
const creatingHypothesis = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith(`/research-projects/${project.id}/hypotheses`)
);
await f.page.getByRole('button', { name: 'Create hypothesis', exact: true }).click();
const hypothesisResponse = await creatingHypothesis;
expect(hypothesisResponse.status()).toBe(201);
const { hypothesis } = await hypothesisResponse.json();
await visible(f.page, /AI-authored \(declared\).*Submitted by operator.*Unvalidated narrative/);
await f.page.getByLabel('Strategy to link', { exact: true }).selectOption(selected.strategyId);
const linking = f.page.waitForResponse(
response =>
response.request().method() === 'PUT' &&
response
.url()
.endsWith(`/research-projects/${project.id}/strategies/${selected.strategyId}`)
);
await f.page.getByRole('button', { name: 'Link strategy', exact: true }).click();
expect((await linking).status()).toBe(204);
await f.page.locator(`a[href="/strategies/${selected.strategyId}"]`).click();
await f.page.getByLabel('Strategy version', { exact: true }).selectOption(selected.id);
// Approval is an authenticated human review of an immutable built-in, not a run bypass.
await f.page
@ -905,6 +949,106 @@ test('browser_approved_canonical_strategy_setup_run_and_reopen', async () => {
expect(stored.metrics).toBeNull();
expect(stored.trades).toBeNull();
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(1);
// Citations are resolved from the persisted canonical result, never copied browser metrics.
await f.page.getByRole('button', { name: 'Save finding', exact: true }).click();
const dialog = f.page.getByRole('dialog', { name: 'Save finding', exact: true });
await dialog.getByLabel('Finding project', { exact: true }).selectOption(project.id);
await dialog
.getByLabel('Finding hypothesis', { exact: true })
.selectOption(hypothesis.latestRevision.id);
await dialog.getByLabel('Finding title', { exact: true }).fill('SMA fixture finding');
await dialog
.getByLabel('Finding body', { exact: true })
.fill('Costs and losses require further validation.');
await dialog.getByLabel('Round Trip Count', { exact: true }).check();
const creatingFinding = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith(`/research-projects/${project.id}/analysis-artifacts`)
);
await dialog.getByRole('button', { name: 'Save finding', exact: true }).click();
const findingResponse = await creatingFinding;
expect(findingResponse.status()).toBe(201);
const submitted = findingResponse.request().postDataJSON();
expect(submitted.evidence).toEqual([
{
runId: run.id,
metricsVersion: 'canonical-analytics/v1',
strategyVersionId: selected.id,
metricPath: 'analytics.metrics.totalReturn',
},
{
runId: run.id,
metricsVersion: 'canonical-analytics/v1',
strategyVersionId: selected.id,
metricPath: 'analytics.metrics.roundTripCount',
},
]);
const { artifact } = await findingResponse.json();
expect(artifact.hypothesisRevisionId).toBe(hypothesis.latestRevision.id);
expect(artifact.latestRevision.evidence[0].value).toBe(result.analytics.metrics.totalReturn);
expect(artifact.latestRevision.evidence[1].value).toBeNull();
await dialog.getByRole('link', { name: 'Open saved finding', exact: true }).click();
await f.page.waitForURL(`${f.origin}/research/${project.id}?artifact=${artifact.id}`);
const evidence = f.page.getByRole('region', { name: 'Referenced measurements', exact: true });
await evidence.waitFor({ state: 'visible' });
expect(await evidence.textContent()).toContain('Unavailable — unsupported round trips');
expect(await evidence.textContent()).toContain('Unit: fraction');
expect(await evidence.textContent()).toContain(
`Raw value: ${result.analytics.metrics.totalReturn}`
);
expect(await evidence.textContent()).toContain(retained.hash);
expect(
await evidence
.getByRole('link', { name: 'Open cited run', exact: true })
.first()
.getAttribute('href')
).toBe(`/backtests/${backtestId}/run/${run.id}`);
expect(
await evidence
.getByRole('link', { name: 'Open cited strategy version', exact: true })
.first()
.getAttribute('href')
).toBe(`/strategies/versions/${selected.id}`);
await f.page.getByRole('button', { name: 'Edit latest revision', exact: true }).click();
await f.page
.getByLabel('Revision body', { exact: true })
.fill('Revised conclusion; original evidence retained.');
const revising = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith(`/analysis-artifacts/${artifact.id}/revisions`)
);
await f.page.getByRole('button', { name: 'Save new revision', exact: true }).click();
expect((await revising).status()).toBe(201);
await f.page.getByRole('button', { name: 'View revision 2', exact: true }).waitFor();
await visible(f.page, 'Revised conclusion; original evidence retained.');
const history = await f.request(`/api/v2/analysis-artifacts/${artifact.id}/revisions`);
expect(history.revisions).toHaveLength(2);
expect(history.revisions[0].evidence).toEqual(history.revisions[1].evidence);
await f.page.getByRole('button', { name: 'View revision 1', exact: true }).click();
await visible(f.page, 'Costs and losses require further validation.');
await visible(f.page, 'Immutable history: this revision is read-only.');
await f.page.reload();
await visible(f.page, 'Costs and losses require further validation.');
await f.page.getByRole('link', { name: 'Open exact hypothesis revision', exact: true }).click();
await f.page.waitForURL(
`${f.origin}/research/${project.id}?hypothesis=${hypothesis.id}&revision=${hypothesis.latestRevision.id}`
);
await visible(f.page, /AI-authored \(declared\).*Unvalidated narrative/);
await f.page.getByRole('button', { name: 'Archive project', exact: true }).click();
await visible(f.page, 'Archived project: research entries are read-only.');
expect(await f.page.getByRole('button', { name: 'New note', exact: true }).count()).toBe(0);
expect(await f.page.getByRole('button', { name: 'New hypothesis', exact: true }).count()).toBe(
0
);
await f.page.getByRole('button', { name: 'SMA fixture finding', exact: true }).click();
await visible(f.page, 'Revised conclusion; original evidence retained.');
await evidence.getByRole('link', { name: 'Open cited run', exact: true }).first().click();
await f.page.waitForURL(completedUrl);
await visible(f.page, '9969.30000000');
expect(await f.request(`/api/v2/runs/${run.id}/results`)).toEqual(result);
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {

View file

@ -0,0 +1,150 @@
import { afterAll, beforeAll, expect, test } from 'bun:test';
import { GlobalWindow } from 'happy-dom';
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { MemoryRouter } from 'react-router-dom';
import type { ResearchEvidence } from '@stock-bot/types';
import {
evidenceReferences,
ResearchAuthorshipBadge,
ResearchEvidenceList,
} from '../../apps/stock/web-app/src/features/research/components/ResearchEvidence';
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
const setFetch = (value: (input: unknown, init?: RequestInit) => Promise<Response>) =>
Object.defineProperty(browser, 'fetch', { configurable: true, value });
const previous = Object.getOwnPropertyDescriptor(globalThis, 'window');
let client: typeof import('../../apps/stock/web-app/src/features/research/services/researchApi');
beforeAll(async () => {
Object.defineProperty(globalThis, 'window', { configurable: true, value: browser });
client = await import('../../apps/stock/web-app/src/features/research/services/researchApi');
});
afterAll(() => {
if (previous) {
Object.defineProperty(globalThis, 'window', previous);
} else {
Reflect.deleteProperty(globalThis, 'window');
}
browser.close();
});
test('research response envelopes reject ambiguous successful saves without retrying', async () => {
for (const response of [
Response.json(null),
Response.json({}),
Response.json({ project: null }),
Response.json({ project: {} }),
Response.json({ project: [] }),
new Response('{'),
new Response(null, { status: 204 }),
]) {
let calls = 0;
setFetch(async () => {
calls++;
return response;
});
try {
await client.researchApi.createProject({ title: 'Possible committed save' });
throw new Error('Invalid success accepted');
} catch (cause) {
expect(cause).toBeInstanceOf(client.ResearchApiError);
expect((cause as InstanceType<typeof client.ResearchApiError>).ambiguous).toBe(true);
}
expect(calls).toBe(1);
}
});
test('research client preserves credentials, revision guards and HTTP error classification', async () => {
const calls: { path: string; init?: RequestInit }[] = [];
setFetch(async (input: unknown, init?: RequestInit) => {
calls.push({ path: String(input), init });
return Response.json({ error: 'Revision conflict' }, { status: 409 });
});
try {
await client.researchApi.updateProject('project/id', { title: 'Draft', expectedRevision: 7 });
throw new Error('Conflict response accepted');
} catch (cause) {
expect(cause).toBeInstanceOf(client.ResearchApiError);
expect((cause as InstanceType<typeof client.ResearchApiError>).ambiguous).toBe(false);
expect((cause as Error).message).toBe('Revision conflict');
}
expect(calls).toHaveLength(1);
expect(calls[0]!.path).toEndWith('/api/v2/research-projects/project%2Fid');
expect(calls[0]!.init?.credentials).toBe('include');
expect(JSON.parse(calls[0]!.init!.body as string)).toEqual({
title: 'Draft',
expectedRevision: 7,
});
setFetch(async () => new Response(null, { status: 204 }));
await expect(client.researchApi.linkStrategy('project', 'strategy')).resolves.toBeUndefined();
setFetch(async () => Response.json({ projects: {} }));
await expect(client.researchApi.listProjects()).rejects.toBeInstanceOf(client.ResearchApiError);
setFetch(async () => Response.json({ projects: [] }));
await expect(client.researchApi.listProjects()).resolves.toEqual({ projects: [] });
});
const evidence: ResearchEvidence = {
runId: 'run',
backtestId: 'backtest',
strategyVersionId: 'version',
metricsVersion: 'canonical-analytics/v1',
metricPath: 'analytics.metrics.totalReturn',
value: 0.123456789012345,
unit: 'fraction',
availability: 'available',
unavailableReason: null,
resultKind: 'canonical',
financialEngine: 'rust',
datasetHash: 'a'.repeat(64),
limitations: [{ code: 'fixture', message: '<script>unsafe narrative</script>' }],
};
test('research evidence exposes exact source, units, raw value, unavailable and legacy limits', () => {
const unavailable: ResearchEvidence = {
...evidence,
runId: 'legacy',
strategyVersionId: undefined,
metricsVersion: 'legacy-display/v1',
metricPath: 'metrics.sharpeRatio',
value: null,
unit: 'ratio',
availability: 'unavailable',
unavailableReason: 'insufficient-data',
resultKind: 'legacy',
financialEngine: 'typescript',
};
const html = renderToStaticMarkup(
createElement(
MemoryRouter,
null,
createElement(ResearchEvidenceList, { evidence: [evidence, unavailable] })
)
);
expect(html).toContain('/backtests/backtest/run/run');
expect(html).toContain('/strategies/versions/version');
expect(html).toContain('0.123456789012345');
expect(html).toContain('Unit: fraction');
expect(html).toContain('Unavailable — insufficient data');
expect(html).toContain('Unverified economics');
expect(html).toContain('typescript');
expect(html).toContain('They do not validate the narrative');
expect(html).not.toContain('<script>');
expect(evidenceReferences([evidence])).toEqual([
{
runId: 'run',
metricsVersion: 'canonical-analytics/v1',
metricPath: 'analytics.metrics.totalReturn',
strategyVersionId: 'version',
},
]);
});
test('ai_authorship_badge separates declared origin from authenticated submitter and validation', () => {
const html = renderToStaticMarkup(
createElement(ResearchAuthorshipBadge, {
authorship: { contentOrigin: 'ai', submittedBy: 'operator' },
})
);
expect(html).toContain('AI-authored (declared)');
expect(html).toContain('Submitted by operator');
expect(html).toContain('Unvalidated narrative');
});

View file

@ -0,0 +1,650 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { GlobalWindow } from 'happy-dom';
import { act, createElement, type ReactElement } from 'react';
import type { Root } from 'react-dom/client';
import type {
CanonicalRunResult,
ResearchRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type {
BacktestRunResult,
ResearchArtifact,
ResearchHypothesis,
ResearchProject,
} from '@stock-bot/types';
import type {
Backtest,
Run,
} from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
const keys = ['window', 'document', 'Event', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT'] as const;
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
let createRoot: typeof import('react-dom/client').createRoot;
let router: typeof import('react-router-dom');
let SaveFindingDialog: typeof import('../../apps/stock/web-app/src/features/research/components/SaveFindingDialog').SaveFindingDialog;
let BacktestDetailPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2').BacktestDetailPageV2;
let root: Root | undefined;
let host: HTMLDivElement;
let navigate: ReturnType<typeof router.useNavigate>;
let closed: number;
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason: Error) => void;
const promise = new Promise<T>((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
type Pending = ReturnType<typeof deferred<Response>> & {
path: string;
method: string;
body: unknown;
settled: boolean;
signal?: AbortSignal | null;
};
const requests: Pending[] = [];
function request(path: string, method = 'GET') {
const value = requests.find(
item => !item.settled && item.path === path && item.method === method
);
if (!value) {
throw new Error(
`Missing ${method} ${path}; requests ${requests.map(item => `${item.method} ${item.path} ${item.settled}`).join(',')}`
);
}
return value;
}
function reply(item: Pending, body: unknown, status = 200) {
item.settled = true;
item.resolve(Response.json(body, { status }));
}
async function flush(action: () => void = () => {}) {
await act(async () => {
action();
await Promise.resolve();
});
}
function button(label: string) {
const item = [...host.querySelectorAll('button')].find(
item => item.textContent?.trim() === label
);
if (!item) {
throw new Error(`Missing ${label}: ${host.textContent}`);
}
return item;
}
function field(label: string) {
const item = host.querySelector(`[aria-label="${label}"]`) as
| HTMLInputElement
| HTMLSelectElement
| HTMLTextAreaElement
| null;
if (!item) {
throw new Error(`Missing field ${label}`);
}
return item;
}
function edit(label: string, value: string) {
const input = field(label);
const prototype =
input.tagName === 'SELECT'
? browser.HTMLSelectElement.prototype
: input.tagName === 'TEXTAREA'
? browser.HTMLTextAreaElement.prototype
: browser.HTMLInputElement.prototype;
Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value);
input.dispatchEvent(
new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', {
bubbles: true,
}) as unknown as Event
);
}
function Probe() {
navigate = router.useNavigate();
return null;
}
const project = (id = 'p1', archived = false): ResearchProject => ({
id,
archived,
title: `Project ${id}`,
description: '',
revision: 1,
ownerPrincipal: 'operator',
updatedBy: 'operator',
createdAt: '2026-10-23',
updatedAt: '2026-10-23',
});
const hypothesis = (id = 'h1', projectId = 'p1', archived = false): ResearchHypothesis => ({
id,
projectId,
archived,
ownerPrincipal: 'operator',
updatedBy: 'operator',
createdAt: '2026-10-23',
updatedAt: '2026-10-23',
latestRevision: {
id: `${id}-revision`,
hypothesisId: id,
ordinal: 2,
title: `Hypothesis ${id}`,
proposition: 'Candidate',
validationCriteria: '',
validationState: 'unvalidated',
contentOrigin: 'human',
submittedBy: 'operator',
createdAt: '2026-10-23',
},
});
const artifact = (hypothesisRevisionId: string | null = null): ResearchArtifact => ({
id: 'saved-finding',
projectId: 'p1',
hypothesisRevisionId,
kind: 'finding',
archived: false,
ownerPrincipal: 'operator',
updatedBy: 'operator',
createdAt: '2026-10-23',
updatedAt: '2026-10-23',
latestRevision: {
id: 'a-revision',
artifactId: 'saved-finding',
ordinal: 1,
title: 'Finding',
body: 'Narrative',
validationState: 'unvalidated',
evidenceState: 'referenced',
evidence: [],
submittedBy: 'operator',
contentOrigin: 'human',
createdAt: '2026-10-23',
},
});
function legacy(runId = 'run'): BacktestRunResult {
return {
runId,
backtestId: 'definition',
engine: 'typescript',
status: 'completed',
completedAt: '2026-10-23',
config: {
name: 'Historical config',
strategy: 'sma',
symbols: ['A.US'],
startDate: '2024-01-01',
endDate: '2024-02-01',
initialCapital: 1000,
commission: 0,
slippage: 0,
dataFrequency: '1d',
parameters: {},
},
metrics: {
totalReturn: 0.23,
sharpeRatio: null,
maxDrawdown: -0.05,
winRate: 0,
totalTrades: 0,
profitFactor: null,
avgWin: 0,
avgLoss: 0,
},
equity: [],
ohlcData: {},
trades: [],
positions: [],
analytics: { exposureTime: null },
executionTime: 1,
};
}
/** Only fields read by the citation picker; the financial report itself is not simulated here. */
function canonical(): CanonicalRunResult {
return {
kind: 'canonical-result/v1',
runId: 'run',
backtestId: 'definition',
status: 'completed',
financialEngine: 'rust',
request: { strategy: { versionId: 'frozen-version' } },
financial: {
limitations: ['Only retained exchange sessions'],
modelLimitations: ['No market impact'],
},
analytics: { metrics: { totalReturn: 0.23, sharpeRatio: null }, fillCount: 3 },
} as unknown as CanonicalRunResult;
}
const definition: Backtest = {
id: 'definition',
name: 'Mutable template',
strategy: 'sma',
symbols: ['A.US'],
startDate: '2024-01-01',
endDate: '2024-02-01',
initialCapital: 1000,
config: {},
createdAt: '2024-01-01',
updatedAt: '2024-01-01',
archivedAt: null,
};
const run = (id = 'run', status: Run['status'] = 'completed'): Run => ({
id,
backtestId: 'definition',
status,
runNumber: 1,
speedMultiplier: null,
progress: 100,
createdAt: '2026-10-23',
updatedAt: '2026-10-23',
});
async function render(element: ReactElement, initial = '/') {
if (!root) {
root = createRoot(host);
}
await flush(() =>
root!.render(
createElement(
router.MemoryRouter,
{ initialEntries: [initial] },
element,
createElement(Probe)
)
)
);
}
async function mountDialog(result: ResearchRunResult = canonical()) {
await render(
createElement(SaveFindingDialog, {
result,
onClose: () => {
closed++;
},
})
);
await flush(() =>
reply(request('/api/v2/research-projects?includeArchived=false'), {
projects: [project(), project('p2'), project('archived', true)],
})
);
}
async function destination(id = 'p1', items = [hypothesis()]) {
await flush(() => edit('Finding project', id));
await flush(() => {
reply(request(`/api/v2/research-projects/${id}`), { project: project(id) });
reply(request(`/api/v2/research-projects/${id}/hypotheses?includeArchived=false`), {
hypotheses: items,
});
});
}
async function draft() {
await destination();
await flush(() => {
edit('Finding title', 'Exact finding');
edit('Finding body', 'Keep this narrative');
});
}
async function preflight() {
await flush(() => button('Save finding').click());
await flush(() => reply(request('/api/v2/research-projects/p1'), { project: project() }));
}
const post = () => request('/api/v2/research-projects/p1/analysis-artifacts', 'POST');
beforeAll(async () => {
for (const [key, value] of Object.entries({
window: browser,
document: browser.document,
Event: browser.Event,
ResizeObserver: browser.ResizeObserver,
IS_REACT_ACT_ENVIRONMENT: true,
})) {
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
}
({ createRoot } = await import('react-dom/client'));
router = await import('react-router-dom');
({ SaveFindingDialog } = await import(
'../../apps/stock/web-app/src/features/research/components/SaveFindingDialog'
));
({ BacktestDetailPageV2 } = await import(
'../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2'
));
});
beforeEach(() => {
requests.length = 0;
closed = 0;
host = browser.document.createElement('div') as unknown as HTMLDivElement;
browser.document.body.append(host as never);
Object.defineProperty(browser, 'confirm', {
configurable: true,
writable: true,
value: () => true,
});
browser.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
const url = new URL(String(input));
const item: Pending = {
...deferred<Response>(),
path: url.pathname + url.search,
method: init?.method ?? 'GET',
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
signal: init?.signal,
settled: false,
};
requests.push(item);
return item.promise; // Deliberately ignore abort: identity fences must handle late replies.
}) as unknown as typeof browser.fetch;
});
afterEach(async () => {
if (root) {
await flush(() => root!.unmount());
}
root = undefined;
host.remove();
});
afterAll(async () => {
await browser.happyDOM.close();
for (const key of keys) {
const descriptor = originals.get(key);
if (descriptor) {
Object.defineProperty(globalThis, key, descriptor);
} else {
Reflect.deleteProperty(globalThis, key);
}
}
});
describe('saved-result finding', () => {
test('canonical citations use the frozen strategy version and immutable hypothesis revision, never metric copies', async () => {
await mountDialog();
await draft();
expect(host.textContent).toContain('No market impact');
expect(host.textContent).toContain('Sharpe Ratio · Unavailable');
expect(field('Finding project').textContent).not.toContain('Project archived');
await flush(() => {
edit('Finding hypothesis', 'h1-revision');
edit('Finding content origin', 'ai');
(field('Sharpe Ratio') as HTMLInputElement).click();
});
await preflight();
await flush(() => reply(request('/api/v2/hypotheses/h1'), { hypothesis: hypothesis() }));
expect(post().body).toEqual({
kind: 'finding',
title: 'Exact finding',
body: 'Keep this narrative',
contentOrigin: 'ai',
hypothesisRevisionId: 'h1-revision',
evidence: [
{
runId: 'run',
metricsVersion: 'canonical-analytics/v1',
metricPath: 'analytics.metrics.totalReturn',
strategyVersionId: 'frozen-version',
},
{
runId: 'run',
metricsVersion: 'canonical-analytics/v1',
metricPath: 'analytics.metrics.sharpeRatio',
strategyVersionId: 'frozen-version',
},
],
});
await flush(() => reply(post(), { artifact: artifact('h1-revision') }, 201));
expect(host.querySelector('a')?.getAttribute('href')).toBe(
'/research/p1?artifact=saved-finding'
);
expect(host.textContent).toContain('narrative remains unvalidated');
expect(closed).toBe(0);
});
test('legacy citations retain qualification and do not infer a strategy version', async () => {
await mountDialog(legacy());
await draft();
await preflight();
expect(host.textContent).toContain('Legacy · Unverified economics');
expect(post().body).toEqual({
kind: 'finding',
title: 'Exact finding',
body: 'Keep this narrative',
contentOrigin: 'human',
hypothesisRevisionId: null,
evidence: [
{ runId: 'run', metricsVersion: 'legacy-display/v1', metricPath: 'metrics.totalReturn' },
],
});
});
test('late project and hypothesis responses cannot overwrite the current destination', async () => {
await mountDialog();
await flush(() => edit('Finding project', 'p1'));
const oldProject = request('/api/v2/research-projects/p1');
const oldHypotheses = request('/api/v2/research-projects/p1/hypotheses?includeArchived=false');
await destination('p2', [
hypothesis('h2', 'p2'),
hypothesis('foreign', 'p1'),
hypothesis('archived', 'p2', true),
]);
await flush(() => edit('Finding hypothesis', 'h2-revision'));
await flush(() => {
reply(oldProject, { project: project('p1') });
reply(oldHypotheses, { hypotheses: [hypothesis()] });
});
expect(oldProject.signal?.aborted).toBe(true);
expect(field('Finding project').value).toBe('p2');
expect(field('Finding hypothesis').value).toBe('h2-revision');
expect(field('Finding hypothesis').textContent).not.toContain('Hypothesis h1');
expect(field('Finding hypothesis').textContent).not.toContain('foreign');
expect(field('Finding hypothesis').textContent).not.toContain('archived');
await destination();
expect(field('Finding hypothesis').value).toBe('');
});
for (const status of [422, 409, 401]) {
test(`${status} preserves the finding draft and never retries automatically`, async () => {
await mountDialog();
await draft();
await preflight();
await flush(() =>
reply(
post(),
{ error: status === 422 ? 'Saved evidence is incomplete' : 'Destination write rejected' },
status
)
);
expect(field('Finding title').value).toBe('Exact finding');
expect(field('Finding body').value).toBe('Keep this narrative');
expect(host.querySelector('[role="alert"]')?.textContent).toContain(
status === 422 ? 'incomplete' : 'rejected'
);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
expect(button('Save finding').disabled).toBe(false);
});
}
test('archived destination found during preflight denies any POST', async () => {
await mountDialog();
await draft();
await flush(() => button('Save finding').click());
await flush(() =>
reply(request('/api/v2/research-projects/p1'), { project: project('p1', true) })
);
expect(button('Save finding').disabled).toBe(true);
expect(host.textContent).toContain('destination project is archived');
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
expect(field('Finding title').value).toBe('Exact finding');
});
test('archived selected hypothesis cannot be cited by a new request', async () => {
await mountDialog();
await draft();
await flush(() => edit('Finding hypothesis', 'h1-revision'));
await preflight();
await flush(() =>
reply(request('/api/v2/hypotheses/h1'), { hypothesis: hypothesis('h1', 'p1', true) })
);
expect(host.textContent).toContain('selected hypothesis is archived');
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
});
for (const response of ['lost', '500', 'malformed'] as const) {
test(`${response} create outcome freezes draft until explicit new request`, async () => {
await mountDialog();
await draft();
await flush(() => {
button('Save finding').click();
button('Save finding').click();
button('Close').click();
});
expect(closed).toBe(0);
expect(requests.filter(item => item.path === '/api/v2/research-projects/p1')).toHaveLength(2);
await flush(() => reply(request('/api/v2/research-projects/p1'), { project: project() }));
const pending = post();
await flush(() => {
if (response === 'lost') {
pending.settled = true;
pending.reject(new Error('Response lost'));
} else if (response === '500') {
reply(pending, { error: 'Server interrupted' }, 500);
} else {
reply(pending, {}, 201);
}
});
expect(host.textContent).toContain('Check saved records before creating another');
expect(button('Save finding').disabled).toBe(true);
expect(field('Finding title').disabled).toBe(true);
expect(field('Finding title').value).toBe('Exact finding');
expect(host.querySelector('a[target="_blank"]')?.getAttribute('href')).toBe('/research/p1');
await flush(() => button('Save finding').click());
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
await flush(() => button('Start new request').click());
expect(field('Finding title').disabled).toBe(false);
expect(button('Save finding').disabled).toBe(false);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
});
}
test('changing result identity resets draft and rejects a late create success', async () => {
await mountDialog();
await draft();
await preflight();
const pending = post();
await render(
createElement(SaveFindingDialog, {
result: legacy('next-run'),
onClose: () => {
closed++;
},
})
);
await flush(() => reply(pending, { artifact: artifact() }, 201));
expect(host.textContent).toContain('Run: next-run');
expect(field('Finding title').value).toBe('');
expect(field('Finding project').value).toBe('');
expect(host.textContent).not.toContain('Open saved finding');
});
test('changed result ignores late projects and unsaved close requires confirmation', async () => {
await render(
createElement(SaveFindingDialog, {
result: legacy(),
onClose: () => {
closed++;
},
})
);
const oldList = request('/api/v2/research-projects?includeArchived=false');
await render(
createElement(SaveFindingDialog, {
result: legacy('next-run'),
onClose: () => {
closed++;
},
})
);
await flush(() => reply(oldList, { projects: [project('old')] }));
expect(field('Finding project').textContent).not.toContain('Project old');
await flush(() => edit('Finding title', 'Keep draft'));
Object.defineProperty(browser, 'confirm', {
configurable: true,
writable: true,
value: () => false,
});
await flush(() => button('Close').click());
expect(closed).toBe(0);
Object.defineProperty(browser, 'confirm', {
configurable: true,
writable: true,
value: () => true,
});
await flush(() => button('Close').click());
expect(closed).toBe(1);
});
test('project load failure is distinct from empty projects and can be retried', async () => {
await render(createElement(SaveFindingDialog, { result: legacy(), onClose: () => {} }));
await flush(() =>
reply(
request('/api/v2/research-projects?includeArchived=false'),
{ error: 'Unavailable projects' },
503
)
);
expect(host.textContent).toContain('Unavailable projects');
expect(host.textContent).not.toContain('No active research projects');
await flush(() => button('Retry projects').click());
await flush(() =>
reply(request('/api/v2/research-projects?includeArchived=false'), { projects: [] })
);
expect(host.textContent).toContain('No active research projects');
});
});
async function mountPage(status: Run['status'] = 'completed') {
await render(
createElement(
router.Routes,
null,
createElement(router.Route, {
path: '/backtests/:id/run/:runId',
element: createElement(BacktestDetailPageV2),
})
),
'/backtests/definition/run/run'
);
await flush(() => {
reply(request('/api/v2/backtests/definition'), { ...definition, archivedAt: '2026-10-23' });
reply(request('/api/v2/backtests/definition/runs'), []);
reply(request('/api/v2/runs/run'), run('run', status));
});
}
describe('backtest finding entry point', () => {
test('archived backtest permits completed matching results and run navigation closes the dialog', async () => {
await mountPage();
expect(button('Save finding').disabled).toBe(true);
await flush(() => reply(request('/api/v2/runs/run/results'), legacy()));
expect(button('Save finding').disabled).toBe(false);
await flush(() => button('Save finding').click());
expect(host.querySelector('[role="dialog"]')).not.toBeNull();
const pending = request('/api/v2/research-projects?includeArchived=false');
await flush(() => navigate('/backtests/definition/run/next-run'));
expect(host.querySelector('[role="dialog"]')).toBeNull();
await flush(() => reply(pending, { projects: [project()] }));
expect(host.querySelector('[role="dialog"]')).toBeNull();
});
for (const source of ['missing', 'wrong-parent', 'wrong-run', 'cancelled'] as const) {
test(`${source} results cannot open finding creation`, async () => {
await mountPage();
await flush(() =>
reply(
request('/api/v2/runs/run/results'),
source === 'missing'
? { error: 'Missing results' }
: {
...legacy(),
...(source === 'wrong-parent'
? { backtestId: 'foreign' }
: source === 'wrong-run'
? { runId: 'foreign' }
: { status: 'cancelled' }),
},
source === 'missing' ? 404 : 200
)
);
expect(button('Save finding').disabled).toBe(true);
await flush(() => button('Save finding').click());
expect(host.querySelector('[role="dialog"]')).toBeNull();
});
}
test('failed runs have no usable evidence action', async () => {
await mountPage('failed');
expect(button('Save finding').disabled).toBe(true);
expect(requests.some(item => item.path.endsWith('/results'))).toBe(false);
});
});

View file

@ -0,0 +1,679 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { GlobalWindow } from 'happy-dom';
import { act, createElement } from 'react';
import type { Root } from 'react-dom/client';
import type {
ResearchArtifact,
ResearchHypothesis,
ResearchProject,
StrategyRecord,
} from '@stock-bot/types';
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
const keys = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const;
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
let createRoot: typeof import('react-dom/client').createRoot;
let router: typeof import('react-router-dom');
let ResearchListPage: typeof import('../../apps/stock/web-app/src/features/research/ResearchListPage').ResearchListPage;
let ResearchProjectPage: typeof import('../../apps/stock/web-app/src/features/research/ResearchProjectPage').ResearchProjectPage;
let root: Root | undefined;
let host: HTMLDivElement;
let navigate: ReturnType<typeof router.useNavigate>;
let location = '';
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (error: Error) => void;
const promise = new Promise<T>((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
type Pending = ReturnType<typeof deferred<Response>> & {
path: string;
method: string;
body: unknown;
settled: boolean;
};
const requests: Pending[] = [];
function request(path: string, method = 'GET') {
const found = requests.find(
item => item.path === `/api/v2/${path}` && item.method === method && !item.settled
);
if (!found) {
throw new Error(
`Missing ${method} ${path}: ${requests
.filter(item => !item.settled)
.map(item => item.path)
.join(', ')}`
);
}
return found;
}
function reply(item: Pending, body: unknown, status = 200) {
item.settled = true;
item.resolve(status === 204 ? new Response(null, { status }) : Response.json(body, { status }));
}
async function flush(action: () => void = () => {}) {
await act(async () => {
action();
await Promise.resolve();
});
}
function button(label: string) {
const found = [...host.querySelectorAll('button')].find(
item => item.textContent?.trim() === label || item.getAttribute('aria-label') === label
);
if (!found) {
throw new Error(`Missing button ${label}: ${host.textContent}`);
}
return found;
}
function click(label: string) {
button(label).click();
}
function field(label: string) {
const found = host.querySelector(`[aria-label="${label}"]`) as
| HTMLInputElement
| HTMLTextAreaElement
| HTMLSelectElement
| null;
if (!found) {
throw new Error(`Missing field ${label}`);
}
return found;
}
function edit(label: string, value: string) {
const input = field(label);
const prototype =
input.tagName === 'SELECT'
? browser.HTMLSelectElement.prototype
: input.tagName === 'TEXTAREA'
? browser.HTMLTextAreaElement.prototype
: browser.HTMLInputElement.prototype;
Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value);
input.dispatchEvent(
new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', {
bubbles: true,
}) as unknown as Event
);
}
function Probe() {
navigate = router.useNavigate();
const current = router.useLocation();
location = current.pathname + current.search;
return null;
}
async function mount(path = '/research/p1') {
root = createRoot(host);
await flush(() =>
root!.render(
createElement(
router.MemoryRouter,
{ initialEntries: [path] },
createElement(
router.Routes,
null,
createElement(router.Route, {
path: '/research',
element: createElement(ResearchListPage),
}),
createElement(router.Route, {
path: '/research/:projectId',
element: createElement(ResearchProjectPage),
})
),
createElement(Probe)
)
)
);
}
const time = '2026-10-23T12:00:00Z';
const project = (id = 'p1', extra: Partial<ResearchProject> = {}): ResearchProject => ({
id,
title: `Project ${id}`,
description: 'Description',
revision: 1,
ownerPrincipal: 'operator',
updatedBy: 'operator',
archived: false,
createdAt: time,
updatedAt: time,
...extra,
});
const hypothesis = (id = 'h1', extra: Partial<ResearchHypothesis> = {}): ResearchHypothesis => ({
id,
projectId: 'p1',
ownerPrincipal: 'operator',
updatedBy: 'operator',
archived: false,
createdAt: time,
updatedAt: time,
latestRevision: {
id: `${id}-r1`,
hypothesisId: id,
ordinal: 1,
title: 'Momentum hypothesis',
proposition: '<img src=x onerror=alert(1)>',
validationCriteria: 'Out of sample',
validationState: 'unvalidated',
submittedBy: 'operator',
contentOrigin: 'ai',
createdAt: time,
},
...extra,
});
const artifact = (id = 'a1', extra: Partial<ResearchArtifact> = {}): ResearchArtifact => ({
id,
projectId: 'p1',
hypothesisRevisionId: null,
kind: 'note',
ownerPrincipal: 'operator',
updatedBy: 'operator',
archived: false,
createdAt: time,
updatedAt: time,
latestRevision: {
id: `${id}-r1`,
artifactId: id,
ordinal: 1,
title: 'Research note',
body: '<script>doNotRun()</script>',
validationState: 'unvalidated',
evidenceState: 'none',
evidence: [],
submittedBy: 'operator',
contentOrigin: 'human',
createdAt: time,
},
...extra,
});
const strategy: StrategyRecord = {
id: 's1',
name: 'Trend',
description: '',
ownerPrincipal: 'operator',
updatedBy: 'operator',
archived: false,
createdAt: time,
updatedAt: time,
};
function replyProject(
value = project(),
hypotheses: ResearchHypothesis[] = [],
artifacts: ResearchArtifact[] = [],
strategies: StrategyRecord[] = []
) {
reply(request(`research-projects/${value.id}`), { project: value });
reply(request(`research-projects/${value.id}/strategies`), { strategies });
reply(request(`research-projects/${value.id}/hypotheses?includeArchived=true`), { hypotheses });
reply(request(`research-projects/${value.id}/analysis-artifacts?includeArchived=true`), {
artifacts,
});
reply(request('strategies'), {
strategies: [strategy, { ...strategy, id: 'archived', name: 'Retired', archived: true }],
});
}
function replyHypothesis(value = hypothesis(), revisions = [value.latestRevision]) {
reply(request(`hypotheses/${value.id}`), { hypothesis: value });
reply(request(`hypotheses/${value.id}/revisions`), { revisions });
}
function replyArtifact(value = artifact(), revisions = [value.latestRevision]) {
reply(request(`analysis-artifacts/${value.id}`), { artifact: value });
reply(request(`analysis-artifacts/${value.id}/revisions`), { revisions });
}
beforeAll(async () => {
for (const [key, value] of Object.entries({
window: browser,
document: browser.document,
IS_REACT_ACT_ENVIRONMENT: true,
})) {
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
}
({ createRoot } = await import('react-dom/client'));
router = await import('react-router-dom');
({ ResearchListPage } = await import(
'../../apps/stock/web-app/src/features/research/ResearchListPage'
));
({ ResearchProjectPage } = await import(
'../../apps/stock/web-app/src/features/research/ResearchProjectPage'
));
});
beforeEach(() => {
requests.length = 0;
host = browser.document.createElement('div') as unknown as HTMLDivElement;
browser.document.body.append(host as never);
Object.defineProperty(browser, 'confirm', {
configurable: true,
writable: true,
value: () => true,
});
browser.fetch = ((url: RequestInfo | URL, init?: RequestInit) => {
const parsed = new URL(String(url));
const item: Pending = {
...deferred<Response>(),
path: parsed.pathname + parsed.search,
method: init?.method ?? 'GET',
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
settled: false,
};
requests.push(item);
return item.promise; // Deliberately ignore cancellation to exercise stale-response guards.
}) as unknown as typeof browser.fetch;
});
afterEach(async () => {
if (root) {
await flush(() => root!.unmount());
}
root = undefined;
host.remove();
});
afterAll(async () => {
await browser.happyDOM.close();
for (const key of keys) {
const descriptor = originals.get(key);
if (descriptor) {
Object.defineProperty(globalThis, key, descriptor);
} else {
delete (globalThis as Record<string, unknown>)[key];
}
}
});
describe('research workspace', () => {
test('project listing distinguishes loading, error and empty and retries reads', async () => {
await mount('/research');
expect(host.textContent).toContain('Loading research projects');
await flush(() =>
reply(request('research-projects?includeArchived=false'), { error: 'Read failed' }, 503)
);
expect(host.textContent).toContain('Read failed');
expect(host.textContent).not.toContain('No research projects yet');
await flush(() => click('Retry projects'));
await flush(() => reply(request('research-projects?includeArchived=false'), { projects: [] }));
expect(host.textContent).toContain('No research projects yet');
});
test('ambiguous project create freezes draft, prevents duplicate requests, and requires deliberate restart', async () => {
await mount('/research');
await flush(() => reply(request('research-projects?includeArchived=false'), { projects: [] }));
await flush(() => click('New project'));
await flush(() => edit('Project title', 'Lost response'));
await flush(() => {
click('Create project');
click('Create project');
});
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
await flush(() => {
const item = request('research-projects', 'POST');
item.settled = true;
item.reject(new Error('Lost'));
});
expect(field('Project title').value).toBe('Lost response');
expect(button('Create project').disabled).toBe(true);
await flush(() => click('Check saved projects'));
await flush(() =>
reply(request('research-projects?includeArchived=true'), { projects: [project()] })
);
expect(field('Project title').value).toBe('Lost response');
await flush(() => click('Start new request'));
expect(button('Create project').disabled).toBe(false);
});
test('late create success cannot navigate away from a newer project', async () => {
await mount('/research');
await flush(() => reply(request('research-projects?includeArchived=false'), { projects: [] }));
await flush(() => click('New project'));
await flush(() => edit('Project title', 'Original'));
await flush(() => click('Create project'));
const old = request('research-projects', 'POST');
await flush(() => navigate('/research/p2'));
await flush(() => replyProject(project('p2')));
await flush(() => reply(old, { project: project('p1') }));
expect(location).toBe('/research/p2');
expect(host.textContent).toContain('Project p2');
});
test('section errors never masquerade as empty records and stale project responses are ignored', async () => {
await mount();
const old = requests.slice();
await flush(() => navigate('/research/p2'));
await flush(() => {
const p = project('p2');
reply(request('research-projects/p2'), { project: p });
reply(request('research-projects/p2/strategies'), { strategies: [] });
reply(
request('research-projects/p2/hypotheses?includeArchived=true'),
{ error: 'Hypotheses unavailable' },
500
);
reply(request('research-projects/p2/analysis-artifacts?includeArchived=true'), {
artifacts: [],
});
const catalogs = requests.filter(item => item.path === '/api/v2/strategies');
reply(catalogs[1]!, { strategies: [] });
});
await flush(() => {
for (const item of old) {
if (item.path.endsWith('/p1')) {
reply(item, { project: project('p1') });
} else if (item.path.includes('hypotheses')) {
reply(item, { hypotheses: [hypothesis()] });
} else if (item.path.includes('analysis-artifacts')) {
reply(item, { artifacts: [] });
} else {
reply(item, { strategies: [] });
}
}
});
expect(host.textContent).toContain('Project p2');
expect(host.textContent).not.toContain('Project p1');
expect(host.textContent).toContain('Hypotheses unavailable');
expect(host.textContent).not.toContain('No hypotheses yet');
});
test('creates declared AI hypothesis and renders escaped, unvalidated narrative with immutable history', async () => {
await mount();
await flush(() => replyProject());
await flush(() => click('New hypothesis'));
await flush(() => {
edit('Hypothesis title', 'Momentum hypothesis');
edit('Proposition', '<img src=x onerror=alert(1)>');
edit('Validation criteria', 'Out of sample');
edit('Declared content origin', 'ai');
});
await flush(() => click('Create hypothesis'));
expect(request('research-projects/p1/hypotheses', 'POST').body).toEqual({
title: 'Momentum hypothesis',
proposition: '<img src=x onerror=alert(1)>',
validationCriteria: 'Out of sample',
contentOrigin: 'ai',
});
await flush(() =>
reply(request('research-projects/p1/hypotheses', 'POST'), { hypothesis: hypothesis() })
);
await flush(() => {
replyProject(project(), [hypothesis()]);
replyHypothesis();
});
expect(location).toBe('/research/p1?hypothesis=h1');
expect(host.textContent).toContain('Unvalidated narrative');
expect(host.textContent).toContain('AI-authored (declared)');
expect(host.querySelector('img')).toBeNull();
await flush(() => click('View revision 1'));
await flush(() => replyHypothesis());
expect(host.textContent).toContain('Immutable history');
expect(
[...host.querySelectorAll('button')].some(item => item.textContent === 'Edit latest revision')
).toBe(false);
});
test('note creation sends no measured claims and preserves an ambiguous draft across record refresh', async () => {
await mount();
await flush(() => replyProject());
await flush(() => click('New note'));
await flush(() => {
edit('Note title', 'Observation');
edit('Note body', 'Needs validation');
});
await flush(() => click('Create note'));
expect(request('research-projects/p1/analysis-artifacts', 'POST').body).toEqual({
kind: 'note',
title: 'Observation',
body: 'Needs validation',
contentOrigin: 'human',
});
await flush(() =>
reply(request('research-projects/p1/analysis-artifacts', 'POST'), { error: 'Uncertain' }, 500)
);
await flush(() => click('Check saved records'));
await flush(() => replyProject(project(), [], [artifact()]));
expect(field('Note body').value).toBe('Needs validation');
expect(button('Create note').disabled).toBe(true);
expect(host.textContent).toContain('unvalidated narrative');
});
test('409 retains revision draft and never silently rebases onto refreshed history', async () => {
await mount('/research/p1?artifact=a1');
await flush(() => replyProject(project(), [], [artifact()]));
await flush(() => replyArtifact());
await flush(() => click('Edit latest revision'));
await flush(() => edit('Revision body', 'Unsaved conclusion'));
await flush(() => click('Save new revision'));
expect(request('analysis-artifacts/a1/revisions', 'POST').body).toMatchObject({
expectedRevision: 1,
body: 'Unsaved conclusion',
evidence: [],
});
await flush(() =>
reply(request('analysis-artifacts/a1/revisions', 'POST'), { error: 'Revision conflict' }, 409)
);
expect(field('Revision body').value).toBe('Unsaved conclusion');
expect(button('Save new revision').disabled).toBe(true);
await flush(() => click('Refresh project'));
await flush(() => replyProject(project(), [], [artifact()]));
expect(field('Revision body').value).toBe('Unsaved conclusion');
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
});
test('membership refreshes project revision before the next metadata write; archived strategies remain visible', async () => {
await mount();
await flush(() => replyProject());
expect(field('Strategy to link').textContent).not.toContain('Retired');
await flush(() => edit('Strategy to link', 's1'));
await flush(() => click('Link strategy'));
await flush(() => reply(request('research-projects/p1/strategies/s1', 'PUT'), undefined, 204));
await flush(() =>
replyProject(project('p1', { revision: 2 }), [], [], [{ ...strategy, archived: true }])
);
expect(host.textContent).toContain('Archived strategy');
await flush(() => click('Edit project'));
await flush(() => edit('Project description', 'New description'));
await flush(() => click('Save project'));
expect(request('research-projects/p1', 'PATCH').body).toMatchObject({
expectedRevision: 2,
description: 'New description',
});
});
test('archived project retains entries and history but exposes only project restore', async () => {
await mount('/research/p1?artifact=a1');
await flush(() =>
replyProject(project('p1', { archived: true }), [], [artifact('a1', { archived: true })])
);
await flush(() => replyArtifact(artifact('a1', { archived: true })));
expect(host.textContent).toContain('Research note');
expect(host.textContent).toContain('Revision history');
const labels = [...host.querySelectorAll('button')].map(item => item.textContent);
expect(labels).toContain('Restore project');
for (const label of [
'New note',
'New hypothesis',
'Restore entry',
'Archive entry',
'Edit latest revision',
'Link strategy',
]) {
expect(labels).not.toContain(label);
}
await flush(() => click('Restore project'));
expect(request('research-projects/p1', 'PATCH').body).toEqual({
expectedRevision: 1,
archived: false,
});
});
test('cross-project entries and foreign revision IDs fail visibly', async () => {
await mount('/research/p1?hypothesis=h1&revision=foreign');
await flush(() => replyProject());
await flush(() => replyHypothesis());
expect(host.textContent).toContain('requested revision does not belong');
await flush(() => navigate('/research/p1?artifact=a1'));
await flush(() => replyArtifact(artifact('a1', { projectId: 'p2' })));
expect(host.textContent).toContain('Artifact does not belong to this project');
expect(host.textContent).not.toContain('<script>doNotRun()');
});
test('failed refresh and remote archival retain an uncertain note draft until explicit discard', async () => {
await mount();
await flush(() => replyProject());
await flush(() => click('New note'));
await flush(() => {
edit('Note title', 'Retained title');
edit('Note body', 'Retained body');
});
await flush(() => click('Create note'));
await flush(() =>
reply(
request('research-projects/p1/analysis-artifacts', 'POST'),
{ error: 'Uncertain write' },
500
)
);
await flush(() => click('Check saved records'));
await flush(() => {
reply(request('research-projects/p1'), { error: 'Project refresh unavailable' }, 503);
reply(request('research-projects/p1/strategies'), { strategies: [] });
reply(request('research-projects/p1/hypotheses?includeArchived=true'), { hypotheses: [] });
reply(request('research-projects/p1/analysis-artifacts?includeArchived=true'), {
artifacts: [],
});
reply(request('strategies'), { strategies: [] });
});
expect(field('Note title').value).toBe('Retained title');
expect(field('Note body').value).toBe('Retained body');
expect(button('Create note').disabled).toBe(true);
expect(host.textContent).toContain('Project status could not be verified');
await flush(() => click('Refresh project'));
await flush(() => replyProject(project('p1', { archived: true })));
expect(field('Note body').value).toBe('Retained body');
expect(button('Create note').disabled).toBe(true);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
});
test('finding revisions retain exact evidence references and link archived hypothesis history', async () => {
const original = hypothesis().latestRevision;
const linked = hypothesis('h1', {
archived: true,
latestRevision: { ...original, id: 'h1-r2', ordinal: 2, title: 'Revised hypothesis' },
});
const originalNote = artifact().latestRevision;
const finding = artifact('a1', {
kind: 'finding',
hypothesisRevisionId: original.id,
latestRevision: {
...originalNote,
title: 'Finding',
evidenceState: 'referenced',
evidence: [
{
runId: '11111111-1111-4111-8111-111111111111',
backtestId: '22222222-2222-4222-8222-222222222222',
strategyVersionId: '33333333-3333-4333-8333-333333333333',
metricsVersion: 'canonical-analytics/v1',
metricPath: 'analytics.metrics.totalReturn',
value: 0.12,
unit: 'fraction',
availability: 'available',
unavailableReason: null,
resultKind: 'canonical',
financialEngine: 'rust',
datasetHash: 'frozen-dataset',
limitations: [],
},
],
},
});
await mount('/research/p1?artifact=a1');
await flush(() => replyProject(project(), [linked], [finding]));
await flush(() => replyArtifact(finding));
await flush(() =>
reply(request('hypotheses/h1/revisions'), { revisions: [original, linked.latestRevision] })
);
const historyLink = host.querySelector('a[href="/research/p1?hypothesis=h1&revision=h1-r1"]');
expect(historyLink).not.toBeNull();
expect(
host.querySelector(
'a[href="/backtests/22222222-2222-4222-8222-222222222222/run/11111111-1111-4111-8111-111111111111"]'
)
).not.toBeNull();
await flush(() => click('Edit latest revision'));
await flush(() => edit('Revision body', 'Updated interpretation, same evidence'));
await flush(() => click('Save new revision'));
expect(request('analysis-artifacts/a1/revisions', 'POST').body).toEqual({
expectedRevision: 1,
title: 'Finding',
body: 'Updated interpretation, same evidence',
contentOrigin: 'human',
evidence: [
{
runId: '11111111-1111-4111-8111-111111111111',
strategyVersionId: '33333333-3333-4333-8333-333333333333',
metricsVersion: 'canonical-analytics/v1',
metricPath: 'analytics.metrics.totalReturn',
},
],
});
await flush(() =>
reply(request('analysis-artifacts/a1/revisions', 'POST'), { artifact: finding })
);
await flush(() => {
replyProject(project(), [linked], [finding]);
replyArtifact(finding);
});
await flush(() =>
reply(request('hypotheses/h1/revisions'), { revisions: [original, linked.latestRevision] })
);
await flush(() =>
(
host.querySelector(
'a[href="/research/p1?hypothesis=h1&revision=h1-r1"]'
) as HTMLAnchorElement
).click()
);
await flush(() => replyHypothesis(linked, [original, linked.latestRevision]));
expect(host.textContent).toContain('Momentum hypothesis');
expect(host.textContent).toContain('Immutable history');
expect(
[...host.querySelectorAll('button')].some(item => item.textContent === 'Edit latest revision')
).toBe(false);
});
test('late entry read and late revision success cannot overwrite a newly selected entry', async () => {
await mount('/research/p1?hypothesis=h1');
await flush(() => replyProject());
const oldRead = request('hypotheses/h1');
const oldHistory = request('hypotheses/h1/revisions');
await flush(() => navigate('/research/p1?artifact=a1'));
await flush(() => replyArtifact());
await flush(() => {
reply(oldRead, { hypothesis: hypothesis() });
reply(oldHistory, { revisions: [hypothesis().latestRevision] });
});
expect(host.textContent).not.toContain('Momentum hypothesis');
await flush(() => click('Edit latest revision'));
await flush(() => edit('Revision body', 'Pending revision'));
await flush(() => click('Save new revision'));
const oldSave = request('analysis-artifacts/a1/revisions', 'POST');
await flush(() => navigate('/research/p1?hypothesis=h2'));
await flush(() => replyHypothesis(hypothesis('h2')));
const before = requests.length;
await flush(() => reply(oldSave, { artifact: artifact() }));
expect(location).toBe('/research/p1?hypothesis=h2');
expect(requests).toHaveLength(before);
});
test('discarding a draft by reopening the same entry reloads it and owned navigation respects refusal', async () => {
await mount('/research/p1?artifact=a1');
await flush(() => replyProject(project(), [], [artifact()]));
await flush(() => replyArtifact());
await flush(() => click('Edit latest revision'));
await flush(() => edit('Revision body', 'Discard me'));
Object.defineProperty(browser, 'confirm', {
configurable: true,
writable: true,
value: () => false,
});
await flush(() => (host.querySelector('a[href="/research"]') as HTMLAnchorElement).click());
expect(location).toBe('/research/p1?artifact=a1');
expect(field('Revision body').value).toBe('Discard me');
await flush(() => click('View latest revision'));
expect(field('Revision body').value).toBe('Discard me');
Object.defineProperty(browser, 'confirm', {
configurable: true,
writable: true,
value: () => true,
});
await flush(() => click('View latest revision'));
await flush(() => replyArtifact());
expect(host.querySelector('[aria-label="Revision body"]')).toBeNull();
expect(host.textContent).not.toContain('Discard me');
});
});