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

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