864 lines
27 KiB
TypeScript
864 lines
27 KiB
TypeScript
/** Authorized research API client. No strategy import, financial simulation, or trading controls. */
|
|
import { z } from 'zod';
|
|
import {
|
|
chronologicalValidationInputSchema,
|
|
chronologicalValidationSubmissionSchema,
|
|
type ChronologicalValidationInput,
|
|
type ChronologicalValidationSubmission,
|
|
} from '@stock-bot/stock-config/chronological-validation';
|
|
import {
|
|
costSensitivityInputSchema,
|
|
costSensitivitySubmissionSchema,
|
|
type CostSensitivityInput,
|
|
type CostSensitivitySubmission,
|
|
} from '@stock-bot/stock-config/cost-sensitivity';
|
|
import {
|
|
experimentComparisonInputSchema,
|
|
type ExperimentComparisonInput,
|
|
} from '@stock-bot/stock-config/experiment-comparison';
|
|
import {
|
|
experimentInputSchema,
|
|
experimentSubmissionSchema,
|
|
type ExperimentInput,
|
|
type ExperimentSubmission,
|
|
} from '@stock-bot/stock-config/experiments';
|
|
import {
|
|
createResearchArtifactSchema,
|
|
createResearchHypothesisSchema,
|
|
researchActorSchema,
|
|
researchEvidenceReferenceSchema,
|
|
researchFindingSourceSchema,
|
|
} from '@stock-bot/stock-config/research';
|
|
import {
|
|
researchAgentBudgetSchema,
|
|
researchAgentIdSchema,
|
|
} from '@stock-bot/stock-config/research-agents';
|
|
import {
|
|
parseChronologicalValidationPreview,
|
|
parseCostSensitivityPreview,
|
|
parseExperimentComparison,
|
|
parseExperimentDetail,
|
|
parseExperimentPreview,
|
|
parseValidationDetail,
|
|
parseWalkForwardDetail,
|
|
parseWalkForwardPreview,
|
|
parseWorkbenchExperimentDetail,
|
|
validationReceiptSchema,
|
|
type ValidationDetailView,
|
|
type WorkbenchExperimentDetailView,
|
|
} from '@stock-bot/stock-config/research-responses';
|
|
import {
|
|
canonicalStrategyJson,
|
|
parseStrategyVersionPackage,
|
|
} from '@stock-bot/stock-config/strategy';
|
|
import {
|
|
walkForwardInputSchema,
|
|
walkForwardSubmissionSchema,
|
|
type WalkForwardInput,
|
|
type WalkForwardSubmission,
|
|
} from '@stock-bot/stock-config/walk-forward';
|
|
import type { StrategyVersionPackage } from '@stock-bot/types';
|
|
|
|
const uuid = z
|
|
.string()
|
|
.uuid()
|
|
.transform(value => value.toLowerCase());
|
|
const hash = z.string().regex(/^[a-f0-9]{64}$/);
|
|
const keySchema = z.string().regex(/^[\x21-\x7e]{1,200}$/);
|
|
const object = z.record(z.unknown());
|
|
const id = (value: string) => encodeURIComponent(uuid.parse(value));
|
|
const same = (a: unknown, b: unknown) => canonicalStrategyJson(a) === canonicalStrategyJson(b);
|
|
const expect = (condition: unknown): void => {
|
|
if (!condition) {
|
|
throw new Error('Research response does not match the requested identity');
|
|
}
|
|
};
|
|
const envelope = (body: unknown, field: string) => object.parse(body)[field];
|
|
const strategyRecord = z.object({
|
|
id: uuid,
|
|
name: z.string(),
|
|
description: z.string(),
|
|
ownerPrincipal: researchAgentIdSchema,
|
|
archived: z.boolean(),
|
|
});
|
|
const versionRecord = z.object({
|
|
id: uuid,
|
|
strategyId: uuid,
|
|
ordinal: z.number().int().positive(),
|
|
origin: z.enum(['candidate', 'builtin']),
|
|
createdBy: researchAgentIdSchema,
|
|
parentVersionId: uuid.nullable(),
|
|
package: z.object({
|
|
artifact: z.object({ sha256: hash }),
|
|
dependencyLock: z.object({ sha256: hash }),
|
|
}),
|
|
});
|
|
const hypothesisRecord = z.object({
|
|
id: uuid,
|
|
projectId: uuid,
|
|
latestRevision: z.object({
|
|
id: uuid,
|
|
ordinal: z.number().int().positive(),
|
|
title: z.string(),
|
|
proposition: z.string(),
|
|
validationCriteria: z.string(),
|
|
contentOrigin: z.literal('ai'),
|
|
submittedBy: researchAgentIdSchema,
|
|
validationState: z.literal('unvalidated'),
|
|
}),
|
|
});
|
|
const findingRecord = z.object({
|
|
id: uuid,
|
|
projectId: uuid,
|
|
hypothesisRevisionId: uuid.nullable(),
|
|
kind: z.enum(['note', 'finding']),
|
|
latestRevision: z.object({
|
|
id: uuid,
|
|
title: z.string(),
|
|
body: z.string(),
|
|
contentOrigin: z.literal('ai'),
|
|
submittedBy: researchAgentIdSchema,
|
|
validationState: z.literal('unvalidated'),
|
|
evidenceState: z.enum(['none', 'referenced']),
|
|
source: researchFindingSourceSchema.nullable(),
|
|
evidence: z.array(
|
|
z
|
|
.object({
|
|
runId: uuid,
|
|
strategyVersionId: uuid.nullable().optional(),
|
|
metricsVersion: z.literal('canonical-analytics/v1'),
|
|
metricPath: z.string(),
|
|
value: z.number().finite().nullable(),
|
|
availability: z.enum(['available', 'unavailable']),
|
|
unavailableReason: z.string().nullable(),
|
|
datasetHash: hash,
|
|
resultKind: z.literal('canonical'),
|
|
financialEngine: z.literal('rust'),
|
|
limitations: z.array(z.object({ code: z.string(), message: z.string() })),
|
|
})
|
|
.refine(
|
|
metric =>
|
|
metric.availability === 'available'
|
|
? metric.value !== null && metric.unavailableReason === null
|
|
: metric.value === null &&
|
|
typeof metric.unavailableReason === 'string' &&
|
|
metric.unavailableReason.trim().length > 0,
|
|
'Metric availability must match its value and reason'
|
|
)
|
|
),
|
|
}),
|
|
});
|
|
|
|
export class ResearchRequestError extends Error {
|
|
constructor(
|
|
message: string,
|
|
public readonly status: number | null,
|
|
/** A mutation may have committed. Reuse its exact receipt; never generate a new one blindly. */
|
|
public readonly uncertain: boolean,
|
|
public readonly operation: string
|
|
) {
|
|
super(message);
|
|
this.name = 'ResearchRequestError';
|
|
}
|
|
}
|
|
export class ResearchWaitExpired<T> extends Error {
|
|
constructor(public readonly last: T | null) {
|
|
super('Research polling deadline reached; accepted jobs remain saved and can be reopened');
|
|
this.name = 'ResearchWaitExpired';
|
|
}
|
|
}
|
|
export interface PollOptions<T> {
|
|
timeoutMs: number;
|
|
intervalMs?: number;
|
|
signal?: AbortSignal;
|
|
onUpdate?: (value: T) => void;
|
|
}
|
|
type ClientOptions = {
|
|
origin: string;
|
|
token: string;
|
|
fetch?: typeof fetch;
|
|
requestTimeoutMs?: number;
|
|
};
|
|
type HypothesisInput = z.input<typeof createResearchHypothesisSchema>;
|
|
type FindingInput = z.input<typeof createResearchArtifactSchema>;
|
|
|
|
/** The backend is authoritative for grants, quotas, evidence, and financial constraints. */
|
|
export class ResearchClient {
|
|
readonly #origin: string;
|
|
readonly #token: string;
|
|
readonly #fetch: typeof fetch;
|
|
readonly #timeout: number;
|
|
|
|
constructor(options: ClientOptions) {
|
|
const origin = new URL(options.origin);
|
|
if (
|
|
!['https:', 'http:'].includes(origin.protocol) ||
|
|
origin.username ||
|
|
origin.password ||
|
|
origin.search ||
|
|
origin.hash ||
|
|
origin.pathname !== '/' ||
|
|
(origin.protocol === 'http:' &&
|
|
!['localhost', '127.0.0.1', '[::1]'].includes(origin.hostname))
|
|
) {
|
|
throw new Error('Use an HTTPS API origin or local loopback HTTP origin without a path');
|
|
}
|
|
if (!/^sb-research\.[A-Za-z0-9_-]+$/.test(options.token)) {
|
|
throw new Error('A research-only credential is required');
|
|
}
|
|
this.#origin = origin.origin;
|
|
this.#token = options.token;
|
|
this.#fetch = options.fetch ?? globalThis.fetch;
|
|
this.#timeout = z
|
|
.number()
|
|
.int()
|
|
.positive()
|
|
.max(2147483647)
|
|
.parse(options.requestTimeoutMs ?? 30000);
|
|
}
|
|
|
|
async #request<T>(
|
|
path: string,
|
|
method: 'GET' | 'POST' | 'PUT',
|
|
status: number,
|
|
parse: (body: unknown) => T,
|
|
body?: unknown,
|
|
key?: string,
|
|
signal?: AbortSignal
|
|
): Promise<T> {
|
|
const operation = `${method} ${path}`;
|
|
const mutation = method !== 'GET';
|
|
if (key !== undefined) {
|
|
keySchema.parse(key);
|
|
}
|
|
// Capture once. A caller changing its draft while awaiting IO cannot change this request.
|
|
const bytes = body === undefined ? undefined : JSON.stringify(body);
|
|
const deadline = timedSignal(this.#timeout);
|
|
const requestSignal = signal ? AbortSignal.any([signal, deadline.signal]) : deadline.signal;
|
|
try {
|
|
let response: Response;
|
|
try {
|
|
response = await abortable(
|
|
() =>
|
|
this.#fetch(`${this.#origin}/api/v2/${path}`, {
|
|
method,
|
|
body: bytes,
|
|
redirect: 'error',
|
|
credentials: 'omit',
|
|
headers: {
|
|
Authorization: `Bearer ${this.#token}`,
|
|
'Content-Type': 'application/json',
|
|
...(key === undefined ? {} : { 'Idempotency-Key': key }),
|
|
},
|
|
signal: requestSignal,
|
|
}),
|
|
requestSignal
|
|
);
|
|
} catch {
|
|
throw new ResearchRequestError(
|
|
'Research response lost or aborted. Reopen saved work before resubmitting.',
|
|
null,
|
|
mutation,
|
|
operation
|
|
);
|
|
}
|
|
const payload: unknown =
|
|
response.status === 204
|
|
? undefined
|
|
: await abortable(() => response.json(), requestSignal).catch(() => undefined);
|
|
if (!response.ok) {
|
|
const error = z.object({ error: z.string() }).safeParse(payload);
|
|
throw new ResearchRequestError(
|
|
error.success ? error.data.error : `Research request failed (${response.status})`,
|
|
response.status,
|
|
mutation && response.status >= 500,
|
|
operation
|
|
);
|
|
}
|
|
try {
|
|
expect(response.status === status);
|
|
return parse(payload);
|
|
} catch {
|
|
throw new ResearchRequestError(
|
|
'Research response identity or evidence could not be verified',
|
|
null,
|
|
mutation,
|
|
operation
|
|
);
|
|
}
|
|
} finally {
|
|
deadline.dispose();
|
|
}
|
|
}
|
|
|
|
budget(signal?: AbortSignal) {
|
|
return this.#request(
|
|
'research-agent/budget',
|
|
'GET',
|
|
200,
|
|
value => researchAgentBudgetSchema.parse(value),
|
|
undefined,
|
|
undefined,
|
|
signal
|
|
);
|
|
}
|
|
compareExperiments(input: ExperimentComparisonInput, signal?: AbortSignal) {
|
|
const normalized = experimentComparisonInputSchema.parse(input);
|
|
return this.#request(
|
|
`experiments/compare?${new URLSearchParams(normalized)}`,
|
|
'GET',
|
|
200,
|
|
value => parseExperimentComparison(envelope(value, 'comparison'), normalized),
|
|
undefined,
|
|
undefined,
|
|
signal
|
|
);
|
|
}
|
|
createHypothesis(projectId: string, input: HypothesisInput) {
|
|
projectId = uuid.parse(projectId);
|
|
const body = createResearchHypothesisSchema.parse({ ...input, contentOrigin: 'ai' });
|
|
return this.#request(
|
|
`research-projects/${id(projectId)}/hypotheses`,
|
|
'POST',
|
|
201,
|
|
value => {
|
|
const saved = hypothesisRecord.parse(envelope(value, 'hypothesis'));
|
|
expect(
|
|
saved.projectId === projectId &&
|
|
same(
|
|
{
|
|
title: saved.latestRevision.title,
|
|
proposition: saved.latestRevision.proposition,
|
|
validationCriteria: saved.latestRevision.validationCriteria,
|
|
contentOrigin: saved.latestRevision.contentOrigin,
|
|
},
|
|
body
|
|
)
|
|
);
|
|
return saved;
|
|
},
|
|
body
|
|
);
|
|
}
|
|
createStrategy(input: { name: string; description: string }) {
|
|
const body = z
|
|
.object({ name: z.string().trim().min(1), description: z.string() })
|
|
.strict()
|
|
.parse(input);
|
|
return this.#request(
|
|
'strategies',
|
|
'POST',
|
|
201,
|
|
value => {
|
|
const saved = strategyRecord.parse(envelope(value, 'strategy'));
|
|
expect(saved.name === body.name && saved.description === body.description);
|
|
return saved;
|
|
},
|
|
body
|
|
);
|
|
}
|
|
linkStrategy(projectId: string, strategyId: string) {
|
|
projectId = uuid.parse(projectId);
|
|
strategyId = uuid.parse(strategyId);
|
|
return this.#request(
|
|
`research-projects/${id(projectId)}/strategies/${id(strategyId)}`,
|
|
'PUT',
|
|
204,
|
|
() => undefined
|
|
);
|
|
}
|
|
/** Null selects automatic catalog lineage; receipt retries retain the original parent. */
|
|
publishVersion(
|
|
strategyId: string,
|
|
input: StrategyVersionPackage,
|
|
key: string,
|
|
parentVersionId: string | null = null
|
|
) {
|
|
strategyId = uuid.parse(strategyId);
|
|
const pkg = parseStrategyVersionPackage(input);
|
|
if (parentVersionId !== null) {
|
|
parentVersionId = uuid.parse(parentVersionId);
|
|
}
|
|
return this.#request(
|
|
`strategies/${id(strategyId)}/versions`,
|
|
'POST',
|
|
201,
|
|
value => {
|
|
const saved = versionRecord.parse(envelope(value, 'version'));
|
|
expect(
|
|
saved.strategyId === strategyId &&
|
|
saved.origin === 'candidate' &&
|
|
(parentVersionId === null || saved.parentVersionId === parentVersionId) &&
|
|
saved.package.artifact.sha256 === pkg.artifact.sha256 &&
|
|
saved.package.dependencyLock.sha256 === pkg.dependencyLock.sha256
|
|
);
|
|
return saved;
|
|
},
|
|
{ package: pkg, parentVersionId },
|
|
key
|
|
);
|
|
}
|
|
previewExperiment(input: ExperimentInput, signal?: AbortSignal) {
|
|
const body = experimentInputSchema.parse({
|
|
...input,
|
|
backtestId: uuid.parse(input.backtestId),
|
|
});
|
|
return this.#request(
|
|
'experiments/preview',
|
|
'POST',
|
|
200,
|
|
value => {
|
|
const preview = parseExperimentPreview(envelope(value, 'preview'));
|
|
expect(same(preview.input, body));
|
|
return preview;
|
|
},
|
|
body,
|
|
undefined,
|
|
signal
|
|
);
|
|
}
|
|
submitExperiment(input: ExperimentSubmission, key: string) {
|
|
const body = experimentSubmissionSchema.parse({
|
|
...input,
|
|
backtestId: uuid.parse(input.backtestId),
|
|
});
|
|
return this.#request(
|
|
'experiments',
|
|
'POST',
|
|
202,
|
|
value => {
|
|
const saved = parseExperimentDetail(envelope(value, 'experiment'));
|
|
const { previewHash, ...original } = body;
|
|
expect(saved.previewHash === previewHash && same(saved.preview.input, original));
|
|
return saved;
|
|
},
|
|
body,
|
|
key
|
|
);
|
|
}
|
|
experiment(experimentId: string, signal?: AbortSignal) {
|
|
experimentId = uuid.parse(experimentId);
|
|
return this.#request(
|
|
`experiments/${id(experimentId)}`,
|
|
'GET',
|
|
200,
|
|
value => {
|
|
const saved = parseWorkbenchExperimentDetail(envelope(value, 'experiment'));
|
|
expect(saved.id === experimentId);
|
|
return saved;
|
|
},
|
|
undefined,
|
|
undefined,
|
|
signal
|
|
);
|
|
}
|
|
cancelExperiment(experimentId: string) {
|
|
experimentId = uuid.parse(experimentId);
|
|
return this.#request(
|
|
`experiments/${id(experimentId)}/cancel`,
|
|
'POST',
|
|
200,
|
|
value => {
|
|
const saved = parseWorkbenchExperimentDetail(envelope(value, 'experiment'));
|
|
expect(saved.id === experimentId && saved.cancelRequested);
|
|
return saved;
|
|
},
|
|
{}
|
|
);
|
|
}
|
|
previewCosts(input: CostSensitivityInput, signal?: AbortSignal) {
|
|
const body = costSensitivityInputSchema.parse({
|
|
...input,
|
|
backtestId: uuid.parse(input.backtestId),
|
|
});
|
|
return this.#request(
|
|
'experiments/cost-sensitivity/preview',
|
|
'POST',
|
|
200,
|
|
value => {
|
|
const preview = parseCostSensitivityPreview(envelope(value, 'preview'));
|
|
expect(same(preview.input, body));
|
|
return preview;
|
|
},
|
|
body,
|
|
undefined,
|
|
signal
|
|
);
|
|
}
|
|
submitCosts(input: CostSensitivitySubmission, key: string) {
|
|
const body = costSensitivitySubmissionSchema.parse({
|
|
...input,
|
|
backtestId: uuid.parse(input.backtestId),
|
|
});
|
|
return this.#request(
|
|
'experiments/cost-sensitivity',
|
|
'POST',
|
|
202,
|
|
value => {
|
|
const saved = parseWorkbenchExperimentDetail(envelope(value, 'experiment'));
|
|
const { previewHash, ...original } = body;
|
|
expect(
|
|
saved.preview.version === 'cost-sensitivity-preview/v1' &&
|
|
saved.previewHash === previewHash &&
|
|
same(saved.preview.input, original)
|
|
);
|
|
return saved;
|
|
},
|
|
body,
|
|
key
|
|
);
|
|
}
|
|
previewValidation(input: ChronologicalValidationInput, signal?: AbortSignal) {
|
|
const body = chronologicalValidationInputSchema.parse({
|
|
...input,
|
|
backtestId: uuid.parse(input.backtestId),
|
|
});
|
|
return this.#request(
|
|
'experiments/validation/preview',
|
|
'POST',
|
|
200,
|
|
value => parseChronologicalValidationPreview(value, body),
|
|
body,
|
|
undefined,
|
|
signal
|
|
);
|
|
}
|
|
submitValidation(input: ChronologicalValidationSubmission, key: string) {
|
|
const body = chronologicalValidationSubmissionSchema.parse({
|
|
...input,
|
|
backtestId: uuid.parse(input.backtestId),
|
|
});
|
|
return this.#request(
|
|
'experiments/validation',
|
|
'POST',
|
|
202,
|
|
value => {
|
|
const saved = parseValidationDetail(envelope(value, 'validation'));
|
|
const { previewHash, ...original } = body;
|
|
expect(saved.previewHash === previewHash && same(saved.preview.input, original));
|
|
return saved;
|
|
},
|
|
body,
|
|
key
|
|
);
|
|
}
|
|
validation(validationId: string, signal?: AbortSignal) {
|
|
validationId = uuid.parse(validationId);
|
|
return this.#request(
|
|
`experiments/validation/${id(validationId)}`,
|
|
'GET',
|
|
200,
|
|
value => {
|
|
const saved = parseValidationDetail(envelope(value, 'validation'));
|
|
expect(saved.id === validationId);
|
|
return saved;
|
|
},
|
|
undefined,
|
|
undefined,
|
|
signal
|
|
);
|
|
}
|
|
advanceValidation(
|
|
validationId: string,
|
|
operation: 'select' | 'finalize',
|
|
input: { previewHash: string; selectionHash?: string },
|
|
key: string
|
|
) {
|
|
validationId = uuid.parse(validationId);
|
|
z.enum(['select', 'finalize']).parse(operation);
|
|
const body = (
|
|
operation === 'select'
|
|
? z.object({ previewHash: hash }).strict()
|
|
: z.object({ previewHash: hash, selectionHash: hash }).strict()
|
|
).parse(input);
|
|
return this.#request(
|
|
`experiments/validation/${id(validationId)}/${operation}`,
|
|
'POST',
|
|
202,
|
|
value => {
|
|
const receipt = validationReceiptSchema.parse(envelope(value, 'receipt'));
|
|
const saved = parseValidationDetail(envelope(value, 'validation'));
|
|
const record = operation === 'select' ? saved.selection : saved.report;
|
|
expect(
|
|
saved.id === validationId &&
|
|
receipt.validationId === validationId &&
|
|
saved.previewHash === body.previewHash &&
|
|
receipt.previewHash === body.previewHash &&
|
|
receipt.selectionHash === saved.selection?.selectionHash &&
|
|
receipt.operation ===
|
|
(operation === 'select' ? 'select-and-admit-holdouts' : 'finalize-report') &&
|
|
record &&
|
|
receipt.id === record.id &&
|
|
receipt.createdAt === record.createdAt &&
|
|
receipt.principal === record.principal &&
|
|
(operation === 'select' ||
|
|
('selectionHash' in body && receipt.selectionHash === body.selectionHash))
|
|
);
|
|
return { receipt, validation: saved };
|
|
},
|
|
body,
|
|
key
|
|
);
|
|
}
|
|
previewWalkForward(input: WalkForwardInput, signal?: AbortSignal) {
|
|
const body = walkForwardInputSchema.parse({
|
|
...input,
|
|
backtestId: uuid.parse(input.backtestId),
|
|
});
|
|
return this.#request(
|
|
'experiments/walk-forward/preview',
|
|
'POST',
|
|
200,
|
|
value => parseWalkForwardPreview(envelope(value, 'preview'), body),
|
|
body,
|
|
undefined,
|
|
signal
|
|
);
|
|
}
|
|
submitWalkForward(input: WalkForwardSubmission, key: string) {
|
|
const body = walkForwardSubmissionSchema.parse({
|
|
...input,
|
|
backtestId: uuid.parse(input.backtestId),
|
|
});
|
|
return this.#request(
|
|
'experiments/walk-forward',
|
|
'POST',
|
|
202,
|
|
value => {
|
|
const saved = parseWalkForwardDetail(envelope(value, 'walkForward'));
|
|
const { previewHash, ...original } = body;
|
|
expect(saved.previewHash === previewHash && same(saved.preview.input, original));
|
|
return saved;
|
|
},
|
|
body,
|
|
key
|
|
);
|
|
}
|
|
walkForward(walkForwardId: string, signal?: AbortSignal) {
|
|
walkForwardId = uuid.parse(walkForwardId);
|
|
return this.#request(
|
|
`experiments/walk-forward/${id(walkForwardId)}`,
|
|
'GET',
|
|
200,
|
|
value => {
|
|
const saved = parseWalkForwardDetail(envelope(value, 'walkForward'));
|
|
expect(saved.id === walkForwardId);
|
|
return saved;
|
|
},
|
|
undefined,
|
|
undefined,
|
|
signal
|
|
);
|
|
}
|
|
finalizeWalkForward(walkForwardId: string, previewHash: string, key: string) {
|
|
walkForwardId = uuid.parse(walkForwardId);
|
|
hash.parse(previewHash);
|
|
return this.#request(
|
|
`experiments/walk-forward/${id(walkForwardId)}/finalize`,
|
|
'POST',
|
|
202,
|
|
value => {
|
|
const receipt = z
|
|
.object({
|
|
id: uuid,
|
|
walkForwardId: uuid,
|
|
operation: z.literal('finalize-walk-forward-report'),
|
|
previewHash: hash,
|
|
reportHash: hash,
|
|
createdAt: z.string().min(1),
|
|
principal: researchActorSchema,
|
|
})
|
|
.parse(envelope(value, 'receipt'));
|
|
const saved = parseWalkForwardDetail(envelope(value, 'walkForward'));
|
|
expect(
|
|
saved.id === walkForwardId &&
|
|
receipt.walkForwardId === walkForwardId &&
|
|
saved.previewHash === previewHash &&
|
|
receipt.previewHash === previewHash &&
|
|
saved.report &&
|
|
receipt.id === saved.report.id &&
|
|
receipt.reportHash === saved.report.reportHash &&
|
|
receipt.createdAt === saved.report.createdAt &&
|
|
receipt.principal === saved.report.principal
|
|
);
|
|
return { receipt, walkForward: saved };
|
|
},
|
|
{ previewHash },
|
|
key
|
|
);
|
|
}
|
|
saveFinding(projectId: string, input: FindingInput) {
|
|
projectId = uuid.parse(projectId);
|
|
const body = createResearchArtifactSchema.parse({
|
|
...input,
|
|
contentOrigin: 'ai',
|
|
hypothesisRevisionId:
|
|
input.hypothesisRevisionId === null || input.hypothesisRevisionId === undefined
|
|
? null
|
|
: uuid.parse(input.hypothesisRevisionId),
|
|
evidence: input.evidence?.map(item => ({
|
|
...item,
|
|
runId: uuid.parse(item.runId),
|
|
strategyVersionId:
|
|
item.strategyVersionId === null || item.strategyVersionId === undefined
|
|
? item.strategyVersionId
|
|
: uuid.parse(item.strategyVersionId),
|
|
})),
|
|
});
|
|
expect(body.kind === 'finding' && body.evidence.length > 0);
|
|
for (const evidence of body.evidence) {
|
|
researchEvidenceReferenceSchema.parse(evidence);
|
|
expect(evidence.metricsVersion === 'canonical-analytics/v1' && evidence.strategyVersionId);
|
|
}
|
|
return this.#request(
|
|
`research-projects/${id(projectId)}/analysis-artifacts`,
|
|
'POST',
|
|
201,
|
|
value => {
|
|
const saved = findingRecord.parse(envelope(value, 'artifact'));
|
|
const revision = saved.latestRevision;
|
|
expect(
|
|
saved.projectId === projectId &&
|
|
saved.hypothesisRevisionId === body.hypothesisRevisionId &&
|
|
saved.kind === 'finding' &&
|
|
revision.title === body.title &&
|
|
revision.body === body.body &&
|
|
revision.evidenceState === 'referenced' &&
|
|
same(revision.source, body.source ?? null) &&
|
|
revision.evidence.length === body.evidence.length &&
|
|
body.evidence.every(item =>
|
|
revision.evidence.some(
|
|
evidence =>
|
|
evidence.runId === item.runId &&
|
|
evidence.strategyVersionId === item.strategyVersionId &&
|
|
evidence.metricsVersion === item.metricsVersion &&
|
|
evidence.metricPath === item.metricPath
|
|
)
|
|
)
|
|
);
|
|
return saved;
|
|
},
|
|
body
|
|
);
|
|
}
|
|
|
|
async waitForExperiment(
|
|
experimentId: string,
|
|
options: PollOptions<WorkbenchExperimentDetailView>
|
|
) {
|
|
return pollResearch(
|
|
signal => this.experiment(experimentId, signal),
|
|
value =>
|
|
value.trials.every(trial =>
|
|
['completed', 'failed', 'cancelled', 'missing'].includes(trial.status)
|
|
),
|
|
options
|
|
);
|
|
}
|
|
async waitForValidation(validationId: string, options: PollOptions<ValidationDetailView>) {
|
|
return pollResearch(
|
|
signal => this.validation(validationId, signal),
|
|
value => {
|
|
const admitted = value.phases.filter(phase => phase.status !== 'not-admitted');
|
|
return admitted.every(
|
|
phase =>
|
|
phase.status === 'missing' ||
|
|
phase.experiment?.trials.every(trial =>
|
|
['completed', 'failed', 'cancelled', 'missing'].includes(trial.status)
|
|
)
|
|
);
|
|
},
|
|
options
|
|
);
|
|
}
|
|
}
|
|
|
|
/** Stops waiting without cancelling accepted jobs; all failed/cancelled/missing trials remain visible. */
|
|
export async function pollResearch<T>(
|
|
read: (signal: AbortSignal) => Promise<T>,
|
|
done: (value: T) => boolean,
|
|
options: PollOptions<T>
|
|
): Promise<T> {
|
|
const timeout = z.number().int().positive().max(2147483647).parse(options.timeoutMs);
|
|
const interval = z
|
|
.number()
|
|
.int()
|
|
.positive()
|
|
.max(2147483647)
|
|
.parse(options.intervalMs ?? 500);
|
|
const deadline = timedSignal(timeout);
|
|
const signal = options.signal
|
|
? AbortSignal.any([options.signal, deadline.signal])
|
|
: deadline.signal;
|
|
let last: T | null = null;
|
|
try {
|
|
while (!signal.aborted) {
|
|
try {
|
|
last = await abortable(() => read(signal), signal);
|
|
} catch (error) {
|
|
if (options.signal?.aborted) {
|
|
throw options.signal.reason;
|
|
}
|
|
if (!deadline.signal.aborted) {
|
|
throw error;
|
|
}
|
|
break;
|
|
}
|
|
if (signal.aborted) {
|
|
break;
|
|
}
|
|
options.onUpdate?.(last);
|
|
if (done(last)) {
|
|
return last;
|
|
}
|
|
await new Promise<void>(resolve => {
|
|
const finish = () => {
|
|
clearTimeout(timer);
|
|
signal.removeEventListener('abort', finish);
|
|
resolve();
|
|
};
|
|
const timer = setTimeout(finish, interval);
|
|
signal.addEventListener('abort', finish, { once: true });
|
|
if (signal.aborted) {
|
|
finish();
|
|
}
|
|
});
|
|
}
|
|
if (options.signal?.aborted) {
|
|
throw options.signal.reason;
|
|
}
|
|
throw new ResearchWaitExpired(last);
|
|
} finally {
|
|
deadline.dispose();
|
|
}
|
|
}
|
|
|
|
/** Bound an operation even when a supplied transport ignores cancellation. Late results are ignored. */
|
|
function abortable<T>(read: () => Promise<T>, signal: AbortSignal): Promise<T> {
|
|
return new Promise((resolve, reject) => {
|
|
const stop = () => reject(signal.reason);
|
|
if (signal.aborted) {
|
|
stop();
|
|
return;
|
|
}
|
|
signal.addEventListener('abort', stop, { once: true });
|
|
try {
|
|
read()
|
|
.then(resolve, reject)
|
|
.finally(() => signal.removeEventListener('abort', stop));
|
|
} catch (error) {
|
|
signal.removeEventListener('abort', stop);
|
|
reject(error);
|
|
}
|
|
});
|
|
}
|
|
|
|
function timedSignal(timeoutMs: number) {
|
|
const controller = new AbortController();
|
|
// Keep the event loop alive while callers await an otherwise uncooperative transport.
|
|
const timer = setTimeout(
|
|
() => controller.abort(new Error('Research deadline reached')),
|
|
timeoutMs
|
|
);
|
|
return { signal: controller.signal, dispose: () => clearTimeout(timer) };
|
|
}
|