From 8dc8724c526832dd93adf5eaf69d84b63b7fae3e Mon Sep 17 00:00:00 2001 From: Boki Date: Tue, 27 Oct 2026 22:00:07 -0400 Subject: [PATCH] fix(research): support typed cross-study findings (RP23) --- README.md | 7 + scripts/research-client.ts | 4 +- scripts/test/research-client.test.ts | 208 +++++++++++++++++++++ test/postgres/ai-research-workflow.test.ts | 79 ++++++++ 4 files changed, 296 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 82fa96d6..419c7601 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,13 @@ then evaluates holdouts and costs, retaining failed trials and exact evidence ci Findings remain explicitly AI-authored and unvalidated narratives. Use [ResearchClient](scripts/research-client.ts) for individual APIs, including walk-forward. +To save a comparison across studies, call `ResearchClient.saveFinding` with `source: null` +or omit `source`. Include a nonempty list of canonical metric references with each run's +exact strategy-version ID. The API resolves their values from retained completed runs; +the finding remains AI-authored and unvalidated. A supplied experiment/report source +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. + 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 55568b55..a8e9689e 100644 --- a/scripts/research-client.ts +++ b/scripts/research-client.ts @@ -705,7 +705,7 @@ export class ResearchClient { : uuid.parse(item.strategyVersionId), })), }); - expect(body.kind === 'finding' && body.evidence.length > 0 && body.source); + expect(body.kind === 'finding' && body.evidence.length > 0); for (const evidence of body.evidence) { researchEvidenceReferenceSchema.parse(evidence); expect(evidence.metricsVersion === 'canonical-analytics/v1' && evidence.strategyVersionId); @@ -724,7 +724,7 @@ export class ResearchClient { revision.title === body.title && revision.body === body.body && revision.evidenceState === 'referenced' && - same(revision.source, body.source) && + same(revision.source, body.source ?? null) && revision.evidence.length === body.evidence.length && body.evidence.every(item => revision.evidence.some( diff --git a/scripts/test/research-client.test.ts b/scripts/test/research-client.test.ts index 78aa0b1b..11fc9a8a 100644 --- a/scripts/test/research-client.test.ts +++ b/scripts/test/research-client.test.ts @@ -35,6 +35,55 @@ function client(handler: (call: Call, index: number) => Response | Promise 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> = { + 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 }; +} describe('authorized research client', () => { test('only research credentials, fixed API origin, no trading methods or redirect credential forwarding', async () => { @@ -368,6 +417,165 @@ describe('authorized research client', () => { 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!; diff --git a/test/postgres/ai-research-workflow.test.ts b/test/postgres/ai-research-workflow.test.ts index 6da17a5b..41b33922 100644 --- a/test/postgres/ai-research-workflow.test.ts +++ b/test/postgres/ai-research-workflow.test.ts @@ -469,6 +469,85 @@ describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust' ); const reopened = await f.client.validation(result.outcomes[0]!.validation!.id); expect(reopened.report).toEqual(result.outcomes[0]!.validation!.report); + + // A comparison across candidates has no single aggregate report attachment. + // Each reference must still resolve to its exact retained native result. + const comparisonInput = { + kind: 'finding' as const, + title: 'Cross-candidate observations', + body: 'AI-generated comparison, unvalidated; no comparability or profitability claim.', + hypothesisRevisionId: result.hypothesis.latestRevision.id, + evidence: result.outcomes.slice(0, 2).map(outcome => ({ + runId: outcome.validation!.report!.test.runId, + strategyVersionId: outcome.versionId, + metricsVersion: 'canonical-analytics/v1' as const, + metricPath: 'analytics.metrics.totalReturn' as const, + })), + }; + expect(new Set(comparisonInput.evidence.map(item => item.strategyVersionId)).size).toBe(2); + for (const source of [null, undefined]) { + const finding = await f.client.saveFinding(f.project.id, { ...comparisonInput, source }); + expect(finding.latestRevision).toMatchObject({ + source: null, + contentOrigin: 'ai', + submittedBy: f.provisioned.agent.id, + validationState: 'unvalidated', + evidenceState: 'referenced', + }); + expect(finding.latestRevision.evidence).toHaveLength(2); + const savedInput = f.requests.at(-1)!.body as Record; + expect(Object.hasOwn(savedInput, 'source')).toBe(source === null); + expect(savedInput.evidence).toEqual(comparisonInput.evidence); + for (const reference of finding.latestRevision.evidence) { + const native = await f.api.getRunResults(reference.runId); + if (!native || !('kind' in native) || native.kind !== 'canonical-result/v1') { + throw new Error('Missing native comparison evidence'); + } + expect(reference.strategyVersionId).toBe(native.request.strategy.versionId); + 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; + 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 artifactsBeforeRefusals = ( + await f.pool.query('SELECT count(*)::int AS count FROM analysis_artifacts') + ).rows[0].count; + const reference = comparisonInput.evidence[0]!; + for (const invalid of [ + { ...reference, strategyVersionId: result.outcomes[1]!.versionId }, + { ...reference, runId: randomUUID() }, + { + ...reference, + runId: broken.screening!.trials[0]!.runId!, + strategyVersionId: broken.versionId, + }, + ]) { + await expect( + f.client.saveFinding(f.project.id, { + ...comparisonInput, + source: null, + evidence: [invalid], + }) + ).rejects.toMatchObject({ status: 422, uncertain: false }); + } + await expect( + f.client.saveFinding(randomUUID(), { ...comparisonInput, source: null }) + ).rejects.toMatchObject({ status: 403, uncertain: false }); + expect( + (await f.pool.query('SELECT count(*)::int AS count FROM analysis_artifacts')).rows[0].count + ).toBe(artifactsBeforeRefusals); + expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe( + before + ); }, 180000); test('real quota refusal and oversized search create no runs; nonmember evidence cannot become a finding', async () => {