diff --git a/README.md b/README.md index 419c7601..c766aaf6 100644 --- a/README.md +++ b/README.md @@ -104,6 +104,12 @@ the finding remains AI-authored and unvalidated. A supplied experiment/report so instead binds the finding to that source and its membership checks. Combining references does not establish that the runs are comparable or create a sealed validation report. +Use `ResearchClient.artifact(artifactId)` to reopen a saved finding or note, and +`ResearchClient.artifactRevisions(artifactId)` to read its immutable history. Select the +revision whose `id` matches the one retained in your research journal; stop if it is absent. +The latest revision can contain a later human interpretation. These authenticated reads +preserve actual authorship, evidence units, unavailable metrics and legacy qualifications. + 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 diff --git a/scripts/research-client.ts b/scripts/research-client.ts index a8e9689e..1368d4b1 100644 --- a/scripts/research-client.ts +++ b/scripts/research-client.ts @@ -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 +) => + 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) => ({ + 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({ diff --git a/scripts/test/research-client.test.ts b/scripts/test/research-client.test.ts index 11fc9a8a..371188d5 100644 --- a/scripts/test/research-client.test.ts +++ b/scripts/test/research-client.test.ts @@ -84,6 +84,194 @@ function crossStudyFinding() { }; return { input, artifact }; } +function readableArtifact(): Awaited> { + 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(() => {})); + 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 () => { diff --git a/test/postgres/ai-research-workflow.test.ts b/test/postgres/ai-research-workflow.test.ts index 41b33922..a3938194 100644 --- a/test/postgres/ai-research-workflow.test.ts +++ b/test/postgres/ai-research-workflow.test.ts @@ -400,6 +400,11 @@ describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust' reportHash: report.reportHash, }); expect(finding.latestRevision.evidence).toHaveLength(6); + const reopenedFinding = await f.client.artifact(finding.id); + expect(reopenedFinding.latestRevision).toMatchObject(finding.latestRevision); + expect(await f.client.artifactRevisions(finding.id)).toEqual([ + reopenedFinding.latestRevision, + ]); for (const evidence of finding.latestRevision.evidence) { const saved = await f.api.getRunResults(evidence.runId); if (!saved || !('kind' in saved) || saved.kind !== 'canonical-result/v1') { @@ -507,17 +512,57 @@ describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust' expect(reference.datasetHash).toBe(native.request.datasetHash); expect(reference.value).toBe(native.analytics.metrics.totalReturn); } - const response = await f.transport( - `http://127.0.0.1:2003/api/v2/analysis-artifacts/${finding.id}`, - { headers: { Authorization: `Bearer ${f.provisioned.token}` } } - ); - expect(response.status).toBe(200); - const retained = (await response.json()).artifact; + const retained = await f.client.artifact(finding.id); expect(retained.latestRevision.id).toBe(finding.latestRevision.id); expect(retained.latestRevision.source).toBeNull(); expect(retained.latestRevision.evidence).toMatchObject(finding.latestRevision.evidence); expect(retained.latestRevision.validationState).toBe('unvalidated'); + const revised = await f.research.reviseArtifact( + finding.id, + { + expectedRevision: retained.latestRevision.ordinal, + title: 'Human follow-up to saved AI comparison', + body: 'A revised interpretation, still unvalidated.', + contentOrigin: 'human', + evidence: comparisonInput.evidence, + source: null, + }, + 'operator' + ); + const latest = await f.client.artifact(finding.id); + expect(latest.latestRevision.id).toBe(revised.latestRevision.id); + expect(latest.latestRevision.contentOrigin).toBe('human'); + expect(latest.latestRevision.submittedBy).toBe('operator'); + const history = await f.client.artifactRevisions(finding.id); + expect(history).toHaveLength(2); + expect(history.find(item => item.id === finding.latestRevision.id)).toEqual( + retained.latestRevision + ); + expect(history.find(item => item.id === revised.latestRevision.id)).toEqual( + latest.latestRevision + ); + expect(latest.latestRevision.evidence).toEqual(retained.latestRevision.evidence); + expect(f.requests.slice(-3).every(item => item.method === 'GET' && item.key === null)).toBe( + true + ); } + const note = await f.research.createArtifact( + f.project.id, + { + kind: 'note', + title: 'Service diagnostic note', + body: 'No measured claim.', + contentOrigin: 'unknown', + }, + 'service' + ); + expect((await f.client.artifact(note.id)).latestRevision).toMatchObject({ + contentOrigin: 'unknown', + submittedBy: 'service', + evidence: [], + evidenceState: 'none', + source: null, + }); const artifactsBeforeRefusals = ( await f.pool.query('SELECT count(*)::int AS count FROM analysis_artifacts') ).rows[0].count; @@ -548,6 +593,18 @@ describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust' expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe( before ); + await f.agents.update(f.provisioned.agent.id, { + expectedRevision: f.provisioned.agent.revision, + enabled: false, + }); + await expect(f.client.artifact(note.id)).rejects.toMatchObject({ + status: 401, + uncertain: false, + }); + await expect(f.client.artifactRevisions(note.id)).rejects.toMatchObject({ + status: 401, + uncertain: false, + }); }, 180000); test('real quota refusal and oversized search create no runs; nonmember evidence cannot become a finding', async () => {