feat(research): reopen original hypothesis revisions (RP29)

This commit is contained in:
Boki 2026-10-28 00:38:38 -04:00
parent bbcec1c439
commit fa78b6a791
4 changed files with 391 additions and 0 deletions

View file

@ -1,6 +1,7 @@
import { createHash } from 'node:crypto';
import { describe, expect, test } from 'bun:test';
import type { ExperimentDetail } from '@stock-bot/stock-config/experiments';
import type { ResearchHypothesis } from '@stock-bot/types';
import { canonicalResultFixture } from '../../test/fixtures/canonical-result';
import { nativeReplayFixture } from '../../test/fixtures/native-replay';
import { comparisonFixture, tableFixture } from '../benchmark-experiment-tables';
@ -38,6 +39,236 @@ function client(handler: (call: Call, index: number) => Response | Promise<Respo
}
const ordinary = () => tableFixture(1) as ExperimentDetail;
function readableHypothesis(): ResearchHypothesis {
const createdAt = '2026-10-28T12:00:00.000Z';
return {
id: hypothesisId,
projectId,
ownerPrincipal: agent,
updatedBy: agent,
archived: false,
createdAt,
updatedAt: createdAt,
latestRevision: {
id: revisionId,
hypothesisId,
ordinal: 1,
title: 'Original research question',
proposition: 'A candidate may behave differently in high volatility.\nUnvalidated.',
validationCriteria: 'Freeze chronological holdouts before exploration.',
submittedBy: agent,
contentOrigin: 'ai',
validationState: 'unvalidated',
createdAt,
},
};
}
describe('retained research hypothesis reads', () => {
test('reopens the complete hypothesis through authenticated GET without mutation', async () => {
const hypothesis = readableHypothesis();
const before = structuredClone(hypothesis);
const { value, calls } = client(() => Response.json({ hypothesis }));
expect(await value.hypothesis(hypothesisId)).toEqual(before);
expect(hypothesis).toEqual(before);
expect(calls).toHaveLength(1);
expect(calls[0]!.url.pathname).toBe(`/api/v2/hypotheses/${hypothesisId}`);
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('recovers the original AI question after a human edit and archival without reordering', async () => {
const original = readableHypothesis().latestRevision;
const latest: typeof original = {
...original,
id: artifactId,
ordinal: 2,
title: 'Later human question',
proposition: 'A different proposition; do not replace the original.',
validationCriteria: 'Different criteria.',
submittedBy: 'operator',
contentOrigin: 'human',
createdAt: '2026-10-28T13:00:00.000Z',
};
const hypothesis: ResearchHypothesis = {
...readableHypothesis(),
latestRevision: latest,
updatedBy: 'operator',
archived: true,
updatedAt: latest.createdAt,
};
// Selection is by saved revision ID, regardless of the response's ordering.
const revisions = [latest, original];
const { value, calls } = client((_call, index) =>
Response.json(index ? { revisions } : { hypothesis })
);
expect(await value.hypothesis(hypothesisId)).toEqual(hypothesis);
const history = await value.hypothesisRevisions(hypothesisId);
expect(history).toEqual(revisions);
expect(history.find(item => item.id === revisionId)).toEqual(original);
expect(history.find(item => item.id === projectId)).toBeUndefined();
expect(calls).toHaveLength(2);
expect(calls[1]!.url.pathname).toBe(`/api/v2/hypotheses/${hypothesisId}/revisions`);
expect(calls.every(call => call.init.method === 'GET' && call.body === undefined)).toBe(true);
});
test('retains service authorship and unknown origin without treating the question as evidence', async () => {
const hypothesis = readableHypothesis();
hypothesis.ownerPrincipal = 'service';
hypothesis.updatedBy = 'service';
hypothesis.latestRevision.submittedBy = 'service';
hypothesis.latestRevision.contentOrigin = 'unknown';
hypothesis.latestRevision.validationCriteria = '';
const { value } = client(() => Response.json({ hypothesis }));
expect(await value.hypothesis(hypothesisId)).toEqual(hypothesis);
});
test('broader retained reads do not relax the AI creation acknowledgement', async () => {
const hypothesis = readableHypothesis();
const { title, proposition, validationCriteria } = hypothesis.latestRevision;
for (const change of [
{ contentOrigin: 'human', submittedBy: 'operator' },
{ contentOrigin: 'unknown', submittedBy: 'service' },
{ submittedBy: 'operator' },
{ validationState: 'validated' },
]) {
const { value, calls } = client(() =>
Response.json(
{
hypothesis: {
...hypothesis,
latestRevision: { ...hypothesis.latestRevision, ...change },
},
},
{ status: 201 }
)
);
await expect(
value.createHypothesis(projectId, { title, proposition, validationCriteria })
).rejects.toMatchObject({ uncertain: true, status: null });
expect(calls).toHaveLength(1);
expect(calls[0]!.body).toEqual({
title,
proposition,
validationCriteria,
contentOrigin: 'ai',
});
}
});
test('rejects foreign identities and malformed hypotheses as read errors', async () => {
const hypothesis = readableHypothesis();
const revision = hypothesis.latestRevision;
for (const body of [
null,
{},
{ hypothesis: null },
...[
{ id: projectId },
{ projectId: 'invalid' },
{ ownerPrincipal: 'anonymous' },
{ updatedBy: 'anonymous' },
{ archived: null },
{ createdAt: '' },
{ latestRevision: null },
...[
{ hypothesisId: projectId },
{ id: 'invalid' },
{ ordinal: 0 },
{ title: null },
{ proposition: null },
{ validationCriteria: undefined },
{ submittedBy: 'anonymous' },
{ contentOrigin: 'generated' },
{ validationState: 'validated' },
{ createdAt: '' },
].map(change => ({ latestRevision: { ...revision, ...change } })),
].map(change => ({ hypothesis: { ...hypothesis, ...change } })),
]) {
const { value, calls } = client(() => Response.json(body));
await expect(value.hypothesis(hypothesisId)).rejects.toMatchObject({
name: 'ResearchRequestError',
uncertain: false,
status: null,
});
expect(calls).toHaveLength(1);
expect(calls[0]!.init.method).toBe('GET');
}
});
test('rejects empty, mixed-parent and duplicate histories instead of substituting latest', async () => {
const revision = readableHypothesis().latestRevision;
for (const revisions of [
null,
[],
[{ ...revision, hypothesisId: projectId }],
[revision, { ...revision, ordinal: 2 }],
[revision, { ...revision, id: artifactId }],
[{ ...revision, ordinal: 0 }],
[{ ...revision, validationState: 'validated' }],
[{ ...revision, proposition: null }],
]) {
const { value, calls } = client(() => Response.json({ revisions }));
await expect(value.hypothesisRevisions(hypothesisId)).rejects.toMatchObject({
uncertain: false,
status: null,
});
expect(calls).toHaveLength(1);
}
});
test('invalid IDs, unavailable responses and aborts never create or retry hypotheses', async () => {
const invalid = client(() => {
throw new Error('No transport expected');
});
expect(() => invalid.value.hypothesis('../strategies')).toThrow();
expect(() => invalid.value.hypothesisRevisions('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.hypothesis(hypothesisId)).rejects.toMatchObject({
status,
uncertain: false,
});
await expect(value.hypothesisRevisions(hypothesisId)).rejects.toMatchObject({
status,
uncertain: false,
});
expect(calls).toHaveLength(2);
}
const controller = new AbortController();
const stalled = client(() => new Promise<Response>(() => {}));
const pending = stalled.value.hypothesis(hypothesisId, controller.signal);
controller.abort();
await expect(pending).rejects.toMatchObject({ uncertain: false });
await expect(
stalled.value.hypothesisRevisions(hypothesisId, controller.signal)
).rejects.toMatchObject({ uncertain: false });
expect(stalled.calls).toHaveLength(1);
});
test('both reads observe the existing deadline even with an uncooperative transport', async () => {
const calls: RequestInit[] = [];
const value = new ResearchClient({
origin: 'http://127.0.0.1:2003',
token,
requestTimeoutMs: 5,
fetch: ((_url: string | URL | Request, init?: RequestInit) => {
calls.push(init!);
return new Promise<Response>(() => {});
}) as typeof fetch,
});
await expect(value.hypothesis(hypothesisId)).rejects.toMatchObject({ uncertain: false });
await expect(value.hypothesisRevisions(hypothesisId)).rejects.toMatchObject({
uncertain: false,
});
expect(calls).toHaveLength(2);
expect(calls.every(call => call.method === 'GET' && call.signal?.aborted)).toBe(true);
});
});
describe('frozen market data inspection', () => {
test('reads the complete requested snapshot without changing bars or metadata', async () => {
const dataset = nativeReplayFixture().dataset;