diff --git a/apps/stock/web-app/src/components/ui/formStyles.ts b/apps/stock/web-app/src/components/ui/formStyles.ts new file mode 100644 index 00000000..ee68b009 --- /dev/null +++ b/apps/stock/web-app/src/components/ui/formStyles.ts @@ -0,0 +1,4 @@ +export const fieldClass = + 'w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary disabled:opacity-50'; +export const actionClass = + 'px-3 py-2 rounded-md border border-border text-sm text-primary-500 disabled:opacity-50'; diff --git a/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx b/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx index 5f8e4468..649c8ace 100644 --- a/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx +++ b/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx @@ -2,7 +2,7 @@ import { useState } from 'react'; import { Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'; import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research'; import type { CanonicalMetrics } from '@stock-bot/types'; -import { actionClass } from '@/features/strategies/components/StrategyParameterForm'; +import { actionClass } from '@/components/ui/formStyles'; import { downloadJsonText } from '@/utils/downloadJsonText'; import { DatasetDownload } from './DatasetDownload'; diff --git a/apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx b/apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx index 1f509579..f9bfc316 100644 --- a/apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx +++ b/apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx @@ -5,15 +5,12 @@ import { type CanonicalResearchSettings, } from '@stock-bot/stock-config/canonical-research'; import { parseFinancialDecimal } from '@stock-bot/types'; -import { actionClass, fieldClass } from '@/features/strategies/components/StrategyParameterForm'; +import { actionClass, fieldClass } from '@/components/ui/formStyles'; import { StrategySelection, type CatalogSelection, } from '@/features/strategies/components/StrategySelection'; -import { - confirmDiscard, - useUnsavedWarning, -} from '@/features/strategies/components/useUnsavedWarning'; +import { confirmDiscard, useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { backtestApiV2, type Backtest, diff --git a/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx b/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx index 12588b78..477d7631 100644 --- a/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx +++ b/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx @@ -4,10 +4,7 @@ import { StrategySelection, type CatalogSelection, } from '@/features/strategies/components/StrategySelection'; -import { - confirmDiscard, - useUnsavedWarning, -} from '@/features/strategies/components/useUnsavedWarning'; +import { confirmDiscard, useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { backtestApiV2, type Backtest } from '../services/backtestApiV2'; import type { HistoricalSelection } from '../services/historical-selection'; import { HistoricalDataSelection } from './HistoricalDataSelection'; diff --git a/apps/stock/web-app/src/features/backtest/components/DatasetDownload.tsx b/apps/stock/web-app/src/features/backtest/components/DatasetDownload.tsx index b45657e3..0305ccae 100644 --- a/apps/stock/web-app/src/features/backtest/components/DatasetDownload.tsx +++ b/apps/stock/web-app/src/features/backtest/components/DatasetDownload.tsx @@ -1,5 +1,5 @@ import { useEffect, useRef, useState } from 'react'; -import { actionClass } from '@/features/strategies/components/StrategyParameterForm'; +import { actionClass } from '@/components/ui/formStyles'; import { downloadJsonText } from '@/utils/downloadJsonText'; import { backtestApiV2 } from '../services/backtestApiV2'; diff --git a/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx b/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx index f4b97216..478af3a0 100644 --- a/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx +++ b/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from 'react'; import type { CanonicalDatasetPreparation } from '@stock-bot/stock-config/canonical-research'; import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; -import { actionClass, fieldClass } from '@/features/strategies/components/StrategyParameterForm'; +import { actionClass, fieldClass } from '@/components/ui/formStyles'; import { backtestApiV2, DatasetPreparationRequestError, diff --git a/apps/stock/web-app/src/features/backtest/components/RunReproduction.tsx b/apps/stock/web-app/src/features/backtest/components/RunReproduction.tsx index 9e52d113..955b5e1d 100644 --- a/apps/stock/web-app/src/features/backtest/components/RunReproduction.tsx +++ b/apps/stock/web-app/src/features/backtest/components/RunReproduction.tsx @@ -6,7 +6,7 @@ import type { } from '@stock-bot/stock-config/canonical-research'; import { Button } from '@/components/ui/Button'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/Dialog'; -import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning'; +import { useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { backtestApiV2, ReproductionSubmissionError, type Run } from '../services/backtestApiV2'; interface Props { diff --git a/apps/stock/web-app/src/features/backtest/components/StoredSourceInspector.tsx b/apps/stock/web-app/src/features/backtest/components/StoredSourceInspector.tsx index 37ff26f9..d713a89a 100644 --- a/apps/stock/web-app/src/features/backtest/components/StoredSourceInspector.tsx +++ b/apps/stock/web-app/src/features/backtest/components/StoredSourceInspector.tsx @@ -4,7 +4,7 @@ import type { StoredSourceInspection, StoredSourceQuery, } from '@stock-bot/stock-config/stored-source'; -import { actionClass, fieldClass } from '@/features/strategies/components/StrategyParameterForm'; +import { actionClass, fieldClass } from '@/components/ui/formStyles'; import { storedSourceApi } from '../services/storedSourceApi'; const instant = (value: number | null) => diff --git a/apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage.tsx b/apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage.tsx index 03f40b07..db58d301 100644 --- a/apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage.tsx +++ b/apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage.tsx @@ -2,8 +2,8 @@ import { useEffect, useRef, useState } from 'react'; import { Link, useParams } from 'react-router-dom'; import type { ChronologicalValidationActionReceipt } from '@stock-bot/stock-config/chronological-validation'; import { Button } from '@/components/ui/Button'; -import { chronologicalFindingSource } from '@/features/research/components/findingSources'; -import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning'; +import { chronologicalFindingSource } from '@/features/research/services/findingSources'; +import { useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { ExperimentCounts } from './components/ExperimentCounts'; import { RegimeEvidenceUnavailable } from './components/RegimeEvidenceUnavailable'; import { SourceFindingAction } from './components/SourceFindingAction'; diff --git a/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx b/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx index 07724154..99a2ee01 100644 --- a/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx +++ b/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx @@ -2,8 +2,8 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import { Link, useParams } from 'react-router-dom'; import type { ExperimentTrial } from '@stock-bot/stock-config/experiments'; import { Button } from '@/components/ui/Button'; -import { experimentFindingSource } from '@/features/research/components/findingSources'; -import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning'; +import { experimentFindingSource } from '@/features/research/services/findingSources'; +import { useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { ExperimentCounts } from './components/ExperimentCounts'; import { ExperimentInputs } from './components/ExperimentInputs'; import { ExperimentTrialRecovery } from './components/ExperimentTrialRecovery'; diff --git a/apps/stock/web-app/src/features/experiments/WalkForwardDetailPage.tsx b/apps/stock/web-app/src/features/experiments/WalkForwardDetailPage.tsx index 27ad028a..0d449267 100644 --- a/apps/stock/web-app/src/features/experiments/WalkForwardDetailPage.tsx +++ b/apps/stock/web-app/src/features/experiments/WalkForwardDetailPage.tsx @@ -2,8 +2,8 @@ import { useEffect, useRef, useState } from 'react'; import { Link, useParams } from 'react-router-dom'; import type { WalkForwardReceipt } from '@stock-bot/stock-config/walk-forward'; import { Button } from '@/components/ui/Button'; -import { walkForwardFindingSource } from '@/features/research/components/findingSources'; -import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning'; +import { walkForwardFindingSource } from '@/features/research/services/findingSources'; +import { useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { RegimeEvidenceUnavailable } from './components/RegimeEvidenceUnavailable'; import { SourceFindingAction } from './components/SourceFindingAction'; import { ValidationEvidence } from './components/ValidationEvidence'; diff --git a/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx b/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx index 3df497ff..76e68394 100644 --- a/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx +++ b/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx @@ -7,7 +7,7 @@ import { StrategySelection, type CatalogSelection, } from '@/features/strategies/components/StrategySelection'; -import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning'; +import { useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { useExperimentSubmission } from '../hooks/useExperimentSubmission'; import { useExperimentTemplates } from '../hooks/useExperimentTemplates'; import { ChronologicalValidationPreflight } from './ChronologicalValidationPreflight'; diff --git a/apps/stock/web-app/src/features/experiments/components/SourceFindingAction.tsx b/apps/stock/web-app/src/features/experiments/components/SourceFindingAction.tsx index dd0f392e..d3a91117 100644 --- a/apps/stock/web-app/src/features/experiments/components/SourceFindingAction.tsx +++ b/apps/stock/web-app/src/features/experiments/components/SourceFindingAction.tsx @@ -1,7 +1,7 @@ import { useState } from 'react'; import { Button } from '@/components/ui/Button'; -import type { FindingDraftSource } from '@/features/research/components/findingSources'; import { SaveSourceFindingDialog } from '@/features/research/components/SaveFindingDialog'; +import type { FindingDraftSource } from '@/features/research/services/findingSources'; export function SourceFindingAction({ source, diff --git a/apps/stock/web-app/src/features/paper/PaperDeploymentPage.tsx b/apps/stock/web-app/src/features/paper/PaperDeploymentPage.tsx index 3ae268c0..59c857ca 100644 --- a/apps/stock/web-app/src/features/paper/PaperDeploymentPage.tsx +++ b/apps/stock/web-app/src/features/paper/PaperDeploymentPage.tsx @@ -4,7 +4,7 @@ import type { PaperDeployment, PaperDeploymentStatus, } from '@stock-bot/stock-config/paper-deployments'; -import { actionClass, fieldClass } from '../strategies/components/StrategyParameterForm'; +import { actionClass, fieldClass } from '@/components/ui/formStyles'; import { paperApi } from './paperApi'; export function PaperDeploymentPage() { diff --git a/apps/stock/web-app/src/features/paper/PaperDeploymentsPage.tsx b/apps/stock/web-app/src/features/paper/PaperDeploymentsPage.tsx index 6c8c2ef2..c89fb43c 100644 --- a/apps/stock/web-app/src/features/paper/PaperDeploymentsPage.tsx +++ b/apps/stock/web-app/src/features/paper/PaperDeploymentsPage.tsx @@ -6,11 +6,11 @@ import type { PaperPromotionPreview, } from '@stock-bot/stock-config/paper-deployments'; import { paperPromotionInputSchema } from '@stock-bot/stock-config/paper-deployments'; +import { actionClass, fieldClass } from '@/components/ui/formStyles'; +import { useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { chronologicalValidationDurableApi } from '../experiments/services/chronologicalValidationDurableApi'; import { experimentApi } from '../experiments/services/experimentApi'; import { walkForwardApi } from '../experiments/services/walkForwardApi'; -import { actionClass, fieldClass } from '../strategies/components/StrategyParameterForm'; -import { useUnsavedWarning } from '../strategies/components/useUnsavedWarning'; import { paperApi, PaperApiError } from './paperApi'; const message = (cause: unknown) => diff --git a/apps/stock/web-app/src/features/research/ResearchAgentsPage.tsx b/apps/stock/web-app/src/features/research/ResearchAgentsPage.tsx index 7c23c774..86f5cb73 100644 --- a/apps/stock/web-app/src/features/research/ResearchAgentsPage.tsx +++ b/apps/stock/web-app/src/features/research/ResearchAgentsPage.tsx @@ -6,8 +6,8 @@ import { type ResearchAgentLimits, type ResearchAgentRecord, } from '@stock-bot/stock-config/research-agents'; -import { actionClass, fieldClass } from '../strategies/components/StrategyParameterForm'; -import { useUnsavedWarning } from '../strategies/components/useUnsavedWarning'; +import { actionClass, fieldClass } from '@/components/ui/formStyles'; +import { useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { ResearchAgentApiError, researchAgentsApi } from './services/researchAgentsApi'; const limitFields: Array<[keyof ResearchAgentLimits, string, string]> = [ diff --git a/apps/stock/web-app/src/features/research/ResearchListPage.tsx b/apps/stock/web-app/src/features/research/ResearchListPage.tsx index 6d667451..90d49bcf 100644 --- a/apps/stock/web-app/src/features/research/ResearchListPage.tsx +++ b/apps/stock/web-app/src/features/research/ResearchListPage.tsx @@ -3,8 +3,8 @@ import { Link, useNavigate } from 'react-router-dom'; import { createResearchProjectSchema } from '@stock-bot/stock-config/research'; 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 { actionClass, fieldClass } from '@/components/ui/formStyles'; +import { confirmDiscard, useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { researchApi, ResearchApiError } from './services/researchApi'; export function ResearchListPage() { diff --git a/apps/stock/web-app/src/features/research/ResearchProjectPage.tsx b/apps/stock/web-app/src/features/research/ResearchProjectPage.tsx index bd2618b7..24bd3456 100644 --- a/apps/stock/web-app/src/features/research/ResearchProjectPage.tsx +++ b/apps/stock/web-app/src/features/research/ResearchProjectPage.tsx @@ -8,8 +8,8 @@ import type { 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 { actionClass, fieldClass } from '@/components/ui/formStyles'; +import { confirmDiscard, useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { strategyApi } from '../strategies/services/strategyApi'; import { CreateResearchEntry } from './components/CreateResearchEntry'; import { ResearchEntry } from './components/ResearchEntry'; diff --git a/apps/stock/web-app/src/features/research/components/CreateResearchEntry.tsx b/apps/stock/web-app/src/features/research/components/CreateResearchEntry.tsx index a955a87c..f2809372 100644 --- a/apps/stock/web-app/src/features/research/components/CreateResearchEntry.tsx +++ b/apps/stock/web-app/src/features/research/components/CreateResearchEntry.tsx @@ -5,8 +5,8 @@ import { } from '@stock-bot/stock-config/research'; import type { ResearchArtifact, ResearchContentOrigin, ResearchHypothesis } 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 { actionClass, fieldClass } from '@/components/ui/formStyles'; +import { confirmDiscard, useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { researchApi, ResearchApiError } from '../services/researchApi'; interface Props { diff --git a/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx b/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx index 692e3644..5999384c 100644 --- a/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx +++ b/apps/stock/web-app/src/features/research/components/ResearchEntry.tsx @@ -1,43 +1,16 @@ -import { useEffect, useRef, useState } from 'react'; +import { useEffect, useState } from 'react'; import { Link } from 'react-router-dom'; -import { - reviseResearchArtifactSchema, - reviseResearchHypothesisSchema, -} from '@stock-bot/stock-config/research'; -import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; -import type { - ResearchArtifact, - ResearchArtifactRevision, - ResearchContentOrigin, - ResearchHypothesis, - ResearchHypothesisRevision, -} from '@stock-bot/types'; +import type { ResearchContentOrigin, ResearchHypothesis } from '@stock-bot/types'; import { Card } from '@/components/ui/Card'; -import { downloadJsonText } from '@/utils/downloadJsonText'; -import { actionClass, fieldClass } from '../../strategies/components/StrategyParameterForm'; -import { confirmDiscard, useUnsavedWarning } from '../../strategies/components/useUnsavedWarning'; -import { researchApi, ResearchApiError } from '../services/researchApi'; +import { actionClass, fieldClass } from '@/components/ui/formStyles'; +import { useResearchEntry, type ResearchEntryWorkflowOptions } from '../hooks/useResearchEntry'; +import { researchApi } from '../services/researchApi'; import { FindingSource } from './FindingSource'; -import { - evidenceReferences, - ResearchAuthorshipBadge, - ResearchEvidenceList, -} from './ResearchEvidence'; +import { 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; +interface Props extends ResearchEntryWorkflowOptions { hypotheses: ResearchHypothesis[]; onSelectRevision: (id: string | null) => void; - onRefresh: () => void; - onDirty: (dirty: boolean) => void; } function HypothesisReference({ projectId, @@ -120,284 +93,44 @@ export function ResearchEntry({ onRefresh, onDirty, }: Props) { - const mounted = useRef(false); - const pending = useRef(false); - const [entry, setEntry] = useState(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('human'); - const [saving, setSaving] = useState(false); - const [error, setError] = useState(''); - const [blocked, setBlocked] = useState(false); - const [archiveUncertain, setArchiveUncertain] = useState(false); - const [downloadError, setDownloadError] = useState(''); - 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(''); - setDownloadError(''); - setEntry(null); - const load = async (): Promise => { - 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 download = () => { - if (loading || saving || !entry || !revision) { - return; - } - setDownloadError(''); - try { - const record = { - kind: 'research-revision-export/v1', - projectId, - entry: - entry.kind === 'hypothesis' - ? { id: entry.entity.id, kind: 'hypothesis' } - : { - id: entry.entity.id, - kind: entry.entity.kind, - hypothesisRevisionId: entry.entity.hypothesisRevisionId, - }, - revision, - }; - downloadJsonText(JSON.stringify(record), `research-${entry.entity.id}-${revision.id}.json`); - } catch (cause) { - setDownloadError( - cause instanceof Error ? cause.message : 'Could not download saved revision' - ); - } - }; - const readonly = - archived || Boolean(writeBlocked) || entry?.entity.archived || Boolean(revisionId); - const beginEdit = () => { - if (!revision || readonly || archiveUncertain) { - 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 || - archiveUncertain || - !title.trim() || - (kind === 'hypothesis' && !body.trim()) - ) { - return; - } - pending.current = true; - setSaving(true); - setError(''); - try { - let saved: ResearchHypothesis | ResearchArtifact; - let matches: boolean; - if (entry.kind === 'hypothesis') { - const input = reviseResearchHypothesisSchema.parse({ - expectedRevision: entry.entity.latestRevision.ordinal, - title, - proposition: body, - validationCriteria: criteria, - contentOrigin: origin, - }); - ({ hypothesis: saved } = await researchApi.reviseHypothesis(id, input)); - matches = - saved.latestRevision.hypothesisId === id && - saved.latestRevision.title === input.title && - saved.latestRevision.proposition === input.proposition && - saved.latestRevision.validationCriteria === input.validationCriteria; - } else { - const input = reviseResearchArtifactSchema.parse({ - expectedRevision: entry.entity.latestRevision.ordinal, - title, - body, - contentOrigin: origin, - evidence: evidenceReferences(entry.entity.latestRevision.evidence), - ...(entry.entity.latestRevision.source !== undefined - ? { source: entry.entity.latestRevision.source } - : {}), - }); - ({ artifact: saved } = await researchApi.reviseArtifact(id, input)); - matches = - saved.kind === entry.entity.kind && - saved.hypothesisRevisionId === entry.entity.hypothesisRevisionId && - saved.latestRevision.artifactId === id && - saved.latestRevision.title === input.title && - saved.latestRevision.body === input.body && - saved.latestRevision.evidenceState === (input.evidence.length ? 'referenced' : 'none') && - Array.isArray(saved.latestRevision.evidence) && - canonicalStrategyJson(evidenceReferences(saved.latestRevision.evidence)) === - canonicalStrategyJson(input.evidence) && - canonicalStrategyJson(saved.latestRevision.source ?? null) === - canonicalStrategyJson(entry.entity.latestRevision.source ?? null); - } - if ( - !matches || - saved.id !== id || - saved.projectId !== projectId || - saved.ownerPrincipal !== entry.entity.ownerPrincipal || - saved.latestRevision.id === entry.entity.latestRevision.id || - saved.latestRevision.ordinal !== entry.entity.latestRevision.ordinal + 1 || - saved.latestRevision.contentOrigin !== origin || - saved.latestRevision.validationState !== 'unvalidated' - ) { - throw new ResearchApiError('The saved revision response could not be verified.', null); - } - 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 || - archiveUncertain || - !confirmDiscard(editing) || - !window.confirm(`${entry.entity.archived ? 'Restore' : 'Archive'} this research entry?`) - ) { - return; - } - pending.current = true; - setSaving(true); - setError(''); - try { - const targetArchived = !entry.entity.archived; - let saved: ResearchHypothesis | ResearchArtifact; - let matches: boolean; - if (entry.kind === 'hypothesis') { - ({ hypothesis: saved } = await researchApi.archiveHypothesis(id, targetArchived)); - matches = saved.latestRevision.hypothesisId === id; - } else { - ({ artifact: saved } = await researchApi.archiveArtifact(id, targetArchived)); - matches = - saved.latestRevision.artifactId === id && - saved.kind === entry.entity.kind && - saved.hypothesisRevisionId === entry.entity.hypothesisRevisionId; - } - // Archive has no narrative revision precondition. A concurrent edit may be newer. - if ( - !matches || - saved.id !== id || - saved.projectId !== projectId || - saved.ownerPrincipal !== entry.entity.ownerPrincipal || - saved.archived !== targetArchived || - saved.latestRevision.validationState !== 'unvalidated' - ) { - throw new ResearchApiError('The archive response could not be verified.', null); - } - 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'); - setArchiveUncertain(!(cause instanceof ResearchApiError) || cause.ambiguous); - } - } finally { - pending.current = false; - if (mounted.current) { - setSaving(false); - } - } - }; + const { + entry, + revision, + loading, + loadError, + downloadError, + download, + saving, + readonly, + archiveUncertain, + editing, + title, + setTitle, + body, + setBody, + criteria, + setCriteria, + origin, + setOrigin, + save, + error, + blocked, + beginEdit, + archive, + retry, + discardArchiveDraft, + discardRevisionAndReload, + discardRevisionDraft, + } = useResearchEntry({ + projectId, + id, + kind, + revisionId, + archived, + writeBlocked, + onRefresh, + onDirty, + }); return ( {loading &&

Loading research entry and revision history...

} @@ -406,7 +139,7 @@ export function ResearchEntry({

{loadError}

- @@ -505,17 +238,7 @@ export function ResearchEntry({ className={actionClass} type="button" disabled={saving} - onClick={() => { - if (confirmDiscard(editing)) { - setLoading(true); - setEditing(false); - setArchiveUncertain(false); - setBlocked(false); - setError(''); - setReload(value => value + 1); - onRefresh(); - } - }} + onClick={discardArchiveDraft} > Discard draft and reload archive state @@ -581,19 +304,7 @@ export function ResearchEntry({ The draft is preserved. Reload and review saved history before starting another revision; this request will not be retried.

- @@ -616,12 +327,7 @@ export function ResearchEntry({ className={actionClass} type="button" disabled={saving} - onClick={() => { - if (confirmDiscard(true)) { - setEditing(false); - setError(''); - } - }} + onClick={discardRevisionDraft} > Discard revision draft diff --git a/apps/stock/web-app/src/features/research/components/ResearchEvidence.tsx b/apps/stock/web-app/src/features/research/components/ResearchEvidence.tsx index 8177017b..c29dde3d 100644 --- a/apps/stock/web-app/src/features/research/components/ResearchEvidence.tsx +++ b/apps/stock/web-app/src/features/research/components/ResearchEvidence.tsx @@ -1,9 +1,5 @@ import { Link } from 'react-router-dom'; -import type { - ResearchAuthorship, - ResearchEvidence, - ResearchEvidenceReference, -} from '@stock-bot/types'; +import type { ResearchAuthorship, ResearchEvidence } from '@stock-bot/types'; export function ResearchAuthorshipBadge({ authorship }: { authorship: ResearchAuthorship }) { const origin = @@ -18,14 +14,6 @@ export function ResearchAuthorshipBadge({ authorship }: { authorship: ResearchAu

); } -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()); diff --git a/apps/stock/web-app/src/features/research/components/SaveFindingDialog.tsx b/apps/stock/web-app/src/features/research/components/SaveFindingDialog.tsx index c97f524b..767633e9 100644 --- a/apps/stock/web-app/src/features/research/components/SaveFindingDialog.tsx +++ b/apps/stock/web-app/src/features/research/components/SaveFindingDialog.tsx @@ -1,39 +1,19 @@ -import { useEffect, useRef, useState } from 'react'; import { Link } from 'react-router-dom'; import type { ResearchRunResult } from '@stock-bot/stock-config/canonical-research'; -import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; -import type { - ResearchArtifact, - ResearchContentOrigin, - ResearchEvidenceReference, - ResearchHypothesis, - ResearchProject, -} from '@stock-bot/types'; +import type { ResearchContentOrigin } 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 { FindingSource } from './FindingSource'; +import { fieldClass } from '@/components/ui/formStyles'; +import { confirmDiscard } from '@/hooks/useUnsavedWarning'; +import { useFindingDraft, type FindingDraftOptions } from '../hooks/useFindingDraft'; import { findingMetricKey, singleRunFindingSource, type FindingDraftSource, -} from './findingSources'; +} from '../services/findingSources'; +import { FindingSource } from './FindingSource'; import { ResearchEvidenceList, researchMetricLabel } from './ResearchEvidence'; -function referenceIdentities(references: ResearchEvidenceReference[]) { - return references.map(({ runId, metricsVersion, metricPath, strategyVersionId }) => ({ - runId, - metricsVersion, - metricPath, - strategyVersionId: strategyVersionId ?? null, - })); -} - /** Preserve the original single-run API and initial total-return selection. */ export function SaveFindingDialog({ result, @@ -57,240 +37,42 @@ export function SaveSourceFindingDialog(props: { }) { return ; } -function FindingDraft({ - source: incoming, - onClose, - onDirtyChange, -}: { - source: FindingDraftSource; - onClose: () => void; - onDirtyChange?: (dirty: boolean) => void; -}) { - // Retain the exact open-time source and choices through background page refreshes. - const [source] = useState(() => structuredClone(incoming)); - const metrics = source.runs.flatMap(run => run.metrics); - const [projects, setProjects] = useState([]); - const [projectsLoading, setProjectsLoading] = useState(true); - const [projectsError, setProjectsError] = useState(''); - const [reloadProjects, setReloadProjects] = useState(0); - const [projectId, setProjectId] = useState(''); - const [project, setProject] = useState(null); - const [hypotheses, setHypotheses] = useState([]); - 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('human'); - const [selectedMetrics, setSelectedMetrics] = useState(source.initialSelection); - const [pending, setPending] = useState(false); - const [ambiguous, setAmbiguous] = useState(false); - const [error, setError] = useState(''); - const [saved, setSaved] = useState(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 !== source.initialSelection.length || - selectedMetrics.some((key, index) => key !== source.initialSelection[index]) - ); - useUnsavedWarning(dirty); - useEffect(() => { - onDirtyChange?.(dirty || pending || ambiguous); - }, [dirty, pending, ambiguous, onDirtyChange]); - useEffect(() => () => onDirtyChange?.(false), [onDirtyChange]); - - useEffect(() => { - alive.current = true; - 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 || - !metrics.length - ) { - 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: metrics - .filter(metric => selectedMetrics.includes(findingMetricKey(metric.reference))) - .map(metric => metric.reference), - ...(source.context ? { source: source.context } : {}), - }; - 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' || - artifact.archived !== false || - artifact.latestRevision.artifactId !== artifact.id || - artifact.latestRevision.ordinal !== 1 || - artifact.latestRevision.title !== input.title || - artifact.latestRevision.body !== input.body || - artifact.latestRevision.contentOrigin !== input.contentOrigin || - artifact.latestRevision.validationState !== 'unvalidated' || - artifact.latestRevision.evidenceState !== 'referenced' || - canonicalStrategyJson(artifact.latestRevision.source ?? null) !== - canonicalStrategyJson(source.context) || - !Array.isArray(artifact.latestRevision.evidence) || - canonicalStrategyJson(referenceIdentities(artifact.latestRevision.evidence)) !== - canonicalStrategyJson(referenceIdentities(input.evidence ?? [])) - ) { - 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); - } - } - } +function FindingDraft(props: FindingDraftOptions) { + const { + source, + metrics, + projects, + projectsLoading, + projectsError, + retryProjects, + projectId, + selectProject, + project, + hypotheses, + hypothesisRevisionId, + setHypothesisRevisionId, + destinationLoading, + destinationError, + refreshDestination, + title, + setTitle, + body, + setBody, + contentOrigin, + setContentOrigin, + selectedMetrics, + setSelectedMetrics, + pending, + ambiguous, + error, + saved, + dirty, + blocked, + destinationActive, + close, + save, + startNewRequest, + } = useFindingDraft(props); return ( !open && close()}> @@ -333,7 +115,7 @@ function FindingDraft({ {projectsError && (
{projectsError}{' '} -
@@ -362,10 +144,7 @@ function FindingDraft({ className={fieldClass} disabled={blocked || projectsLoading} value={projectId} - onChange={event => { - setProjectId(event.target.value); - setHypothesisRevisionId(''); - }} + onChange={event => selectProject(event.target.value)} > {projects.map(item => ( @@ -384,7 +163,7 @@ function FindingDraft({ @@ -514,19 +293,7 @@ function FindingDraft({ > Check saved records - diff --git a/apps/stock/web-app/src/features/research/hooks/useFindingDraft.ts b/apps/stock/web-app/src/features/research/hooks/useFindingDraft.ts new file mode 100644 index 00000000..f4197237 --- /dev/null +++ b/apps/stock/web-app/src/features/research/hooks/useFindingDraft.ts @@ -0,0 +1,307 @@ +import { useEffect, useRef, useState } from 'react'; +import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; +import type { + ResearchArtifact, + ResearchContentOrigin, + ResearchEvidenceReference, + ResearchHypothesis, + ResearchProject, +} from '@stock-bot/types'; +import { confirmDiscard, useUnsavedWarning } from '@/hooks/useUnsavedWarning'; +import { findingMetricKey, type FindingDraftSource } from '../services/findingSources'; +import { researchApi, ResearchApiError, type ArtifactInput } from '../services/researchApi'; + +export interface FindingDraftOptions { + source: FindingDraftSource; + onClose: () => void; + onDirtyChange?: (dirty: boolean) => void; +} +function referenceIdentities(references: ResearchEvidenceReference[]) { + return references.map(({ runId, metricsVersion, metricPath, strategyVersionId }) => ({ + runId, + metricsVersion, + metricPath, + strategyVersionId: strategyVersionId ?? null, + })); +} + +/** Retains the open-time evidence, verifies the destination, and owns one finding + * submission. An uncertain write requires explicit review before another request. */ +export function useFindingDraft({ source: incoming, onClose, onDirtyChange }: FindingDraftOptions) { + // Retain the exact open-time source and choices through background page refreshes. + const [source] = useState(() => structuredClone(incoming)); + const metrics = source.runs.flatMap(run => run.metrics); + const [projects, setProjects] = useState([]); + const [projectsLoading, setProjectsLoading] = useState(true); + const [projectsError, setProjectsError] = useState(''); + const [reloadProjects, setReloadProjects] = useState(0); + const [projectId, setProjectId] = useState(''); + const [project, setProject] = useState(null); + const [hypotheses, setHypotheses] = useState([]); + 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('human'); + const [selectedMetrics, setSelectedMetrics] = useState(source.initialSelection); + const [pending, setPending] = useState(false); + const [ambiguous, setAmbiguous] = useState(false); + const [error, setError] = useState(''); + const [saved, setSaved] = useState(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 !== source.initialSelection.length || + selectedMetrics.some((key, index) => key !== source.initialSelection[index]) + ); + useUnsavedWarning(dirty); + useEffect(() => { + onDirtyChange?.(dirty || pending || ambiguous); + }, [dirty, pending, ambiguous, onDirtyChange]); + useEffect(() => () => onDirtyChange?.(false), [onDirtyChange]); + + useEffect(() => { + alive.current = true; + 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 || + !metrics.length + ) { + 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: metrics + .filter(metric => selectedMetrics.includes(findingMetricKey(metric.reference))) + .map(metric => metric.reference), + ...(source.context ? { source: source.context } : {}), + }; + 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' || + artifact.archived !== false || + artifact.latestRevision.artifactId !== artifact.id || + artifact.latestRevision.ordinal !== 1 || + artifact.latestRevision.title !== input.title || + artifact.latestRevision.body !== input.body || + artifact.latestRevision.contentOrigin !== input.contentOrigin || + artifact.latestRevision.validationState !== 'unvalidated' || + artifact.latestRevision.evidenceState !== 'referenced' || + canonicalStrategyJson(artifact.latestRevision.source ?? null) !== + canonicalStrategyJson(source.context) || + !Array.isArray(artifact.latestRevision.evidence) || + canonicalStrategyJson(referenceIdentities(artifact.latestRevision.evidence)) !== + canonicalStrategyJson(referenceIdentities(input.evidence ?? [])) + ) { + 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 retryProjects = () => setReloadProjects(value => value + 1); + const refreshDestination = () => setReloadDestination(value => value + 1); + const selectProject = (id: string) => { + setProjectId(id); + setHypothesisRevisionId(''); + }; + const startNewRequest = () => { + if ( + window.confirm( + 'The previous request may have saved this finding. Start a new request only after checking saved records. Continue?' + ) + ) { + setAmbiguous(false); + setError(''); + } + }; + return { + source, + metrics, + projects, + projectsLoading, + projectsError, + retryProjects, + projectId, + selectProject, + project, + hypotheses, + hypothesisRevisionId, + setHypothesisRevisionId, + destinationLoading, + destinationError, + refreshDestination, + title, + setTitle, + body, + setBody, + contentOrigin, + setContentOrigin, + selectedMetrics, + setSelectedMetrics, + pending, + ambiguous, + error, + saved, + dirty, + blocked, + destinationActive, + close, + save, + startNewRequest, + }; +} diff --git a/apps/stock/web-app/src/features/research/hooks/useResearchEntry.ts b/apps/stock/web-app/src/features/research/hooks/useResearchEntry.ts new file mode 100644 index 00000000..a5cf4bfa --- /dev/null +++ b/apps/stock/web-app/src/features/research/hooks/useResearchEntry.ts @@ -0,0 +1,378 @@ +import { useEffect, useRef, useState } from 'react'; +import { + reviseResearchArtifactSchema, + reviseResearchHypothesisSchema, +} from '@stock-bot/stock-config/research'; +import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; +import type { + ResearchArtifact, + ResearchArtifactRevision, + ResearchContentOrigin, + ResearchHypothesis, + ResearchHypothesisRevision, +} from '@stock-bot/types'; +import { confirmDiscard, useUnsavedWarning } from '@/hooks/useUnsavedWarning'; +import { downloadJsonText } from '@/utils/downloadJsonText'; +import { evidenceReferences } from '../services/evidenceReferences'; +import { researchApi, ResearchApiError } from '../services/researchApi'; + +type Entry = + | { kind: 'hypothesis'; entity: ResearchHypothesis; revisions: ResearchHypothesisRevision[] } + | { kind: 'artifact'; entity: ResearchArtifact; revisions: ResearchArtifactRevision[] }; +export interface ResearchEntryWorkflowOptions { + projectId: string; + id: string; + kind: 'hypothesis' | 'artifact'; + revisionId: string | null; + archived: boolean; + writeBlocked: string; + onRefresh: () => void; + onDirty: (dirty: boolean) => void; +} +/** Owns one mounted entry's reads, draft and acknowledged writes. The parent keys + * this hook's component by entry/revision so late completions cannot claim another draft. */ +export function useResearchEntry({ + projectId, + id, + kind, + revisionId, + archived, + writeBlocked, + onRefresh, + onDirty, +}: ResearchEntryWorkflowOptions) { + const mounted = useRef(false); + const pending = useRef(false); + const [entry, setEntry] = useState(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('human'); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(''); + const [blocked, setBlocked] = useState(false); + const [archiveUncertain, setArchiveUncertain] = useState(false); + const [downloadError, setDownloadError] = useState(''); + 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(''); + setDownloadError(''); + setEntry(null); + const load = async (): Promise => { + 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 download = () => { + if (loading || saving || !entry || !revision) { + return; + } + setDownloadError(''); + try { + const record = { + kind: 'research-revision-export/v1', + projectId, + entry: + entry.kind === 'hypothesis' + ? { id: entry.entity.id, kind: 'hypothesis' } + : { + id: entry.entity.id, + kind: entry.entity.kind, + hypothesisRevisionId: entry.entity.hypothesisRevisionId, + }, + revision, + }; + downloadJsonText(JSON.stringify(record), `research-${entry.entity.id}-${revision.id}.json`); + } catch (cause) { + setDownloadError( + cause instanceof Error ? cause.message : 'Could not download saved revision' + ); + } + }; + const readonly = + archived || Boolean(writeBlocked) || entry?.entity.archived || Boolean(revisionId); + const beginEdit = () => { + if (!revision || readonly || archiveUncertain) { + 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 || + archiveUncertain || + !title.trim() || + (kind === 'hypothesis' && !body.trim()) + ) { + return; + } + pending.current = true; + setSaving(true); + setError(''); + try { + let saved: ResearchHypothesis | ResearchArtifact; + let matches: boolean; + if (entry.kind === 'hypothesis') { + const input = reviseResearchHypothesisSchema.parse({ + expectedRevision: entry.entity.latestRevision.ordinal, + title, + proposition: body, + validationCriteria: criteria, + contentOrigin: origin, + }); + ({ hypothesis: saved } = await researchApi.reviseHypothesis(id, input)); + matches = + saved.latestRevision.hypothesisId === id && + saved.latestRevision.title === input.title && + saved.latestRevision.proposition === input.proposition && + saved.latestRevision.validationCriteria === input.validationCriteria; + } else { + const input = reviseResearchArtifactSchema.parse({ + expectedRevision: entry.entity.latestRevision.ordinal, + title, + body, + contentOrigin: origin, + evidence: evidenceReferences(entry.entity.latestRevision.evidence), + ...(entry.entity.latestRevision.source !== undefined + ? { source: entry.entity.latestRevision.source } + : {}), + }); + ({ artifact: saved } = await researchApi.reviseArtifact(id, input)); + matches = + saved.kind === entry.entity.kind && + saved.hypothesisRevisionId === entry.entity.hypothesisRevisionId && + saved.latestRevision.artifactId === id && + saved.latestRevision.title === input.title && + saved.latestRevision.body === input.body && + saved.latestRevision.evidenceState === (input.evidence.length ? 'referenced' : 'none') && + Array.isArray(saved.latestRevision.evidence) && + canonicalStrategyJson(evidenceReferences(saved.latestRevision.evidence)) === + canonicalStrategyJson(input.evidence) && + canonicalStrategyJson(saved.latestRevision.source ?? null) === + canonicalStrategyJson(entry.entity.latestRevision.source ?? null); + } + if ( + !matches || + saved.id !== id || + saved.projectId !== projectId || + saved.ownerPrincipal !== entry.entity.ownerPrincipal || + saved.latestRevision.id === entry.entity.latestRevision.id || + saved.latestRevision.ordinal !== entry.entity.latestRevision.ordinal + 1 || + saved.latestRevision.contentOrigin !== origin || + saved.latestRevision.validationState !== 'unvalidated' + ) { + throw new ResearchApiError('The saved revision response could not be verified.', null); + } + 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 || + archiveUncertain || + !confirmDiscard(editing) || + !window.confirm(`${entry.entity.archived ? 'Restore' : 'Archive'} this research entry?`) + ) { + return; + } + pending.current = true; + setSaving(true); + setError(''); + try { + const targetArchived = !entry.entity.archived; + let saved: ResearchHypothesis | ResearchArtifact; + let matches: boolean; + if (entry.kind === 'hypothesis') { + ({ hypothesis: saved } = await researchApi.archiveHypothesis(id, targetArchived)); + matches = saved.latestRevision.hypothesisId === id; + } else { + ({ artifact: saved } = await researchApi.archiveArtifact(id, targetArchived)); + matches = + saved.latestRevision.artifactId === id && + saved.kind === entry.entity.kind && + saved.hypothesisRevisionId === entry.entity.hypothesisRevisionId; + } + // Archive has no narrative revision precondition. A concurrent edit may be newer. + if ( + !matches || + saved.id !== id || + saved.projectId !== projectId || + saved.ownerPrincipal !== entry.entity.ownerPrincipal || + saved.archived !== targetArchived || + saved.latestRevision.validationState !== 'unvalidated' + ) { + throw new ResearchApiError('The archive response could not be verified.', null); + } + 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'); + setArchiveUncertain(!(cause instanceof ResearchApiError) || cause.ambiguous); + } + } finally { + pending.current = false; + if (mounted.current) { + setSaving(false); + } + } + }; + const discardArchiveDraft = () => { + if (confirmDiscard(editing)) { + setLoading(true); + setEditing(false); + setArchiveUncertain(false); + setBlocked(false); + setError(''); + setReload(value => value + 1); + onRefresh(); + } + }; + const discardRevisionAndReload = () => { + if (confirmDiscard(true)) { + setEditing(false); + setBlocked(false); + setError(''); + setReload(value => value + 1); + onRefresh(); + } + }; + const discardRevisionDraft = () => { + if (confirmDiscard(true)) { + setEditing(false); + setError(''); + } + }; + const retry = () => setReload(value => value + 1); + return { + entry, + revision, + loading, + loadError, + downloadError, + download, + saving, + readonly, + archiveUncertain, + editing, + title, + setTitle, + body, + setBody, + criteria, + setCriteria, + origin, + setOrigin, + save, + error, + blocked, + beginEdit, + archive, + retry, + discardArchiveDraft, + discardRevisionAndReload, + discardRevisionDraft, + }; +} diff --git a/apps/stock/web-app/src/features/research/services/evidenceReferences.ts b/apps/stock/web-app/src/features/research/services/evidenceReferences.ts new file mode 100644 index 00000000..a2038887 --- /dev/null +++ b/apps/stock/web-app/src/features/research/services/evidenceReferences.ts @@ -0,0 +1,10 @@ +import type { ResearchEvidence, ResearchEvidenceReference } from '@stock-bot/types'; + +export function evidenceReferences(evidence: ResearchEvidence[]): ResearchEvidenceReference[] { + return evidence.map(({ runId, metricsVersion, metricPath, strategyVersionId }) => ({ + runId, + metricsVersion, + metricPath, + ...(strategyVersionId ? { strategyVersionId } : {}), + })); +} diff --git a/apps/stock/web-app/src/features/research/components/findingSources.ts b/apps/stock/web-app/src/features/research/services/findingSources.ts similarity index 94% rename from apps/stock/web-app/src/features/research/components/findingSources.ts rename to apps/stock/web-app/src/features/research/services/findingSources.ts index 37a04d9f..4e2de623 100644 --- a/apps/stock/web-app/src/features/research/components/findingSources.ts +++ b/apps/stock/web-app/src/features/research/services/findingSources.ts @@ -7,11 +7,13 @@ import { canonicalResearchMetricPaths, legacyResearchMetricPaths, } from '@stock-bot/stock-config/research'; +import type { + ValidationDetailView, + WalkForwardDetailView, + WorkbenchExperimentDetailView, +} from '@stock-bot/stock-config/research-responses'; import type { ResearchFindingSource } from '@stock-bot/types'; -import type { ValidationDetailView } from '@/features/experiments/services/chronologicalValidationDurableApi'; -import type { WorkbenchExperimentDetailView } from '@/features/experiments/services/experimentApi'; -import type { WalkForwardDetailView } from '@/features/experiments/services/walkForwardApi'; -import type { ArtifactInput } from '../services/researchApi'; +import type { ArtifactInput } from './researchApi'; type Reference = NonNullable[number]; export interface FindingMetricChoice { diff --git a/apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx b/apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx index d54d0eb5..5e64e363 100644 --- a/apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx +++ b/apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx @@ -1,13 +1,14 @@ import { useEffect, useRef, useState } from 'react'; import { Link, Navigate, useNavigate, useParams } from 'react-router-dom'; import type { StrategyRecord, StrategyVersionSummary } from '@stock-bot/types'; +import { actionClass, fieldClass } from '@/components/ui/formStyles'; +import { confirmDiscard, useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { BuiltinReview } from './components/BuiltinReview'; import { CandidatePublication } from './components/CandidatePublication'; import { StrategyMetadataForm } from './components/StrategyMetadataForm'; -import { actionClass, fieldClass, StrategyParameterForm } from './components/StrategyParameterForm'; +import { StrategyParameterForm } from './components/StrategyParameterForm'; import { versionPath } from './components/StrategySelection'; import { VersionComparison, VersionIdentity } from './components/StrategyVersionPanel'; -import { confirmDiscard, useUnsavedWarning } from './components/useUnsavedWarning'; import { useStrategyClone } from './hooks/useStrategyClone'; import { strategyApi, type Parameters } from './services/strategyApi'; diff --git a/apps/stock/web-app/src/features/strategies/StrategyListPage.tsx b/apps/stock/web-app/src/features/strategies/StrategyListPage.tsx index 3f7b25c7..1de4faf2 100644 --- a/apps/stock/web-app/src/features/strategies/StrategyListPage.tsx +++ b/apps/stock/web-app/src/features/strategies/StrategyListPage.tsx @@ -1,8 +1,8 @@ import { useEffect, useRef, useState } from 'react'; import { Link, useNavigate } from 'react-router-dom'; import type { StrategyRecord } from '@stock-bot/types'; -import { actionClass, fieldClass } from './components/StrategyParameterForm'; -import { confirmDiscard, useUnsavedWarning } from './components/useUnsavedWarning'; +import { actionClass, fieldClass } from '@/components/ui/formStyles'; +import { confirmDiscard, useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { strategyApi } from './services/strategyApi'; export function StrategyListPage() { diff --git a/apps/stock/web-app/src/features/strategies/components/BuiltinReview.tsx b/apps/stock/web-app/src/features/strategies/components/BuiltinReview.tsx index a19243b0..5b36e0e3 100644 --- a/apps/stock/web-app/src/features/strategies/components/BuiltinReview.tsx +++ b/apps/stock/web-app/src/features/strategies/components/BuiltinReview.tsx @@ -1,8 +1,8 @@ import { useEffect, useRef, useState } from 'react'; import type { StrategyVersionSummary } from '@stock-bot/types'; +import { actionClass, fieldClass } from '@/components/ui/formStyles'; import { API_BASE_URL, apiFetch } from '@/lib/api'; import { strategyApi } from '../services/strategyApi'; -import { actionClass, fieldClass } from './StrategyParameterForm'; /** Human approval records review; it cannot make candidate code executable. */ export function BuiltinReview({ diff --git a/apps/stock/web-app/src/features/strategies/components/CandidatePublication.tsx b/apps/stock/web-app/src/features/strategies/components/CandidatePublication.tsx index 0813d594..ca755e59 100644 --- a/apps/stock/web-app/src/features/strategies/components/CandidatePublication.tsx +++ b/apps/stock/web-app/src/features/strategies/components/CandidatePublication.tsx @@ -1,12 +1,12 @@ import { useEffect, useRef, useState } from 'react'; import type { StrategyVersionPackage } from '@stock-bot/types'; +import { actionClass, fieldClass } from '@/components/ui/formStyles'; import { CandidatePublicationError, publishCandidate, readCandidatePackage, type PublishedCandidate, } from '../services/candidatePublication'; -import { actionClass, fieldClass } from './StrategyParameterForm'; /** Key by family/parent identity. A lost write keeps exactly one package and receipt. */ export function CandidatePublication({ diff --git a/apps/stock/web-app/src/features/strategies/components/StrategyMetadataForm.tsx b/apps/stock/web-app/src/features/strategies/components/StrategyMetadataForm.tsx index a8c43365..f24154c3 100644 --- a/apps/stock/web-app/src/features/strategies/components/StrategyMetadataForm.tsx +++ b/apps/stock/web-app/src/features/strategies/components/StrategyMetadataForm.tsx @@ -1,6 +1,6 @@ import type { StrategyRecord } from '@stock-bot/types'; -import { actionClass, fieldClass } from './StrategyParameterForm'; -import { confirmDiscard } from './useUnsavedWarning'; +import { actionClass, fieldClass } from '@/components/ui/formStyles'; +import { confirmDiscard } from '@/hooks/useUnsavedWarning'; interface Props { strategy: StrategyRecord; diff --git a/apps/stock/web-app/src/features/strategies/components/StrategyParameterForm.tsx b/apps/stock/web-app/src/features/strategies/components/StrategyParameterForm.tsx index c224b863..eabdaa91 100644 --- a/apps/stock/web-app/src/features/strategies/components/StrategyParameterForm.tsx +++ b/apps/stock/web-app/src/features/strategies/components/StrategyParameterForm.tsx @@ -1,12 +1,8 @@ import { useEffect, useRef, useState } from 'react'; import type { StrategyParameterSchema, StrategyParameterValue } from '@stock-bot/types'; +import { actionClass, fieldClass } from '@/components/ui/formStyles'; import { strategyApi, type Parameters } from '../services/strategyApi'; -export const fieldClass = - 'w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary disabled:opacity-50'; -export const actionClass = - 'px-3 py-2 rounded-md border border-border text-sm text-primary-500 disabled:opacity-50'; - export function parameterFields( schema: StrategyParameterSchema, raw: Record, diff --git a/apps/stock/web-app/src/features/strategies/components/StrategySelection.tsx b/apps/stock/web-app/src/features/strategies/components/StrategySelection.tsx index 656fabb6..cab1dbf7 100644 --- a/apps/stock/web-app/src/features/strategies/components/StrategySelection.tsx +++ b/apps/stock/web-app/src/features/strategies/components/StrategySelection.tsx @@ -1,8 +1,9 @@ import { useEffect, useRef, useState } from 'react'; import { Link } from 'react-router-dom'; import type { StrategyRecord, StrategyVersionSummary } from '@stock-bot/types'; +import { actionClass, fieldClass } from '@/components/ui/formStyles'; import { strategyApi, type Parameters } from '../services/strategyApi'; -import { actionClass, fieldClass, StrategyParameterForm } from './StrategyParameterForm'; +import { StrategyParameterForm } from './StrategyParameterForm'; export interface CatalogSelection { strategyVersionId?: string | null; diff --git a/apps/stock/web-app/src/features/strategies/components/StrategyVersionPanel.tsx b/apps/stock/web-app/src/features/strategies/components/StrategyVersionPanel.tsx index 4e333a43..34198259 100644 --- a/apps/stock/web-app/src/features/strategies/components/StrategyVersionPanel.tsx +++ b/apps/stock/web-app/src/features/strategies/components/StrategyVersionPanel.tsx @@ -1,7 +1,7 @@ import { useEffect, useState } from 'react'; import type { StrategyVersionPackage, StrategyVersionSummary } from '@stock-bot/types'; +import { actionClass, fieldClass } from '@/components/ui/formStyles'; import { strategyApi } from '../services/strategyApi'; -import { actionClass, fieldClass } from './StrategyParameterForm'; export function VersionIdentity({ version }: { version: StrategyVersionSummary }) { const pkg = version.package; diff --git a/apps/stock/web-app/src/features/strategies/components/useUnsavedWarning.ts b/apps/stock/web-app/src/hooks/useUnsavedWarning.ts similarity index 100% rename from apps/stock/web-app/src/features/strategies/components/useUnsavedWarning.ts rename to apps/stock/web-app/src/hooks/useUnsavedWarning.ts diff --git a/docs/development/architecture-cleanup-execution.md b/docs/development/architecture-cleanup-execution.md index c0d71bda..181a6e45 100644 --- a/docs/development/architecture-cleanup-execution.md +++ b/docs/development/architecture-cleanup-execution.md @@ -25,3 +25,5 @@ Agents use root-reserved disjoint files in the integration worktree. Root alone - **CL26:** Moved existing shared server helpers to explicit trading-runtime subpaths, shared financial wire contracts to config, split metadata verifier from executable loader, and made artifact paths lazy. Config/runtime/API/orchestrator builds and full source typecheck passed. Architecture/Turbo/browser gates: 30 passed (7363 assertions); shared admission/storage/feed tests passed; isolated retained worker final15 passed after preserving rejection diagnostics. Native finance unchanged. - **CL35:** Actual FastAPI app/lifespan and optional capability tests: 11 passed. Missing scientific/multipart dependencies do not prevent unrelated routes; unavailable initialization returns503, health observes state. Successful optimizer/model paths tested with stubs; load-to-list output shape corrected and covered. No heavy scientific packages installed. + +- **CL30:** Independent workspace/finding UI suites: 203 passed, 1306 assertions; agent full relevant UI set344 passed, 2143 assertions. Full source typecheck and scoped lint/format passed. Extracted feature-owned read/draft/write hooks; neutral styles and unsaved warning imports replace cross-feature dependencies; custody and uncertainty behavior preserved. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index 7541816c..bfac71d4 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**Active: E13 architecture cleanup, CL22–CL35 (9/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md). +**Active: E13 architecture cleanup, CL22–CL35 (10/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md). **Current scheduled backlog: 99/99 complete.** The owner resumed performance and authorized review of all seven conditions. P08 and O02 are implemented; five optional extensions remain deliberately deferred, and four merged IDs are redirects. This is not a claim that all 108 retained IDs were implemented. [Decisions, measurements and validation](../conditional-review.md). diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index ee2d0248..9a4131fb 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -3906,7 +3906,7 @@ "epic": "E13", "priority": "P2", "severity": "Medium", - "status": "ready", + "status": "done", "dependencies": ["CL25"], "decision_dependencies": [], "task_file": "backlog/tasks/CL30.md", @@ -3916,7 +3916,9 @@ "completed_commit": null, "blocker": null, "release_gates": [], - "completion_evidence": "architecture-cleanup-execution.md" + "completion_evidence": "architecture-cleanup-execution.md", + "integration_state": "accepted", + "validation": "Independent workspace/finding UI suites: 203 passed, 1306 assertions; agent full relevant UI set344 passed, 2143 assertions. Full source typecheck and scoped lint/format passed. Extracted feature-owned read/draft/write hooks; neutral styles and unsaved warning imports replace cross-feature dependencies; custody and uncertainty behavior preserved." }, { "id": "CL31", @@ -4007,7 +4009,7 @@ "complexity": "M", "assignment": null, "write_locks": ["CL35"], - "completed_commit": null, + "completed_commit": "7ae6ac21c471f8841ba1985b5ce0d42c04401704", "blocker": null, "release_gates": [], "completion_evidence": "architecture-cleanup-execution.md", @@ -10399,7 +10401,7 @@ ], "work_policy": "Root integrates/commits reviewed tasks; agents own disjoint explicit files in the root integration worktree. Only root builds shared outputs and runs combined gates. No isolated native agent build claim.", "first_wave": ["CL22", "CL23", "CL24"], - "completed": 9, - "last_verification": "Actual FastAPI app/lifespan and optional capability tests: 11 passed. Missing scientific/multipart dependencies do not prevent unrelated routes; unavailable initialization returns503, health observes state. Successful optimizer/model paths tested with stubs; load-to-list output shape corrected and covered. No heavy scientific packages installed." + "completed": 10, + "last_verification": "Independent workspace/finding UI suites: 203 passed, 1306 assertions; agent full relevant UI set344 passed, 2143 assertions. Full source typecheck and scoped lint/format passed. Extracted feature-owned read/draft/write hooks; neutral styles and unsaved warning imports replace cross-feature dependencies; custody and uncertainty behavior preserved." } } diff --git a/docs/development/backlog/tasks/CL30.md b/docs/development/backlog/tasks/CL30.md index 697c6ae4..7ee10a67 100644 --- a/docs/development/backlog/tasks/CL30.md +++ b/docs/development/backlog/tasks/CL30.md @@ -18,3 +18,7 @@ Late response, dirty draft, acknowledgement, double-submit, archive/finding regr No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree. + +## Accepted verification + +Independent workspace/finding UI suites: 203 passed, 1306 assertions; agent full relevant UI set344 passed, 2143 assertions. Full source typecheck and scoped lint/format passed. Extracted feature-owned read/draft/write hooks; neutral styles and unsaved warning imports replace cross-feature dependencies; custody and uncertainty behavior preserved. diff --git a/test/integration/research-client.test.tsx b/test/integration/research-client.test.tsx index ca614be9..f669edea 100644 --- a/test/integration/research-client.test.tsx +++ b/test/integration/research-client.test.tsx @@ -5,10 +5,10 @@ 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'; +import { evidenceReferences } from '../../apps/stock/web-app/src/features/research/services/evidenceReferences'; const browser = new GlobalWindow({ url: 'http://localhost:5173' }); const setFetch = (value: (input: unknown, init?: RequestInit) => Promise) => diff --git a/test/integration/research-source-ui.test.tsx b/test/integration/research-source-ui.test.tsx index e6ff55d3..4fa929c0 100644 --- a/test/integration/research-source-ui.test.tsx +++ b/test/integration/research-source-ui.test.tsx @@ -32,7 +32,7 @@ import type { } from '@stock-bot/types'; import { buildExperimentPreview } from '../../apps/stock/web-api/src/services/experiment-input'; import { prepareChronologicalValidation } from '../../apps/stock/web-api/src/services/validation-preview'; -import type { FindingDraftSource } from '../../apps/stock/web-app/src/features/research/components/findingSources'; +import type { FindingDraftSource } from '../../apps/stock/web-app/src/features/research/services/findingSources'; import type { ArtifactInput } from '../../apps/stock/web-app/src/features/research/services/researchApi'; import { nativeReplayFixture } from '../fixtures/native-replay'; import { walkForwardDataset } from '../fixtures/walk-forward'; @@ -45,7 +45,7 @@ let router: typeof import('react-router-dom'); let SaveSourceFindingDialog: typeof import('../../apps/stock/web-app/src/features/research/components/SaveFindingDialog').SaveSourceFindingDialog; let ResearchEntry: typeof import('../../apps/stock/web-app/src/features/research/components/ResearchEntry').ResearchEntry; let researchApi: typeof import('../../apps/stock/web-app/src/features/research/services/researchApi').researchApi; -let sources: typeof import('../../apps/stock/web-app/src/features/research/components/findingSources'); +let sources: typeof import('../../apps/stock/web-app/src/features/research/services/findingSources'); let ExperimentDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments/ExperimentDetailPage').ExperimentDetailPage; let ChronologicalValidationDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage').ChronologicalValidationDetailPage; let WalkForwardDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments/WalkForwardDetailPage').WalkForwardDetailPage; @@ -255,9 +255,7 @@ beforeAll(async () => { ({ researchApi } = await import( '../../apps/stock/web-app/src/features/research/services/researchApi' )); - sources = await import( - '../../apps/stock/web-app/src/features/research/components/findingSources' - ); + sources = await import('../../apps/stock/web-app/src/features/research/services/findingSources'); ({ ExperimentDetailPage } = await import( '../../apps/stock/web-app/src/features/experiments/ExperimentDetailPage' ));