refactor(web): isolate research workflows and shared form utilities (CL30)
This commit is contained in:
parent
7ae6ac21c4
commit
a411f9a665
41 changed files with 859 additions and 699 deletions
4
apps/stock/web-app/src/components/ui/formStyles.ts
Normal file
4
apps/stock/web-app/src/components/ui/formStyles.ts
Normal file
|
|
@ -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';
|
||||
|
|
@ -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';
|
||||
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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) =>
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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() {
|
||||
|
|
|
|||
|
|
@ -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) =>
|
||||
|
|
|
|||
|
|
@ -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]> = [
|
||||
|
|
|
|||
|
|
@ -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() {
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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<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);
|
||||
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<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 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 (
|
||||
<Card className="p-4 space-y-4">
|
||||
{loading && <p role="status">Loading research entry and revision history...</p>}
|
||||
|
|
@ -406,7 +139,7 @@ export function ResearchEntry({
|
|||
<p role="alert" className="text-error">
|
||||
{loadError}
|
||||
</p>
|
||||
<button className={actionClass} onClick={() => setReload(value => value + 1)}>
|
||||
<button className={actionClass} onClick={retry}>
|
||||
Retry research entry
|
||||
</button>
|
||||
</div>
|
||||
|
|
@ -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
|
||||
</button>
|
||||
|
|
@ -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.
|
||||
</p>
|
||||
<button
|
||||
className={actionClass}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (confirmDiscard(true)) {
|
||||
setEditing(false);
|
||||
setBlocked(false);
|
||||
setError('');
|
||||
setReload(value => value + 1);
|
||||
onRefresh();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<button className={actionClass} type="button" onClick={discardRevisionAndReload}>
|
||||
Discard draft and reload history
|
||||
</button>
|
||||
</div>
|
||||
|
|
@ -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
|
||||
</button>
|
||||
|
|
|
|||
|
|
@ -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
|
|||
</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());
|
||||
|
|
|
|||
|
|
@ -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 <FindingDraft key={props.source.key} {...props} />;
|
||||
}
|
||||
function FindingDraft({
|
||||
source: incoming,
|
||||
onClose,
|
||||
onDirtyChange,
|
||||
}: {
|
||||
source: FindingDraftSource;
|
||||
onClose: () => void;
|
||||
onDirtyChange?: (dirty: boolean) => void;
|
||||
}) {
|
||||
// Retain the exact open-time source and choices through background page refreshes.
|
||||
const [source] = useState(() => structuredClone(incoming));
|
||||
const metrics = source.runs.flatMap(run => run.metrics);
|
||||
const [projects, setProjects] = useState<ResearchProject[]>([]);
|
||||
const [projectsLoading, setProjectsLoading] = useState(true);
|
||||
const [projectsError, setProjectsError] = useState('');
|
||||
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[]>(source.initialSelection);
|
||||
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 !== 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 (
|
||||
<Dialog open onOpenChange={open => !open && close()}>
|
||||
<DialogContent className="max-w-2xl w-[min(42rem,95vw)]">
|
||||
|
|
@ -333,7 +115,7 @@ function FindingDraft({
|
|||
{projectsError && (
|
||||
<div role="alert">
|
||||
{projectsError}{' '}
|
||||
<Button variant="outline" onClick={() => setReloadProjects(value => value + 1)}>
|
||||
<Button variant="outline" onClick={retryProjects}>
|
||||
Retry projects
|
||||
</Button>
|
||||
</div>
|
||||
|
|
@ -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)}
|
||||
>
|
||||
<option value="">Select an active project</option>
|
||||
{projects.map(item => (
|
||||
|
|
@ -384,7 +163,7 @@ function FindingDraft({
|
|||
<Button
|
||||
variant="outline"
|
||||
disabled={blocked || destinationLoading}
|
||||
onClick={() => setReloadDestination(value => value + 1)}
|
||||
onClick={refreshDestination}
|
||||
>
|
||||
Refresh destination
|
||||
</Button>
|
||||
|
|
@ -514,19 +293,7 @@ function FindingDraft({
|
|||
>
|
||||
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('');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button variant="outline" onClick={startNewRequest}>
|
||||
Start new request
|
||||
</Button>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -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<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[]>(source.initialSelection);
|
||||
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 !== 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,
|
||||
};
|
||||
}
|
||||
|
|
@ -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<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);
|
||||
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<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 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,
|
||||
};
|
||||
}
|
||||
|
|
@ -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 } : {}),
|
||||
}));
|
||||
}
|
||||
|
|
@ -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<ArtifactInput['evidence']>[number];
|
||||
export interface FindingMetricChoice {
|
||||
|
|
@ -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';
|
||||
|
||||
|
|
|
|||
|
|
@ -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() {
|
||||
|
|
|
|||
|
|
@ -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({
|
||||
|
|
|
|||
|
|
@ -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({
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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<string, string>,
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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).
|
||||
|
||||
|
|
|
|||
|
|
@ -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."
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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<Response>) =>
|
||||
|
|
|
|||
|
|
@ -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'
|
||||
));
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue