feat(research): reopen artifacts and immutable history (RP25)
This commit is contained in:
parent
f9b97c3004
commit
e39989c4d5
4 changed files with 385 additions and 16 deletions
|
|
@ -57,7 +57,7 @@ import {
|
|||
type WalkForwardInput,
|
||||
type WalkForwardSubmission,
|
||||
} from '@stock-bot/stock-config/walk-forward';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
import type { ResearchEvidence, StrategyVersionPackage } from '@stock-bot/types';
|
||||
|
||||
const uuid = z
|
||||
.string()
|
||||
|
|
@ -107,6 +107,14 @@ const hypothesisRecord = z.object({
|
|||
validationState: z.literal('unvalidated'),
|
||||
}),
|
||||
});
|
||||
const availabilityMatches = (
|
||||
metric: Pick<ResearchEvidence, 'availability' | 'value' | 'unavailableReason'>
|
||||
) =>
|
||||
metric.availability === 'available'
|
||||
? metric.value !== null && metric.unavailableReason === null
|
||||
: metric.value === null &&
|
||||
typeof metric.unavailableReason === 'string' &&
|
||||
metric.unavailableReason.trim().length > 0;
|
||||
const findingRecord = z.object({
|
||||
id: uuid,
|
||||
projectId: uuid,
|
||||
|
|
@ -136,19 +144,86 @@ const findingRecord = z.object({
|
|||
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'
|
||||
)
|
||||
.refine(availabilityMatches, 'Metric availability must match its value and reason')
|
||||
),
|
||||
}),
|
||||
});
|
||||
|
||||
// Reads include human revisions, notes and qualified historical measurements.
|
||||
// Creation keeps the narrower AI/canonical findingRecord above.
|
||||
const retainedEvidenceRecord = z
|
||||
.object({
|
||||
runId: uuid,
|
||||
backtestId: uuid,
|
||||
strategyVersionId: uuid.nullable().optional(),
|
||||
metricsVersion: z.enum(['canonical-analytics/v1', 'legacy-display/v1']),
|
||||
metricPath: z.string(),
|
||||
value: z.number().finite().nullable(),
|
||||
unit: z.enum(['fraction', 'ratio', 'count', 'currency']),
|
||||
availability: z.enum(['available', 'unavailable']),
|
||||
unavailableReason: z.string().nullable(),
|
||||
datasetHash: hash.nullable(),
|
||||
resultKind: z.enum(['canonical', 'legacy']),
|
||||
financialEngine: z.enum(['rust', 'native', 'typescript', 'legacy']),
|
||||
limitations: z.array(z.object({ code: z.string(), message: z.string() })),
|
||||
})
|
||||
.refine(availabilityMatches, 'Metric availability must match its value and reason')
|
||||
.refine(
|
||||
metric =>
|
||||
metric.metricsVersion === 'canonical-analytics/v1'
|
||||
? metric.resultKind === 'canonical' &&
|
||||
metric.financialEngine === 'rust' &&
|
||||
metric.datasetHash !== null
|
||||
: metric.resultKind === 'legacy' &&
|
||||
metric.financialEngine !== 'rust' &&
|
||||
!metric.strategyVersionId,
|
||||
'Metrics version must match the retained result and engine'
|
||||
);
|
||||
const referenceOf = ({
|
||||
runId,
|
||||
metricsVersion,
|
||||
metricPath,
|
||||
strategyVersionId,
|
||||
}: z.output<typeof retainedEvidenceRecord>) => ({
|
||||
runId,
|
||||
metricsVersion,
|
||||
metricPath,
|
||||
strategyVersionId,
|
||||
});
|
||||
const artifactRevisionRecord = z
|
||||
.object({
|
||||
id: uuid,
|
||||
artifactId: uuid,
|
||||
ordinal: z.number().int().positive(),
|
||||
title: z.string(),
|
||||
body: z.string(),
|
||||
submittedBy: researchActorSchema,
|
||||
contentOrigin: z.enum(['human', 'ai', 'unknown']),
|
||||
validationState: z.literal('unvalidated'),
|
||||
evidenceState: z.enum(['none', 'referenced']),
|
||||
source: researchFindingSourceSchema.nullable().default(null),
|
||||
evidence: z.array(retainedEvidenceRecord),
|
||||
createdAt: z.string().min(1),
|
||||
})
|
||||
.refine(
|
||||
revision =>
|
||||
revision.evidenceState === (revision.evidence.length ? 'referenced' : 'none') &&
|
||||
createResearchArtifactSchema.shape.evidence.safeParse(revision.evidence.map(referenceOf))
|
||||
.success &&
|
||||
(!revision.source ||
|
||||
(revision.evidence.length > 0 &&
|
||||
revision.evidence.every(metric => metric.metricsVersion === 'canonical-analytics/v1'))),
|
||||
'Retained evidence must match its state, references and source'
|
||||
);
|
||||
const artifactRecord = findingRecord.extend({
|
||||
ownerPrincipal: researchActorSchema,
|
||||
updatedBy: researchActorSchema,
|
||||
archived: z.boolean(),
|
||||
createdAt: z.string().min(1),
|
||||
updatedAt: z.string().min(1),
|
||||
latestRevision: artifactRevisionRecord,
|
||||
});
|
||||
|
||||
export class ResearchRequestError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
|
|
@ -687,6 +762,49 @@ export class ResearchClient {
|
|||
key
|
||||
);
|
||||
}
|
||||
artifact(artifactId: string, signal?: AbortSignal) {
|
||||
artifactId = uuid.parse(artifactId);
|
||||
return this.#request(
|
||||
`analysis-artifacts/${id(artifactId)}`,
|
||||
'GET',
|
||||
200,
|
||||
value => {
|
||||
const saved = artifactRecord.parse(envelope(value, 'artifact'));
|
||||
expect(
|
||||
saved.id === artifactId &&
|
||||
saved.latestRevision.artifactId === artifactId &&
|
||||
(saved.kind !== 'finding' || saved.latestRevision.evidence.length > 0)
|
||||
);
|
||||
return saved;
|
||||
},
|
||||
undefined,
|
||||
undefined,
|
||||
signal
|
||||
);
|
||||
}
|
||||
artifactRevisions(artifactId: string, signal?: AbortSignal) {
|
||||
artifactId = uuid.parse(artifactId);
|
||||
return this.#request(
|
||||
`analysis-artifacts/${id(artifactId)}/revisions`,
|
||||
'GET',
|
||||
200,
|
||||
value => {
|
||||
const revisions = z
|
||||
.array(artifactRevisionRecord)
|
||||
.min(1)
|
||||
.parse(envelope(value, 'revisions'));
|
||||
expect(
|
||||
revisions.every(revision => revision.artifactId === artifactId) &&
|
||||
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
|
||||
);
|
||||
}
|
||||
saveFinding(projectId: string, input: FindingInput) {
|
||||
projectId = uuid.parse(projectId);
|
||||
const body = createResearchArtifactSchema.parse({
|
||||
|
|
|
|||
|
|
@ -84,6 +84,194 @@ function crossStudyFinding() {
|
|||
};
|
||||
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 () => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue