refactor(api): validate shared product response contracts (CL25)

This commit is contained in:
Boki 2026-10-28 13:57:37 -04:00
parent e2292e4883
commit 366a6054bf
22 changed files with 989 additions and 451 deletions

View file

@ -72,6 +72,10 @@
"./diagnostics": {
"types": "./dist/contracts/diagnostics.d.ts",
"default": "./dist/contracts/diagnostics.js"
},
"./product-responses": {
"types": "./dist/contracts/product-responses/index.d.ts",
"default": "./dist/contracts/product-responses/index.js"
}
},
"scripts": {

View file

@ -0,0 +1,55 @@
import { z } from 'zod';
import { datasetHashSchema } from '../backtest';
// Read contracts accept existing identifiers and date-only legacy dates. New-input
// validation belongs to the command schemas; response parsing never rewrites saved data.
const id = z.string().min(1);
const date = z.string().refine(value => Number.isFinite(Date.parse(value)), 'Invalid date');
const parameters = z.record(z.union([z.string(), z.number().finite(), z.boolean()]));
export const backtestResponseSchema = z.object({
id,
name: z.string(),
strategy: id,
strategyVersionId: id.nullable().optional(),
strategyParameters: parameters.nullable().optional(),
symbols: z.array(id),
startDate: date,
endDate: date,
initialCapital: z.number().finite(),
config: z.record(z.unknown()),
createdAt: date,
updatedAt: date,
archivedAt: date.nullable(),
});
export const runResponseSchema = z.object({
id,
originalRunId: id.nullable().optional(),
backtestId: id,
runNumber: z.number().int().positive(),
status: z.enum(['pending', 'running', 'completed', 'failed', 'cancelled', 'paused']),
speedMultiplier: z.number().finite().nullable(),
error: z.string().nullable().optional(),
startedAt: date.nullable().optional(),
completedAt: date.nullable().optional(),
pausedAt: date.nullable().optional(),
progress: z.number().finite(),
cancelRequested: z.boolean().optional(),
attemptNumber: z.number().int().nonnegative().optional(),
currentDate: date.nullable().optional(),
createdAt: date,
updatedAt: date,
dataset: z
.object({
requestedHash: datasetHashSchema.nullable(),
pinnedHash: datasetHashSchema.nullable(),
source: z.enum(['auto', 'questdb', 'eod']).nullable(),
state: z.enum(['requested', 'preparing', 'pinned', 'unavailable', 'unknown']),
})
.optional(),
});
/** JSON wire values, after Date serialization; financial result contracts stay separate. */
export type BacktestResponse = z.infer<typeof backtestResponseSchema>;
export type RunResponse = z.infer<typeof runResponseSchema>;

View file

@ -0,0 +1,4 @@
/** Browser-safe read contracts shared by HTTP producers and consumers. */
export * from './backtests';
export * from './strategies';
export * from './research';

View file

@ -0,0 +1,106 @@
import { z } from 'zod';
import { researchActorSchema, researchFindingSourceSchema } from '../research';
const id = z.string().min(1);
const date = z.string().refine(value => Number.isFinite(Date.parse(value)), 'Invalid date');
const ordinal = z.number().int().positive();
const authorship = {
submittedBy: researchActorSchema,
contentOrigin: z.enum(['human', 'ai', 'unknown']),
};
const record = {
id,
ownerPrincipal: researchActorSchema,
updatedBy: researchActorSchema,
archived: z.boolean(),
createdAt: date,
updatedAt: date,
};
export const researchProjectResponseSchema = z.object({
...record,
title: z.string(),
description: z.string(),
revision: ordinal,
});
export const researchHypothesisRevisionResponseSchema = z.object({
...authorship,
id,
hypothesisId: id,
ordinal,
title: z.string(),
proposition: z.string(),
validationCriteria: z.string(),
validationState: z.literal('unvalidated'),
createdAt: date,
});
export const researchHypothesisResponseSchema = z
.object({
...record,
projectId: id,
latestRevision: researchHypothesisRevisionResponseSchema,
})
.refine(value => value.latestRevision.hypothesisId === value.id, 'Wrong hypothesis revision');
export const researchEvidenceResponseSchema = z.object({
runId: id,
backtestId: id,
strategyVersionId: id.nullable().optional(),
metricsVersion: z.enum(['canonical-analytics/v1', 'legacy-display/v1']),
metricPath: z.string().min(1),
value: z.number().finite().nullable(),
unit: z.enum(['fraction', 'ratio', 'count', 'currency']),
availability: z.enum(['available', 'unavailable']),
unavailableReason: z.string().nullable(),
resultKind: z.enum(['canonical', 'legacy']),
financialEngine: z.enum(['rust', 'native', 'typescript', 'legacy']),
datasetHash: z
.string()
.regex(/^[a-f0-9]{64}$/)
.nullable(),
limitations: z.array(z.object({ code: z.string(), message: z.string() })),
});
export const researchArtifactRevisionResponseSchema = z.object({
...authorship,
id,
artifactId: id,
ordinal,
title: z.string(),
body: z.string(),
validationState: z.literal('unvalidated'),
evidenceState: z.enum(['none', 'referenced']),
evidence: z.array(researchEvidenceResponseSchema),
// Older retained records do not have a source scope.
source: researchFindingSourceSchema.nullable().optional(),
createdAt: date,
});
export const researchArtifactResponseSchema = z
.object({
...record,
projectId: id,
hypothesisRevisionId: id.nullable(),
kind: z.enum(['note', 'finding']),
latestRevision: researchArtifactRevisionResponseSchema,
})
.refine(value => value.latestRevision.artifactId === value.id, 'Wrong artifact revision');
export const researchProjectEnvelopeSchema = z.object({ project: researchProjectResponseSchema });
export const researchProjectsEnvelopeSchema = z.object({
projects: z.array(researchProjectResponseSchema),
});
export const researchHypothesisEnvelopeSchema = z.object({
hypothesis: researchHypothesisResponseSchema,
});
export const researchHypothesesEnvelopeSchema = z.object({
hypotheses: z.array(researchHypothesisResponseSchema),
});
export const researchHypothesisRevisionsEnvelopeSchema = z.object({
revisions: z.array(researchHypothesisRevisionResponseSchema),
});
export const researchArtifactEnvelopeSchema = z.object({
artifact: researchArtifactResponseSchema,
});
export const researchArtifactsEnvelopeSchema = z.object({
artifacts: z.array(researchArtifactResponseSchema),
});
export const researchArtifactRevisionsEnvelopeSchema = z.object({
revisions: z.array(researchArtifactRevisionResponseSchema),
});

View file

@ -0,0 +1,75 @@
import { z } from 'zod';
import { researchActorSchema } from '../research';
import { parseStrategyVersionPackage, strategyVersionPackageSchema } from '../strategy';
const id = z.string().min(1);
const date = z.string().refine(value => Number.isFinite(Date.parse(value)), 'Invalid date');
export const strategyRecordResponseSchema = z.object({
id,
name: z.string(),
description: z.string(),
ownerPrincipal: researchActorSchema,
updatedBy: researchActorSchema,
archived: z.boolean(),
createdAt: date,
updatedAt: date,
});
// A catalog summary deliberately excludes executable content. Reuse the stored
// package schema rather than creating a second parameter or provenance format.
const packageMetadata = strategyVersionPackageSchema.extend({
artifact: strategyVersionPackageSchema.shape.artifact.omit({ content: true }),
dependencyLock: strategyVersionPackageSchema.shape.dependencyLock.omit({ content: true }),
});
export const strategyVersionResponseSchema = z.object({
id,
strategyId: id,
ordinal: z.number().int().positive(),
parentVersionId: id.nullable(),
createdBy: researchActorSchema,
origin: z.enum(['candidate', 'builtin']),
createdAt: date,
package: packageMetadata,
reviewStatus: z.enum(['pending', 'approved', 'revoked']),
runnable: z.literal(false),
reason: z.string(),
});
export const strategyReviewResponseSchema = z.object({
id,
ordinal: z.number().int().positive(),
decision: z.enum(['approve', 'revoke']),
actor: z.literal('operator'),
reason: z.string(),
createdAt: date,
});
export const strategyParameterValidationResponseSchema = z.object({
parameters: z.record(z.union([z.string(), z.number().finite(), z.boolean()])),
runnable: z.literal(false),
reason: z.string(),
});
export const strategyArtifactResponseSchema = z.object({
package: z.unknown().transform((value, ctx) => {
try {
return parseStrategyVersionPackage(value);
} catch {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Invalid retained strategy package' });
return z.NEVER;
}
}),
});
export const strategyResponseSchema = z.object({ strategy: strategyRecordResponseSchema });
export const strategiesResponseSchema = z.object({
strategies: z.array(strategyRecordResponseSchema),
});
export const strategyVersionsResponseSchema = z.object({
versions: z.array(strategyVersionResponseSchema),
});
export const strategyVersionDetailResponseSchema = z.object({
version: strategyVersionResponseSchema,
reviews: z.array(strategyReviewResponseSchema),
});
export const strategyReviewReceiptSchema = z.object({ version: strategyVersionResponseSchema });
export const strategyCloneResponseSchema = z.object({
strategy: strategyRecordResponseSchema,
version: strategyVersionResponseSchema,
});

View file

@ -101,6 +101,12 @@ const packageSchema = z
})
.strict();
// Response contracts reuse the retained package shape without evaluating executable bytes.
export {
parameterSchema as strategyParameterSchema,
packageSchema as strategyVersionPackageSchema,
};
const period = (minimum: number): StrategyParameterProperty => ({
type: 'integer',
minimum,

View file

@ -83,7 +83,7 @@ export class BacktestService {
runId: run?.id,
status: run?.status ?? 'pending',
updatedAt: run?.updatedAt ?? backtest.updatedAt,
error: run?.error,
error: run?.error ?? undefined,
};
}
}

View file

@ -1,6 +1,7 @@
import type { QueryResultRow } from 'pg';
import type { IServiceContainer } from '@stock-bot/services';
import type { BacktestDefinitionInput } from '@stock-bot/stock-config/backtest';
import type { BacktestResponse, RunResponse } from '@stock-bot/stock-config/product-responses';
import type {
BacktestRunDatasetSelection,
ResearchActor,
@ -28,38 +29,30 @@ export interface BacktestRequest {
strategyParameters?: Record<string, StrategyParameterValue> | null;
}
export interface Backtest {
id: string;
archivedAt: string | null;
/** The HTTP serializer converts these database Dates to the shared JSON wire shape. */
export interface Backtest
extends Omit<BacktestResponse, 'startDate' | 'endDate' | 'createdAt' | 'updatedAt'> {
strategyVersionId: string | null;
strategyParameters: Record<string, StrategyParameterValue> | null;
name: string;
strategy: string;
symbols: string[];
startDate: Date;
endDate: Date;
initialCapital: number;
config: Record<string, unknown>;
createdAt: Date;
updatedAt: Date;
}
export interface Run {
export interface Run
extends Omit<
RunResponse,
'startedAt' | 'completedAt' | 'pausedAt' | 'currentDate' | 'createdAt' | 'updatedAt'
> {
originalRunId: string | null;
dataset: BacktestRunDatasetSelection;
id: string;
backtestId: string;
runNumber: number;
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused';
speedMultiplier: number | null;
error?: string;
startedAt?: Date;
completedAt?: Date;
pausedAt?: Date;
progress: number;
startedAt?: Date | null;
completedAt?: Date | null;
pausedAt?: Date | null;
cancelRequested: boolean;
attemptNumber: number;
currentDate?: Date;
currentDate?: Date | null;
createdAt: Date;
updatedAt: Date;
}

View file

@ -175,11 +175,11 @@ export function RunControls({ run, onPause, onResume, onCancel, onSpeedChange }:
<span className="text-text-secondary">Duration:</span>
<span className="ml-2 text-text-primary font-medium">{formatDuration()}</span>
</div>
{run.currentSimulationDate && (
{run.currentDate && (
<div className="col-span-2">
<span className="text-text-secondary">Current Date:</span>
<span className="ml-2 text-text-primary font-medium">
{formatDate(run.currentSimulationDate)}
{formatDate(run.currentDate)}
</span>
</div>
)}

View file

@ -18,50 +18,25 @@ import type {
CanonicalStoredSourcePreparation,
ResearchRunResult,
} from '@stock-bot/stock-config/canonical-research';
import {
backtestResponseSchema,
runResponseSchema,
type BacktestResponse as Backtest,
type RunResponse as Run,
} from '@stock-bot/stock-config/product-responses';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import type {
BacktestRunDatasetSelection,
BacktestRunResult,
HistoricalDatasetCatalogEntry,
StrategyParameterValue,
} from '@stock-bot/types';
import { API_BASE_URL, apiFetch as fetch } from '@/lib/api';
import { requestJson } from '@/lib/requestJson';
export interface Backtest {
id: string;
name: string;
strategy: string;
strategyVersionId?: string | null;
strategyParameters?: Record<string, StrategyParameterValue> | null;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
config: Record<string, unknown>;
createdAt: string;
updatedAt: string;
archivedAt: string | null;
}
export interface Run {
id: string;
originalRunId?: string | null;
backtestId: string;
runNumber: number;
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused';
speedMultiplier: number | null;
error?: string;
startedAt?: string;
completedAt?: string;
pausedAt?: string;
progress: number;
cancelRequested?: boolean;
attemptNumber?: number;
currentSimulationDate?: string;
createdAt: string;
updatedAt: string;
dataset?: BacktestRunDatasetSelection;
}
export type {
BacktestResponse as Backtest,
RunResponse as Run,
} from '@stock-bot/stock-config/product-responses';
export interface CreateBacktestRequest {
name: string;
@ -112,6 +87,28 @@ export class ReproductionSubmissionError extends Error {
return this.status === null || this.status >= 500;
}
}
function productRequest<T>(
path: string,
init: RequestInit,
status: number,
parse: (body: unknown) => T
): Promise<T> {
return requestJson(`${API_BASE_URL}/api/v2/${path}`, init, status, parse, {
create: message => new Error(message),
invalid: () =>
new Error(
'The backtest response could not be verified. Check saved runs before submitting again.'
),
lostMessage: 'The backtest response was lost. Check saved runs before submitting again.',
failureLabel: 'Backtest request failed',
});
}
const jsonRequest = (method: string, body: unknown): RequestInit => ({
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const acknowledgement = z.object({ message: z.string() });
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
const nullableText = (value: unknown) => value === null || typeof value === 'string';
@ -456,45 +453,33 @@ export const backtestApiV2 = {
};
},
async reproduceRun(originalRunId: string, submissionKey: string): Promise<Run> {
let response: Response;
try {
response = await fetch(
`${API_BASE_URL}/api/v2/runs/${encodeURIComponent(originalRunId)}/reproduce`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': submissionKey },
body: '{}',
return requestJson(
`${API_BASE_URL}/api/v2/runs/${encodeURIComponent(originalRunId)}/reproduce`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': submissionKey },
body: '{}',
},
202,
body => {
const run = runResponseSchema.parse(body);
if (run.id === originalRunId || run.originalRunId !== originalRunId) {
throw new Error('Wrong original run identity');
}
);
} catch {
throw new ReproductionSubmissionError(
'The reproduction response was lost. Retry with this same submission key to recover the accepted run.',
null
);
}
if (!response.ok) {
const error = await requestError(response, 'Could not reproduce original run');
throw new ReproductionSubmissionError(error.message, response.status);
}
const body: unknown = await response.json().catch(() => null);
if (
response.status !== 202 ||
!isRecord(body) ||
typeof body.id !== 'string' ||
!body.id ||
body.id === originalRunId ||
typeof body.backtestId !== 'string' ||
body.originalRunId !== originalRunId ||
!['pending', 'running', 'completed', 'failed', 'cancelled', 'paused'].includes(
String(body.status)
)
) {
throw new ReproductionSubmissionError(
'The accepted reproduction response could not be verified. Retry with this same submission key.',
null
);
}
return body as unknown as Run;
return run;
},
{
create: (message, status) => new ReproductionSubmissionError(message, status),
invalid: () =>
new ReproductionSubmissionError(
'The accepted reproduction response could not be verified. Retry with this same submission key.',
null
),
lostMessage:
'The reproduction response was lost. Retry with this same submission key to recover the accepted run.',
failureLabel: 'Could not reproduce original run',
}
);
},
async reproductionComparison(
id: string,
@ -636,130 +621,95 @@ export const backtestApiV2 = {
}
return (await response.json()).dataset;
},
// Backtest operations
async createBacktest(request: CreateBacktestRequest): Promise<Backtest> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
// Web saves are deliberately separate from durable run submission.
body: JSON.stringify({ ...request, autoStart: false }),
});
if (!response.ok) {
throw await requestError(response, 'Failed to create backtest');
}
return response.json();
// Templates are saved separately from durable run submission.
createBacktest(request: CreateBacktestRequest): Promise<Backtest> {
return productRequest(
'backtests',
jsonRequest('POST', { ...request, autoStart: false }),
201,
backtestResponseSchema.parse
);
},
async getBacktest(id: string): Promise<Backtest> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`);
if (!response.ok) {
throw new Error(`Failed to get backtest: ${response.statusText}`);
}
return response.json();
getBacktest(id: string): Promise<Backtest> {
return productRequest(
`backtests/${encodeURIComponent(id)}`,
{},
200,
backtestResponseSchema.parse
);
},
async listBacktests(
listBacktests(
limit = 50,
offset = 0,
includeArchived = false,
signal?: AbortSignal
): Promise<Backtest[]> {
const response = await fetch(
`${API_BASE_URL}/api/v2/backtests?limit=${limit}&offset=${offset}${includeArchived ? '&includeArchived=true' : ''}`,
{ signal }
return productRequest(
`backtests?limit=${limit}&offset=${offset}${includeArchived ? '&includeArchived=true' : ''}`,
{ signal },
200,
backtestResponseSchema.array().parse
);
if (!response.ok) {
throw await requestError(response, 'Failed to list backtests');
}
return response.json();
},
async updateBacktest(id: string, updates: Partial<CreateBacktestRequest>): Promise<Backtest> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
updateBacktest(id: string, updates: Partial<CreateBacktestRequest>): Promise<Backtest> {
return productRequest(
`backtests/${encodeURIComponent(id)}`,
jsonRequest('PUT', updates),
200,
backtestResponseSchema.parse
);
},
deleteBacktest(id: string): Promise<void> {
return productRequest(
`backtests/${encodeURIComponent(id)}`,
{ method: 'DELETE' },
204,
z.undefined().parse
);
},
setBacktestArchived(id: string, archived: boolean): Promise<Backtest> {
return productRequest(
`backtests/${encodeURIComponent(id)}/archive`,
jsonRequest('POST', { archived }),
200,
backtestResponseSchema.parse
);
},
createRun(backtestId: string, request?: CreateRunRequest, submissionKey?: string): Promise<Run> {
return productRequest(
`backtests/${encodeURIComponent(backtestId)}/runs`,
{
...jsonRequest('POST', request || {}),
headers: {
'Content-Type': 'application/json',
...(submissionKey ? { 'Idempotency-Key': submissionKey } : {}),
},
},
body: JSON.stringify(updates),
});
if (!response.ok) {
throw await requestError(response, 'Failed to update backtest');
}
return response.json();
202,
body => {
const run = runResponseSchema.parse(body);
if (run.backtestId !== backtestId) {
throw new Error('Wrong backtest identity');
}
return run;
}
);
},
async deleteBacktest(id: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, {
method: 'DELETE',
});
if (!response.ok) {
throw await requestError(response, 'Failed to delete backtest');
}
listRuns(backtestId: string): Promise<Run[]> {
return productRequest(
`backtests/${encodeURIComponent(backtestId)}/runs`,
{},
200,
runResponseSchema.array().parse
);
},
async setBacktestArchived(id: string, archived: boolean): Promise<Backtest> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}/archive`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ archived }),
});
if (!response.ok) {
throw await requestError(response, 'Failed to change archive status');
}
return response.json();
},
// Run operations
async createRun(
backtestId: string,
request?: CreateRunRequest,
submissionKey?: string
): Promise<Run> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(submissionKey ? { 'Idempotency-Key': submissionKey } : {}),
},
body: JSON.stringify(request || {}),
});
if (!response.ok) {
throw await requestError(response, 'Failed to create run');
}
return response.json();
},
async listRuns(backtestId: string): Promise<Run[]> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`);
if (!response.ok) {
throw new Error(`Failed to list runs: ${response.statusText}`);
}
return response.json();
},
async getRun(id: string, signal?: AbortSignal): Promise<Run> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}`, { signal });
if (!response.ok) {
throw new Error(`Failed to get run: ${response.statusText}`);
}
return response.json();
getRun(id: string, signal?: AbortSignal): Promise<Run> {
return productRequest(
`runs/${encodeURIComponent(id)}`,
{ signal },
200,
runResponseSchema.parse
);
},
async getRunResults(runId: string, signal?: AbortSignal): Promise<ResearchRunResult> {
@ -777,48 +727,36 @@ export const backtestApiV2 = {
},
async pauseRun(id: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/pause`, {
method: 'POST',
});
if (!response.ok) {
throw new Error(`Failed to pause run: ${response.statusText}`);
}
await productRequest(
`runs/${encodeURIComponent(id)}/pause`,
{ method: 'POST' },
200,
acknowledgement.parse
);
},
async resumeRun(id: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/resume`, {
method: 'POST',
});
if (!response.ok) {
throw new Error(`Failed to resume run: ${response.statusText}`);
}
await productRequest(
`runs/${encodeURIComponent(id)}/resume`,
{ method: 'POST' },
200,
acknowledgement.parse
);
},
async cancelRun(id: string, signal?: AbortSignal): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/cancel`, {
method: 'POST',
signal,
});
if (!response.ok) {
throw new Error(`Failed to cancel run: ${response.statusText}`);
}
await productRequest(
`runs/${encodeURIComponent(id)}/cancel`,
{ method: 'POST', signal },
202,
acknowledgement.parse
);
},
async updateRunSpeed(id: string, speedMultiplier: number | null): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/speed`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ speedMultiplier }),
});
if (!response.ok) {
throw new Error(`Failed to update run speed: ${response.statusText}`);
}
await productRequest(
`runs/${encodeURIComponent(id)}/speed`,
jsonRequest('PUT', { speedMultiplier }),
200,
acknowledgement.parse
);
},
// Note: WebSocket connections are handled by the useWebSocket hook

View file

@ -1,5 +1,15 @@
import type { z } from 'zod';
import { researchFindingSourceSchema } from '@stock-bot/stock-config/research';
import { z } from 'zod';
import {
researchArtifactEnvelopeSchema,
researchArtifactRevisionsEnvelopeSchema,
researchArtifactsEnvelopeSchema,
researchHypothesesEnvelopeSchema,
researchHypothesisEnvelopeSchema,
researchHypothesisRevisionsEnvelopeSchema,
researchProjectEnvelopeSchema,
researchProjectsEnvelopeSchema,
strategiesResponseSchema,
} from '@stock-bot/stock-config/product-responses';
import type {
createResearchArtifactSchema,
createResearchHypothesisSchema,
@ -8,15 +18,8 @@ import type {
reviseResearchHypothesisSchema,
updateResearchProjectSchema,
} from '@stock-bot/stock-config/research';
import type {
ResearchArtifact,
ResearchArtifactRevision,
ResearchHypothesis,
ResearchHypothesisRevision,
ResearchProject,
StrategyRecord,
} from '@stock-bot/types';
import { API_BASE_URL, apiFetch } from '@/lib/api';
import { API_BASE_URL } from '@/lib/api';
import { requestJson } from '@/lib/requestJson';
export type ProjectInput = z.input<typeof createResearchProjectSchema>;
export type ProjectUpdate = z.input<typeof updateResearchProjectSchema>;
@ -37,86 +40,23 @@ export class ResearchApiError extends Error {
return this.status === null || this.status >= 500;
}
}
type ResponseField =
| 'project'
| 'projects'
| 'strategies'
| 'hypothesis'
| 'hypotheses'
| 'artifact'
| 'artifacts'
| 'revisions';
const record = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
const identified = (value: unknown): value is Record<string, unknown> =>
record(value) && typeof value.id === 'string' && value.id.length > 0;
function validSource(value: Record<string, unknown>): boolean {
if (value.source === undefined || value.source === null) {
return true;
}
const parsed = researchFindingSourceSchema.safeParse(value.source);
if (!parsed.success) {
return false;
}
value.source = parsed.data;
return true;
}
function validEnvelope(body: unknown, field: ResponseField): boolean {
if (!record(body)) {
return false;
}
const validItem = (item: unknown): boolean => {
if (!identified(item)) {
return false;
}
if (field === 'project' || field === 'projects') {
return typeof item.title === 'string' && Number.isInteger(item.revision);
}
if (['hypothesis', 'hypotheses', 'artifact', 'artifacts'].includes(field)) {
return (
typeof item.projectId === 'string' &&
identified(item.latestRevision) &&
validSource(item.latestRevision)
);
}
return validSource(item);
};
const value = body[field];
return ['project', 'hypothesis', 'artifact'].includes(field)
? validItem(value)
: Array.isArray(value) && value.every(validItem);
}
async function request<T>(
function request<S extends z.ZodTypeAny>(
path: string,
init: RequestInit,
field: ResponseField | null
): Promise<T> {
let response;
try {
response = await apiFetch(`${API_BASE_URL}/api/v2/${path}`, init);
} catch (cause) {
if (init?.signal?.aborted) {
throw cause;
}
throw new ResearchApiError(
schema: S,
status = 200
): Promise<z.output<S>> {
return requestJson(`${API_BASE_URL}/api/v2/${path}`, init, status, body => schema.parse(body), {
create: (message, code) => new ResearchApiError(message, code),
invalid: () =>
new ResearchApiError(
'The research response could not be read. Check saved records before submitting again.',
null
),
lostMessage:
'The research request response was lost. Check saved records before submitting again.',
null
);
}
const body = response.status === 204 ? undefined : await response.json().catch(() => undefined);
if (!response.ok) {
throw new ResearchApiError(
typeof body?.error === 'string' ? body.error : `Research request failed (${response.status})`,
response.status
);
}
if (field === null ? response.status !== 204 : !validEnvelope(body, field)) {
throw new ResearchApiError(
'The research response could not be read. Check saved records before submitting again.',
null
);
}
return body as T;
failureLabel: 'Research request failed',
});
}
const id = encodeURIComponent;
const json = (method: string, body: unknown): RequestInit => ({
@ -126,119 +66,113 @@ const json = (method: string, body: unknown): RequestInit => ({
});
export const researchApi = {
listProjects: (includeArchived = false, signal?: AbortSignal) =>
request<{ projects: ResearchProject[] }>(
request(
`research-projects?includeArchived=${includeArchived}`,
{ signal },
'projects'
researchProjectsEnvelopeSchema
),
createProject: (body: ProjectInput) =>
request<{ project: ResearchProject }>('research-projects', json('POST', body), 'project'),
request('research-projects', json('POST', body), researchProjectEnvelopeSchema, 201),
getProject: (projectId: string, signal?: AbortSignal) =>
request<{ project: ResearchProject }>(
`research-projects/${id(projectId)}`,
{ signal },
'project'
),
request(`research-projects/${id(projectId)}`, { signal }, researchProjectEnvelopeSchema),
updateProject: (projectId: string, body: ProjectUpdate) =>
request<{ project: ResearchProject }>(
request(
`research-projects/${id(projectId)}`,
json('PATCH', body),
'project'
researchProjectEnvelopeSchema
),
listStrategies: (projectId: string, signal?: AbortSignal) =>
request<{ strategies: StrategyRecord[] }>(
request(
`research-projects/${id(projectId)}/strategies`,
{
signal,
},
'strategies'
strategiesResponseSchema
),
linkStrategy: (projectId: string, strategyId: string) =>
request<void>(
request(
`research-projects/${id(projectId)}/strategies/${id(strategyId)}`,
{
method: 'PUT',
},
null
z.undefined(),
204
),
unlinkStrategy: (projectId: string, strategyId: string) =>
request<void>(
request(
`research-projects/${id(projectId)}/strategies/${id(strategyId)}`,
{
method: 'DELETE',
},
null
z.undefined(),
204
),
listHypotheses: (projectId: string, includeArchived = false, signal?: AbortSignal) =>
request<{ hypotheses: ResearchHypothesis[] }>(
request(
`research-projects/${id(projectId)}/hypotheses?includeArchived=${includeArchived}`,
{ signal },
'hypotheses'
researchHypothesesEnvelopeSchema
),
createHypothesis: (projectId: string, body: HypothesisInput) =>
request<{ hypothesis: ResearchHypothesis }>(
request(
`research-projects/${id(projectId)}/hypotheses`,
json('POST', body),
'hypothesis'
researchHypothesisEnvelopeSchema,
201
),
getHypothesis: (hypothesisId: string, signal?: AbortSignal) =>
request<{ hypothesis: ResearchHypothesis }>(
`hypotheses/${id(hypothesisId)}`,
{ signal },
'hypothesis'
),
request(`hypotheses/${id(hypothesisId)}`, { signal }, researchHypothesisEnvelopeSchema),
hypothesisRevisions: (hypothesisId: string, signal?: AbortSignal) =>
request<{ revisions: ResearchHypothesisRevision[] }>(
request(
`hypotheses/${id(hypothesisId)}/revisions`,
{ signal },
'revisions'
researchHypothesisRevisionsEnvelopeSchema
),
reviseHypothesis: (hypothesisId: string, body: HypothesisRevisionInput) =>
request<{ hypothesis: ResearchHypothesis }>(
request(
`hypotheses/${id(hypothesisId)}/revisions`,
json('POST', body),
'hypothesis'
researchHypothesisEnvelopeSchema,
201
),
archiveHypothesis: (hypothesisId: string, archived: boolean) =>
request<{ hypothesis: ResearchHypothesis }>(
request(
`hypotheses/${id(hypothesisId)}`,
json('PATCH', { archived }),
'hypothesis'
researchHypothesisEnvelopeSchema
),
listArtifacts: (projectId: string, includeArchived = false, signal?: AbortSignal) =>
request<{ artifacts: ResearchArtifact[] }>(
request(
`research-projects/${id(projectId)}/analysis-artifacts?includeArchived=${includeArchived}`,
{ signal },
'artifacts'
researchArtifactsEnvelopeSchema
),
createArtifact: (projectId: string, body: ArtifactInput) =>
request<{ artifact: ResearchArtifact }>(
request(
`research-projects/${id(projectId)}/analysis-artifacts`,
json('POST', body),
'artifact'
researchArtifactEnvelopeSchema,
201
),
getArtifact: (artifactId: string, signal?: AbortSignal) =>
request<{ artifact: ResearchArtifact }>(
`analysis-artifacts/${id(artifactId)}`,
{ signal },
'artifact'
),
request(`analysis-artifacts/${id(artifactId)}`, { signal }, researchArtifactEnvelopeSchema),
artifactRevisions: (artifactId: string, signal?: AbortSignal) =>
request<{ revisions: ResearchArtifactRevision[] }>(
request(
`analysis-artifacts/${id(artifactId)}/revisions`,
{ signal },
'revisions'
researchArtifactRevisionsEnvelopeSchema
),
reviseArtifact: (artifactId: string, body: ArtifactRevisionInput) =>
request<{ artifact: ResearchArtifact }>(
request(
`analysis-artifacts/${id(artifactId)}/revisions`,
json('POST', body),
'artifact'
researchArtifactEnvelopeSchema,
201
),
archiveArtifact: (artifactId: string, archived: boolean) =>
request<{ artifact: ResearchArtifact }>(
request(
`analysis-artifacts/${id(artifactId)}`,
json('PATCH', { archived }),
'artifact'
researchArtifactEnvelopeSchema
),
};

View file

@ -1,23 +1,34 @@
import type {
ParameterValidationResult,
StrategyParameterValue,
StrategyRecord,
StrategyReviewEvent,
StrategyVersionPackage,
StrategyVersionSummary,
} from '@stock-bot/types';
import { API_BASE_URL, apiFetch } from '@/lib/api';
import type { z } from 'zod';
import {
strategiesResponseSchema,
strategyArtifactResponseSchema,
strategyCloneResponseSchema,
strategyParameterValidationResponseSchema,
strategyResponseSchema,
strategyReviewReceiptSchema,
strategyVersionDetailResponseSchema,
strategyVersionsResponseSchema,
} from '@stock-bot/stock-config/product-responses';
import type { StrategyParameterValue } from '@stock-bot/types';
import { API_BASE_URL } from '@/lib/api';
import { requestJson } from '@/lib/requestJson';
export type Parameters = Record<string, StrategyParameterValue>;
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const response = await apiFetch(`${API_BASE_URL}/api/v2/${path}`, init);
const body = await response.json().catch(() => null);
if (!response.ok) {
throw new Error(
typeof body?.error === 'string' ? body.error : `Strategy request failed (${response.status})`
);
}
return body as T;
function request<S extends z.ZodTypeAny>(
path: string,
init: RequestInit,
schema: S,
status = 200
): Promise<z.output<S>> {
return requestJson(`${API_BASE_URL}/api/v2/${path}`, init, status, body => schema.parse(body), {
create: message => new Error(message),
invalid: () =>
new Error(
'The strategy response could not be verified. Check saved records before submitting again.'
),
lostMessage: 'The strategy response was lost. Check saved records before submitting again.',
failureLabel: 'Strategy request failed',
});
}
const json = (method: string, body: unknown, key?: string): RequestInit => ({
method,
@ -26,40 +37,41 @@ const json = (method: string, body: unknown, key?: string): RequestInit => ({
});
const id = encodeURIComponent;
export const strategyApi = {
list: (signal?: AbortSignal) =>
request<{ strategies: StrategyRecord[] }>('strategies', { signal }),
list: (signal?: AbortSignal) => request('strategies', { signal }, strategiesResponseSchema),
get: (strategyId: string, signal?: AbortSignal) =>
request<{ strategy: StrategyRecord }>(`strategies/${id(strategyId)}`, { signal }),
request(`strategies/${id(strategyId)}`, { signal }, strategyResponseSchema),
create: (body: { name: string; description: string }) =>
request<{ strategy: StrategyRecord }>('strategies', json('POST', body)),
request('strategies', json('POST', body), strategyResponseSchema, 201),
update: (strategyId: string, body: { name?: string; description?: string; archived?: boolean }) =>
request<{ strategy: StrategyRecord }>(`strategies/${id(strategyId)}`, json('PATCH', body)),
request(`strategies/${id(strategyId)}`, json('PATCH', body), strategyResponseSchema),
versions: (strategyId: string, signal?: AbortSignal) =>
request<{ versions: StrategyVersionSummary[] }>(`strategies/${id(strategyId)}/versions`, {
signal,
}),
request(`strategies/${id(strategyId)}/versions`, { signal }, strategyVersionsResponseSchema),
version: (versionId: string, signal?: AbortSignal) =>
request<{ version: StrategyVersionSummary; reviews: StrategyReviewEvent[] }>(
`strategy-versions/${id(versionId)}`,
{ signal }
),
request(`strategy-versions/${id(versionId)}`, { signal }, strategyVersionDetailResponseSchema),
artifact: (versionId: string, signal?: AbortSignal) =>
request<{ package: StrategyVersionPackage }>(`strategy-versions/${id(versionId)}/artifact`, {
signal,
}),
request(
`strategy-versions/${id(versionId)}/artifact`,
{ signal },
strategyArtifactResponseSchema
),
validate: (versionId: string, parameters: Parameters) =>
request<ParameterValidationResult>(
request(
`strategy-versions/${id(versionId)}/validate`,
json('POST', { parameters })
json('POST', { parameters }),
strategyParameterValidationResponseSchema
),
review: (versionId: string, body: { decision: 'approve'; reason: string }) =>
request<{ version: StrategyVersionSummary }>(
request(
`strategy-versions/${id(versionId)}/reviews`,
json('POST', body)
json('POST', body),
strategyReviewReceiptSchema,
201
),
clone: (versionId: string, body: { name: string; description: string }, key: string) =>
request<{ strategy: StrategyRecord; version: StrategyVersionSummary }>(
request(
`strategy-versions/${id(versionId)}/clone`,
json('POST', body, key)
json('POST', body, key),
strategyCloneResponseSchema,
201
),
};

View file

@ -25,7 +25,8 @@ export async function requestJson<T>(
}
throw errors.create(errors.lostMessage, null);
}
const body: unknown = await response.json().catch(() => null);
const body: unknown =
response.status === 204 ? undefined : await response.json().catch(() => null);
if (!response.ok) {
const message =
body && typeof body === 'object' && 'error' in body && typeof body.error === 'string'

View file

@ -17,3 +17,5 @@ Agents use root-reserved disjoint files in the integration worktree. Root alone
- **CL27:** Root rebuilt DI and independently ran ingestion-handler-initialization: 6 passed, 27 assertions. Enabled-instance identity, two-container isolation, failure propagation, operations waiting for init, unchanged schedules and duplicate registration covered. Scoped lint/format passed.
- **CL34:** Independent provider normalization suite: 6 passed, 10 assertions. Disposable PostgreSQL pipeline safety: 8 passed, 28 assertions, including verified mapping preservation, unverified update and replay identity. Scoped lint/format passed; active QM session manager preserved.
- **CL25:** Shared response wire schemas and server type aliases; root mapping/date/invalid-response/run-control tests 59 passed (388 assertions), agent complete focused UI/transport/reproduction set 358 passed. Scoped lint/format passed. Preserves historical optional records and submission receipt/idempotency guards.

View file

@ -1,6 +1,6 @@
# Canonical development backlog
**Active: E13 architecture cleanup, CL22–CL35 (5/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md).
**Active: E13 architecture cleanup, CL22–CL35 (6/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md).
**Current scheduled backlog: 99/99 complete.** The owner resumed performance and authorized review of all seven conditions. P08 and O02 are implemented; five optional extensions remain deliberately deferred, and four merged IDs are redirects. This is not a claim that all 108 retained IDs were implemented. [Decisions, measurements and validation](../conditional-review.md).

View file

@ -3810,7 +3810,7 @@
"epic": "E13",
"priority": "P1",
"severity": "High",
"status": "ready",
"status": "done",
"dependencies": [],
"decision_dependencies": [],
"task_file": "backlog/tasks/CL25.md",
@ -3820,7 +3820,9 @@
"completed_commit": null,
"blocker": null,
"release_gates": [],
"completion_evidence": "architecture-cleanup-execution.md"
"completion_evidence": "architecture-cleanup-execution.md",
"integration_state": "accepted",
"validation": "Shared response wire schemas and server type aliases; root mapping/date/invalid-response/run-control tests 59 passed (388 assertions), agent complete focused UI/transport/reproduction set 358 passed. Scoped lint/format passed. Preserves historical optional records and submission receipt/idempotency guards."
},
{
"id": "CL26",
@ -3853,7 +3855,7 @@
"complexity": "M",
"assignment": null,
"write_locks": ["CL27"],
"completed_commit": null,
"completed_commit": "5c9e32d0ef1811acd2b79a59c896d55233c2179e",
"blocker": null,
"release_gates": [],
"completion_evidence": "architecture-cleanup-execution.md",
@ -3902,7 +3904,7 @@
"epic": "E13",
"priority": "P2",
"severity": "Medium",
"status": "blocked",
"status": "ready",
"dependencies": ["CL25"],
"decision_dependencies": [],
"task_file": "backlog/tasks/CL30.md",
@ -3910,7 +3912,7 @@
"assignment": null,
"write_locks": ["CL30"],
"completed_commit": null,
"blocker": "Implementation dependencies",
"blocker": null,
"release_gates": [],
"completion_evidence": "architecture-cleanup-execution.md"
},
@ -3981,7 +3983,7 @@
"complexity": "M",
"assignment": null,
"write_locks": ["CL34"],
"completed_commit": null,
"completed_commit": "e2292e4883516cf2e4cb5d19d3dff003f60567b7",
"blocker": null,
"release_gates": [],
"completion_evidence": "architecture-cleanup-execution.md",
@ -10391,7 +10393,7 @@
],
"work_policy": "Root integrates/commits reviewed tasks; agents own disjoint explicit files in the root integration worktree. Only root builds shared outputs and runs combined gates. No isolated native agent build claim.",
"first_wave": ["CL22", "CL23", "CL24"],
"completed": 5,
"last_verification": "Independent provider normalization suite: 6 passed, 10 assertions. Disposable PostgreSQL pipeline safety: 8 passed, 28 assertions, including verified mapping preservation, unverified update and replay identity. Scoped lint/format passed; active QM session manager preserved."
"completed": 6,
"last_verification": "Shared response wire schemas and server type aliases; root mapping/date/invalid-response/run-control tests 59 passed (388 assertions), agent complete focused UI/transport/reproduction set 358 passed. Scoped lint/format passed. Preserves historical optional records and submission receipt/idempotency guards."
}
}

View file

@ -18,3 +18,7 @@ Response roundtrips; malformed/wrong identity/abort/lost acknowledgement; types
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
Shared response wire schemas and server type aliases; root mapping/date/invalid-response/run-control tests 59 passed (388 assertions), agent complete focused UI/transport/reproduction set 358 passed. Scoped lint/format passed. Preserves historical optional records and submission receipt/idempotency guards.

View file

@ -83,7 +83,11 @@ function request(path: string, method = 'GET') {
}
return found;
}
function reply(pending: Request, body: unknown, status = 200) {
function reply(
pending: Request,
body: unknown,
status = pending.method === 'POST' && pending.path === '/api/v2/backtests' ? 201 : 200
) {
pending.settled = true;
pending.resolve(Response.json(body, { status }));
}
@ -729,7 +733,7 @@ describe('run selection and persisted status authority', () => {
await flush(() => reply(first, run('A', 'running', { progress: 20 })));
expect(requests.filter(item => item.path === '/api/v2/runs/A')).toHaveLength(3);
await flush(() => fail(request('/api/v2/runs/A')));
expect(latest.error).toContain('Network unavailable');
expect(latest.error).toContain('The backtest response was lost');
expect(latest.currentRun?.progress).toBe(20);
expect(polls()).toBe(1);
await advance(1000);
@ -793,7 +797,9 @@ describe('run selection and persisted status authority', () => {
await selectRunning('A', initial);
await flush(() => click('Cancel run'));
expect(host.textContent).toContain('Cancellation requested');
await flush(() => reply(request('/api/v2/runs/A/cancel', 'POST'), { accepted: true }, 202));
await flush(() =>
reply(request('/api/v2/runs/A/cancel', 'POST'), { message: 'Cancellation requested' }, 202)
);
expect(latest.currentRun?.status).toBe(initial);
const acknowledged = initial === 'pending' ? 'cancelled' : 'running';
await flush(() =>
@ -831,9 +837,11 @@ describe('run selection and persisted status authority', () => {
await flush(() => click('Cancel run'));
await flush(() => fail(request('/api/v2/runs/A/cancel', 'POST')));
expect(latest.cancelRequested).toBe(false);
expect(latest.error).toContain('Network unavailable');
expect(latest.error).toContain('The backtest response was lost');
await flush(() => click('Cancel run'));
await flush(() => reply(request('/api/v2/runs/A/cancel', 'POST'), { accepted: true }, 202));
await flush(() =>
reply(request('/api/v2/runs/A/cancel', 'POST'), { message: 'Cancellation requested' }, 202)
);
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
expect(latest.currentRun?.status).toBe('completed');
@ -889,7 +897,9 @@ describe('actual detail page result states', () => {
await mountPage('running');
await flush(() => click('Cancel run'));
expect(host.textContent).toContain('Cancellation requested');
await flush(() => reply(request('/api/v2/runs/A/cancel', 'POST'), {}, 202));
await flush(() =>
reply(request('/api/v2/runs/A/cancel', 'POST'), { message: 'Cancellation requested' }, 202)
);
expect(host.textContent).not.toContain('Run cancelled');
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'cancelled')));
expect(host.textContent).toContain('Run cancelled');
@ -939,14 +949,41 @@ describe('actual detail page result states', () => {
});
async function selectBacktestStrategy(preselected = false) {
const family = { id: 'family', name: 'Test strategy', archived: false };
const family = {
id: 'family',
name: 'Test strategy',
description: '',
archived: false,
ownerPrincipal: 'operator',
updatedBy: 'operator',
createdAt: '2026-01-01',
updatedAt: '2026-01-01',
};
const version = {
id: 'version-one',
strategyId: 'family',
ordinal: 1,
origin: 'builtin',
parentVersionId: null,
createdBy: 'operator',
createdAt: '2026-01-01',
reviewStatus: 'approved',
runnable: false,
reason: 'Configure canonical settings',
package: {
version: 1,
program: {
strategyId: 'fixture',
strategyVersion: 'v1',
apiVersion: 'canonical-ts/v1',
checkpointVersion: 'fixture/v1',
},
artifact: { format: 'esm-bundle/v1', entryExport: 'createFixture', sha256: 'a'.repeat(64) },
dependencyLock: { format: 'bun-lock/v1', sha256: 'b'.repeat(64) },
source: { revision: 'c'.repeat(40), dirty: false },
build: { tool: 'bun', version: '1.2.17', target: 'browser' },
parameterSchema: {
version: 1,
type: 'object',
properties: {},
required: [],
@ -1390,7 +1427,7 @@ describe('explicit save and repeat-safe run submission', () => {
await flush(() => reply(request('/api/v2/runs/B'), run('B', 'failed', { error: 'B failure' })));
await flush(() => fail(submitting));
expect(pageLocation).toBe('/backtests/definition/run/B');
expect(host.textContent).toContain('Run submission failed: Network unavailable');
expect(host.textContent).toContain('Run submission failed: The backtest response was lost');
expect(host.textContent).toContain('Run failed: B failure');
await flush(() => click('Retry submission'));
const retry = request('/api/v2/backtests/definition/runs', 'POST');
@ -1409,7 +1446,7 @@ describe('explicit save and repeat-safe run submission', () => {
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
expect(latest.isSubmitting).toBe(true);
await flush(() => fail(first));
expect(latest.submissionError).toContain('Network unavailable');
expect(latest.submissionError).toContain('The backtest response was lost');
await flush(() => {
void latest.updateBacktest('definition', { initialCapital: 2000 });
});
@ -1450,7 +1487,7 @@ describe('explicit save and repeat-safe run submission', () => {
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
await flush(() => reply(first, { error: 'Submission unavailable' }, 503));
expect(host.textContent).toContain('Run submission failed');
expect(host.textContent).toContain('Network unavailable');
expect(host.textContent).toContain('The backtest response was lost');
expect(host.textContent).toContain('Submit the current configuration');
await flush(() => click('Retry submission'));
const retry = request('/api/v2/backtests/definition/runs', 'POST');
@ -1698,7 +1735,7 @@ describe('template archive and restore', () => {
expect(original.signal?.aborted).toBe(true);
await flush(() => (lateFailure ? fail(original) : reply(original, [definition])));
expect(host.textContent).toContain('Loading backtests...');
expect(host.textContent).not.toContain('Network unavailable');
expect(host.textContent).not.toContain('The backtest response was lost');
await flush(() => reply(current, []));
expect(host.textContent).toContain('No backtests yet.');
expect(host.textContent).not.toContain('Loading backtests...');

View file

@ -0,0 +1,351 @@
import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';
import { GlobalWindow } from 'happy-dom';
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import type { IServiceContainer } from '@stock-bot/services';
import type {
ResearchArtifact,
ResearchAuthorship,
ResearchHypothesis,
StrategyVersionSummary,
} from '@stock-bot/types';
import {
backtestResponseSchema,
researchArtifactResponseSchema,
researchHypothesisResponseSchema,
researchProjectResponseSchema,
runResponseSchema,
strategyVersionResponseSchema,
type RunResponse,
} from '../../apps/stock/config/src/contracts/product-responses';
import { builtinCatalogDescriptors } from '../../apps/stock/config/src/contracts/strategy';
import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes';
import { createStrategyRoutes } from '../../apps/stock/web-api/src/routes/strategies.routes';
import { mapBacktest, mapRun } from '../../apps/stock/web-api/src/services/backtests/mapping';
import { RunControls } from '../../apps/stock/web-app/src/features/backtest/components/RunControls';
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
const original = Object.getOwnPropertyDescriptor(globalThis, 'window');
let backtest: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2');
let research: typeof import('../../apps/stock/web-app/src/features/research/services/researchApi');
let strategies: typeof import('../../apps/stock/web-app/src/features/strategies/services/strategyApi');
beforeAll(async () => {
Object.defineProperty(globalThis, 'window', { value: browser, configurable: true });
backtest = await import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2');
research = await import('../../apps/stock/web-app/src/features/research/services/researchApi');
strategies = await import(
'../../apps/stock/web-app/src/features/strategies/services/strategyApi'
);
});
beforeEach(() => {
Object.defineProperty(globalThis, 'window', { value: browser, configurable: true });
});
afterAll(() => {
if (original) {
Object.defineProperty(globalThis, 'window', original);
} else {
Reflect.deleteProperty(globalThis, 'window');
}
browser.happyDOM.abort();
});
const now = new Date('2026-10-28T14:32:00Z');
const backtestId = '11111111-1111-4111-8111-111111111111';
const runId = '22222222-2222-4222-8222-222222222222';
const row = {
id: backtestId,
name: 'Saved research',
strategy: 'sma_crossover',
symbols: ['AAPL.US'],
start_date: now,
end_date: new Date('2026-10-29'),
initial_capital: '10000',
config: {},
created_at: now,
updated_at: now,
archived_at: null,
};
const run = () =>
mapRun({
id: runId,
backtest_id: backtestId,
run_number: 1,
status: 'running',
speed_multiplier: null,
error: null,
started_at: now,
completed_at: null,
paused_at: null,
progress: '12.5',
current_simulation_date: now,
created_at: now,
updated_at: now,
cancel_requested: false,
attempt_number: 1,
});
function respond(body: unknown, status = 200) {
const fetch = mock(async (_input: unknown, _init?: RequestInit) =>
status === 204 ? new Response(null, { status }) : Response.json(body, { status })
);
browser.fetch = fetch as unknown as typeof browser.fetch;
return fetch;
}
test('real server backtest/run mappings survive JSON serialization and display the server clock field', async () => {
const mapped = mapBacktest(row);
respond(mapped);
const saved = await backtest.backtestApiV2.getBacktest(backtestId);
expect(saved).toEqual(backtestResponseSchema.parse(await Response.json(mapped).json()));
expect(saved.initialCapital).toBe(10000);
expect(saved.startDate).toBe(now.toISOString());
expect(saved.archivedAt).toBeNull();
respond(run());
const savedRun = await backtest.backtestApiV2.getRun(runId);
expect(savedRun.currentDate).toBe(now.toISOString());
expect(savedRun.completedAt).toBeNull();
expect(savedRun.dataset?.state).toBe('unknown');
const noop = () => {};
const html = renderToStaticMarkup(
createElement(RunControls, {
run: savedRun,
onPause: noop,
onResume: noop,
onCancel: noop,
onSpeedChange: noop,
})
);
expect(html).toContain(now.toLocaleString());
expect(html).toContain('12.5%');
});
test('existing optional fields remain optional without accepting malformed rendered fields', async () => {
const legacy: RunResponse = {
id: 'old-run',
backtestId: 'old-template',
runNumber: 1,
status: 'completed',
speedMultiplier: null,
progress: 100,
createdAt: '2024-01-01',
updatedAt: '2024-01-01',
};
expect(runResponseSchema.parse(legacy)).toEqual(legacy);
const serialized = await Response.json(mapBacktest(row)).json();
for (const bad of [
{ ...serialized, symbols: 'AAPL' },
{ ...serialized, initialCapital: '10000' },
{ ...serialized, config: null },
]) {
respond(bad);
await expect(backtest.backtestApiV2.getBacktest(backtestId)).rejects.toThrow(
'could not be verified'
);
}
for (const bad of [
{ ...legacy, progress: '100' },
{ ...legacy, runNumber: null },
{ ...legacy, currentDate: 'not a date' },
]) {
respond(bad);
await expect(backtest.backtestApiV2.getRun('old-run')).rejects.toThrow('could not be verified');
}
});
test('strategy and research records roundtrip from actual routes through browser clients', async () => {
const databaseRow = {
...row,
title: 'Research project',
description: 'Unvalidated narrative',
revision: 1,
owner_principal: 'operator',
updated_by: 'operator',
};
const container = {
postgres: { query: async () => ({ rows: [databaseRow] }) },
logger: { error: () => {} },
} as unknown as IServiceContainer;
const researchRoutes = createResearchRoutes(container);
browser.fetch = ((input: unknown, init?: RequestInit) =>
researchRoutes.request(String(input), init)) as unknown as typeof browser.fetch;
const projects = await research.researchApi.listProjects();
expect(projects.projects).toEqual([
researchProjectResponseSchema.parse({
id: backtestId,
title: databaseRow.title,
description: databaseRow.description,
revision: 1,
ownerPrincipal: 'operator',
updatedBy: 'operator',
archived: false,
createdAt: now.toISOString(),
updatedAt: now.toISOString(),
}),
]);
const catalogRoutes = createStrategyRoutes(container);
browser.fetch = ((input: unknown, init?: RequestInit) =>
catalogRoutes.request(String(input), init)) as unknown as typeof browser.fetch;
const catalog = await strategies.strategyApi.list();
expect(catalog.strategies[0]).toMatchObject({ id: backtestId, name: row.name, archived: false });
expect(catalog.strategies[0]?.createdAt).toBe(now.toISOString());
});
const authorship: ResearchAuthorship & { createdAt: string } = {
submittedBy: 'operator',
contentOrigin: 'human',
createdAt: now.toISOString(),
};
const record: Omit<ResearchHypothesis, 'latestRevision'> = {
id: 'record',
projectId: 'project',
ownerPrincipal: 'operator',
updatedBy: 'operator',
archived: false,
createdAt: now.toISOString(),
updatedAt: now.toISOString(),
};
const hypothesis: ResearchHypothesis = {
...record,
latestRevision: {
...authorship,
id: 'revision',
hypothesisId: 'record',
ordinal: 1,
title: 'Hypothesis',
proposition: 'Testable claim',
validationCriteria: '',
validationState: 'unvalidated',
},
};
const artifact: ResearchArtifact = {
...record,
kind: 'note',
hypothesisRevisionId: null,
latestRevision: {
...authorship,
id: 'revision',
artifactId: 'record',
ordinal: 1,
title: 'Notes',
body: '',
validationState: 'unvalidated',
evidenceState: 'none',
evidence: [],
},
};
test('research parsers validate nested rendered fields and revision ownership, preserving legacy source omission', async () => {
expect(researchHypothesisResponseSchema.parse(hypothesis)).toEqual(hypothesis);
expect(researchArtifactResponseSchema.parse(artifact)).toEqual(artifact);
for (const malformed of [
{ ...artifact, latestRevision: { ...artifact.latestRevision, evidence: null } },
{ ...artifact, latestRevision: { ...artifact.latestRevision, contentOrigin: 'verified' } },
{ ...artifact, latestRevision: { ...artifact.latestRevision, artifactId: 'another' } },
{ ...artifact, latestRevision: { ...artifact.latestRevision, source: {} } },
]) {
respond({ artifact: malformed }, 201);
await expect(
research.researchApi.createArtifact('project', { kind: 'note', title: 'Notes', body: '' })
).rejects.toMatchObject({ ambiguous: true, status: null });
}
respond({ projects: [{ id: 'project', title: 'Partial', revision: 1 }] });
await expect(research.researchApi.listProjects()).rejects.toBeInstanceOf(
research.ResearchApiError
);
});
test('catalog schema reuses retained parameter and package shapes without requiring a new execution declaration', async () => {
const builtin = builtinCatalogDescriptors[0]!;
const version: StrategyVersionSummary = {
id: 'version',
strategyId: 'family',
ordinal: 1,
parentVersionId: null,
createdBy: 'operator',
origin: 'builtin',
createdAt: now.toISOString(),
package: {
version: 1,
program: builtin.program,
parameterSchema: builtin.parameterSchema,
artifact: {
format: 'esm-bundle/v1',
entryExport: builtin.entryExport,
sha256: 'a'.repeat(64),
},
dependencyLock: { format: 'bun-lock/v1', sha256: 'b'.repeat(64) },
source: { revision: 'c'.repeat(40), dirty: false },
build: { tool: 'bun', version: '1.2.17', target: 'browser' },
},
reviewStatus: 'approved',
runnable: false,
reason: 'Explicit policy required',
};
const parsed: StrategyVersionSummary = strategyVersionResponseSchema.parse(version);
expect(parsed).toEqual(version);
respond({ versions: [version] });
const catalog: { versions: StrategyVersionSummary[] } =
await strategies.strategyApi.versions('family');
expect(catalog).toEqual({ versions: [version] });
respond({ versions: [{ ...version, package: { ...version.package, parameterSchema: {} } }] });
await expect(strategies.strategyApi.versions('family')).rejects.toThrow('could not be verified');
});
test('reproduction receipts preserve identity, status, idempotency key and no automatic write retry', async () => {
const originalRunId = '33333333-3333-4333-8333-333333333333';
const accepted = { ...run(), originalRunId };
const fetch = respond(accepted, 202);
const value = await backtest.backtestApiV2.reproduceRun(originalRunId, 'retained-key');
expect(value.id).toBe(runId);
expect(fetch).toHaveBeenCalledTimes(1);
expect(fetch.mock.calls[0]?.[1]).toMatchObject({
credentials: 'include',
headers: { 'Idempotency-Key': 'retained-key' },
});
for (const [body, status] of [
[{ ...accepted, originalRunId: runId }, 202],
[accepted, 200],
[{ id: runId }, 202],
] as const) {
const calls = respond(body, status);
await expect(
backtest.backtestApiV2.reproduceRun(originalRunId, 'retained-key')
).rejects.toMatchObject({ ambiguous: true, status: null });
expect(calls).toHaveBeenCalledTimes(1);
}
respond({ error: 'Review revoked' }, 409);
await expect(
backtest.backtestApiV2.reproduceRun(originalRunId, 'retained-key')
).rejects.toMatchObject({ ambiguous: false, status: 409, message: 'Review revoked' });
});
test('204 acknowledgements are accepted only where intended; cancellations remain acknowledged 202 writes', async () => {
respond(null, 204);
await expect(research.researchApi.linkStrategy('project', 'strategy')).resolves.toBeUndefined();
respond(null, 204);
await expect(backtest.backtestApiV2.deleteBacktest(backtestId)).resolves.toBeUndefined();
respond({ message: 'Cancellation requested' }, 202);
await expect(backtest.backtestApiV2.cancelRun(runId)).resolves.toBeUndefined();
const calls = respond({}, 202);
await expect(backtest.backtestApiV2.cancelRun(runId)).rejects.toThrow('could not be verified');
expect(calls).toHaveBeenCalledTimes(1);
respond({}, 200);
await expect(research.researchApi.linkStrategy('project', 'strategy')).rejects.toMatchObject({
ambiguous: true,
});
});
test('all shared transports preserve abort causes and classify lost research writes as ambiguous without retries', async () => {
const controller = new AbortController();
controller.abort();
const cause = new DOMException('Cancelled', 'AbortError');
const fetch = mock(async () => {
throw cause;
});
browser.fetch = fetch as unknown as typeof browser.fetch;
await expect(backtest.backtestApiV2.getRun(runId, controller.signal)).rejects.toBe(cause);
await expect(strategies.strategyApi.list(controller.signal)).rejects.toBe(cause);
await expect(research.researchApi.listProjects(false, controller.signal)).rejects.toBe(cause);
await expect(
research.researchApi.createProject({ title: 'Potentially saved' })
).rejects.toMatchObject({ ambiguous: true, status: null });
expect(fetch).toHaveBeenCalledTimes(4);
});

View file

@ -439,7 +439,9 @@ describe('saved-result finding', () => {
201
)
);
expect(host.textContent).toContain('saved finding response could not be verified');
expect(host.textContent).toMatch(
/saved finding response could not be verified|The research response could not be read/
);
expect(host.textContent).not.toContain('Finding saved.');
expect(field('Finding title').value).toBe('Exact finding');
expect(field('Finding body').value).toBe('Keep this narrative');
@ -453,7 +455,9 @@ describe('saved-result finding', () => {
await draft();
await preflight();
await flush(() => reply(post(), { artifact: { ...acceptedFinding(), archived: true } }, 201));
expect(host.textContent).toContain('saved finding response could not be verified');
expect(host.textContent).toMatch(
/saved finding response could not be verified|The research response could not be read/
);
expect(button('Save finding').disabled).toBe(true);
});
test.each([
@ -507,7 +511,9 @@ describe('saved-result finding', () => {
break;
}
await flush(() => reply(post(), { artifact: saved }, 201));
expect(host.textContent).toContain('saved finding response could not be verified');
expect(host.textContent).toMatch(
/saved finding response could not be verified|The research response could not be read/
);
expect(host.textContent).toContain('Check saved records before creating another');
expect(host.textContent).not.toContain('Finding saved.');
expect(host.textContent).not.toContain('Open saved finding');

View file

@ -60,7 +60,7 @@ function request(path: string, method = 'GET') {
}
return found;
}
function reply(item: Pending, body: unknown, status = 200) {
function reply(item: Pending, body: unknown, status = item.method === 'POST' ? 201 : 200) {
item.settled = true;
item.resolve(status === 204 ? new Response(null, { status }) : Response.json(body, { status }));
}
@ -787,8 +787,8 @@ describe('research workspace', () => {
201
)
);
expect(host.textContent).toContain(
'The saved research entry response could not be verified.'
expect(host.textContent).toMatch(
/The saved research entry response could not be verified\.|The research response could not be read\./
);
expect(field(kind === 'hypothesis' ? 'Hypothesis title' : 'Note title').value).toBe(
creationDraft.title
@ -996,7 +996,9 @@ describe('research workspace', () => {
},
})
);
expect(host.textContent).toContain('The saved revision response could not be verified.');
expect(host.textContent).toMatch(
/The saved revision response could not be verified\.|The research response could not be read\./
);
expect(field('Revision title').value).toBe(revisionDraft.title);
expect(field('Revision body').value).toBe(revisionDraft.body);
expect(field('Revision content origin').value).toBe('unknown');
@ -1045,7 +1047,9 @@ describe('research workspace', () => {
artifact: { ...saved, latestRevision: { ...saved.latestRevision, ...change } },
})
);
expect(host.textContent).toContain('The saved revision response could not be verified.');
expect(host.textContent).toMatch(
/The saved revision response could not be verified\.|The research response could not be read\./
);
expect(field('Revision body').value).toBe(revisionDraft.body);
expect(button('Save new revision').disabled).toBe(true);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
@ -1240,7 +1244,9 @@ describe('research workspace', () => {
},
})
);
expect(host.textContent).toContain('The archive response could not be verified.');
expect(host.textContent).toMatch(
/The archive response could not be verified\.|The research response could not be read\./
);
expect(field('Revision title').value).toBe(revisionDraft.title);
expect(field('Revision body').value).toBe(revisionDraft.body);
expect(button('Save new revision').disabled).toBe(true);
@ -1259,7 +1265,9 @@ describe('research workspace', () => {
: artifact('a1', { archived: true });
const patch = await submitEntryArchive(original);
await flush(() => reply(patch, { [kind]: original }));
expect(host.textContent).toContain('The archive response could not be verified.');
expect(host.textContent).toMatch(
/The archive response could not be verified\.|The research response could not be read\./
);
expect(button('Restore entry').disabled).toBe(true);
expect(requests.filter(item => !item.settled)).toHaveLength(0);
});
@ -1514,7 +1522,7 @@ describe('research workspace', () => {
unavailableReason: null,
resultKind: 'canonical',
financialEngine: 'rust',
datasetHash: 'frozen-dataset',
datasetHash: 'f'.repeat(64),
limitations: [],
},
],

View file

@ -699,7 +699,7 @@ describe('strategy workbench', () => {
autoStart: false,
});
expect((post.body as { config: object }).config).not.toHaveProperty('fastPeriod');
await flush(() => reply(post, definition));
await flush(() => reply(post, definition, 201));
expect(saved).toEqual(definition);
expect(requests.some(item => item.path.endsWith('/runs'))).toBe(false);
});