stock-bot/scripts/test/research-client.test.ts

977 lines
38 KiB
TypeScript

import { createHash } from 'node:crypto';
import { describe, expect, test } from 'bun:test';
import type { ExperimentDetail } from '@stock-bot/stock-config/experiments';
import { comparisonFixture, tableFixture } from '../benchmark-experiment-tables';
import {
pollResearch,
ResearchClient,
ResearchRequestError,
ResearchWaitExpired,
} from '../research-client';
const token = 'sb-research.fixture-only-token';
const agent = 'agent:11111111-1111-4111-8111-111111111111';
const projectId = '22222222-2222-4222-8222-222222222222';
const hypothesisId = '33333333-3333-4333-8333-333333333333';
const revisionId = '44444444-4444-4444-8444-444444444444';
const artifactId = '55555555-5555-4555-8555-555555555555';
const requestKey = 'research-cycle-fixture:trial:1';
type Call = { url: URL; init: RequestInit; body: unknown };
function client(handler: (call: Call, index: number) => Response | Promise<Response>) {
const calls: Call[] = [];
const value = new ResearchClient({
origin: 'http://127.0.0.1:2003',
token,
fetch: ((url: string | URL | Request, init?: RequestInit) => {
const call = {
url: new URL(String(url)),
init: init!,
body: init?.body ? JSON.parse(String(init.body)) : undefined,
};
calls.push(call);
return Promise.resolve(handler(call, calls.length - 1));
}) as typeof fetch,
});
return { value, calls };
}
const ordinary = () => tableFixture(1) as ExperimentDetail;
function crossStudyFinding() {
const detail = ordinary();
const input = {
kind: 'finding' as const,
title: 'Compare two candidates',
body: 'These synthetic results do not validate the hypothesis.',
evidence: [
{
runId: detail.trials[0]!.runId!,
strategyVersionId: detail.strategyVersionId,
metricsVersion: 'canonical-analytics/v1' as const,
metricPath: 'analytics.metrics.totalReturn' as const,
},
{
runId: '66666666-6666-4666-8666-666666666666',
strategyVersionId: '77777777-7777-4777-8777-777777777777',
metricsVersion: 'canonical-analytics/v1' as const,
metricPath: 'analytics.metrics.totalReturn' as const,
},
],
};
const artifact: Awaited<ReturnType<ResearchClient['saveFinding']>> = {
id: artifactId,
projectId,
hypothesisRevisionId: null,
kind: 'finding',
latestRevision: {
id: revisionId,
title: input.title,
body: input.body,
contentOrigin: 'ai',
submittedBy: agent,
validationState: 'unvalidated',
evidenceState: 'referenced',
source: null,
evidence: input.evidence.map((reference, index) => ({
...reference,
value: index === 0 ? -0.01 : 0.02,
availability: 'available',
unavailableReason: null,
datasetHash: detail.datasetHash,
resultKind: 'canonical',
financialEngine: 'rust',
limitations: [{ code: 'fixture', message: 'Synthetic demonstration' }],
})),
},
};
return { input, artifact };
}
function readableArtifact(): Awaited<ReturnType<ResearchClient['artifact']>> {
const { artifact } = crossStudyFinding();
const createdAt = '2026-10-27T12:00:00.000Z';
return {
...artifact,
ownerPrincipal: agent,
updatedBy: agent,
archived: false,
createdAt,
updatedAt: createdAt,
latestRevision: {
...artifact.latestRevision,
submittedBy: agent,
artifactId,
ordinal: 1,
createdAt,
evidence: artifact.latestRevision.evidence.map(reference => ({
...reference,
backtestId: ordinary().backtestId,
unit: 'fraction',
})),
},
};
}
describe('retained research artifact reads', () => {
test('reopens a saved artifact through authenticated GET without admission', async () => {
const artifact = readableArtifact();
const { value, calls } = client(() => Response.json({ artifact }));
const saved = await value.artifact(artifactId.toUpperCase());
expect(saved).toEqual(artifact);
expect(calls).toHaveLength(1);
expect(calls[0]!.url.pathname).toBe(`/api/v2/analysis-artifacts/${artifactId}`);
expect(calls[0]!.init.method).toBe('GET');
expect(calls[0]!.body).toBeUndefined();
expect(new Headers(calls[0]!.init.headers).get('authorization')).toBe(`Bearer ${token}`);
expect(new Headers(calls[0]!.init.headers).has('idempotency-key')).toBe(false);
});
test('retains exact old AI revision when latest is human-authored', async () => {
const original = readableArtifact().latestRevision;
const updated: typeof original = {
...structuredClone(original),
id: hypothesisId,
ordinal: 2,
contentOrigin: 'human',
submittedBy: 'operator',
body: 'Revised human interpretation, still unvalidated.',
};
const revisions = [updated, original];
const { value, calls } = client(() => Response.json({ revisions }));
const history = await value.artifactRevisions(artifactId);
expect(history).toEqual(revisions);
expect(history.find(item => item.id === revisionId)).toEqual(original);
expect(history[0]!.submittedBy).toBe('operator');
expect(calls).toHaveLength(1);
expect(calls[0]!.url.pathname).toBe(`/api/v2/analysis-artifacts/${artifactId}/revisions`);
expect(calls[0]!.init.method).toBe('GET');
});
test('reads human legacy findings and service notes without certifying old measurements', async () => {
const artifact = readableArtifact();
artifact.latestRevision.contentOrigin = 'human';
artifact.latestRevision.submittedBy = 'operator';
artifact.latestRevision.evidence = [
{
...artifact.latestRevision.evidence[0]!,
strategyVersionId: null,
metricsVersion: 'legacy-display/v1',
metricPath: 'metrics.totalReturn',
resultKind: 'legacy',
financialEngine: 'native',
datasetHash: null,
limitations: [{ code: 'legacy-unverified-economics', message: 'Historical display only' }],
},
];
const read = client(() => Response.json({ artifact }));
expect(await read.value.artifact(artifactId)).toEqual(artifact);
const note = readableArtifact();
note.kind = 'note';
note.archived = true;
note.latestRevision.contentOrigin = 'unknown';
note.latestRevision.submittedBy = 'service';
note.latestRevision.evidenceState = 'none';
note.latestRevision.evidence = [];
const { source: _source, ...withoutSource } = note.latestRevision;
const notes = client(() =>
Response.json({ artifact: { ...note, latestRevision: withoutSource } })
);
const saved = await notes.value.artifact(artifactId);
expect(saved.kind).toBe('note');
expect(saved.archived).toBe(true);
expect(saved.latestRevision.source).toBeNull();
expect(saved.latestRevision.contentOrigin).toBe('unknown');
expect(saved.latestRevision.submittedBy).toBe('service');
expect(saved.latestRevision.evidence).toEqual([]);
});
test('rejects foreign artifact identity and malformed retained evidence as read errors', async () => {
const artifact = readableArtifact();
const revision = artifact.latestRevision;
const badRevisions = [
{ artifactId: projectId },
{ validationState: 'validated' },
{ evidenceState: 'none' },
{ evidence: [] },
{ evidence: [revision.evidence[0], revision.evidence[0]] },
{ source: { kind: 'experiment/v1', experimentId: projectId, previewHash: 'bad-hash' } },
...[
{ runId: 'bad-id' },
{ metricPath: 'analytics.metrics.unknown' },
{ metricsVersion: 'legacy-display/v1' },
{ value: null },
{ unit: 'dollars' },
{ availability: 'unavailable' },
{ unavailableReason: 'Contradictory' },
{ datasetHash: null },
{ resultKind: 'legacy' },
{ financialEngine: 'native' },
].map(change => ({ evidence: [{ ...revision.evidence[0], ...change }] })),
];
const bodies = [
{},
{ artifact: null },
{ artifact: { ...artifact, id: projectId } },
...badRevisions.map(change => ({
artifact: { ...artifact, latestRevision: { ...revision, ...change } },
})),
];
for (const body of bodies) {
const { value, calls } = client(() => Response.json(body));
await expect(value.artifact(artifactId)).rejects.toMatchObject({
name: 'ResearchRequestError',
uncertain: false,
status: null,
});
expect(calls).toHaveLength(1);
expect(calls[0]!.init.method).toBe('GET');
}
});
test('rejects missing, mixed-parent and duplicate history instead of replacing original identity', async () => {
const revision = readableArtifact().latestRevision;
for (const revisions of [
null,
[],
[{ ...revision, artifactId: projectId }],
[revision, { ...revision, ordinal: 2 }],
[revision, { ...revision, id: projectId }],
[{ ...revision, ordinal: 0 }],
]) {
const { value, calls } = client(() => Response.json({ revisions }));
await expect(value.artifactRevisions(artifactId)).rejects.toMatchObject({
uncertain: false,
status: null,
});
expect(calls).toHaveLength(1);
}
});
test('invalid IDs, HTTP failures and aborts never create or retry work', async () => {
const invalid = client(() => {
throw new Error('No transport expected');
});
expect(() => invalid.value.artifact('../strategies')).toThrow();
expect(() => invalid.value.artifactRevisions('bad-id')).toThrow();
expect(invalid.calls).toHaveLength(0);
for (const status of [401, 404, 503]) {
const { value, calls } = client(() => Response.json({ error: 'Unavailable' }, { status }));
await expect(value.artifact(artifactId)).rejects.toMatchObject({ status, uncertain: false });
await expect(value.artifactRevisions(artifactId)).rejects.toMatchObject({
status,
uncertain: false,
});
expect(calls).toHaveLength(2);
}
const controller = new AbortController();
const stalled = client(() => new Promise<Response>(() => {}));
const pending = stalled.value.artifact(artifactId, controller.signal);
controller.abort(new Error('Stop reading'));
await expect(pending).rejects.toMatchObject({ uncertain: false });
expect(stalled.calls).toHaveLength(1);
await expect(
stalled.value.artifactRevisions(artifactId, controller.signal)
).rejects.toMatchObject({ uncertain: false });
expect(stalled.calls).toHaveLength(1);
});
});
describe('authorized research client', () => {
test('only research credentials, fixed API origin, no trading methods or redirect credential forwarding', async () => {
for (const origin of [
'http://example.org',
'https://u:p@example.org',
'https://example.org/a',
'https://example.org/?token=x',
'file:///tmp/a',
]) {
expect(() => new ResearchClient({ origin, token })).toThrow();
}
expect(
() => new ResearchClient({ origin: 'https://example.org', token: 'operator-secret' })
).toThrow();
const detail = ordinary();
const { value, calls } = client(() => Response.json({ experiment: detail }));
await value.experiment(detail.id);
expect(calls[0]!.url.origin).toBe('http://127.0.0.1:2003');
expect(calls[0]!.url.pathname).toBe(`/api/v2/experiments/${detail.id}`);
expect(calls[0]!.init.redirect).toBe('error');
expect(calls[0]!.init.credentials).toBe('omit');
expect(new Headers(calls[0]!.init.headers).get('authorization')).toBe(`Bearer ${token}`);
expect(JSON.stringify(value)).not.toContain(token);
expect('activate' in value || 'paper' in value || 'request' in value).toBe(false);
expect(() =>
value.advanceValidation(
detail.id,
'../../paper/activate' as 'select',
{ previewHash: detail.previewHash },
requestKey
)
).toThrow();
expect(calls).toHaveLength(1);
});
test('preview and admission preserve captured inputs; uncertain submission recovers with the same exact key and body', async () => {
const detail = ordinary();
let release!: (response: Response) => void;
const { value, calls } = client((_call, index) =>
index === 0
? new Promise<Response>(resolve => {
release = resolve;
})
: index === 1
? Promise.reject(new Error('Response lost after durable admission'))
: Response.json({ experiment: detail }, { status: 202 })
);
const input = structuredClone(detail.preview.input);
const checking = value.previewExperiment(input);
input.name = 'Changed after sending';
release(Response.json({ preview: detail.preview }));
expect((await checking).input.name).toBe(detail.name);
const body = { ...detail.preview.input, previewHash: detail.previewHash };
await expect(value.submitExperiment(body, requestKey)).rejects.toMatchObject({
uncertain: true,
});
expect(calls).toHaveLength(2);
expect((await value.submitExperiment(body, requestKey)).id).toBe(detail.id);
expect(String(calls[1]!.init.body)).toBe(String(calls[2]!.init.body));
expect(new Headers(calls[1]!.init.headers).get('idempotency-key')).toBe(requestKey);
expect(new Headers(calls[2]!.init.headers).get('idempotency-key')).toBe(requestKey);
});
test('wrong receipt identities, lost response and 429 are surfaced without automatic new admission', async () => {
const detail = ordinary(),
body = { ...detail.preview.input, previewHash: detail.previewHash };
const malformed = client(() =>
Response.json({ experiment: { ...detail, previewHash: 'f'.repeat(64) } }, { status: 202 })
);
await expect(malformed.value.submitExperiment(body, requestKey)).rejects.toMatchObject({
status: null,
uncertain: true,
});
expect(malformed.calls).toHaveLength(1);
const lost = client(() => {
throw new Error('private transport details');
});
await expect(lost.value.submitExperiment(body, requestKey)).rejects.toMatchObject({
status: null,
uncertain: true,
});
const denied = client(() =>
Response.json({ error: 'Bounded work budget exceeded' }, { status: 429 })
);
await expect(denied.value.previewExperiment(detail.preview.input)).rejects.toMatchObject({
status: 429,
uncertain: false,
message: 'Bounded work budget exceeded',
});
expect(denied.calls).toHaveLength(1);
const oversized = {
...detail.preview.input,
grid: { fastPeriod: Array.from({ length: 101 }, (_, i) => i + 1) },
};
expect(() => denied.value.previewExperiment(oversized)).toThrow();
expect(denied.calls).toHaveLength(1);
});
test('candidate publication is inert data; it cannot import generated source or substitute a version identity', async () => {
const detail = ordinary();
const pkg = structuredClone(detail.preview.request.strategy.package);
pkg.artifact.content =
'globalThis.__research_client_executed = true; throw new Error("Never import");';
pkg.artifact.sha256 = createHash('sha256').update(pkg.artifact.content).digest('hex');
const saved = {
id: detail.strategyVersionId,
strategyId: detail.preview.request.strategy.familyId,
ordinal: 1,
origin: 'candidate',
createdBy: agent,
parentVersionId: null,
package: pkg,
};
const good = client(() => Response.json({ version: saved }, { status: 201 }));
expect((await good.value.publishVersion(saved.strategyId, pkg, requestKey)).id).toBe(saved.id);
expect((globalThis as Record<string, unknown>).__research_client_executed).toBeUndefined();
expect(good.calls[0]!.body).toEqual({ package: pkg, parentVersionId: null });
const bad = client(() =>
Response.json({ version: { ...saved, origin: 'builtin' } }, { status: 201 })
);
await expect(bad.value.publishVersion(saved.strategyId, pkg, requestKey)).rejects.toMatchObject(
{ uncertain: true }
);
});
test('automatic publication lineage accepts and retains the server-selected parent', async () => {
const detail = ordinary();
const pkg = detail.preview.request.strategy.package;
const saved = {
id: detail.strategyVersionId,
strategyId: detail.preview.request.strategy.familyId,
ordinal: 2,
origin: 'candidate',
createdBy: agent,
parentVersionId: 'abcdefab-abcd-4bcd-8bcd-000000000002',
package: pkg,
};
const publication = client(() => Response.json({ version: saved }, { status: 201 }));
const implicit = await publication.value.publishVersion(saved.strategyId, pkg, requestKey);
const explicitNull = await publication.value.publishVersion(
saved.strategyId,
pkg,
requestKey,
null
);
expect(implicit).toMatchObject({ id: saved.id, parentVersionId: saved.parentVersionId });
expect(explicitNull).toEqual(implicit);
expect(publication.calls).toHaveLength(2);
expect(publication.calls[0]!.body).toEqual({ package: pkg, parentVersionId: null });
expect(publication.calls[1]!.init.body).toBe(publication.calls[0]!.init.body!);
});
test('automatic lineage receipt retries retain the original key/body after a newer publication', async () => {
const detail = ordinary();
const pkg = detail.preview.request.strategy.package;
const second = {
id: detail.strategyVersionId,
strategyId: detail.preview.request.strategy.familyId,
ordinal: 2,
origin: 'candidate',
createdBy: agent,
parentVersionId: 'abcdefab-abcd-4bcd-8bcd-000000000002',
package: pkg,
};
const third = {
...second,
id: 'abcdefab-abcd-4bcd-8bcd-000000000003',
ordinal: 3,
parentVersionId: second.id,
};
const publication = client((_call, index) => {
if (index === 0) {
throw new Error('Response lost after the second version committed');
}
return Response.json({ version: index === 1 ? third : second }, { status: 201 });
});
await expect(
publication.value.publishVersion(second.strategyId, pkg, requestKey)
).rejects.toMatchObject({ uncertain: true });
expect(publication.calls).toHaveLength(1);
expect(
await publication.value.publishVersion(second.strategyId, pkg, `${requestKey}:new`)
).toMatchObject({ id: third.id, parentVersionId: second.id });
expect(
await publication.value.publishVersion(second.strategyId, pkg, requestKey)
).toMatchObject({ id: second.id, parentVersionId: second.parentVersionId });
expect(publication.calls).toHaveLength(3);
expect(publication.calls.every(call => call.init.method === 'POST')).toBeTrue();
expect(publication.calls[2]!.init.body).toBe(publication.calls[0]!.init.body!);
expect(publication.calls[2]!.body).toEqual({ package: pkg, parentVersionId: null });
for (const index of [0, 2]) {
expect(new Headers(publication.calls[index]!.init.headers).get('idempotency-key')).toBe(
requestKey
);
}
});
test('publication still rejects wrong explicit lineage, malformed parents, family, origin and hashes', async () => {
const detail = ordinary();
const pkg = detail.preview.request.strategy.package;
const saved = {
id: detail.strategyVersionId,
strategyId: detail.preview.request.strategy.familyId,
ordinal: 2,
origin: 'candidate',
createdBy: agent,
parentVersionId: 'abcdefab-abcd-4bcd-8bcd-000000000002',
package: pkg,
};
const explicit = client(() => Response.json({ version: saved }, { status: 201 }));
await expect(
explicit.value.publishVersion(saved.strategyId, pkg, requestKey, saved.id)
).rejects.toMatchObject({ uncertain: true });
expect(explicit.calls).toHaveLength(1);
expect(explicit.calls[0]!.body).toEqual({ package: pkg, parentVersionId: saved.id });
for (const invalid of [
{ ...saved, parentVersionId: 'not-a-version-id' },
{ ...saved, parentVersionId: 2 },
{ ...saved, parentVersionId: undefined },
{ ...saved, strategyId: 'abcdefab-abcd-4bcd-8bcd-000000000003' },
{ ...saved, origin: 'builtin' },
{ ...saved, package: { ...pkg, artifact: { ...pkg.artifact, sha256: 'f'.repeat(64) } } },
{
...saved,
package: { ...pkg, dependencyLock: { ...pkg.dependencyLock, sha256: 'f'.repeat(64) } },
},
]) {
const rejected = client(() => Response.json({ version: invalid }, { status: 201 }));
await expect(
rejected.value.publishVersion(saved.strategyId, pkg, requestKey)
).rejects.toMatchObject({ uncertain: true });
expect(rejected.calls).toHaveLength(1);
}
});
test('normalizes uppercase identities before captures and binds cancellation and publication receipts', async () => {
const detail = ordinary();
detail.id = 'abcdefab-abcd-4bcd-8bcd-abcdefabcdef';
detail.cancelRequested = true;
const cancel = client(() => Response.json({ experiment: detail }));
expect((await cancel.value.cancelExperiment(detail.id.toUpperCase())).id).toBe(detail.id);
expect(cancel.calls[0]!.url.pathname).toContain(detail.id);
const strategyId = 'abcdefab-abcd-4bcd-8bcd-000000000001';
const parentVersionId = 'abcdefab-abcd-4bcd-8bcd-000000000002';
const pkg = detail.preview.request.strategy.package;
const saved = {
id: detail.strategyVersionId,
strategyId,
parentVersionId,
ordinal: 2,
origin: 'candidate',
createdBy: agent,
package: pkg,
};
const publication = client(() => Response.json({ version: saved }, { status: 201 }));
expect(
(
await publication.value.publishVersion(
strategyId.toUpperCase(),
pkg,
requestKey,
parentVersionId.toUpperCase()
)
).strategyId
).toBe(strategyId);
expect(publication.calls[0]!.body).toMatchObject({ parentVersionId });
});
test('malformed selection/finalization receipts are uncertain and never resubmitted automatically', async () => {
const request = client(() =>
Response.json(
{ receipt: { id: projectId }, validation: {}, walkForward: {} },
{ status: 202 }
)
);
await expect(
request.value.advanceValidation(
projectId,
'select',
{ previewHash: 'a'.repeat(64) },
requestKey
)
).rejects.toMatchObject({ uncertain: true });
await expect(
request.value.advanceValidation(
projectId,
'finalize',
{ previewHash: 'a'.repeat(64), selectionHash: 'b'.repeat(64) },
requestKey
)
).rejects.toMatchObject({ uncertain: true });
await expect(
request.value.finalizeWalkForward(projectId, 'a'.repeat(64), requestKey)
).rejects.toMatchObject({ uncertain: true });
expect(request.calls).toHaveLength(3);
});
test('failed, cancelled, missing and noncomparable outcomes survive polling and comparison', async () => {
const detail = tableFixture(25);
for (const trial of detail.trials) {
if (['pending', 'running', 'paused'].includes(trial.status)) {
trial.status = 'failed';
trial.error = 'Explicit worker diagnostic';
}
}
for (const status of [
'pending',
'running',
'paused',
'completed',
'failed',
'cancelled',
] as const) {
detail.counts[status] = detail.trials.filter(trial => trial.status === status).length;
}
const polling = client(() => Response.json({ experiment: detail }));
const result = await polling.value.waitForExperiment(detail.id, { timeoutMs: 1000 });
expect(result.trials).toEqual(detail.trials);
expect(result.trials.some(trial => trial.status === 'failed' && trial.error)).toBe(true);
expect(result.trials.some(trial => trial.status === 'missing')).toBe(true);
expect(result.trials.some(trial => trial.status === 'completed' && !trial.comparable)).toBe(
true
);
expect(polling.calls).toHaveLength(1);
const comparison = comparisonFixture();
const read = client(() => Response.json({ comparison }));
expect((await read.value.compareExperiments(comparison.selection)).rows).toEqual(
comparison.rows
);
expect(comparison.rows.some(row => !row.ready)).toBe(true);
});
test.each(['null', 'omitted'] as const)(
'cross-study findings accept a %s source and retain exact versioned evidence',
async source => {
const { input, artifact } = crossStudyFinding();
const body = source === 'null' ? { ...input, source: null } : input;
const { value, calls } = client(() => Response.json({ artifact }, { status: 201 }));
const saved = await value.saveFinding(projectId, body);
expect(saved).toEqual(artifact);
expect(saved.latestRevision.source).toBeNull();
expect(saved.latestRevision.evidence).toEqual(artifact.latestRevision.evidence);
expect(saved.latestRevision.validationState).toBe('unvalidated');
expect(saved.latestRevision.contentOrigin).toBe('ai');
expect(calls).toHaveLength(1);
expect(calls[0]!.url.pathname).toBe(
`/api/v2/research-projects/${projectId}/analysis-artifacts`
);
expect(calls[0]!.init.method).toBe('POST');
expect(calls[0]!.body).toEqual({
...body,
hypothesisRevisionId: null,
contentOrigin: 'ai',
});
expect(Object.hasOwn(calls[0]!.body as object, 'source')).toBe(source === 'null');
expect(new Headers(calls[0]!.init.headers).has('idempotency-key')).toBe(false);
}
);
test('findings still bind supplied experiment and report sources exactly', async () => {
const { input, artifact } = crossStudyFinding();
const detail = ordinary();
const sources = [
{ kind: 'experiment/v1' as const, experimentId: detail.id, previewHash: detail.previewHash },
{
kind: 'chronological-report/v1' as const,
validationId: detail.id,
previewHash: detail.previewHash,
reportId: revisionId,
reportHash: 'a'.repeat(64),
},
{
kind: 'walk-forward-report/v1' as const,
walkForwardId: detail.id,
previewHash: detail.previewHash,
reportId: revisionId,
reportHash: 'a'.repeat(64),
},
];
for (const source of sources) {
for (const returned of [source, null, { ...source, previewHash: 'f'.repeat(64) }]) {
const { value, calls } = client(() =>
Response.json(
{
artifact: {
...artifact,
latestRevision: { ...artifact.latestRevision, source: returned },
},
},
{ status: 201 }
)
);
const pending = value.saveFinding(projectId, { ...input, source });
if (returned === source) {
expect((await pending).latestRevision.source).toEqual(source);
} else {
await expect(pending).rejects.toMatchObject({ uncertain: true, status: null });
}
expect(calls).toHaveLength(1);
expect((calls[0]!.body as { source: unknown }).source).toEqual(source);
}
}
});
test('source-free findings reject substituted response identities and malformed evidence without retry', async () => {
const { input, artifact } = crossStudyFinding();
const revision = artifact.latestRevision;
const invalidRevisions = [
{
source: { kind: 'experiment/v1', experimentId: ordinary().id, previewHash: 'f'.repeat(64) },
},
{ contentOrigin: 'human' },
{ submittedBy: 'operator' },
{ validationState: 'validated' },
{ evidenceState: 'none' },
...[
{ runId: hypothesisId },
{ strategyVersionId: hypothesisId },
{ strategyVersionId: null },
{ metricPath: 'analytics.metrics.maxDrawdown' },
{ metricsVersion: 'legacy-display/v1' },
{ value: null },
{ availability: 'unavailable' },
{ unavailableReason: 'Contradictory reason' },
{ resultKind: 'legacy' },
{ financialEngine: 'typescript' },
].map(change => ({
evidence: [{ ...revision.evidence[0], ...change }, revision.evidence[1]],
})),
];
const invalidArtifacts = [
{ ...artifact, projectId: hypothesisId },
{ ...artifact, hypothesisRevisionId: revisionId },
{ ...artifact, kind: 'note' },
...invalidRevisions.map(change => ({
...artifact,
latestRevision: { ...revision, ...change },
})),
];
for (const invalid of invalidArtifacts) {
const { value, calls } = client(() => Response.json({ artifact: invalid }, { status: 201 }));
await expect(value.saveFinding(projectId, input)).rejects.toMatchObject({
uncertain: true,
status: null,
operation: `POST research-projects/${projectId}/analysis-artifacts`,
});
expect(calls).toHaveLength(1);
}
});
test('source-free findings require nonempty unique canonical versioned evidence before transport', () => {
const { input } = crossStudyFinding();
const reference = input.evidence[0]!;
const { strategyVersionId: _version, ...unversioned } = reference;
const invalidInputs = [
{ kind: 'note' },
{ evidence: [] },
{ evidence: [reference, reference] },
{ evidence: [unversioned] },
{ evidence: [{ ...reference, strategyVersionId: null }] },
{ evidence: [{ ...reference, strategyVersionId: 'bad-id' }] },
{ evidence: [{ ...reference, runId: 'bad-id' }] },
{ evidence: [{ ...reference, metricPath: 'analytics.metrics.unknown' }] },
{
evidence: [
{ ...reference, metricsVersion: 'legacy-display/v1', metricPath: 'metrics.totalReturn' },
],
},
{ source: {} },
{ source: { kind: 'experiment/v1', experimentId: projectId, previewHash: 'bad-hash' } },
{
source: {
kind: 'chronological-report/v1',
validationId: projectId,
previewHash: 'a'.repeat(64),
},
},
];
const { value, calls } = client(() => {
throw new Error('Invalid finding must not reach transport');
});
for (const invalid of invalidInputs) {
expect(() =>
value.saveFinding(projectId, { ...input, ...invalid } as Parameters<
ResearchClient['saveFinding']
>[1])
).toThrow();
}
expect(calls).toHaveLength(0);
});
test('AI hypotheses stay unvalidated and findings retain exact canonical sources without validating prose', async () => {
const detail = ordinary(),
runId = detail.trials[0]!.runId!;
const input = {
title: 'A hypothesis',
proposition: 'Trend might persist',
validationCriteria: 'Use chronological holdouts',
};
const evidence = [
{
runId,
strategyVersionId: detail.strategyVersionId,
metricsVersion: 'canonical-analytics/v1' as const,
metricPath: 'analytics.metrics.totalReturn' as const,
},
];
const source = {
kind: 'experiment/v1' as const,
experimentId: detail.id,
previewHash: detail.previewHash,
};
const finding = {
kind: 'finding' as const,
hypothesisRevisionId: revisionId,
title: 'Observed fixture',
body: 'This synthetic result is not a profitability claim.',
evidence,
source,
};
let metric = {
value: 0 as number | null,
availability: 'available',
unavailableReason: null as string | null,
};
const { value, calls } = client((_call, index) =>
Response.json(
index === 0
? {
hypothesis: {
id: hypothesisId,
projectId,
latestRevision: {
...input,
id: revisionId,
ordinal: 1,
contentOrigin: 'ai',
submittedBy: agent,
validationState: 'unvalidated',
},
},
}
: {
artifact: {
id: artifactId,
projectId,
hypothesisRevisionId: revisionId,
kind: 'finding',
latestRevision: {
id: revisionId,
title: finding.title,
body: finding.body,
contentOrigin: 'ai',
submittedBy: agent,
validationState: 'unvalidated',
evidenceState: 'referenced',
source,
evidence: [
{
...evidence[0],
...metric,
datasetHash: detail.datasetHash,
resultKind: 'canonical',
financialEngine: 'rust',
limitations: [{ code: 'fixture', message: 'Synthetic demonstration' }],
},
],
},
},
},
{ status: 201 }
)
);
const hypothesis = await value.createHypothesis(projectId, input);
expect(hypothesis.latestRevision.validationState).toBe('unvalidated');
const saved = await value.saveFinding(projectId, finding);
expect(calls[1]!.url.pathname).toBe(
`/api/v2/research-projects/${projectId}/analysis-artifacts`
);
expect(saved.latestRevision.validationState).toBe('unvalidated');
expect(saved.latestRevision.evidence[0]!.value).toBe(0);
expect(saved.latestRevision.source).toEqual(source);
for (const bad of [
{ value: null, availability: 'available', unavailableReason: null },
{ value: 1, availability: 'unavailable', unavailableReason: 'Too few bars' },
{ value: null, availability: 'unavailable', unavailableReason: null },
{ value: null, availability: 'unavailable', unavailableReason: ' ' },
{ value: 0, availability: 'available', unavailableReason: 'Contradictory reason' },
]) {
metric = bad;
await expect(value.saveFinding(projectId, finding)).rejects.toMatchObject({
uncertain: true,
});
}
metric = { value: null, availability: 'unavailable', unavailableReason: 'Too few bars' };
expect((await value.saveFinding(projectId, finding)).latestRevision.evidence[0]).toMatchObject(
metric
);
expect((calls[0]!.body as { contentOrigin: string }).contentOrigin).toBe('ai');
const denied = client(() =>
Response.json({ error: 'Evidence is not a member of this source' }, { status: 409 })
);
await expect(denied.value.saveFinding(projectId, finding)).rejects.toMatchObject({
status: 409,
uncertain: false,
});
expect(denied.calls).toHaveLength(1);
expect(() => denied.value.saveFinding(projectId, { ...finding, evidence: [] })).toThrow();
});
});
describe('bounded research polling', () => {
test('deadline preserves last diagnostic snapshot and never cancels server work', async () => {
let reads = 0;
const error = await pollResearch(
async () => ({ status: 'running', attempt: ++reads }),
() => false,
{ timeoutMs: 15, intervalMs: 5 }
).catch(error => error);
expect(error).toBeInstanceOf(ResearchWaitExpired);
expect(error.last.status).toBe('running');
expect(reads).toBeGreaterThan(0);
});
test('explicit abort and failed read stop polling without hiding 429 or other diagnostics', async () => {
const controller = new AbortController();
const aborted = pollResearch(
async () => {
controller.abort(new Error('Owner stopped waiting'));
return 1;
},
() => false,
{ timeoutMs: 1000, intervalMs: 1, signal: controller.signal }
);
await expect(aborted).rejects.toThrow('Owner stopped waiting');
let calls = 0;
const error = new ResearchRequestError('Budget unavailable', 429, false, 'GET fixture');
await expect(
pollResearch(
async () => {
calls++;
throw error;
},
() => false,
{ timeoutMs: 1000 }
)
).rejects.toBe(error);
expect(calls).toBe(1);
expect(
() => new ResearchClient({ origin: 'http://localhost', token, requestTimeoutMs: Infinity })
).toThrow();
});
});
test('polling deadlines and aborts bound a transport that ignores cancellation', async () => {
const never = () => new Promise<never>(() => {});
const timeout = await pollResearch(never, () => false, { timeoutMs: 10 }).catch(error => error);
expect(timeout).toBeInstanceOf(ResearchWaitExpired);
expect(timeout.last).toBeNull();
const controller = new AbortController();
const pending = pollResearch(never, () => false, { timeoutMs: 1000, signal: controller.signal });
controller.abort(new Error('Stop uncooperative transport'));
await expect(pending).rejects.toThrow('Stop uncooperative transport');
const bounded = new ResearchClient({
origin: 'http://localhost',
token,
requestTimeoutMs: 10,
fetch: never as unknown as typeof fetch,
});
await expect(bounded.budget()).rejects.toMatchObject({ uncertain: false, status: null });
});
test('captured recipe inputs normalize template UUIDs before preview and receipt submission', async () => {
const value = ordinary();
const read = client(() =>
Response.json({ error: 'Fixture stops before admission' }, { status: 429 })
);
const backtestId = 'abcdefab-abcd-4bcd-8bcd-abcdefabcdef';
await expect(
read.value.previewExperiment({ ...value.preview.input, backtestId: backtestId.toUpperCase() })
).rejects.toMatchObject({ status: 429 });
expect(read.calls[0]!.body).toMatchObject({ backtestId });
await expect(
read.value.submitExperiment(
{
...value.preview.input,
backtestId: backtestId.toUpperCase(),
previewHash: value.previewHash,
},
requestKey
)
).rejects.toMatchObject({ status: 429 });
expect(read.calls[1]!.body).toMatchObject({ backtestId });
await expect(
read.value.previewCosts({
name: 'Uppercase costs',
backtestId: backtestId.toUpperCase(),
scenarios: [{ feeRate: '0.01', slippageRate: '0.01' }],
})
).rejects.toMatchObject({ status: 429 });
expect(read.calls[2]!.body).toMatchObject({ backtestId });
});