feat(research): isolate candidates and add reviewed paper promotion
This commit is contained in:
parent
26b97265c6
commit
25b5cbf481
128 changed files with 13038 additions and 1388 deletions
|
|
@ -550,6 +550,13 @@ export function BacktestDetailPageV2() {
|
|||
>
|
||||
Retry execution eligibility
|
||||
</button>
|
||||
{canonicalCapability?.execution && !isCapabilityLoading && (
|
||||
<span className="block break-all">
|
||||
Isolated candidate sandbox: {canonicalCapability.execution.imageId}. Limit{' '}
|
||||
{canonicalCapability.execution.profile.limits.wallMs / 1000}s per container; agent
|
||||
attempt deadlines may be shorter.
|
||||
</span>
|
||||
)}
|
||||
{backtest?.strategyVersionId && (
|
||||
<>
|
||||
{' '}
|
||||
|
|
|
|||
|
|
@ -68,9 +68,19 @@ export function CanonicalResults({
|
|||
>
|
||||
<h3 className="font-semibold">Canonical research result</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Rust financial simulation · retained TypeScript built-in. Completion does not establish
|
||||
strategy profitability or authorize trading.
|
||||
Rust financial simulation ·{' '}
|
||||
{request.strategy.origin === 'candidate'
|
||||
? 'isolated TypeScript candidate'
|
||||
: 'retained TypeScript built-in'}
|
||||
. Completion does not establish strategy profitability or authorize trading.
|
||||
</p>
|
||||
{request.strategy.origin === 'candidate' && (
|
||||
<p className="text-sm break-all">
|
||||
Sandbox {request.strategy.execution.imageId} · Author-declared warmup{' '}
|
||||
{request.strategy.package.execution?.warmupBars} bars. Candidate code is unverified;
|
||||
retained seeds and inputs support an actual reproduction comparison.
|
||||
</p>
|
||||
)}
|
||||
<dl className="grid gap-3 text-sm sm:grid-cols-2 break-all">
|
||||
<div>
|
||||
<dt>Run</dt>
|
||||
|
|
|
|||
|
|
@ -32,9 +32,10 @@ const policyFields: {
|
|||
{
|
||||
key: 'ownerBudget',
|
||||
label: 'Owner budget',
|
||||
group: 'Capital allocation',
|
||||
group: 'Strategy sizing',
|
||||
kind: 'decimal',
|
||||
description: 'USD allocated to this strategy; it cannot exceed initial capital.',
|
||||
description:
|
||||
'USD sizing input supplied to the strategy. Rust enforces the separate position, exposure and cash constraints. This input cannot exceed initial capital.',
|
||||
},
|
||||
{
|
||||
key: 'feeRate',
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { z } from 'zod';
|
||||
import { candidateExecutionSchema } from '@stock-bot/stock-config/candidate-execution';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
CanonicalDatasetCatalogEntry,
|
||||
|
|
@ -562,7 +563,18 @@ export const backtestApiV2 = {
|
|||
if (!response.ok) {
|
||||
throw await requestError(response, 'Could not check canonical execution eligibility');
|
||||
}
|
||||
return response.json();
|
||||
const capability = z
|
||||
.object({
|
||||
available: z.boolean(),
|
||||
reason: z.string().nullable(),
|
||||
execution: candidateExecutionSchema.optional(),
|
||||
})
|
||||
.strict()
|
||||
.parse(await response.json());
|
||||
if (capability.execution && !capability.available) {
|
||||
throw new Error('Unavailable execution cannot advertise an admitted sandbox profile');
|
||||
}
|
||||
return capability;
|
||||
},
|
||||
async listCanonicalDatasets(signal?: AbortSignal): Promise<CanonicalDatasetCatalogEntry[]> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/datasets/canonical?limit=50&offset=0`, {
|
||||
|
|
|
|||
|
|
@ -348,6 +348,7 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
experimentId={experiment.id}
|
||||
backtestId={experiment.backtestId}
|
||||
previewHash={experiment.previewHash}
|
||||
strategyOrigin={experiment.preview.request.strategy.origin}
|
||||
experimentCancelled={experiment.cancelRequested}
|
||||
trial={trial}
|
||||
disabled={mutating || loading}
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ export function ChronologicalValidationPreflight({
|
|||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
candidate,
|
||||
disabled,
|
||||
eligible,
|
||||
onDirty,
|
||||
|
|
@ -44,6 +45,7 @@ export function ChronologicalValidationPreflight({
|
|||
backtestId: string;
|
||||
name: string;
|
||||
grid: string;
|
||||
candidate?: ChronologicalValidationSubmission['candidate'];
|
||||
disabled: boolean;
|
||||
eligible: boolean;
|
||||
onDirty: (dirty: boolean) => void;
|
||||
|
|
@ -72,7 +74,15 @@ export function ChronologicalValidationPreflight({
|
|||
const request = useRef<AbortController | null>(null);
|
||||
const pending = useRef(false);
|
||||
const alive = useRef(false);
|
||||
const identity = JSON.stringify({ backtestId, name, grid, windows, disabled, eligible });
|
||||
const identity = JSON.stringify({
|
||||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
candidate,
|
||||
windows,
|
||||
disabled,
|
||||
eligible,
|
||||
});
|
||||
const currentIdentity = useRef(identity);
|
||||
currentIdentity.current = identity;
|
||||
const preview =
|
||||
|
|
@ -123,6 +133,7 @@ export function ChronologicalValidationPreflight({
|
|||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
...(candidate ? { candidate } : {}),
|
||||
recipe: parseValidationWindows(windows),
|
||||
});
|
||||
const value = await chronologicalValidationApi.preview(input, controller.signal);
|
||||
|
|
@ -325,7 +336,9 @@ export function ChronologicalValidationPreflight({
|
|||
</p>
|
||||
<p>
|
||||
Input checks only. Warmup sufficiency is not evidence of profitability or statistical
|
||||
adequacy. Only deterministic, unfitted strategies with zero label horizon are supported.
|
||||
adequacy. Built-in strategies use the declared unfitted model. Candidate warmup is
|
||||
author-declared and candidate behavior is unverified; fitting and nonzero label horizons
|
||||
have no supported validation contract.
|
||||
</p>
|
||||
<div className="grid gap-3 lg:grid-cols-3">
|
||||
{preview.partitions.map(part => (
|
||||
|
|
|
|||
|
|
@ -13,6 +13,10 @@ import {
|
|||
} from '@stock-bot/stock-config/experiments';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { backtestApiV2, type Backtest } from '@/features/backtest/services/backtestApiV2';
|
||||
import {
|
||||
StrategySelection,
|
||||
type CatalogSelection,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
|
||||
import {
|
||||
experimentApi,
|
||||
|
|
@ -94,6 +98,19 @@ export function ExperimentEditor({
|
|||
const [backtestId, setBacktestId] = useState(initialBacktestId);
|
||||
const [name, setName] = useState('');
|
||||
const [grid, setGrid] = useState('{}');
|
||||
const [useCandidate, setUseCandidate] = useState(false);
|
||||
const [candidateSelection, setCandidateSelection] = useState<CatalogSelection>({});
|
||||
const [candidateValid, setCandidateValid] = useState(false);
|
||||
const candidateRevision = useRef(0);
|
||||
const candidateValidity = useRef(false);
|
||||
const renderedCandidateRevision = candidateRevision.current;
|
||||
const candidate =
|
||||
useCandidate && candidateSelection.strategyVersionId
|
||||
? {
|
||||
versionId: candidateSelection.strategyVersionId,
|
||||
parameters: candidateSelection.strategyParameters ?? {},
|
||||
}
|
||||
: undefined;
|
||||
const [backtests, setBacktests] = useState<Backtest[]>([]);
|
||||
const [templateLoading, setTemplateLoading] = useState(true);
|
||||
const [templateError, setTemplateError] = useState('');
|
||||
|
|
@ -113,6 +130,7 @@ export function ExperimentEditor({
|
|||
walkForwardDirty ||
|
||||
Boolean(
|
||||
name ||
|
||||
useCandidate ||
|
||||
grid !== '{}' ||
|
||||
backtestId !== initialBacktestId ||
|
||||
mode !== 'parameters' ||
|
||||
|
|
@ -179,7 +197,12 @@ export function ExperimentEditor({
|
|||
change();
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (submissionOwner.current || previewLoading) {
|
||||
if (
|
||||
submissionOwner.current ||
|
||||
previewLoading ||
|
||||
candidateRevision.current !== renderedCandidateRevision ||
|
||||
(useCandidate && !candidateValid)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const current = ++generation.current;
|
||||
|
|
@ -194,11 +217,21 @@ export function ExperimentEditor({
|
|||
const value =
|
||||
modeRef.current === 'cost-sensitivity'
|
||||
? await experimentApi.costPreview(
|
||||
costSensitivityInputSchema.parse({ backtestId, name, scenarios }),
|
||||
costSensitivityInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
scenarios,
|
||||
...(candidate ? { candidate } : {}),
|
||||
}),
|
||||
controller.signal
|
||||
)
|
||||
: await experimentApi.preview(
|
||||
experimentInputSchema.parse({ backtestId, name, grid: JSON.parse(grid) }),
|
||||
experimentInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
...(candidate ? { candidate } : {}),
|
||||
}),
|
||||
controller.signal
|
||||
);
|
||||
if (alive.current && current === generation.current) {
|
||||
|
|
@ -356,6 +389,49 @@ export function ExperimentEditor({
|
|||
Load more backtests
|
||||
</Button>
|
||||
)}
|
||||
<label className="block text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={useCandidate}
|
||||
disabled={Boolean(lockedBy)}
|
||||
onChange={event => {
|
||||
if (submissionOwner.current) {
|
||||
return;
|
||||
}
|
||||
candidateRevision.current++;
|
||||
invalidate(() => setUseCandidate(event.target.checked));
|
||||
}}
|
||||
/>{' '}
|
||||
Use an isolated candidate version
|
||||
</label>
|
||||
{useCandidate && (
|
||||
<section aria-label="Candidate experiment strategy" className="space-y-2">
|
||||
<p className="text-sm">
|
||||
Select an immutable candidate and validate its base parameters. The saved backtest
|
||||
supplies the dataset, capital and financial policy. Preview checks candidate
|
||||
eligibility.
|
||||
</p>
|
||||
<StrategySelection
|
||||
value={candidateSelection}
|
||||
onChange={value => {
|
||||
if (submissionOwner.current) {
|
||||
return;
|
||||
}
|
||||
candidateRevision.current++;
|
||||
invalidate(() => setCandidateSelection(value));
|
||||
}}
|
||||
onValidityChange={valid => {
|
||||
if (submissionOwner.current || valid === candidateValidity.current) {
|
||||
return;
|
||||
}
|
||||
candidateValidity.current = valid;
|
||||
candidateRevision.current++;
|
||||
invalidate(() => setCandidateValid(valid));
|
||||
}}
|
||||
disabled={Boolean(lockedBy)}
|
||||
/>
|
||||
</section>
|
||||
)}
|
||||
<label className="block text-sm">
|
||||
Experiment type
|
||||
<select
|
||||
|
|
@ -469,6 +545,7 @@ export function ExperimentEditor({
|
|||
disabled={
|
||||
Boolean(lockedBy) ||
|
||||
previewLoading ||
|
||||
(useCandidate && !candidateValid) ||
|
||||
!backtests.some(item => item.id === backtestId) ||
|
||||
!name.trim()
|
||||
}
|
||||
|
|
@ -514,8 +591,13 @@ export function ExperimentEditor({
|
|||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
candidate={candidate}
|
||||
disabled={mode !== 'parameters' || (lockedBy !== null && lockedBy !== 'chronological')}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
eligible={
|
||||
!templateLoading &&
|
||||
(!useCandidate || candidateValid) &&
|
||||
backtests.some(item => item.id === backtestId)
|
||||
}
|
||||
onDirty={setValidationDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
|
|
@ -524,8 +606,13 @@ export function ExperimentEditor({
|
|||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
candidate={candidate}
|
||||
disabled={mode !== 'parameters' || (lockedBy !== null && lockedBy !== 'walk-forward')}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
eligible={
|
||||
!templateLoading &&
|
||||
(!useCandidate || candidateValid) &&
|
||||
backtests.some(item => item.id === backtestId)
|
||||
}
|
||||
onDirty={setWalkForwardDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ export function ExperimentInputs({ preview }: { preview: WorkbenchExperimentPrev
|
|||
<dd>{new Date(dataset.bounds.warmupStart).toISOString()}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Initial capital / owner budget (USD)</dt>
|
||||
<dt>Initial capital / strategy sizing budget (USD)</dt>
|
||||
<dd>
|
||||
{request.policy.matching.risk.ledger.initialCapital} /{' '}
|
||||
{request.strategy.selection.ownerBudget}
|
||||
|
|
@ -50,6 +50,27 @@ export function ExperimentInputs({ preview }: { preview: WorkbenchExperimentPrev
|
|||
<dd>{request.strategy.selection.seed}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{request.strategy.origin === 'candidate' && (
|
||||
<section aria-label="Isolated candidate execution" className="space-y-1 break-all">
|
||||
<p>
|
||||
Isolated TypeScript candidate ·{' '}
|
||||
{request.strategy.reviewId
|
||||
? `Review ${request.strategy.reviewId}`
|
||||
: 'Unreviewed research candidate'}
|
||||
</p>
|
||||
<p>
|
||||
Author-declared warmup: {request.strategy.package.execution?.warmupBars} bars. Arbitrary
|
||||
code may ignore the seeded RNG; reproduction compares actual economic results.
|
||||
</p>
|
||||
<p>Sandbox image: {request.strategy.execution.imageId}</p>
|
||||
<p>
|
||||
Limits: {request.strategy.execution.profile.limits.memoryBytes / 1048576} MiB memory,{' '}
|
||||
{request.strategy.execution.profile.limits.cpuQuota} CPU,{' '}
|
||||
{request.strategy.execution.profile.limits.wallMs / 1000} seconds per container; an
|
||||
agent attempt deadline may be shorter.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
<p>
|
||||
{costs
|
||||
? 'Template cost diagnostics only. Strategy parameters, dataset, seed, capital, half-spread and risk limits remain fixed; each fee/slippage scenario executes independently. No strategy selection or ranking is performed.'
|
||||
|
|
@ -97,6 +118,13 @@ export function ExperimentInputs({ preview }: { preview: WorkbenchExperimentPrev
|
|||
strategy: {
|
||||
versionId: request.strategy.versionId,
|
||||
reviewId: request.strategy.reviewId,
|
||||
origin: request.strategy.origin,
|
||||
...(request.strategy.origin === 'candidate'
|
||||
? {
|
||||
execution: request.strategy.execution,
|
||||
declaredWarmup: request.strategy.package.execution?.warmupBars,
|
||||
}
|
||||
: {}),
|
||||
selection: request.strategy.selection,
|
||||
artifactHash: request.strategy.package.artifact.sha256,
|
||||
dependencyLockHash: request.strategy.package.dependencyLock.sha256,
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ interface Props {
|
|||
experimentId: string;
|
||||
backtestId: string;
|
||||
previewHash: string;
|
||||
strategyOrigin?: 'builtin' | 'candidate';
|
||||
experimentCancelled: boolean;
|
||||
trial: ExperimentTrial;
|
||||
disabled: boolean;
|
||||
|
|
@ -39,6 +40,7 @@ export function ExperimentTrialRecovery({
|
|||
experimentId,
|
||||
backtestId,
|
||||
previewHash,
|
||||
strategyOrigin = 'builtin',
|
||||
experimentCancelled,
|
||||
trial,
|
||||
disabled,
|
||||
|
|
@ -92,7 +94,7 @@ export function ExperimentTrialRecovery({
|
|||
setHistoryLoading(true);
|
||||
setHistoryError('');
|
||||
void experimentApi
|
||||
.retryHistory(experimentId, trial.runId, trial.trialKey, controller.signal)
|
||||
.retryHistory(experimentId, trial.runId, trial.trialKey, controller.signal, strategyOrigin)
|
||||
.then(value => {
|
||||
if (current) {
|
||||
setHistory(value);
|
||||
|
|
@ -112,7 +114,15 @@ export function ExperimentTrialRecovery({
|
|||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [experimentId, trial.runId, trial.trialKey, trial.retryCount, historyOpen, historyReload]);
|
||||
}, [
|
||||
experimentId,
|
||||
trial.runId,
|
||||
trial.trialKey,
|
||||
trial.retryCount,
|
||||
historyOpen,
|
||||
historyReload,
|
||||
strategyOrigin,
|
||||
]);
|
||||
const review = () => {
|
||||
if (disabled || !freshAllowed || !trial.runId || intentRef.current) {
|
||||
return;
|
||||
|
|
@ -323,7 +333,7 @@ export function ExperimentTrialRecovery({
|
|||
</div>
|
||||
<div>
|
||||
<dt>Approval at retry admission</dt>
|
||||
<dd>{item.reviewId}</dd>
|
||||
<dd>{item.reviewId ?? 'Unreviewed isolated candidate'}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ export function WalkForwardPreflight({
|
|||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
candidate,
|
||||
disabled,
|
||||
eligible,
|
||||
onDirty,
|
||||
|
|
@ -42,6 +43,7 @@ export function WalkForwardPreflight({
|
|||
backtestId: string;
|
||||
name: string;
|
||||
grid: string;
|
||||
candidate?: WalkForwardSubmission['candidate'];
|
||||
disabled: boolean;
|
||||
eligible: boolean;
|
||||
onDirty: (value: boolean) => void;
|
||||
|
|
@ -72,7 +74,15 @@ export function WalkForwardPreflight({
|
|||
posting = useRef(false),
|
||||
generation = useRef(0),
|
||||
read = useRef<AbortController | null>(null);
|
||||
const identity = JSON.stringify({ backtestId, name, grid, windows, disabled, eligible }),
|
||||
const identity = JSON.stringify({
|
||||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
candidate,
|
||||
windows,
|
||||
disabled,
|
||||
eligible,
|
||||
}),
|
||||
currentIdentity = useRef(identity);
|
||||
currentIdentity.current = identity;
|
||||
const preview =
|
||||
|
|
@ -125,6 +135,7 @@ export function WalkForwardPreflight({
|
|||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
...(candidate ? { candidate } : {}),
|
||||
windows: windows.map((window, index) =>
|
||||
parseValidationWindows(window, `Window ${index + 1} `)
|
||||
),
|
||||
|
|
|
|||
|
|
@ -1,131 +1,18 @@
|
|||
import { z } from 'zod';
|
||||
import { type ChronologicalValidationInput } from '@stock-bot/stock-config/chronological-validation';
|
||||
import {
|
||||
chronologicalValidationInputSchema,
|
||||
chronologicalValidationPolicy,
|
||||
type ChronologicalValidationInput,
|
||||
type ChronologicalValidationPreview,
|
||||
type ValidationPartitionPreview,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
invalidValidationPreview as invalid,
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import { parseExperimentPreview, type ExperimentPreviewView } from './experimentApi';
|
||||
|
||||
export type ValidationPartitionView = Omit<ValidationPartitionPreview, 'dataset'> & {
|
||||
dataset: ExperimentPreviewView['dataset'];
|
||||
};
|
||||
export type ChronologicalValidationPreviewView = Omit<
|
||||
ChronologicalValidationPreview,
|
||||
'source' | 'partitions'
|
||||
> & {
|
||||
source: ExperimentPreviewView;
|
||||
partitions: [ValidationPartitionView, ValidationPartitionView, ValidationPartitionView];
|
||||
};
|
||||
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const counts = z.object({
|
||||
totalBars: counter,
|
||||
availableWarmup: counter,
|
||||
admittedWarmup: counter,
|
||||
ignoredLateWarmup: counter,
|
||||
availableEvaluation: counter,
|
||||
terminalAtEnd: counter,
|
||||
unavailableAtEnd: counter,
|
||||
});
|
||||
const partition = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
dataset: z.unknown(),
|
||||
request: z.unknown(),
|
||||
counts,
|
||||
requiredWarmup: counter.positive(),
|
||||
warnings: z.array(z.string()),
|
||||
});
|
||||
const prepared = z.object({
|
||||
version: z.literal('chronological-validation-preview/v1'),
|
||||
execution: z.literal('preview-only'),
|
||||
previewHash: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
input: chronologicalValidationInputSchema,
|
||||
source: z.unknown(),
|
||||
policy: z.unknown(),
|
||||
partitions: z.tuple([partition, partition, partition]),
|
||||
});
|
||||
const same = (left: unknown, right: unknown) =>
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const invalid = () =>
|
||||
new Error(
|
||||
'The chronological validation preview could not be verified. Preview the current inputs again.'
|
||||
);
|
||||
export {
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
type ValidationPartitionView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
|
||||
export function parseChronologicalValidationPreview(
|
||||
body: unknown,
|
||||
input: ChronologicalValidationInput
|
||||
): ChronologicalValidationPreviewView {
|
||||
const value = prepared.parse(z.object({ preview: z.unknown() }).parse(body).preview);
|
||||
const source = parseExperimentPreview(value.source);
|
||||
const { recipe: _recipe, ...sourceInput } = input;
|
||||
if (
|
||||
!same(value.input, input) ||
|
||||
!same(source.input, sourceInput) ||
|
||||
!same(value.policy, chronologicalValidationPolicy)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const phases = ['train', 'validation', 'test'] as const;
|
||||
const partitions = value.partitions.map((part, index): ValidationPartitionView => {
|
||||
const phase = phases[index];
|
||||
if (!phase || part.phase !== phase) {
|
||||
throw invalid();
|
||||
}
|
||||
const decoded = parseExperimentPreview({
|
||||
...source,
|
||||
dataset: part.dataset,
|
||||
request: part.request,
|
||||
});
|
||||
const { request, dataset } = decoded;
|
||||
const expected = {
|
||||
...source.request,
|
||||
datasetHash: dataset.hash,
|
||||
policy: {
|
||||
...source.request.policy,
|
||||
risk_boundaries: request.policy.risk_boundaries,
|
||||
matching: {
|
||||
...source.request.policy.matching,
|
||||
risk: {
|
||||
...source.request.policy.matching.risk,
|
||||
ledger: {
|
||||
...source.request.policy.matching.risk.ledger,
|
||||
riskSession: request.policy.matching.risk.ledger.riskSession,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
const measured = part.counts;
|
||||
const metadata = (manifest: ExperimentPreviewView['dataset']) => {
|
||||
const { hash: _hash, bounds: _bounds, barCount: _barCount, ...retained } = manifest;
|
||||
return retained;
|
||||
};
|
||||
if (
|
||||
!same(request, expected) ||
|
||||
!same(dataset.bounds, input.recipe[phase]) ||
|
||||
!same(metadata(dataset), metadata(source.dataset)) ||
|
||||
measured.totalBars !== dataset.barCount ||
|
||||
dataset.bounds.warmupStart < source.dataset.bounds.warmupStart ||
|
||||
dataset.bounds.tradeStart < source.dataset.bounds.tradeStart ||
|
||||
dataset.bounds.tradeEnd > source.dataset.bounds.tradeEnd ||
|
||||
measured.totalBars !==
|
||||
measured.availableWarmup +
|
||||
measured.availableEvaluation +
|
||||
measured.terminalAtEnd +
|
||||
measured.unavailableAtEnd ||
|
||||
measured.availableWarmup !== measured.admittedWarmup + measured.ignoredLateWarmup ||
|
||||
measured.admittedWarmup < part.requiredWarmup ||
|
||||
measured.availableEvaluation === 0
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...part, phase, request, dataset };
|
||||
}) as [ValidationPartitionView, ValidationPartitionView, ValidationPartitionView];
|
||||
return { ...value, source, policy: chronologicalValidationPolicy, partitions };
|
||||
}
|
||||
export const chronologicalValidationApi = {
|
||||
async preview(
|
||||
input: ChronologicalValidationInput,
|
||||
|
|
|
|||
|
|
@ -1,276 +1,30 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
chronologicalValidationInputSchema,
|
||||
type ChronologicalValidationActionReceipt,
|
||||
type ChronologicalValidationDetail,
|
||||
type ChronologicalValidationFinalizationInput,
|
||||
type ChronologicalValidationSelectionInput,
|
||||
type ChronologicalValidationSubmission,
|
||||
type ChronologicalValidationSummary,
|
||||
type ValidationResultEvidence,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import { researchActorSchema } from '@stock-bot/stock-config/research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
invalidValidationResponse as invalid,
|
||||
parseValidationDetail,
|
||||
validationReceiptSchema as receipt,
|
||||
sameValidationInput as same,
|
||||
validationSummarySchema as summary,
|
||||
ValidationApiError,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import {
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from './chronologicalValidationApi';
|
||||
import {
|
||||
experimentMetricsSchema,
|
||||
parseExperimentDetail,
|
||||
type ExperimentDetailView,
|
||||
} from './experimentApi';
|
||||
|
||||
export type ValidationDetailView = Omit<ChronologicalValidationDetail, 'preview' | 'phases'> & {
|
||||
preview: ChronologicalValidationPreviewView;
|
||||
phases: Array<{
|
||||
phase: 'train' | 'validation' | 'test';
|
||||
status: 'not-admitted' | 'admitted' | 'missing';
|
||||
experimentId: string | null;
|
||||
experiment: ExperimentDetailView | null;
|
||||
}>;
|
||||
};
|
||||
export class ValidationApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
||||
uuid = z.string().uuid(),
|
||||
count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const candidate = z.object({
|
||||
index: count,
|
||||
trialKey: hash,
|
||||
parameters: z.record(z.union([z.string(), z.number().finite(), z.boolean()])),
|
||||
});
|
||||
const actor = researchActorSchema;
|
||||
const summary = z.object({
|
||||
id: uuid,
|
||||
name: z.string().min(1),
|
||||
backtestId: uuid,
|
||||
createdAt: z.string().min(1),
|
||||
cancelRequested: z.boolean(),
|
||||
previewHash: hash,
|
||||
trainingCandidateCount: count.min(1).max(100),
|
||||
stage: z.enum(['training', 'holdouts', 'reported']),
|
||||
});
|
||||
export const validationEvidenceSchema = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
experimentId: uuid,
|
||||
runId: uuid,
|
||||
sourceCandidateIndex: count,
|
||||
trialKey: hash,
|
||||
parameters: candidate.shape.parameters,
|
||||
datasetHash: hash,
|
||||
requestHash: hash,
|
||||
economicHash: hash,
|
||||
metrics: experimentMetricsSchema,
|
||||
unavailable: z.record(z.string()),
|
||||
completePeriodCount: count,
|
||||
periodicSampleCount: count,
|
||||
fillCount: count,
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const selection = z.object({
|
||||
version: z.literal('chronological-validation-selection/v1'),
|
||||
id: uuid,
|
||||
validationId: uuid,
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
reviewId: uuid,
|
||||
winner: candidate,
|
||||
training: z.array(validationEvidenceSchema).min(1).max(100),
|
||||
holdoutExperimentIds: z.object({ validation: uuid, test: uuid }),
|
||||
});
|
||||
const report = z.object({
|
||||
version: z.literal('chronological-validation-report/v1'),
|
||||
id: uuid,
|
||||
validationId: uuid,
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
reportHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
reset: z.literal('initial-capital-empty-positions'),
|
||||
training: z.array(validationEvidenceSchema).min(1).max(100),
|
||||
validation: validationEvidenceSchema,
|
||||
test: validationEvidenceSchema,
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const capability = z.object({ available: z.boolean(), reason: z.string().nullable() });
|
||||
const phase = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
status: z.enum(['not-admitted', 'admitted', 'missing']),
|
||||
experimentId: uuid.nullable(),
|
||||
experiment: z.unknown(),
|
||||
});
|
||||
const detail = summary.extend({
|
||||
preview: z.unknown(),
|
||||
phases: z.tuple([phase, phase, phase]),
|
||||
selection: selection.nullable(),
|
||||
report: report.nullable(),
|
||||
actions: z.object({ select: capability, finalize: capability }),
|
||||
});
|
||||
const receipt = z.object({
|
||||
id: uuid,
|
||||
validationId: uuid,
|
||||
operation: z.enum(['select-and-admit-holdouts', 'finalize-report']),
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
});
|
||||
const same = (a: unknown, b: unknown) => canonicalStrategyJson(a) === canonicalStrategyJson(b);
|
||||
const invalid = () =>
|
||||
new ValidationApiError(
|
||||
'The saved validation response could not be verified. Refresh or retry the same request.',
|
||||
null
|
||||
);
|
||||
export function parseValidationDetail(raw: unknown): ValidationDetailView {
|
||||
const value = detail.parse(raw);
|
||||
const rawPreview = z.object({ input: chronologicalValidationInputSchema }).parse(value.preview);
|
||||
const preview = parseChronologicalValidationPreview({ preview: value.preview }, rawPreview.input);
|
||||
if (
|
||||
value.backtestId !== preview.input.backtestId ||
|
||||
value.name !== preview.input.name ||
|
||||
value.previewHash !== preview.previewHash ||
|
||||
value.trainingCandidateCount !== preview.source.candidates.length ||
|
||||
(value.stage === 'training') !== (value.selection === null) ||
|
||||
(value.stage === 'reported') !== (value.report !== null)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const phases = value.phases.map((item, index) => {
|
||||
const name = (['train', 'validation', 'test'] as const)[index];
|
||||
if (item.phase !== name || (item.status === 'admitted') !== (item.experiment !== null)) {
|
||||
throw invalid();
|
||||
}
|
||||
const expectedId =
|
||||
name === 'train'
|
||||
? value.id
|
||||
: (value.selection?.holdoutExperimentIds[name ?? 'validation'] ?? null);
|
||||
if (
|
||||
item.experimentId !== expectedId ||
|
||||
(item.status === 'not-admitted') !== (expectedId === null)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const experiment = item.experiment === null ? null : parseExperimentDetail(item.experiment);
|
||||
if (experiment) {
|
||||
const prototype = preview.partitions[index];
|
||||
const parameters =
|
||||
name === 'train'
|
||||
? prototype?.request.strategy.selection.parameters
|
||||
: value.selection?.winner.parameters;
|
||||
if (!prototype || !parameters) {
|
||||
throw invalid();
|
||||
}
|
||||
const expectedRequest = {
|
||||
...prototype.request,
|
||||
strategy: {
|
||||
...prototype.request.strategy,
|
||||
reviewId:
|
||||
name === 'train' ? prototype.request.strategy.reviewId : value.selection?.reviewId,
|
||||
selection: { ...prototype.request.strategy.selection, parameters },
|
||||
},
|
||||
};
|
||||
const expectedCandidates =
|
||||
name === 'train' ? preview.source.candidates : [{ ...value.selection?.winner, index: 0 }];
|
||||
if (
|
||||
experiment.id !== expectedId ||
|
||||
experiment.backtestId !== value.backtestId ||
|
||||
!same(experiment.preview.request, expectedRequest) ||
|
||||
!same(experiment.preview.dataset, prototype.dataset) ||
|
||||
!same(experiment.preview.candidates, expectedCandidates) ||
|
||||
!same(experiment.preview.input.grid, name === 'train' ? preview.input.grid : {})
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
return { ...item, experiment };
|
||||
});
|
||||
const validateEvidence = (
|
||||
item: z.infer<typeof validationEvidenceSchema>,
|
||||
expectedPhase: 'train' | 'validation' | 'test'
|
||||
) => {
|
||||
const index = ['train', 'validation', 'test'].indexOf(expectedPhase);
|
||||
const candidateValue = preview.source.candidates[item.sourceCandidateIndex];
|
||||
const phaseValue = phases[index];
|
||||
const trial = phaseValue?.experiment?.trials.find(
|
||||
trial => trial.runId === item.runId && trial.trialKey === item.trialKey
|
||||
);
|
||||
if (
|
||||
!candidateValue ||
|
||||
!phaseValue ||
|
||||
item.phase !== expectedPhase ||
|
||||
item.experimentId !== phaseValue.experimentId ||
|
||||
item.trialKey !== candidateValue.trialKey ||
|
||||
!same(item.parameters, candidateValue.parameters) ||
|
||||
item.datasetHash !== preview.partitions[index]?.dataset.hash ||
|
||||
(expectedPhase !== 'train' && item.sourceCandidateIndex !== value.selection?.winner.index) ||
|
||||
(phaseValue.experiment &&
|
||||
(!trial ||
|
||||
trial.status !== 'completed' ||
|
||||
!trial.comparable ||
|
||||
!same(trial.metrics, item.metrics) ||
|
||||
!same(trial.unavailable, item.unavailable) ||
|
||||
!same(trial.limitations, item.limitations)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
};
|
||||
if (value.selection) {
|
||||
const chosen = value.selection;
|
||||
if (
|
||||
chosen.validationId !== value.id ||
|
||||
chosen.previewHash !== value.previewHash ||
|
||||
!same(chosen.winner, preview.source.candidates[chosen.winner.index]) ||
|
||||
chosen.training.length !== value.trainingCandidateCount ||
|
||||
chosen.training.some((item, index) => item.sourceCandidateIndex !== index) ||
|
||||
new Set([value.id, chosen.holdoutExperimentIds.validation, chosen.holdoutExperimentIds.test])
|
||||
.size !== 3
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
for (const item of chosen.training) {
|
||||
validateEvidence(item, 'train');
|
||||
if (item.metrics.totalReturn === null) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (value.report) {
|
||||
const saved = value.report;
|
||||
if (
|
||||
!value.selection ||
|
||||
saved.validationId !== value.id ||
|
||||
saved.previewHash !== value.previewHash ||
|
||||
saved.selectionHash !== value.selection.selectionHash ||
|
||||
!same(saved.training, value.selection.training)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
validateEvidence(saved.validation, 'validation');
|
||||
validateEvidence(saved.test, 'test');
|
||||
}
|
||||
if (
|
||||
(value.actions.select.available && (value.selection || value.cancelRequested)) ||
|
||||
(value.actions.finalize.available &&
|
||||
(!value.selection || value.report || value.cancelRequested))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...value, preview, phases } as ValidationDetailView;
|
||||
}
|
||||
export {
|
||||
parseValidationDetail,
|
||||
ValidationApiError,
|
||||
validationEvidenceSchema,
|
||||
type ValidationDetailView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
export type { ValidationResultEvidence };
|
||||
|
||||
const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key];
|
||||
async function request<T>(
|
||||
path: string,
|
||||
|
|
@ -386,4 +140,3 @@ export const chronologicalValidationDurableApi = {
|
|||
return value;
|
||||
}),
|
||||
};
|
||||
export type { ValidationResultEvidence };
|
||||
|
|
|
|||
|
|
@ -1,341 +1,46 @@
|
|||
import { z } from 'zod';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
costScenarioSchema,
|
||||
costSensitivityInputSchema,
|
||||
type CostSensitivityDetail,
|
||||
type CostSensitivityInput,
|
||||
type CostSensitivityPreview,
|
||||
type CostSensitivitySubmission,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
experimentRetrySchema,
|
||||
MAX_EXPERIMENT_TRIALS,
|
||||
type ExperimentDetail,
|
||||
type ExperimentInput,
|
||||
type ExperimentPreview,
|
||||
type ExperimentRetryInput,
|
||||
type ExperimentSubmission,
|
||||
type ExperimentSummary,
|
||||
type ExperimentTrialRetry,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import { researchActorSchema } from '@stock-bot/stock-config/research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
ExperimentApiError,
|
||||
invalidExperimentResponse as invalid,
|
||||
parseCostSensitivityPreview,
|
||||
parseExperimentDetail,
|
||||
parseExperimentPreview,
|
||||
parseExperimentSummary as parseSummary,
|
||||
parseWorkbenchExperimentDetail,
|
||||
experimentRetryReceiptSchema as retryReceipt,
|
||||
sameExperimentInput as same,
|
||||
type ExperimentRetryTarget,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
|
||||
export class ExperimentApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/);
|
||||
const count = z.number().int().nonnegative().max(MAX_EXPERIMENT_TRIALS);
|
||||
const counter = z.number().int().nonnegative().max(2147483647);
|
||||
const scalar = z.union([z.string(), z.number().finite(), z.boolean()]);
|
||||
const candidate = z
|
||||
.object({
|
||||
index: count,
|
||||
trialKey: hash,
|
||||
parameters: z.record(scalar),
|
||||
})
|
||||
.strict();
|
||||
const statuses = ['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'] as const;
|
||||
const counts = z.object({
|
||||
pending: count,
|
||||
running: count,
|
||||
paused: count,
|
||||
completed: count,
|
||||
failed: count,
|
||||
cancelled: count,
|
||||
});
|
||||
const summary = z.object({
|
||||
kind: z.enum(['parameters', 'cost-sensitivity']).optional(),
|
||||
id: z.string().uuid(),
|
||||
name: z.string().min(1),
|
||||
backtestId: z.string().uuid(),
|
||||
createdAt: z.string().min(1),
|
||||
cancelRequested: z.boolean(),
|
||||
trialCount: count.min(1),
|
||||
counts,
|
||||
datasetHash: hash,
|
||||
strategyVersionId: z.string().uuid(),
|
||||
previewHash: hash,
|
||||
});
|
||||
const timestamp = z.number().int().min(-8640000000000000).max(8640000000000000);
|
||||
const dataset = z
|
||||
.object({
|
||||
version: z.literal(2),
|
||||
hash,
|
||||
bounds: z.object({
|
||||
warmupStart: timestamp,
|
||||
tradeStart: timestamp,
|
||||
tradeEnd: timestamp,
|
||||
}),
|
||||
series: z.array(
|
||||
z.object({ id: z.string(), instrumentId: z.string(), interval: z.string() }).passthrough()
|
||||
),
|
||||
})
|
||||
.passthrough();
|
||||
/** Only the manifest fields consumed by this UI are structurally decoded here. */
|
||||
export type ExperimentPreviewView = Omit<ExperimentPreview, 'dataset'> & {
|
||||
dataset: z.infer<typeof dataset>;
|
||||
};
|
||||
export type ExperimentDetailView = Omit<ExperimentDetail, 'preview'> & {
|
||||
preview: ExperimentPreviewView;
|
||||
};
|
||||
export type CostSensitivityPreviewView = Omit<CostSensitivityPreview, 'dataset' | 'source'> & {
|
||||
dataset: ExperimentPreviewView['dataset'];
|
||||
source: ExperimentPreviewView;
|
||||
};
|
||||
export type WorkbenchExperimentPreviewView = ExperimentPreviewView | CostSensitivityPreviewView;
|
||||
export type CostSensitivityDetailView = Omit<CostSensitivityDetail, 'preview'> & {
|
||||
preview: CostSensitivityPreviewView;
|
||||
};
|
||||
export type WorkbenchExperimentDetailView = ExperimentDetailView | CostSensitivityDetailView;
|
||||
const preview = z
|
||||
.object({
|
||||
version: z.literal('research-experiment-preview/v1'),
|
||||
previewHash: hash,
|
||||
input: experimentInputSchema,
|
||||
request: canonicalRunRequestSchema,
|
||||
dataset,
|
||||
candidates: z.array(candidate).min(1).max(MAX_EXPERIMENT_TRIALS),
|
||||
})
|
||||
.strict();
|
||||
const metric = z.number().finite().nullable();
|
||||
export const experimentMetricsSchema = z.object({
|
||||
totalReturn: metric,
|
||||
cagr: metric,
|
||||
maxDrawdown: metric,
|
||||
exposureTime: metric,
|
||||
volatility: metric,
|
||||
downsideDeviation: metric,
|
||||
sharpeRatio: metric,
|
||||
sortinoRatio: metric,
|
||||
var95: metric,
|
||||
cvar95: metric,
|
||||
var99: metric,
|
||||
alpha: z.null(),
|
||||
beta: z.null(),
|
||||
informationRatio: z.null(),
|
||||
roundTripCount: z.null(),
|
||||
winRate: z.null(),
|
||||
profitFactor: z.null(),
|
||||
avgWin: z.null(),
|
||||
avgLoss: z.null(),
|
||||
});
|
||||
const trial = candidate.extend({
|
||||
runId: z.string().uuid().nullable(),
|
||||
attemptNumber: counter,
|
||||
retryCount: counter,
|
||||
status: z.enum([...statuses, 'missing']),
|
||||
progress: z.number().finite().min(0).max(100),
|
||||
cancelRequested: z.boolean(),
|
||||
error: z.string().nullable(),
|
||||
comparable: z.boolean(),
|
||||
diagnostic: z.string().nullable(),
|
||||
metrics: experimentMetricsSchema.nullable(),
|
||||
unavailable: z.record(z.string()).nullable(),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const detail = summary.extend({
|
||||
standalone: z.boolean().optional(),
|
||||
preview,
|
||||
trials: z.array(trial).max(MAX_EXPERIMENT_TRIALS),
|
||||
});
|
||||
const retryReceipt = z.object({
|
||||
id: z.string().uuid(),
|
||||
experimentId: z.string().uuid(),
|
||||
runId: z.string().uuid(),
|
||||
trialKey: hash,
|
||||
retryNumber: counter.min(1),
|
||||
previousAttemptNumber: counter,
|
||||
previousAttemptId: z.string().uuid().nullable(),
|
||||
error: z.string().nullable(),
|
||||
progress: z.number().finite().min(0).max(100),
|
||||
currentDate: z.string().nullable(),
|
||||
startedAt: z.string().nullable(),
|
||||
completedAt: z.string().nullable(),
|
||||
pausedAt: z.string().nullable(),
|
||||
failureUpdatedAt: z.string().min(1),
|
||||
recordedAt: z.string().min(1),
|
||||
principal: researchActorSchema,
|
||||
reviewId: z.string().uuid(),
|
||||
});
|
||||
/** Immutable source identity captured when the operator reviews a failed trial. */
|
||||
export interface ExperimentRetryTarget {
|
||||
experimentId: string;
|
||||
backtestId: string;
|
||||
previewHash: string;
|
||||
runId: string;
|
||||
trialKey: string;
|
||||
}
|
||||
const same = (left: unknown, right: unknown) =>
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const invalid = () =>
|
||||
new ExperimentApiError(
|
||||
'The experiment response could not be verified. Refresh or retry the same submission.',
|
||||
null
|
||||
);
|
||||
export {
|
||||
ExperimentApiError,
|
||||
experimentMetricsSchema,
|
||||
parseCostSensitivityPreview,
|
||||
parseExperimentDetail,
|
||||
parseExperimentPreview,
|
||||
parseWorkbenchExperimentDetail,
|
||||
type CostSensitivityDetailView,
|
||||
type CostSensitivityPreviewView,
|
||||
type ExperimentDetailView,
|
||||
type ExperimentPreviewView,
|
||||
type ExperimentRetryTarget,
|
||||
type WorkbenchExperimentDetailView,
|
||||
type WorkbenchExperimentPreviewView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
|
||||
function parseSummary(value: unknown): ExperimentSummary {
|
||||
const parsed = summary.parse(value);
|
||||
if (Object.values(parsed.counts).reduce((sum, value) => sum + value, 0) > parsed.trialCount) {
|
||||
throw invalid();
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
export function parseExperimentPreview(value: unknown): ExperimentPreviewView {
|
||||
const parsed = preview.parse(value);
|
||||
if (
|
||||
parsed.input.backtestId !== parsed.request.backtestId ||
|
||||
parsed.dataset.hash !== parsed.request.datasetHash ||
|
||||
parsed.dataset.bounds.warmupStart > parsed.dataset.bounds.tradeStart ||
|
||||
parsed.dataset.bounds.tradeStart >= parsed.dataset.bounds.tradeEnd ||
|
||||
!parsed.dataset.series.some(
|
||||
series =>
|
||||
series.id === parsed.request.strategy.selection.seriesId &&
|
||||
series.instrumentId === parsed.request.strategy.selection.instrumentId
|
||||
) ||
|
||||
parsed.candidates.some((item, index) => item.index !== index) ||
|
||||
new Set(parsed.candidates.map(item => item.trialKey)).size !== parsed.candidates.length
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
// The server retains and verifies the complete manifest; the browser only renders its identity/window.
|
||||
return parsed;
|
||||
}
|
||||
const costCandidate = candidate.extend({ costs: costScenarioSchema });
|
||||
const costPreview = preview
|
||||
.omit({ version: true, input: true, candidates: true })
|
||||
.extend({
|
||||
version: z.literal('cost-sensitivity-preview/v1'),
|
||||
input: costSensitivityInputSchema,
|
||||
source: z.unknown(),
|
||||
candidates: z.array(costCandidate).min(2).max(MAX_EXPERIMENT_TRIALS),
|
||||
})
|
||||
.strict();
|
||||
const costDetail = summary.extend({
|
||||
kind: z.literal('cost-sensitivity'),
|
||||
standalone: z.boolean().optional(),
|
||||
preview: z.unknown(),
|
||||
trials: z.array(trial.extend({ costs: costScenarioSchema })).max(MAX_EXPERIMENT_TRIALS),
|
||||
});
|
||||
export function parseCostSensitivityPreview(raw: unknown): CostSensitivityPreviewView {
|
||||
const parsed = costPreview.parse(raw),
|
||||
source = parseExperimentPreview(parsed.source);
|
||||
const costs = [
|
||||
{
|
||||
feeRate: source.request.policy.matching.risk.feeRate,
|
||||
slippageRate: source.request.policy.matching.slippageRate,
|
||||
},
|
||||
...parsed.input.scenarios,
|
||||
];
|
||||
if (
|
||||
!same(source.input, {
|
||||
backtestId: parsed.input.backtestId,
|
||||
name: parsed.input.name,
|
||||
grid: {},
|
||||
}) ||
|
||||
source.candidates.length !== 1 ||
|
||||
!same(source.candidates[0]?.parameters, source.request.strategy.selection.parameters) ||
|
||||
!same(parsed.request, source.request) ||
|
||||
!same(parsed.dataset, source.dataset) ||
|
||||
parsed.candidates.length !== costs.length ||
|
||||
new Set(costs.map(canonicalStrategyJson)).size !== costs.length ||
|
||||
new Set(parsed.candidates.map(item => item.trialKey)).size !== costs.length ||
|
||||
parsed.candidates.some(
|
||||
(item, index) =>
|
||||
item.index !== index ||
|
||||
!same(item.parameters, source.request.strategy.selection.parameters) ||
|
||||
!same(item.costs, costs[index])
|
||||
)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...parsed, source } as CostSensitivityPreviewView;
|
||||
}
|
||||
function checkDetail(
|
||||
parsed: z.infer<typeof detail> | z.infer<typeof costDetail>,
|
||||
retained: WorkbenchExperimentPreviewView
|
||||
) {
|
||||
parseSummary(parsed);
|
||||
if (
|
||||
parsed.backtestId !== retained.input.backtestId ||
|
||||
parsed.name !== retained.input.name ||
|
||||
parsed.previewHash !== retained.previewHash ||
|
||||
parsed.datasetHash !== retained.request.datasetHash ||
|
||||
parsed.strategyVersionId !== retained.request.strategy.versionId ||
|
||||
parsed.trialCount !== retained.candidates.length ||
|
||||
parsed.trials.length !== parsed.trialCount
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const costKind = retained.version === 'cost-sensitivity-preview/v1';
|
||||
if (
|
||||
(costKind && parsed.kind !== 'cost-sensitivity') ||
|
||||
(!costKind && parsed.kind === 'cost-sensitivity')
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const runIds = new Set<string>();
|
||||
for (const [index, item] of parsed.trials.entries()) {
|
||||
const expected = retained.candidates[index];
|
||||
if (
|
||||
!expected ||
|
||||
item.index !== expected.index ||
|
||||
item.trialKey !== expected.trialKey ||
|
||||
!same(item.parameters, expected.parameters) ||
|
||||
(costKind &&
|
||||
(!('costs' in item) || !('costs' in expected) || !same(item.costs, expected.costs))) ||
|
||||
(item.status === 'missing') !== (item.runId === null) ||
|
||||
(item.status === 'missing' && (item.attemptNumber !== 0 || item.retryCount !== 0)) ||
|
||||
(item.comparable && (item.status !== 'completed' || !item.metrics || !item.unavailable)) ||
|
||||
(item.runId !== null && runIds.has(item.runId))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
if (item.runId) {
|
||||
runIds.add(item.runId);
|
||||
}
|
||||
}
|
||||
if (
|
||||
statuses.some(
|
||||
status =>
|
||||
parsed.counts[status] !== parsed.trials.filter(item => item.status === status).length
|
||||
)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
|
||||
return { ...parsed, preview: retained };
|
||||
}
|
||||
export function parseExperimentDetail(value: unknown): ExperimentDetailView {
|
||||
const parsed = detail.parse(value);
|
||||
return checkDetail(parsed, parseExperimentPreview(parsed.preview)) as ExperimentDetailView;
|
||||
}
|
||||
export function parseWorkbenchExperimentDetail(value: unknown): WorkbenchExperimentDetailView {
|
||||
const version = z.object({ preview: z.object({ version: z.string() }) }).parse(value)
|
||||
.preview.version;
|
||||
if (version === 'research-experiment-preview/v1') {
|
||||
return parseExperimentDetail(value);
|
||||
}
|
||||
if (version !== 'cost-sensitivity-preview/v1') {
|
||||
throw invalid();
|
||||
}
|
||||
const parsed = costDetail.parse(value);
|
||||
return checkDetail(
|
||||
parsed,
|
||||
parseCostSensitivityPreview(parsed.preview)
|
||||
) as CostSensitivityDetailView;
|
||||
}
|
||||
async function request<T>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
|
|
@ -433,6 +138,8 @@ export const experimentApi = {
|
|||
experiment.id !== target.experimentId ||
|
||||
experiment.backtestId !== target.backtestId ||
|
||||
experiment.previewHash !== target.previewHash ||
|
||||
(receipt.reviewId === null &&
|
||||
experiment.preview.request.strategy.origin !== 'candidate') ||
|
||||
!current ||
|
||||
current.retryCount < receipt.retryNumber ||
|
||||
current.attemptNumber < receipt.previousAttemptNumber
|
||||
|
|
@ -443,7 +150,13 @@ export const experimentApi = {
|
|||
return { retry: receipt as ExperimentTrialRetry, experiment };
|
||||
}
|
||||
),
|
||||
retryHistory: (experimentId: string, runId: string, trialKey: string, signal?: AbortSignal) =>
|
||||
retryHistory: (
|
||||
experimentId: string,
|
||||
runId: string,
|
||||
trialKey: string,
|
||||
signal?: AbortSignal,
|
||||
origin: 'builtin' | 'candidate' = 'builtin'
|
||||
) =>
|
||||
request(
|
||||
`/${encodeURIComponent(experimentId)}/trials/${encodeURIComponent(runId)}/retries`,
|
||||
{ signal },
|
||||
|
|
@ -457,6 +170,7 @@ export const experimentApi = {
|
|||
item.experimentId !== experimentId ||
|
||||
item.runId !== runId ||
|
||||
item.trialKey !== trialKey ||
|
||||
(item.reviewId === null && origin !== 'candidate') ||
|
||||
item.retryNumber !== index + 1
|
||||
)
|
||||
) {
|
||||
|
|
|
|||
|
|
@ -1,119 +1,20 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
experimentComparisonDimensions,
|
||||
experimentComparisonInputSchema,
|
||||
type ExperimentComparison,
|
||||
type ExperimentComparisonInput,
|
||||
} from '@stock-bot/stock-config/experiment-comparison';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import {
|
||||
parseWorkbenchExperimentDetail,
|
||||
type WorkbenchExperimentDetailView,
|
||||
} from './experimentApi';
|
||||
invalidExperimentComparison as invalid,
|
||||
parseExperimentComparison,
|
||||
type ExperimentComparisonView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
|
||||
export type ExperimentComparisonView = Omit<ExperimentComparison, 'experiments'> & {
|
||||
experiments: [WorkbenchExperimentDetailView, WorkbenchExperimentDetailView];
|
||||
};
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
||||
uuid = z.string().uuid();
|
||||
const schema = z.object({
|
||||
version: z.literal('experiment-comparison/v1'),
|
||||
policy: z.literal('retained-input-compatibility/v1'),
|
||||
selection: z.object({ leftId: uuid, rightId: uuid, referenceTrialKey: hash }).strict(),
|
||||
reference: z.object({
|
||||
experimentId: uuid,
|
||||
trialKey: hash,
|
||||
index: z.number().int().nonnegative(),
|
||||
runId: uuid.nullable(),
|
||||
summaryAvailable: z.boolean(),
|
||||
diagnostic: z.string().nullable(),
|
||||
}),
|
||||
experiments: z.tuple([z.unknown(), z.unknown()]),
|
||||
rows: z
|
||||
.array(
|
||||
z.object({
|
||||
experimentId: uuid,
|
||||
trialKey: hash,
|
||||
inputCompatibility: z.enum(['match', 'mismatch']),
|
||||
differences: z.array(z.enum(experimentComparisonDimensions)),
|
||||
summaryAvailable: z.boolean(),
|
||||
ready: z.boolean(),
|
||||
})
|
||||
)
|
||||
.min(2)
|
||||
.max(200),
|
||||
limitations: z.array(z.string().min(1)).min(1),
|
||||
});
|
||||
const invalid = () =>
|
||||
new Error('The experiment comparison could not be verified. Refresh the same selection.');
|
||||
export function parseComparisonQuery(params: URLSearchParams): ExperimentComparisonInput {
|
||||
const allowed = ['leftId', 'rightId', 'referenceTrialKey'];
|
||||
for (const key of params.keys()) {
|
||||
if (!allowed.includes(key) || params.getAll(key).length !== 1) {
|
||||
throw new Error(
|
||||
'Comparison URL requires two different experiment IDs and at most one reference trial key. Unknown or repeated query fields are not supported.'
|
||||
);
|
||||
}
|
||||
}
|
||||
const result = experimentComparisonInputSchema.safeParse(Object.fromEntries(params));
|
||||
if (!result.success) {
|
||||
throw new Error(
|
||||
'Select two different saved experiments to compare. The URL must contain valid leftId and rightId values and, when supplied, a valid referenceTrialKey.'
|
||||
);
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
export function parseExperimentComparison(
|
||||
raw: unknown,
|
||||
input: ExperimentComparisonInput
|
||||
): ExperimentComparisonView {
|
||||
const value = schema.parse(raw),
|
||||
experiments = value.experiments.map(
|
||||
parseWorkbenchExperimentDetail
|
||||
) as ExperimentComparisonView['experiments'];
|
||||
const [left, right] = experiments;
|
||||
const expectedKey = input.referenceTrialKey ?? left.trials[0]?.trialKey;
|
||||
const reference = left.trials.find(trial => trial.trialKey === expectedKey);
|
||||
if (
|
||||
!reference ||
|
||||
left.id !== input.leftId ||
|
||||
right.id !== input.rightId ||
|
||||
value.selection.leftId !== input.leftId ||
|
||||
value.selection.rightId !== input.rightId ||
|
||||
value.selection.referenceTrialKey !== expectedKey ||
|
||||
value.reference.experimentId !== left.id ||
|
||||
value.reference.trialKey !== reference.trialKey ||
|
||||
value.reference.index !== reference.index ||
|
||||
value.reference.runId !== reference.runId ||
|
||||
value.reference.summaryAvailable !== reference.comparable ||
|
||||
value.reference.diagnostic !== reference.diagnostic
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const expectedRows = experiments.flatMap(experiment =>
|
||||
experiment.trials.map(trial => ({ experimentId: experiment.id, trial }))
|
||||
);
|
||||
if (value.rows.length !== expectedRows.length) {
|
||||
throw invalid();
|
||||
}
|
||||
value.rows.forEach((row, index) => {
|
||||
const expected = expectedRows[index],
|
||||
order = row.differences.map(key => experimentComparisonDimensions.indexOf(key));
|
||||
if (
|
||||
!expected ||
|
||||
row.experimentId !== expected.experimentId ||
|
||||
row.trialKey !== expected.trial.trialKey ||
|
||||
order.some((position, i) => i > 0 && position <= (order[i - 1] ?? -1)) ||
|
||||
(row.inputCompatibility === 'match') !== (row.differences.length === 0) ||
|
||||
row.summaryAvailable !== expected.trial.comparable ||
|
||||
row.ready !==
|
||||
(row.inputCompatibility === 'match' && row.summaryAvailable && reference.comparable)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
});
|
||||
return { ...value, experiments };
|
||||
}
|
||||
export {
|
||||
parseExperimentComparison,
|
||||
parseComparisonQuery,
|
||||
type ExperimentComparisonView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
export const experimentComparisonApi = {
|
||||
async get(
|
||||
input: ExperimentComparisonInput,
|
||||
|
|
|
|||
|
|
@ -1,312 +1,31 @@
|
|||
import { z } from 'zod';
|
||||
import { researchActorSchema } from '@stock-bot/stock-config/research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
MAX_WALK_FORWARD_RUNS,
|
||||
MAX_WALK_FORWARD_WINDOWS,
|
||||
walkForwardInputSchema,
|
||||
walkForwardPolicy,
|
||||
type WalkForwardDetail,
|
||||
walkForwardHashSchema as hash,
|
||||
invalidWalkForwardResponse as invalid,
|
||||
parseWalkForwardDetail,
|
||||
parseWalkForwardPreview,
|
||||
sameWalkForwardInput as same,
|
||||
walkForwardSummarySchema as summary,
|
||||
walkForwardIdSchema as uuid,
|
||||
WalkForwardApiError,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import {
|
||||
type WalkForwardFinalizationInput,
|
||||
type WalkForwardInput,
|
||||
type WalkForwardSubmission,
|
||||
type WalkForwardSummary,
|
||||
} from '@stock-bot/stock-config/walk-forward';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import {
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from './chronologicalValidationApi';
|
||||
import {
|
||||
parseValidationDetail,
|
||||
validationEvidenceSchema,
|
||||
type ValidationDetailView,
|
||||
} from './chronologicalValidationDurableApi';
|
||||
import { parseExperimentPreview, type ExperimentPreviewView } from './experimentApi';
|
||||
|
||||
export type WalkForwardPreviewView = {
|
||||
version: 'walk-forward-preview/v1';
|
||||
execution: 'preview-only';
|
||||
previewHash: string;
|
||||
input: WalkForwardInput;
|
||||
source: ExperimentPreviewView;
|
||||
policy: typeof walkForwardPolicy;
|
||||
windows: { index: number; preview: ChronologicalValidationPreviewView }[];
|
||||
counts: {
|
||||
windows: number;
|
||||
trainingRuns: number;
|
||||
holdoutRuns: number;
|
||||
totalRuns: number;
|
||||
maxRuns: number;
|
||||
};
|
||||
};
|
||||
export type WalkForwardDetailView = Omit<WalkForwardDetail, 'preview' | 'windows'> & {
|
||||
preview: WalkForwardPreviewView;
|
||||
windows: {
|
||||
index: number;
|
||||
validationId: string;
|
||||
status: 'admitted' | 'missing';
|
||||
validation: ValidationDetailView | null;
|
||||
}[];
|
||||
};
|
||||
export class WalkForwardApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
||||
uuid = z.string().uuid(),
|
||||
count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const same = (left: unknown, right: unknown) =>
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const invalid = () =>
|
||||
new WalkForwardApiError(
|
||||
'The walk-forward response could not be verified. Refresh or retry the same request.',
|
||||
null
|
||||
);
|
||||
const prepared = z.object({
|
||||
version: z.literal('walk-forward-preview/v1'),
|
||||
execution: z.literal('preview-only'),
|
||||
previewHash: hash,
|
||||
input: walkForwardInputSchema,
|
||||
source: z.unknown(),
|
||||
policy: z.unknown(),
|
||||
windows: z
|
||||
.array(z.object({ index: count, preview: z.unknown() }))
|
||||
.min(2)
|
||||
.max(MAX_WALK_FORWARD_WINDOWS),
|
||||
counts: z.object({
|
||||
windows: count,
|
||||
trainingRuns: count,
|
||||
holdoutRuns: count,
|
||||
totalRuns: count,
|
||||
maxRuns: count,
|
||||
}),
|
||||
});
|
||||
export function parseWalkForwardPreview(
|
||||
raw: unknown,
|
||||
expected?: WalkForwardInput
|
||||
): WalkForwardPreviewView {
|
||||
const value = prepared.parse(raw),
|
||||
source = parseExperimentPreview(value.source);
|
||||
const { windows: recipes, ...sourceInput } = value.input;
|
||||
const size = recipes.length,
|
||||
candidates = source.candidates.length;
|
||||
if (
|
||||
(expected && !same(value.input, expected)) ||
|
||||
!same(source.input, sourceInput) ||
|
||||
!same(value.policy, walkForwardPolicy) ||
|
||||
value.windows.length !== size ||
|
||||
!same(value.counts, {
|
||||
windows: size,
|
||||
trainingRuns: size * candidates,
|
||||
holdoutRuns: size * 2,
|
||||
totalRuns: size * (candidates + 2),
|
||||
maxRuns: MAX_WALK_FORWARD_RUNS,
|
||||
}) ||
|
||||
value.counts.totalRuns > MAX_WALK_FORWARD_RUNS
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const windows = value.windows.map((item, index) => {
|
||||
const recipe = recipes[index],
|
||||
previous = recipes[index - 1];
|
||||
if (
|
||||
!recipe ||
|
||||
item.index !== index ||
|
||||
(previous &&
|
||||
(recipe.train.tradeStart < previous.train.tradeStart ||
|
||||
recipe.train.tradeEnd <= previous.train.tradeEnd ||
|
||||
recipe.validation.tradeStart < previous.test.tradeEnd))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const name = `${value.input.name} · window ${index + 1}`;
|
||||
const preview = parseChronologicalValidationPreview(
|
||||
{ preview: item.preview },
|
||||
{ ...sourceInput, name, recipe }
|
||||
);
|
||||
const { previewHash: _windowHash, ...childSource } = preview.source;
|
||||
const { previewHash: _sourceHash, ...originalSource } = source;
|
||||
if (!same(childSource, { ...originalSource, input: { ...sourceInput, name } })) {
|
||||
throw invalid();
|
||||
}
|
||||
return { index, preview };
|
||||
});
|
||||
return { ...value, source, windows, policy: walkForwardPolicy };
|
||||
}
|
||||
const summary = z
|
||||
.object({
|
||||
id: uuid,
|
||||
backtestId: uuid,
|
||||
name: z.string().min(1),
|
||||
previewHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
cancelRequested: z.boolean(),
|
||||
windowCount: count.min(2).max(MAX_WALK_FORWARD_WINDOWS),
|
||||
reportedWindowCount: count,
|
||||
trainingRunCount: count,
|
||||
plannedRunCount: count.max(MAX_WALK_FORWARD_RUNS),
|
||||
stage: z.enum(['windows', 'reported']),
|
||||
})
|
||||
.superRefine((item, context) => {
|
||||
if (
|
||||
item.reportedWindowCount > item.windowCount ||
|
||||
item.trainingRunCount < item.windowCount ||
|
||||
item.plannedRunCount !== item.trainingRunCount + 2 * item.windowCount
|
||||
) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'Inconsistent walk-forward counts',
|
||||
});
|
||||
}
|
||||
});
|
||||
const report = z.object({
|
||||
version: z.literal('walk-forward-report/v1'),
|
||||
id: uuid,
|
||||
walkForwardId: uuid,
|
||||
previewHash: hash,
|
||||
reportHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: researchActorSchema,
|
||||
reset: z.literal('initial-capital-empty-positions'),
|
||||
segments: z
|
||||
.array(
|
||||
z.object({
|
||||
index: count,
|
||||
validationId: uuid,
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
reportId: uuid,
|
||||
reportHash: hash,
|
||||
validation: validationEvidenceSchema,
|
||||
test: validationEvidenceSchema,
|
||||
})
|
||||
)
|
||||
.min(2)
|
||||
.max(MAX_WALK_FORWARD_WINDOWS),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const detail = z.object({
|
||||
preview: z.unknown(),
|
||||
windows: z.array(
|
||||
z.object({
|
||||
index: count,
|
||||
validationId: uuid,
|
||||
status: z.enum(['admitted', 'missing']),
|
||||
validation: z.unknown(),
|
||||
})
|
||||
),
|
||||
report: report.nullable(),
|
||||
actions: z.object({
|
||||
finalize: z.object({ available: z.boolean(), reason: z.string().nullable() }),
|
||||
}),
|
||||
});
|
||||
export function parseWalkForwardDetail(raw: unknown): WalkForwardDetailView {
|
||||
const base = summary.parse(raw),
|
||||
value = detail.parse(raw),
|
||||
preview = parseWalkForwardPreview(value.preview);
|
||||
if (
|
||||
base.backtestId !== preview.input.backtestId ||
|
||||
base.name !== preview.input.name ||
|
||||
base.previewHash !== preview.previewHash ||
|
||||
base.windowCount !== preview.counts.windows ||
|
||||
base.trainingRunCount !== preview.counts.trainingRuns ||
|
||||
base.plannedRunCount !== preview.counts.totalRuns ||
|
||||
value.windows.length !== base.windowCount ||
|
||||
new Set(value.windows.map(item => item.validationId)).size !== base.windowCount ||
|
||||
(base.stage === 'reported') !== (value.report !== null)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const windows = value.windows.map((item, index) => {
|
||||
if (item.index !== index || (item.status === 'missing') !== (item.validation === null)) {
|
||||
throw invalid();
|
||||
}
|
||||
const validation = item.validation === null ? null : parseValidationDetail(item.validation);
|
||||
if (
|
||||
validation &&
|
||||
(validation.id !== item.validationId ||
|
||||
validation.backtestId !== base.backtestId ||
|
||||
!same(validation.preview, preview.windows[index]?.preview))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...item, validation };
|
||||
});
|
||||
if (
|
||||
base.reportedWindowCount !== windows.filter(item => item.validation?.report).length ||
|
||||
(value.actions.finalize.available &&
|
||||
(base.cancelRequested ||
|
||||
value.report ||
|
||||
windows.some(
|
||||
item =>
|
||||
!item.validation?.report ||
|
||||
item.validation.cancelRequested ||
|
||||
item.validation.phases.some(
|
||||
phase =>
|
||||
phase.status !== 'admitted' ||
|
||||
!phase.experiment ||
|
||||
phase.experiment.cancelRequested ||
|
||||
phase.experiment.trials.some(
|
||||
trial =>
|
||||
trial.status !== 'completed' || !trial.comparable || trial.cancelRequested
|
||||
)
|
||||
)
|
||||
)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
if (value.report) {
|
||||
const saved = value.report;
|
||||
if (
|
||||
saved.walkForwardId !== base.id ||
|
||||
saved.previewHash !== base.previewHash ||
|
||||
saved.segments.length !== base.windowCount
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
for (const [index, segment] of saved.segments.entries()) {
|
||||
const member = windows[index],
|
||||
frozen = preview.windows[index]?.preview,
|
||||
child = member?.validation?.report;
|
||||
const candidate = frozen?.source.candidates[segment.validation.sourceCandidateIndex];
|
||||
if (
|
||||
!member ||
|
||||
!frozen ||
|
||||
!candidate ||
|
||||
segment.index !== index ||
|
||||
segment.validationId !== member.validationId ||
|
||||
segment.previewHash !== frozen.previewHash ||
|
||||
segment.validation.phase !== 'validation' ||
|
||||
segment.test.phase !== 'test' ||
|
||||
segment.validation.sourceCandidateIndex !== segment.test.sourceCandidateIndex ||
|
||||
segment.validation.datasetHash !== frozen.partitions[1].dataset.hash ||
|
||||
segment.test.datasetHash !== frozen.partitions[2].dataset.hash ||
|
||||
[segment.validation, segment.test].some(
|
||||
item =>
|
||||
item.trialKey !== candidate.trialKey || !same(item.parameters, candidate.parameters)
|
||||
) ||
|
||||
(member.validation &&
|
||||
(!child ||
|
||||
segment.reportId !== child.id ||
|
||||
segment.reportHash !== child.reportHash ||
|
||||
segment.selectionHash !== child.selectionHash ||
|
||||
!same(segment.validation, child.validation) ||
|
||||
!same(segment.test, child.test)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
}
|
||||
return { ...base, ...value, preview, windows };
|
||||
}
|
||||
export {
|
||||
WalkForwardApiError,
|
||||
parseWalkForwardDetail,
|
||||
parseWalkForwardPreview,
|
||||
type WalkForwardDetailView,
|
||||
type WalkForwardPreviewView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
|
||||
const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key];
|
||||
async function request<T>(
|
||||
path: string,
|
||||
|
|
|
|||
216
apps/stock/web-app/src/features/paper/PaperDeploymentPage.tsx
Normal file
216
apps/stock/web-app/src/features/paper/PaperDeploymentPage.tsx
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import type {
|
||||
PaperDeployment,
|
||||
PaperDeploymentStatus,
|
||||
} from '@stock-bot/stock-config/paper-deployments';
|
||||
import { actionClass, fieldClass } from '../strategies/components/StrategyParameterForm';
|
||||
import { paperApi } from './paperApi';
|
||||
|
||||
export function PaperDeploymentPage() {
|
||||
const { deploymentId = '' } = useParams<{ deploymentId: string }>();
|
||||
return <PaperDeploymentView key={deploymentId} id={deploymentId} />;
|
||||
}
|
||||
function PaperDeploymentView({ id }: { id: string }) {
|
||||
const [deployment, setDeployment] = useState<PaperDeployment | null>(null),
|
||||
[status, setStatus] = useState<PaperDeploymentStatus | null>(null),
|
||||
[error, setError] = useState(''),
|
||||
[pending, setPending] = useState(false),
|
||||
[loading, setLoading] = useState(true),
|
||||
[recover, setRecover] = useState(false),
|
||||
[reason, setReason] = useState('Operator halt');
|
||||
const alive = useRef(true),
|
||||
sequence = useRef(0),
|
||||
writing = useRef(false);
|
||||
const refresh = async () => {
|
||||
if (writing.current) {
|
||||
return;
|
||||
}
|
||||
const current = ++sequence.current;
|
||||
setError('');
|
||||
try {
|
||||
const next = await paperApi.status(id);
|
||||
if (alive.current && current === sequence.current) {
|
||||
setStatus(next);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current && current === sequence.current) {
|
||||
setStatus(null);
|
||||
setError(cause instanceof Error ? cause.message : 'Paper status unavailable');
|
||||
}
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
const abort = new AbortController();
|
||||
void paperApi
|
||||
.get(id, abort.signal)
|
||||
.then(value => {
|
||||
if (alive.current) {
|
||||
setDeployment(value);
|
||||
void refresh();
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (alive.current) {
|
||||
setError(cause instanceof Error ? cause.message : 'Deployment unavailable');
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (alive.current) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
alive.current = false;
|
||||
sequence.current++;
|
||||
abort.abort();
|
||||
};
|
||||
}, [id]);
|
||||
const command = async (operation: 'bind' | 'activate' | 'halt') => {
|
||||
if (writing.current) {
|
||||
return;
|
||||
}
|
||||
writing.current = true;
|
||||
sequence.current++;
|
||||
setPending(true);
|
||||
setError('');
|
||||
try {
|
||||
const value = await paperApi.command(
|
||||
id,
|
||||
operation,
|
||||
operation === 'activate'
|
||||
? { recoverPending: recover }
|
||||
: operation === 'halt'
|
||||
? { reason }
|
||||
: {}
|
||||
);
|
||||
if (alive.current) {
|
||||
setStatus(value);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setStatus(null);
|
||||
setError(
|
||||
(cause instanceof Error ? cause.message : 'Paper command unavailable') +
|
||||
' Refresh readiness before another activation.'
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
writing.current = false;
|
||||
if (alive.current) {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
if (loading) {
|
||||
return <p role="status">Loading paper deployment…</p>;
|
||||
}
|
||||
return (
|
||||
<main className="space-y-5 p-6">
|
||||
<Link to="/paper">Paper deployments</Link>
|
||||
<h1 className="text-2xl">
|
||||
{deployment?.preview.input.name ?? 'Paper deployment unavailable'}
|
||||
</h1>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{deployment && (
|
||||
<>
|
||||
<p>
|
||||
Immutable version {deployment.preview.strategy.versionId} · reviewed by{' '}
|
||||
{deployment.principal} at {deployment.createdAt}
|
||||
</p>
|
||||
<p>
|
||||
Account {deployment.preview.configuration.matching.risk.ledger.accountId}. Live trading
|
||||
is unavailable.
|
||||
</p>
|
||||
<p>{deployment.preview.input.reason}</p>
|
||||
<ul>
|
||||
{deployment.preview.limitations.map(item => (
|
||||
<li key={item}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
<details>
|
||||
<summary>Retained promotion and evidence</summary>
|
||||
<pre className="overflow-auto text-xs">{JSON.stringify(deployment, null, 2)}</pre>
|
||||
</details>
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-xl">Paper host readiness</h2>
|
||||
<button disabled={pending} className={actionClass} onClick={() => void refresh()}>
|
||||
Refresh readiness
|
||||
</button>
|
||||
{status ? (
|
||||
<>
|
||||
<p>
|
||||
{status.readiness.active
|
||||
? 'Active paper execution'
|
||||
: 'Halted or inactive paper execution'}{' '}
|
||||
· {status.readiness.connected ? 'Feed connected' : 'Feed disconnected'}
|
||||
</p>
|
||||
<ul>
|
||||
{status.readiness.reasons.map(item => (
|
||||
<li key={item}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>Bound deployment: {status.boundDeploymentId ?? 'None'}</p>
|
||||
<button
|
||||
className={actionClass}
|
||||
disabled={pending || Boolean(status.boundDeploymentId)}
|
||||
onClick={() => void command('bind')}
|
||||
>
|
||||
Bind halted deployment
|
||||
</button>
|
||||
<label className="block">
|
||||
<input
|
||||
aria-label="Recover pending paper work"
|
||||
type="checkbox"
|
||||
checked={recover}
|
||||
disabled={pending}
|
||||
onChange={e => setRecover(e.target.checked)}
|
||||
/>{' '}
|
||||
Explicitly recover retained pending work on activation
|
||||
</label>
|
||||
<button
|
||||
className={actionClass}
|
||||
disabled={
|
||||
pending ||
|
||||
status.boundDeploymentId !== id ||
|
||||
status.readiness.active ||
|
||||
!status.readiness.connected
|
||||
}
|
||||
onClick={() => void command('activate')}
|
||||
>
|
||||
Activate paper
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<p>Readiness has not been confirmed. Activation is unavailable.</p>
|
||||
)}
|
||||
<label className="block">
|
||||
Halt reason
|
||||
<input
|
||||
aria-label="Halt reason"
|
||||
className={fieldClass}
|
||||
value={reason}
|
||||
onChange={e => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className={actionClass}
|
||||
disabled={pending || !reason.trim()}
|
||||
onClick={() => void command('halt')}
|
||||
>
|
||||
Halt paper
|
||||
</button>
|
||||
<p>
|
||||
Startup is inactive. A trusted feed producer must connect and provide fresh quotes
|
||||
before an operator can activate. Existing capital and checkpoints are retained.
|
||||
Activation rechecks current approval and build. Revoking catalog approval blocks new
|
||||
activation; use Halt paper to stop an already active account.
|
||||
</p>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
{pending && <p role="status">Confirming paper command…</p>}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
459
apps/stock/web-app/src/features/paper/PaperDeploymentsPage.tsx
Normal file
459
apps/stock/web-app/src/features/paper/PaperDeploymentsPage.tsx
Normal file
|
|
@ -0,0 +1,459 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import type {
|
||||
PaperDeployment,
|
||||
PaperPromotionInput,
|
||||
PaperPromotionPreview,
|
||||
} from '@stock-bot/stock-config/paper-deployments';
|
||||
import { paperPromotionInputSchema } from '@stock-bot/stock-config/paper-deployments';
|
||||
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) =>
|
||||
cause instanceof Error ? cause.message : 'Paper request failed';
|
||||
const initialTransport = JSON.stringify(
|
||||
{
|
||||
accountId: '',
|
||||
sessionId: '',
|
||||
quoteSeriesId: '',
|
||||
riskSession: { calendarId: '', calendarRevision: '', sessionId: '', startsAt: 0 },
|
||||
policy: {
|
||||
version: 1,
|
||||
sourceId: '',
|
||||
priceBasis: 'raw',
|
||||
maxFeedAgeMs: 60000,
|
||||
observations: [],
|
||||
cadence: [],
|
||||
calendars: [],
|
||||
riskBoundaries: [],
|
||||
},
|
||||
},
|
||||
null,
|
||||
2
|
||||
);
|
||||
type Source = {
|
||||
source: PaperPromotionInput['outOfSample'];
|
||||
tests: Array<{ runId: string; label: string }>;
|
||||
};
|
||||
export function PaperDeploymentsPage() {
|
||||
const navigate = useNavigate(),
|
||||
alive = useRef(true),
|
||||
busy = useRef(false),
|
||||
generation = useRef(0),
|
||||
frozen = useRef(false),
|
||||
dirty = useRef(false),
|
||||
receipt = useRef<{ preview: PaperPromotionPreview; key: string } | null>(null);
|
||||
const [rows, setRows] = useState<PaperDeployment[]>([]),
|
||||
[loading, setLoading] = useState(true),
|
||||
[error, setError] = useState(''),
|
||||
[pending, setPending] = useState(false),
|
||||
[uncertain, setUncertain] = useState(false);
|
||||
const [name, setName] = useState(''),
|
||||
[kind, setKind] = useState<'chronological' | 'walk-forward'>('chronological'),
|
||||
[sourceId, setSourceId] = useState(''),
|
||||
[costId, setCostId] = useState('');
|
||||
const [source, setSource] = useState<Source | null>(null),
|
||||
[cost, setCost] = useState<{
|
||||
id: string;
|
||||
previewHash: string;
|
||||
trials: Array<{ runId: string; label: string }>;
|
||||
} | null>(null),
|
||||
[testRunId, setTestRunId] = useState(''),
|
||||
[costRunId, setCostRunId] = useState('');
|
||||
const [transport, setTransport] = useState(initialTransport),
|
||||
[reason, setReason] = useState(''),
|
||||
[ack, setAck] = useState(false),
|
||||
[preview, setPreview] = useState<PaperPromotionPreview | null>(null);
|
||||
useUnsavedWarning(dirty.current || pending || uncertain);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
const abort = new AbortController();
|
||||
void paperApi
|
||||
.list(abort.signal)
|
||||
.then(value => {
|
||||
if (alive.current) {
|
||||
setRows(value.deployments);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (alive.current) {
|
||||
setError(message(cause));
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (alive.current) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
alive.current = false;
|
||||
generation.current++;
|
||||
abort.abort();
|
||||
};
|
||||
}, []);
|
||||
const change = (action: () => void) => {
|
||||
if (busy.current || frozen.current) {
|
||||
return;
|
||||
}
|
||||
dirty.current = true;
|
||||
generation.current++;
|
||||
receipt.current = null;
|
||||
setPreview(null);
|
||||
setError('');
|
||||
action();
|
||||
};
|
||||
const run = async (work: () => Promise<void>, retryReceipt = false) => {
|
||||
if (busy.current || (frozen.current && !retryReceipt)) {
|
||||
return;
|
||||
}
|
||||
busy.current = true;
|
||||
setPending(true);
|
||||
setError('');
|
||||
try {
|
||||
await work();
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setError(message(cause));
|
||||
}
|
||||
} finally {
|
||||
busy.current = false;
|
||||
if (alive.current) {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const loadEvidence = () =>
|
||||
run(async () => {
|
||||
const captured = generation.current;
|
||||
const sourcePromise =
|
||||
kind === 'chronological'
|
||||
? chronologicalValidationDurableApi.get(sourceId).then(value => {
|
||||
if (!value.report) {
|
||||
throw new Error('Chronological report is not sealed');
|
||||
}
|
||||
return {
|
||||
source: {
|
||||
kind: 'chronological-report/v1' as const,
|
||||
validationId: value.id,
|
||||
reportId: value.report.id,
|
||||
reportHash: value.report.reportHash,
|
||||
previewHash: value.report.previewHash,
|
||||
},
|
||||
tests: [{ runId: value.report.test.runId, label: 'Sealed chronological test' }],
|
||||
};
|
||||
})
|
||||
: walkForwardApi.get(sourceId).then(value => {
|
||||
if (!value.report) {
|
||||
throw new Error('Walk-forward report is not sealed');
|
||||
}
|
||||
return {
|
||||
source: {
|
||||
kind: 'walk-forward-report/v1' as const,
|
||||
walkForwardId: value.id,
|
||||
reportId: value.report.id,
|
||||
reportHash: value.report.reportHash,
|
||||
previewHash: value.report.previewHash,
|
||||
},
|
||||
tests: value.report.segments.map(segment => ({
|
||||
runId: segment.test.runId,
|
||||
label: `Window ${segment.index + 1} test`,
|
||||
})),
|
||||
};
|
||||
});
|
||||
const [nextSource, nextCost] = await Promise.all([sourcePromise, experimentApi.get(costId)]);
|
||||
if (
|
||||
nextCost.preview.version !== 'cost-sensitivity-preview/v1' ||
|
||||
nextCost.trials.some(t => t.status !== 'completed' || !t.runId)
|
||||
) {
|
||||
throw new Error('Select a fully completed cost-sensitivity study');
|
||||
}
|
||||
if (!alive.current || captured !== generation.current) {
|
||||
return;
|
||||
}
|
||||
const trials = nextCost.trials.map((trial, index) => {
|
||||
const scenario =
|
||||
nextCost.preview.version === 'cost-sensitivity-preview/v1'
|
||||
? nextCost.preview.candidates[index]?.costs
|
||||
: null;
|
||||
return {
|
||||
runId: trial.runId ?? '',
|
||||
label: `${index === 0 ? 'Baseline' : `Scenario ${index}`} · fee ${scenario?.feeRate}, slippage ${scenario?.slippageRate}`,
|
||||
};
|
||||
});
|
||||
setSource(nextSource);
|
||||
setCost({ id: nextCost.id, previewHash: nextCost.previewHash, trials });
|
||||
setTestRunId(nextSource.tests[0]?.runId ?? '');
|
||||
setCostRunId(trials[0]?.runId ?? '');
|
||||
});
|
||||
const review = () =>
|
||||
run(async () => {
|
||||
if (!source || !cost) {
|
||||
throw new Error('Load sealed test and completed cost evidence first');
|
||||
}
|
||||
const input = paperPromotionInputSchema.parse({
|
||||
name,
|
||||
outOfSample: source.source,
|
||||
testRunId,
|
||||
costExperimentId: cost.id,
|
||||
costPreviewHash: cost.previewHash,
|
||||
costRunId,
|
||||
transport: JSON.parse(transport),
|
||||
reason,
|
||||
acknowledgeTrustedCode: ack,
|
||||
});
|
||||
const captured = generation.current,
|
||||
next = await paperApi.preview(input);
|
||||
if (alive.current && captured === generation.current) {
|
||||
setPreview(next);
|
||||
receipt.current = { preview: next, key: crypto.randomUUID() };
|
||||
}
|
||||
});
|
||||
const create = () =>
|
||||
run(async () => {
|
||||
const captured = receipt.current;
|
||||
if (!preview || !captured || captured.preview !== preview) {
|
||||
throw new Error('Review a current preview first');
|
||||
}
|
||||
try {
|
||||
const saved = await paperApi.create(
|
||||
captured.preview.input,
|
||||
captured.preview.previewHash,
|
||||
captured.key
|
||||
);
|
||||
if (alive.current) {
|
||||
frozen.current = false;
|
||||
dirty.current = false;
|
||||
setUncertain(false);
|
||||
navigate(`/paper/${saved.id}`);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current && (!(cause instanceof PaperApiError) || cause.uncertain)) {
|
||||
frozen.current = true;
|
||||
setUncertain(true);
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
}, true);
|
||||
const disabled = pending || uncertain;
|
||||
return (
|
||||
<main
|
||||
className="space-y-6 p-6"
|
||||
onClickCapture={event => {
|
||||
const link = (event.target as HTMLElement).closest('a');
|
||||
if (
|
||||
link &&
|
||||
(!link.target || link.target === '_self') &&
|
||||
!link.hasAttribute('download') &&
|
||||
event.button === 0 &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey &&
|
||||
!event.shiftKey &&
|
||||
!event.altKey &&
|
||||
(dirty.current || busy.current || frozen.current) &&
|
||||
!window.confirm(
|
||||
'Leave this paper promotion draft or unconfirmed submission? Its exact retry inputs and key will be discarded. You can inspect saved records in another tab.'
|
||||
)
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<h1 className="text-2xl">Paper deployments</h1>
|
||||
<p>
|
||||
Promote reviewed research into a halted paper account. Live trading is unavailable. Creating
|
||||
a deployment does not connect a feed or activate trading.
|
||||
</p>
|
||||
{loading ? (
|
||||
<p role="status">Loading deployments…</p>
|
||||
) : rows.length ? (
|
||||
<ul>
|
||||
{rows.map(row => (
|
||||
<li key={row.id}>
|
||||
<Link to={`/paper/${row.id}`}>{row.preview.input.name}</Link> ·{' '}
|
||||
{row.preview.configuration.matching.risk.ledger.accountId}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>No paper deployments yet.</p>
|
||||
)}
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-xl">Review a new promotion</h2>
|
||||
<p>
|
||||
Use a sealed report and completed cost study from{' '}
|
||||
<Link to="/experiments">experiments</Link>. Future sessions and feed metadata must be
|
||||
supplied explicitly; no calendar is inferred.
|
||||
</p>
|
||||
<fieldset disabled={disabled} className="space-y-3">
|
||||
<label className="block">
|
||||
Deployment name
|
||||
<input
|
||||
aria-label="Deployment name"
|
||||
className={fieldClass}
|
||||
value={name}
|
||||
onChange={e => change(() => setName(e.target.value))}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Report type
|
||||
<select
|
||||
aria-label="Report type"
|
||||
className={fieldClass}
|
||||
value={kind}
|
||||
onChange={e =>
|
||||
change(() => {
|
||||
setKind(e.target.value as typeof kind);
|
||||
setSource(null);
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="chronological">Chronological validation</option>
|
||||
<option value="walk-forward">Walk-forward series</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
Report owner ID
|
||||
<input
|
||||
aria-label="Report owner ID"
|
||||
className={fieldClass}
|
||||
value={sourceId}
|
||||
onChange={e =>
|
||||
change(() => {
|
||||
setSourceId(e.target.value);
|
||||
setSource(null);
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Cost experiment ID
|
||||
<input
|
||||
aria-label="Cost experiment ID"
|
||||
className={fieldClass}
|
||||
value={costId}
|
||||
onChange={e =>
|
||||
change(() => {
|
||||
setCostId(e.target.value);
|
||||
setCost(null);
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<button className={actionClass} type="button" onClick={() => void loadEvidence()}>
|
||||
Load evidence
|
||||
</button>
|
||||
{source && (
|
||||
<label className="block">
|
||||
Test run
|
||||
<select
|
||||
aria-label="Test run"
|
||||
className={fieldClass}
|
||||
value={testRunId}
|
||||
onChange={e => change(() => setTestRunId(e.target.value))}
|
||||
>
|
||||
{source.tests.map(item => (
|
||||
<option key={item.runId} value={item.runId}>
|
||||
{item.label} · {item.runId}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{cost && (
|
||||
<label className="block">
|
||||
Paper cost scenario
|
||||
<select
|
||||
aria-label="Paper cost scenario"
|
||||
className={fieldClass}
|
||||
value={costRunId}
|
||||
onChange={e => change(() => setCostRunId(e.target.value))}
|
||||
>
|
||||
{cost.trials.map(item => (
|
||||
<option key={item.runId} value={item.runId}>
|
||||
{item.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<label className="block">
|
||||
Explicit paper transport and future sessions (JSON)
|
||||
<textarea
|
||||
aria-label="Paper transport"
|
||||
className={`${fieldClass} font-mono`}
|
||||
rows={15}
|
||||
value={transport}
|
||||
onChange={e => change(() => setTransport(e.target.value))}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Review rationale
|
||||
<textarea
|
||||
aria-label="Review rationale"
|
||||
className={fieldClass}
|
||||
value={reason}
|
||||
onChange={e => change(() => setReason(e.target.value))}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<input
|
||||
aria-label="Authorize trusted paper code"
|
||||
type="checkbox"
|
||||
checked={ack}
|
||||
onChange={e => change(() => setAck(e.target.checked))}
|
||||
/>{' '}
|
||||
I reviewed the strategy code, holdout and costs, and authorize these exact bytes as
|
||||
trusted paper-host code, including AI-originated code.
|
||||
</label>
|
||||
<button className={actionClass} type="button" onClick={() => void review()}>
|
||||
Preview promotion
|
||||
</button>
|
||||
</fieldset>
|
||||
{preview && (
|
||||
<section className="space-y-2">
|
||||
<h3>Exact promotion preview</h3>
|
||||
<p>
|
||||
Version {preview.strategy.versionId} · {preview.strategy.origin}
|
||||
</p>
|
||||
<p>
|
||||
Account {preview.configuration.matching.risk.ledger.accountId} · initial capital{' '}
|
||||
{preview.configuration.matching.risk.ledger.initialCapital}
|
||||
</p>
|
||||
<p>
|
||||
Test return: {preview.evidence.test.metrics.totalReturn ?? 'Unavailable'} · fills{' '}
|
||||
{preview.evidence.test.fillCount}
|
||||
</p>
|
||||
<p>
|
||||
Paper-host hash: <code>{preview.host.hostSha256}</code>
|
||||
</p>
|
||||
<ul>
|
||||
{preview.limitations.map(item => (
|
||||
<li key={item}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
<details>
|
||||
<summary>Frozen configuration and evidence</summary>
|
||||
<pre className="overflow-auto text-xs">{JSON.stringify(preview, null, 2)}</pre>
|
||||
</details>
|
||||
<button disabled={pending} className={actionClass} onClick={() => void create()}>
|
||||
{uncertain ? 'Retry same promotion receipt' : 'Create halted deployment'}
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
{uncertain && (
|
||||
<p role="status">
|
||||
The previous submission may have succeeded. The draft is frozen; retry uses the same key
|
||||
and cannot create a second deployment.
|
||||
</p>
|
||||
)}
|
||||
{pending && <p role="status">Checking paper promotion…</p>}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
2
apps/stock/web-app/src/features/paper/index.ts
Normal file
2
apps/stock/web-app/src/features/paper/index.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export { PaperDeploymentsPage } from './PaperDeploymentsPage';
|
||||
export { PaperDeploymentPage } from './PaperDeploymentPage';
|
||||
110
apps/stock/web-app/src/features/paper/paperApi.ts
Normal file
110
apps/stock/web-app/src/features/paper/paperApi.ts
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
paperDeploymentSchema,
|
||||
paperDeploymentStatusSchema,
|
||||
paperPromotionInputSchema,
|
||||
paperPromotionPreviewSchema,
|
||||
type PaperPromotionInput,
|
||||
} from '@stock-bot/stock-config/paper-deployments';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
|
||||
export class PaperApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get uncertain() {
|
||||
return this.status === null || this.status >= 500 || this.status === 408;
|
||||
}
|
||||
}
|
||||
async function request<S extends z.ZodTypeAny>(
|
||||
path: string,
|
||||
schema: S,
|
||||
init?: RequestInit
|
||||
): Promise<z.output<S>> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await apiFetch(`${API_BASE_URL}/api/v2/paper-deployments${path}`, init);
|
||||
} catch (error) {
|
||||
if (init?.signal?.aborted) {
|
||||
throw error;
|
||||
}
|
||||
throw new PaperApiError(
|
||||
'The paper response was lost. Check saved status before changing the request.',
|
||||
null
|
||||
);
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const error = z.object({ error: z.string() }).safeParse(body);
|
||||
throw new PaperApiError(
|
||||
error.success ? error.data.error : `Paper request failed (${response.status})`,
|
||||
response.status
|
||||
);
|
||||
}
|
||||
try {
|
||||
return schema.parse(body);
|
||||
} catch {
|
||||
throw new PaperApiError('Paper response could not be verified; check saved status.', null);
|
||||
}
|
||||
}
|
||||
const json = (body: unknown, key?: string): RequestInit => ({
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...(key ? { 'Idempotency-Key': key } : {}) },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
export const paperApi = {
|
||||
list: (signal?: AbortSignal) =>
|
||||
request('', z.object({ deployments: z.array(paperDeploymentSchema) }).strict(), { signal }),
|
||||
get: async (id: string, signal?: AbortSignal) => {
|
||||
const value = await request(`/${encodeURIComponent(id)}`, paperDeploymentSchema, { signal });
|
||||
if (value.id !== id) {
|
||||
throw new PaperApiError('Paper deployment identity mismatch', null);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
preview: async (input: PaperPromotionInput, signal?: AbortSignal) => {
|
||||
const parsed = paperPromotionInputSchema.parse(input),
|
||||
value = await request('/preview', paperPromotionPreviewSchema, { ...json(parsed), signal });
|
||||
if (canonicalStrategyJson(value.input) !== canonicalStrategyJson(parsed)) {
|
||||
throw new PaperApiError('Paper preview input mismatch', null);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
create: async (input: PaperPromotionInput, previewHash: string, key: string) => {
|
||||
const parsed = paperPromotionInputSchema.parse(input),
|
||||
value = await request('', paperDeploymentSchema, json({ ...parsed, previewHash }, key));
|
||||
if (
|
||||
value.preview.previewHash !== previewHash ||
|
||||
canonicalStrategyJson(value.preview.input) !== canonicalStrategyJson(parsed)
|
||||
) {
|
||||
throw new PaperApiError('Paper promotion receipt mismatch', null);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
status: async (id: string, signal?: AbortSignal) => {
|
||||
const value = await request(
|
||||
`/${encodeURIComponent(id)}/readiness`,
|
||||
paperDeploymentStatusSchema,
|
||||
{ signal }
|
||||
);
|
||||
if (value.deploymentId !== id) {
|
||||
throw new PaperApiError('Paper status identity mismatch', null);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
command: async (id: string, operation: 'bind' | 'activate' | 'halt', body: unknown) => {
|
||||
const value = await request(
|
||||
`/${encodeURIComponent(id)}/${operation}`,
|
||||
paperDeploymentStatusSchema,
|
||||
json(body)
|
||||
);
|
||||
if (value.deploymentId !== id) {
|
||||
throw new PaperApiError('Paper command identity mismatch', null);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
};
|
||||
|
|
@ -28,6 +28,7 @@ export function ResearchAgentsPage() {
|
|||
const [name, setName] = useState('');
|
||||
const [projects, setProjects] = useState(search.get('projectId') ?? '');
|
||||
const [backtests, setBacktests] = useState('');
|
||||
const [candidateBacktests, setCandidateBacktests] = useState('');
|
||||
const [limits, setLimits] = useState<Record<string, string>>(() =>
|
||||
Object.fromEntries(limitFields.map(([key, , value]) => [key, value]))
|
||||
);
|
||||
|
|
@ -43,7 +44,7 @@ export function ResearchAgentsPage() {
|
|||
const writing = useRef(false);
|
||||
const generation = useRef(0);
|
||||
const budgetRequests = useRef(new Map<string, number>());
|
||||
useUnsavedWarning(Boolean(name || backtests || token || uncertain));
|
||||
useUnsavedWarning(Boolean(name || backtests || candidateBacktests || token || uncertain));
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
|
|
@ -87,6 +88,9 @@ export function ResearchAgentsPage() {
|
|||
name,
|
||||
allowedProjectIds: identifiers(projects),
|
||||
allowedBacktestIds: identifiers(backtests),
|
||||
...(candidateBacktests.trim()
|
||||
? { allowOwnCandidateBacktestIds: identifiers(candidateBacktests) }
|
||||
: {}),
|
||||
limits: Object.fromEntries(limitFields.map(([key]) => [key, Number(limits[key])])),
|
||||
});
|
||||
if (!parsed.success) {
|
||||
|
|
@ -109,6 +113,7 @@ export function ResearchAgentsPage() {
|
|||
setToken(result.token);
|
||||
setName('');
|
||||
setBacktests('');
|
||||
setCandidateBacktests('');
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
|
|
@ -266,6 +271,20 @@ export function ResearchAgentsPage() {
|
|||
Separate IDs with commas or whitespace. Empty lists grant no access. Backtests must
|
||||
already have an eligible immutable version, retained dataset and canonical policy.
|
||||
</p>
|
||||
<label className="block">
|
||||
Allow own candidates on backtest IDs
|
||||
<textarea
|
||||
aria-label="Allow own candidates on backtest IDs"
|
||||
className={fieldClass}
|
||||
value={candidateBacktests}
|
||||
onChange={event => setCandidateBacktests(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Optional subset of the allowed backtests. This permits the agent’s own immutable
|
||||
candidates to run in isolation under the same frozen financial policy. Review revocation
|
||||
still blocks new admissions.
|
||||
</p>
|
||||
{limitFields.map(([key, label]) => (
|
||||
<label key={key} className="block">
|
||||
{label}
|
||||
|
|
@ -321,7 +340,10 @@ export function ResearchAgentsPage() {
|
|||
<Link to={`/backtests/${grant.backtestId}`} className="text-primary-500">
|
||||
{grant.backtestId}
|
||||
</Link>{' '}
|
||||
· Policy {grant.policyHash}
|
||||
· Policy {grant.policyHash} ·{' '}
|
||||
{grant.allowOwnCandidates
|
||||
? 'Owned isolated candidates allowed'
|
||||
: 'Template strategy only'}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import type {
|
|||
StrategyVersionSummary,
|
||||
} from '@stock-bot/types';
|
||||
import { BuiltinReview } from './components/BuiltinReview';
|
||||
import { CandidatePublication } from './components/CandidatePublication';
|
||||
import { actionClass, fieldClass, StrategyParameterForm } from './components/StrategyParameterForm';
|
||||
import { versionPath } from './components/StrategySelection';
|
||||
import { confirmDiscard, useUnsavedWarning } from './components/useUnsavedWarning';
|
||||
|
|
@ -33,6 +34,7 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
|
|||
const [parameters, setParameters] = useState<Parameters>({});
|
||||
const [validParameters, setValidParameters] = useState(false);
|
||||
const [parameterEdits, setParameterEdits] = useState(false);
|
||||
const [publicationDirty, setPublicationDirty] = useState(false);
|
||||
const [cloneOpen, setCloneOpen] = useState(false);
|
||||
const [cloneName, setCloneName] = useState('');
|
||||
const [cloneDescription, setCloneDescription] = useState('');
|
||||
|
|
@ -52,7 +54,10 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
|
|||
strategy && (name !== strategy.name || description !== strategy.description)
|
||||
);
|
||||
const dirty =
|
||||
metadataDirty || parameterEdits || (cloneOpen && Boolean(cloneName || cloneDescription));
|
||||
metadataDirty ||
|
||||
parameterEdits ||
|
||||
publicationDirty ||
|
||||
(cloneOpen && Boolean(cloneName || cloneDescription));
|
||||
useUnsavedWarning(dirty);
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
|
|
@ -291,11 +296,25 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
|
|||
{strategy.archived ? 'Restore strategy' : 'Archive strategy'}
|
||||
</button>
|
||||
</form>
|
||||
<CandidatePublication
|
||||
key={`publication:${strategyId}:${versionId ?? ''}`}
|
||||
strategyId={strategyId}
|
||||
parentVersionId={versionId ?? null}
|
||||
disabled={
|
||||
strategy.archived ||
|
||||
cloning ||
|
||||
cloneFrozen ||
|
||||
versionLoading ||
|
||||
Boolean(versionId && !version)
|
||||
}
|
||||
onDirtyChange={setPublicationDirty}
|
||||
onPublished={published => navigate(versionPath(published))}
|
||||
/>
|
||||
<section className="space-y-3">
|
||||
<h2 className="font-semibold">Immutable versions</h2>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Publish version packages using the existing catalog API. Metadata edits do not change
|
||||
retained code.
|
||||
Published packages preserve exact code and dependency hashes. Metadata edits do not
|
||||
change retained code.
|
||||
</p>
|
||||
<label className="block text-sm">
|
||||
Strategy version
|
||||
|
|
@ -305,7 +324,7 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
|
|||
value={versionId ?? ''}
|
||||
disabled={cloning || cloneFrozen}
|
||||
onChange={event => {
|
||||
if (confirmDiscard(parameterEdits)) {
|
||||
if (confirmDiscard(parameterEdits || publicationDirty)) {
|
||||
navigate(
|
||||
event.target.value
|
||||
? `/strategies/${strategyId}/versions/${event.target.value}`
|
||||
|
|
@ -429,7 +448,8 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
|
|||
)}
|
||||
<p className="text-sm text-text-secondary">
|
||||
The clone retains exact artifact bytes and parent lineage. It is a new
|
||||
candidate awaiting review; cloning does not enable execution.
|
||||
candidate. Research eligibility requires a declared isolated execution
|
||||
contract and an available sandbox.
|
||||
</p>
|
||||
<label className="block text-sm">
|
||||
Clone name
|
||||
|
|
@ -517,7 +537,7 @@ function VersionIdentity({ version }: { version: StrategyVersionSummary }) {
|
|||
</p>
|
||||
<p role="status">
|
||||
{version.origin === 'candidate'
|
||||
? 'Candidate execution is unavailable until isolated execution is supported.'
|
||||
? 'Candidate research uses the isolated runtime. Eligibility is checked against the retained package, dataset and financial policy.'
|
||||
: 'Canonical execution requires approval, a matching executable build, a supported dataset and an explicit simulation policy.'}
|
||||
</p>
|
||||
<p>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,197 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
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({
|
||||
strategyId,
|
||||
parentVersionId,
|
||||
disabled,
|
||||
onDirtyChange,
|
||||
onPublished,
|
||||
}: {
|
||||
strategyId: string;
|
||||
parentVersionId: string | null;
|
||||
disabled: boolean;
|
||||
onDirtyChange: (dirty: boolean) => void;
|
||||
onPublished: (version: PublishedCandidate) => void;
|
||||
}) {
|
||||
const [pkg, setPackage] = useState<StrategyVersionPackage | null>(null);
|
||||
const [filename, setFilename] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [pending, setPending] = useState(false);
|
||||
const [uncertain, setUncertain] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const active = useRef(false);
|
||||
const generation = useRef(0);
|
||||
const writing = useRef(false);
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
const intent = useRef<{ pkg: StrategyVersionPackage; key: string } | null>(null);
|
||||
const dirtyCallback = useRef(onDirtyChange);
|
||||
dirtyCallback.current = onDirtyChange;
|
||||
useEffect(() => {
|
||||
active.current = true;
|
||||
return () => {
|
||||
active.current = false;
|
||||
generation.current++;
|
||||
dirtyCallback.current(false);
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
onDirtyChange(Boolean(filename || pkg || uncertain));
|
||||
}, [filename, pkg, uncertain, onDirtyChange]);
|
||||
const select = async (file: File | undefined) => {
|
||||
if (writing.current || intent.current) {
|
||||
return;
|
||||
}
|
||||
const current = ++generation.current;
|
||||
setPackage(null);
|
||||
setError('');
|
||||
setFilename(file?.name ?? '');
|
||||
intent.current = null;
|
||||
if (!file) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
try {
|
||||
const parsed = await readCandidatePackage(await file.text());
|
||||
if (active.current && current === generation.current) {
|
||||
setPackage(parsed);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (active.current && current === generation.current) {
|
||||
setError(cause instanceof Error ? cause.message : 'Package could not be read');
|
||||
}
|
||||
} finally {
|
||||
if (active.current && current === generation.current) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const publish = async () => {
|
||||
if (writing.current || (!intent.current && (disabled || loading || !pkg))) {
|
||||
return;
|
||||
}
|
||||
if (!intent.current && pkg) {
|
||||
intent.current = { pkg, key: crypto.randomUUID() };
|
||||
}
|
||||
const captured = intent.current;
|
||||
if (!captured) {
|
||||
return;
|
||||
}
|
||||
writing.current = true;
|
||||
setPending(true);
|
||||
setError('');
|
||||
try {
|
||||
const saved = await publishCandidate(strategyId, captured.pkg, parentVersionId, captured.key);
|
||||
if (active.current) {
|
||||
intent.current = null;
|
||||
setUncertain(false);
|
||||
setPackage(null);
|
||||
setFilename('');
|
||||
if (fileInput.current) {
|
||||
fileInput.current.value = '';
|
||||
}
|
||||
onDirtyChange(false);
|
||||
onPublished(saved);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (active.current) {
|
||||
setError(cause instanceof Error ? cause.message : 'Publication failed');
|
||||
const lost = !(cause instanceof CandidatePublicationError) || cause.uncertain;
|
||||
setUncertain(lost);
|
||||
if (!lost) {
|
||||
intent.current = null;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
writing.current = false;
|
||||
if (active.current) {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
return (
|
||||
<section
|
||||
aria-label="Publish candidate version"
|
||||
className="space-y-3 border border-border rounded p-4"
|
||||
>
|
||||
<h3 className="font-semibold">Publish candidate version</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Upload a self-contained strategy package. Research evaluates candidate code in the isolated
|
||||
runtime with Rust financial constraints. Warmup is an author declaration; paper promotion
|
||||
requires a separate operator review.
|
||||
</p>
|
||||
<label className="block text-sm">
|
||||
Candidate package (JSON)
|
||||
<input
|
||||
ref={fileInput}
|
||||
type="file"
|
||||
accept="application/json,.json"
|
||||
aria-label="Candidate package (JSON)"
|
||||
className={fieldClass}
|
||||
disabled={disabled || pending || uncertain}
|
||||
onChange={event => void select(event.target.files?.[0])}
|
||||
/>
|
||||
</label>
|
||||
{loading && <p role="status">Checking retained package...</p>}
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{pkg && (
|
||||
<dl className="text-sm break-all space-y-1">
|
||||
<dt>Program</dt>
|
||||
<dd>
|
||||
{pkg.program.strategyId} / {pkg.program.strategyVersion}
|
||||
</dd>
|
||||
<dt>Artifact SHA256</dt>
|
||||
<dd>{pkg.artifact.sha256}</dd>
|
||||
<dt>Dependency lock SHA256</dt>
|
||||
<dd>{pkg.dependencyLock.sha256}</dd>
|
||||
<dt>Author-declared warmup bars</dt>
|
||||
<dd>{pkg.execution?.warmupBars}</dd>
|
||||
<dt>Parent version</dt>
|
||||
<dd>{parentVersionId ?? 'First version in this family'}</dd>
|
||||
</dl>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={pending || (!intent.current && (disabled || loading || !pkg))}
|
||||
onClick={() => void publish()}
|
||||
>
|
||||
{pending
|
||||
? 'Publishing...'
|
||||
: uncertain
|
||||
? 'Retry same publication'
|
||||
: 'Publish immutable candidate'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={pending || uncertain || disabled || !filename}
|
||||
onClick={() => {
|
||||
if (writing.current || intent.current) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
setLoading(false);
|
||||
setPackage(null);
|
||||
setFilename('');
|
||||
setError('');
|
||||
intent.current = null;
|
||||
if (fileInput.current) {
|
||||
fileInput.current.value = '';
|
||||
}
|
||||
}}
|
||||
>
|
||||
Clear package
|
||||
</button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -222,7 +222,7 @@ export function StrategySelection({
|
|||
</Link>
|
||||
<p className="text-xs text-text-muted">
|
||||
{selected.origin === 'candidate'
|
||||
? 'Candidate execution is unavailable until isolated execution is supported.'
|
||||
? 'Candidate research requires an isolated execution declaration and an available sandbox. Eligibility is checked when preparing the run.'
|
||||
: 'Reviewed built-in versions require a supported dataset, explicit policy and matching executable build before execution.'}
|
||||
</p>
|
||||
{family?.archived && (
|
||||
|
|
|
|||
|
|
@ -0,0 +1,105 @@
|
|||
import { z } from 'zod';
|
||||
import { parseStrategyVersionPackage } from '@stock-bot/stock-config/strategy';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
|
||||
export class CandidatePublicationError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get uncertain() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
export interface PublishedCandidate {
|
||||
id: string;
|
||||
strategyId: string;
|
||||
ordinal: number;
|
||||
}
|
||||
const hash = async (value: string) =>
|
||||
[...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value)))]
|
||||
.map(byte => byte.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
|
||||
/** Parse and hash inert bytes. Generated code is never imported or compiled in the browser. */
|
||||
export async function readCandidatePackage(text: string): Promise<StrategyVersionPackage> {
|
||||
const pkg = parseStrategyVersionPackage(JSON.parse(text));
|
||||
if (pkg.execution?.kind !== 'isolated-candidate/v1') {
|
||||
throw new Error('Package must declare isolated-candidate/v1 execution and its warmup bars');
|
||||
}
|
||||
const [artifact, lock] = await Promise.all([
|
||||
hash(pkg.artifact.content),
|
||||
hash(pkg.dependencyLock.content),
|
||||
]);
|
||||
if (artifact !== pkg.artifact.sha256 || lock !== pkg.dependencyLock.sha256) {
|
||||
throw new Error('Package artifact or dependency-lock hash does not match its retained bytes');
|
||||
}
|
||||
return pkg;
|
||||
}
|
||||
export async function publishCandidate(
|
||||
strategyId: string,
|
||||
pkg: StrategyVersionPackage,
|
||||
parentVersionId: string | null,
|
||||
key: string
|
||||
): Promise<PublishedCandidate> {
|
||||
strategyId = z.string().uuid().parse(strategyId).toLowerCase();
|
||||
parentVersionId = z.string().uuid().nullable().parse(parentVersionId)?.toLowerCase() ?? null;
|
||||
const body = JSON.stringify({ package: pkg, parentVersionId });
|
||||
let response: Response;
|
||||
try {
|
||||
response = await apiFetch(
|
||||
`${API_BASE_URL}/api/v2/strategies/${encodeURIComponent(strategyId)}/versions`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
|
||||
body,
|
||||
}
|
||||
);
|
||||
} catch {
|
||||
throw new CandidatePublicationError(
|
||||
'Publication response was lost. Retry the same publication to recover its receipt.',
|
||||
null
|
||||
);
|
||||
}
|
||||
const raw: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const parsed = z.object({ error: z.string() }).safeParse(raw);
|
||||
throw new CandidatePublicationError(
|
||||
parsed.success ? parsed.data.error : `Publication failed (${response.status})`,
|
||||
response.status
|
||||
);
|
||||
}
|
||||
const parsed = z
|
||||
.object({
|
||||
version: z.object({
|
||||
id: z.string().uuid(),
|
||||
strategyId: z.string().uuid(),
|
||||
ordinal: z.number().int().positive(),
|
||||
origin: z.literal('candidate'),
|
||||
parentVersionId: z.string().uuid().nullable(),
|
||||
package: z.object({
|
||||
artifact: z.object({ sha256: z.string() }),
|
||||
dependencyLock: z.object({ sha256: z.string() }),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.safeParse(raw);
|
||||
if (
|
||||
!parsed.success ||
|
||||
response.status !== 201 ||
|
||||
parsed.data.version.strategyId !== strategyId ||
|
||||
parsed.data.version.parentVersionId !== parentVersionId ||
|
||||
parsed.data.version.package.artifact.sha256 !== pkg.artifact.sha256 ||
|
||||
parsed.data.version.package.dependencyLock.sha256 !== pkg.dependencyLock.sha256
|
||||
) {
|
||||
throw new CandidatePublicationError(
|
||||
'Publication response could not be verified. Retry the same publication.',
|
||||
null
|
||||
);
|
||||
}
|
||||
const { id, ordinal } = parsed.data.version;
|
||||
return { id, strategyId, ordinal };
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue