feat(research): reopen original hypothesis revisions (RP29)
This commit is contained in:
parent
bbcec1c439
commit
fa78b6a791
4 changed files with 391 additions and 0 deletions
|
|
@ -123,6 +123,12 @@ revision whose `id` matches the one retained in your research journal; stop if i
|
|||
The latest revision can contain a later human interpretation. These authenticated reads
|
||||
preserve actual authorship, evidence units, unavailable metrics and legacy qualifications.
|
||||
|
||||
Reopen the original research question with `ResearchClient.hypothesis(hypothesisId)` and
|
||||
`ResearchClient.hypothesisRevisions(hypothesisId)`. Match the saved hypothesis revision ID
|
||||
from your journal or finding, and stop if it is absent. A later human edit can change the
|
||||
latest proposition and validation criteria; archived questions and their original revisions
|
||||
remain readable. These reads preserve actual authorship and do not validate a hypothesis.
|
||||
|
||||
The receipt journal is mandatory and created exclusively. On interruption, inspect its
|
||||
intents and accepted IDs, reopen durable resources, and retry only the exact idempotent
|
||||
request. Do not blindly restart a cycle: hypothesis, family and finding creation do not
|
||||
|
|
|
|||
|
|
@ -109,6 +109,21 @@ const hypothesisRecord = z.object({
|
|||
validationState: z.literal('unvalidated'),
|
||||
}),
|
||||
});
|
||||
// Reopening history preserves its actual author; creation still requires an AI acknowledgement.
|
||||
const hypothesisRevisionRecord = hypothesisRecord.shape.latestRevision.extend({
|
||||
hypothesisId: uuid,
|
||||
submittedBy: researchActorSchema,
|
||||
contentOrigin: z.enum(['human', 'ai', 'unknown']),
|
||||
createdAt: z.string().min(1),
|
||||
});
|
||||
const retainedHypothesisRecord = hypothesisRecord.extend({
|
||||
ownerPrincipal: researchActorSchema,
|
||||
updatedBy: researchActorSchema,
|
||||
archived: z.boolean(),
|
||||
createdAt: z.string().min(1),
|
||||
updatedAt: z.string().min(1),
|
||||
latestRevision: hypothesisRevisionRecord,
|
||||
});
|
||||
const availabilityMatches = (
|
||||
metric: Pick<ResearchEvidence, 'availability' | 'value' | 'unavailableReason'>
|
||||
) =>
|
||||
|
|
@ -792,6 +807,45 @@ export class ResearchClient {
|
|||
signal
|
||||
);
|
||||
}
|
||||
hypothesis(hypothesisId: string, signal?: AbortSignal) {
|
||||
hypothesisId = uuid.parse(hypothesisId);
|
||||
return this.#request(
|
||||
`hypotheses/${id(hypothesisId)}`,
|
||||
'GET',
|
||||
200,
|
||||
value => {
|
||||
const saved = retainedHypothesisRecord.parse(envelope(value, 'hypothesis'));
|
||||
expect(saved.id === hypothesisId && saved.latestRevision.hypothesisId === hypothesisId);
|
||||
return saved;
|
||||
},
|
||||
undefined,
|
||||
undefined,
|
||||
signal
|
||||
);
|
||||
}
|
||||
hypothesisRevisions(hypothesisId: string, signal?: AbortSignal) {
|
||||
hypothesisId = uuid.parse(hypothesisId);
|
||||
return this.#request(
|
||||
`hypotheses/${id(hypothesisId)}/revisions`,
|
||||
'GET',
|
||||
200,
|
||||
value => {
|
||||
const revisions = z
|
||||
.array(hypothesisRevisionRecord)
|
||||
.min(1)
|
||||
.parse(envelope(value, 'revisions'));
|
||||
expect(
|
||||
revisions.every(revision => revision.hypothesisId === hypothesisId) &&
|
||||
new Set(revisions.map(revision => revision.id)).size === revisions.length &&
|
||||
new Set(revisions.map(revision => revision.ordinal)).size === revisions.length
|
||||
);
|
||||
return revisions;
|
||||
},
|
||||
undefined,
|
||||
undefined,
|
||||
signal
|
||||
);
|
||||
}
|
||||
artifact(artifactId: string, signal?: AbortSignal) {
|
||||
artifactId = uuid.parse(artifactId);
|
||||
return this.#request(
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -260,6 +260,81 @@ async function fixture() {
|
|||
}
|
||||
|
||||
describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust', () => {
|
||||
test('hypothesis reads retain original questions, human revisions and archival without writes', async () => {
|
||||
const f = await fixture();
|
||||
const created = await f.client.createHypothesis(f.project.id, f.suggestions().hypothesis);
|
||||
const original = (await f.research.getHypothesis(created.id)).latestRevision;
|
||||
const revised = await f.research.reviseHypothesis(
|
||||
created.id,
|
||||
{
|
||||
expectedRevision: original.ordinal,
|
||||
title: 'Human follow-up question',
|
||||
proposition: 'A changed proposition is not the original research question.',
|
||||
validationCriteria: 'Additional validation remains necessary.',
|
||||
contentOrigin: 'human',
|
||||
},
|
||||
'operator'
|
||||
);
|
||||
const archived = await f.research.archiveHypothesis(created.id, { archived: true }, 'operator');
|
||||
const serviceQuestion = await f.research.createHypothesis(
|
||||
f.project.id,
|
||||
{ title: 'Service diagnostic', proposition: 'No measured claim.', contentOrigin: 'unknown' },
|
||||
'service'
|
||||
);
|
||||
const totals = async () =>
|
||||
(
|
||||
await f.pool.query(`SELECT
|
||||
(SELECT count(*)::int FROM runs) AS runs,
|
||||
(SELECT count(*)::int FROM research_experiments) AS experiments,
|
||||
(SELECT count(*)::int FROM research_hypotheses) AS hypotheses,
|
||||
(SELECT count(*)::int FROM research_hypothesis_revisions) AS revisions,
|
||||
(SELECT count(*)::int FROM analysis_artifacts) AS artifacts`)
|
||||
).rows[0];
|
||||
const before = await totals();
|
||||
const requestStart = f.requests.length;
|
||||
expect(await f.client.hypothesis(created.id)).toEqual(archived);
|
||||
const history = await f.client.hypothesisRevisions(created.id);
|
||||
expect(history).toEqual([original, revised.latestRevision]);
|
||||
expect(history.find(item => item.id === created.latestRevision.id)).toEqual(original);
|
||||
expect<string>(history[0]!.submittedBy).toBe(f.provisioned.agent.id);
|
||||
expect(history[0]!.contentOrigin).toBe('ai');
|
||||
expect(history[1]!.submittedBy).toBe('operator');
|
||||
expect(history[1]!.contentOrigin).toBe('human');
|
||||
expect(history.every(item => item.validationState === 'unvalidated')).toBeTrue();
|
||||
expect(await f.client.hypothesis(serviceQuestion.id)).toEqual(serviceQuestion);
|
||||
expect(await f.client.hypothesisRevisions(serviceQuestion.id)).toEqual([
|
||||
serviceQuestion.latestRevision,
|
||||
]);
|
||||
const missing = randomUUID();
|
||||
await expect(f.client.hypothesis(missing)).rejects.toMatchObject({
|
||||
status: 404,
|
||||
uncertain: false,
|
||||
});
|
||||
await expect(f.client.hypothesisRevisions(missing)).rejects.toMatchObject({
|
||||
status: 404,
|
||||
uncertain: false,
|
||||
});
|
||||
expect(
|
||||
f.requests
|
||||
.slice(requestStart)
|
||||
.every(
|
||||
request => request.method === 'GET' && request.key === null && request.body === undefined
|
||||
)
|
||||
).toBeTrue();
|
||||
expect(await totals()).toEqual(before);
|
||||
await f.agents.update(f.provisioned.agent.id, { expectedRevision: 1, enabled: false });
|
||||
await expect(f.client.hypothesis(created.id)).rejects.toMatchObject({
|
||||
status: 401,
|
||||
uncertain: false,
|
||||
});
|
||||
await expect(f.client.hypothesisRevisions(created.id)).rejects.toMatchObject({
|
||||
status: 401,
|
||||
uncertain: false,
|
||||
});
|
||||
expect(await totals()).toEqual(before);
|
||||
expect(f.executionErrors).toEqual([]);
|
||||
});
|
||||
|
||||
test('research credentials export known immutable snapshots with exact read-only scope', async () => {
|
||||
const f = await fixture();
|
||||
const hash = f.dataset.manifest.hash;
|
||||
|
|
@ -558,6 +633,27 @@ describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust'
|
|||
|
||||
// A comparison across candidates has no single aggregate report attachment.
|
||||
// Each reference must still resolve to its exact retained native result.
|
||||
const originalQuestion = await f.client.hypothesis(result.hypothesis.id);
|
||||
expect(originalQuestion.latestRevision).toMatchObject(result.hypothesis.latestRevision);
|
||||
const revisedQuestion = await f.research.reviseHypothesis(
|
||||
result.hypothesis.id,
|
||||
{
|
||||
expectedRevision: originalQuestion.latestRevision.ordinal,
|
||||
title: 'Later human interpretation',
|
||||
proposition: 'This revision must not replace the candidate study question.',
|
||||
validationCriteria: 'Further validation is required.',
|
||||
contentOrigin: 'human',
|
||||
},
|
||||
'operator'
|
||||
);
|
||||
expect((await f.client.hypothesis(result.hypothesis.id)).latestRevision).toEqual(
|
||||
revisedQuestion.latestRevision
|
||||
);
|
||||
const questionHistory = await f.client.hypothesisRevisions(result.hypothesis.id);
|
||||
expect(questionHistory).toEqual([
|
||||
originalQuestion.latestRevision,
|
||||
revisedQuestion.latestRevision,
|
||||
]);
|
||||
const comparisonInput = {
|
||||
kind: 'finding' as const,
|
||||
title: 'Cross-candidate observations',
|
||||
|
|
@ -594,6 +690,10 @@ describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust'
|
|||
expect(reference.value).toBe(native.analytics.metrics.totalReturn);
|
||||
}
|
||||
const retained = await f.client.artifact(finding.id);
|
||||
expect(retained.hypothesisRevisionId).toBe(originalQuestion.latestRevision.id);
|
||||
expect(questionHistory.find(item => item.id === retained.hypothesisRevisionId)).toEqual(
|
||||
originalQuestion.latestRevision
|
||||
);
|
||||
expect(retained.latestRevision.id).toBe(finding.latestRevision.id);
|
||||
expect(retained.latestRevision.source).toBeNull();
|
||||
expect(retained.latestRevision.evidence).toMatchObject(finding.latestRevision.evidence);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue