From f46fb87c74df3072346b0d56223d0a15585fce15 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 07:39:50 -0500 Subject: [PATCH] T-138: tests --- .../research/test/mcp-file-finding-qa.test.ts | 469 ++++++++++++++++++ 1 file changed, 469 insertions(+) create mode 100644 libs/research/test/mcp-file-finding-qa.test.ts diff --git a/libs/research/test/mcp-file-finding-qa.test.ts b/libs/research/test/mcp-file-finding-qa.test.ts new file mode 100644 index 00000000..397637ba --- /dev/null +++ b/libs/research/test/mcp-file-finding-qa.test.ts @@ -0,0 +1,469 @@ +import { describe, expect, test } from 'bun:test'; +import { + type AppendFindingResult, + FILE_FINDING_ERROR_FILING_FAILED, + FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT, + FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, + FILE_FINDING_MAX_EVIDENCE_REFS, + FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, + FILE_FINDING_MAX_REF_LENGTH, + FILE_FINDING_MAX_SUMMARY_LENGTH, + FILE_FINDING_MAX_TITLE_LENGTH, + FILE_FINDING_MAX_TRIAL_REFS, + type FileFindingResultPayload, + type FiledFindingRecord, + type FindingWritePort, + type TrialRefLookupPort, + areFiledFindingPayloadsEqual, + createFileFindingTool, +} from '../src/mcp/index'; + +// Compile-time guard: the write port exposes exactly one append method (no update/delete). +type Equal = (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 + ? true + : false; +const writePortKeysAreAppendOnly: Equal = true; + +const FIXED_EPOCH_MS = Date.UTC(2025, 5, 2, 15, 30, 0); + +interface RecordingPort { + readonly calls: { record: FiledFindingRecord; idempotencyKey: string | undefined }[]; + readonly port: FindingWritePort; +} + +function recordingPort( + respond: (record: FiledFindingRecord, key: string | undefined) => unknown +): RecordingPort { + const calls: RecordingPort['calls'] = []; + return { + calls, + port: { + async appendFinding(record, idempotencyKey) { + calls.push({ record, idempotencyKey }); + return respond(record, idempotencyKey) as AppendFindingResult; + }, + }, + }; +} + +function createdEcho(record: FiledFindingRecord): AppendFindingResult { + return { status: 'created', id: record.id, createdAt: record.createdAt }; +} + +function lookupFrom( + answer: (ref: string) => unknown +): { readonly queried: string[]; readonly port: TrialRefLookupPort } { + const queried: string[] = []; + return { + queried, + port: { + hasResearchVisibleTrial(ref: string) { + queried.push(ref); + return answer(ref) as boolean; + }, + }, + }; +} + +function counter(fn: () => T): { calls: number; fn: () => T } { + const state = { + calls: 0, + fn: () => { + state.calls += 1; + return fn(); + }, + }; + return state; +} + +const validArgs = { + kind: 'finding', + title: 'QA filing', + summary: 'Research-visible summary.', + trialRefs: ['trial-1'], +}; + +function parseReceipt(text: string | undefined): FileFindingResultPayload { + return JSON.parse(text ?? '') as FileFindingResultPayload; +} + +describe('MCP file_finding QA edge cases', () => { + test('write port type exposes only appendFinding', () => { + expect(writePortKeysAreAppendOnly).toBe(true); + }); + + test('deduplicates trial refs before lookup, verifies in sorted order, and short-circuits on the first unavailable ref', async () => { + const rec = recordingPort(createdEcho); + const lookup = lookupFrom(ref => ref !== 'trial-b'); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookup.port, + newId: () => 'id-1', + now: () => FIXED_EPOCH_MS, + }); + + const res = await tool.execute({ + ...validArgs, + trialRefs: ['trial-c', 'trial-a', 'trial-b', 'trial-a', 'trial-c'], + }); + + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(lookup.queried).toEqual(['trial-a', 'trial-b']); + expect(rec.calls).toHaveLength(0); + }); + + test('accepts a synchronous boolean lookup and queries each unique ref exactly once on success', async () => { + const rec = recordingPort(createdEcho); + const lookup = lookupFrom(() => true); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookup.port, + newId: () => 'id-sync', + now: () => FIXED_EPOCH_MS, + }); + + const res = await tool.execute({ ...validArgs, trialRefs: ['t2', 't1', 't2', 't1'] }); + + expect(res.isError).toBeUndefined(); + expect(lookup.queried).toEqual(['t1', 't2']); + expect(rec.calls).toHaveLength(1); + expect(rec.calls[0]?.record.trialRefs).toEqual(['t1', 't2']); + }); + + test('treats non-boolean lookup answers as a filing failure with zero writes and no metadata generation', async () => { + for (const answer of [1, 'true', null, undefined, {}]) { + const rec = recordingPort(createdEcho); + const ids = counter(() => 'never'); + const clock = counter(() => FIXED_EPOCH_MS); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookupFrom(() => answer).port, + newId: ids.fn, + now: clock.fn, + }); + + const res = await tool.execute(validArgs); + + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(rec.calls).toHaveLength(0); + expect(ids.calls).toBe(0); + expect(clock.calls).toBe(0); + } + }); + + test('rejects unusable generated ids and clock values with a fixed error and zero writes', async () => { + const badSources: readonly { + readonly label: string; + readonly newId: () => string; + readonly now: () => Date | number; + }[] = [ + { label: 'empty id', newId: () => '', now: () => FIXED_EPOCH_MS }, + { label: 'blank id', newId: () => ' ', now: () => FIXED_EPOCH_MS }, + { label: 'non-string id', newId: () => 42 as unknown as string, now: () => FIXED_EPOCH_MS }, + { + label: 'throwing id source', + newId: () => { + throw new Error('postgres://u:p@db/x id sequence exhausted'); + }, + now: () => FIXED_EPOCH_MS, + }, + { label: 'NaN clock', newId: () => 'id-1', now: () => Number.NaN }, + { label: 'infinite clock', newId: () => 'id-1', now: () => Number.POSITIVE_INFINITY }, + { label: 'invalid Date', newId: () => 'id-1', now: () => new Date('not-a-date') }, + { label: 'out-of-range epoch', newId: () => 'id-1', now: () => 9e15 }, + { label: 'string clock', newId: () => 'id-1', now: () => '2025-01-01' as unknown as number }, + { + label: 'throwing clock', + newId: () => 'id-1', + now: () => { + throw new Error('clock unavailable at /srv/secret.ts:1:1'); + }, + }, + ]; + + for (const source of badSources) { + const rec = recordingPort(createdEcho); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookupFrom(() => true).port, + newId: source.newId, + now: source.now, + }); + + const res = await tool.execute(validArgs); + + expect({ label: source.label, isError: res.isError }).toEqual({ + label: source.label, + isError: true, + }); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(rec.calls).toHaveLength(0); + } + }); + + test('stores Date and epoch clock values as identical UTC ISO timestamps', async () => { + const fromDate = recordingPort(createdEcho); + const fromEpoch = recordingPort(createdEcho); + const lookup = lookupFrom(() => true).port; + + await createFileFindingTool({ + port: fromDate.port, + trialLookup: lookup, + newId: () => 'id-d', + now: () => new Date(FIXED_EPOCH_MS), + }).execute(validArgs); + await createFileFindingTool({ + port: fromEpoch.port, + trialLookup: lookup, + newId: () => 'id-e', + now: () => FIXED_EPOCH_MS, + }).execute(validArgs); + + expect(fromDate.calls[0]?.record.createdAt).toBe('2025-06-02T15:30:00.000Z'); + expect(fromEpoch.calls[0]?.record.createdAt).toBe('2025-06-02T15:30:00.000Z'); + }); + + test('passes the trimmed idempotency key to the port and undefined when omitted', async () => { + const rec = recordingPort(createdEcho); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookupFrom(() => true).port, + newId: () => 'id-k', + now: () => FIXED_EPOCH_MS, + }); + + await tool.execute({ ...validArgs, idempotencyKey: '\t retry-key-7 \n' }); + await tool.execute(validArgs); + + expect(rec.calls.map(c => c.idempotencyKey)).toEqual(['retry-key-7', undefined]); + }); + + test('receipt reflects the port-stored id and timestamp on replay, not freshly generated metadata', async () => { + const rec = recordingPort(() => ({ + status: 'replayed', + id: 'stored-original', + createdAt: '2024-12-31T23:59:59.000Z', + })); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookupFrom(() => true).port, + newId: () => 'fresh-id', + now: () => FIXED_EPOCH_MS, + }); + + const res = await tool.execute({ ...validArgs, idempotencyKey: 'k' }); + + expect(res.isError).toBeUndefined(); + expect(parseReceipt(res.content[0]?.text)).toEqual({ + id: 'stored-original', + createdAt: '2024-12-31T23:59:59.000Z', + created: false, + }); + }); + + test('maps malformed port outcomes to the fixed filing error and conflict to the fixed conflict error', async () => { + const malformed: readonly unknown[] = [ + null, + undefined, + 'created', + {}, + { status: 'updated', id: 'x', createdAt: 'y' }, + { status: 'created', id: '', createdAt: '2025-01-01T00:00:00.000Z' }, + { status: 'created', id: 'x' }, + { status: 'replayed', id: 7, createdAt: '2025-01-01T00:00:00.000Z' }, + ]; + + for (const outcome of malformed) { + const tool = createFileFindingTool({ + port: recordingPort(() => outcome).port, + trialLookup: lookupFrom(() => true).port, + newId: () => 'id-m', + now: () => FIXED_EPOCH_MS, + }); + const res = await tool.execute(validArgs); + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + } + + const conflictTool = createFileFindingTool({ + port: recordingPort(() => ({ status: 'conflict' })).port, + trialLookup: lookupFrom(() => true).port, + newId: () => 'id-c', + now: () => FIXED_EPOCH_MS, + }); + const conflict = await conflictTool.execute({ ...validArgs, idempotencyKey: 'k' }); + expect(conflict.isError).toBe(true); + expect(conflict.content[0]?.text).toBe(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT); + }); + + test('accepts every field exactly at its hard limit', async () => { + const rec = recordingPort(createdEcho); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookupFrom(() => true).port, + newId: () => 'id-limit', + now: () => FIXED_EPOCH_MS, + }); + const trialRefs = Array.from({ length: FILE_FINDING_MAX_TRIAL_REFS }, (_, i) => + `t${String(i).padStart(2, '0')}`.padEnd(FILE_FINDING_MAX_REF_LENGTH, 'x') + ); + const evidenceRefs = Array.from({ length: FILE_FINDING_MAX_EVIDENCE_REFS }, (_, i) => + `e${String(i).padStart(2, '0')}`.padEnd(FILE_FINDING_MAX_REF_LENGTH, 'y') + ); + + const res = await tool.execute({ + kind: 'dead_end', + title: 'T'.repeat(FILE_FINDING_MAX_TITLE_LENGTH), + summary: 'S'.repeat(FILE_FINDING_MAX_SUMMARY_LENGTH), + trialRefs, + evidenceRefs, + idempotencyKey: 'K'.repeat(FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH), + }); + + expect(res.isError).toBeUndefined(); + expect(rec.calls).toHaveLength(1); + expect(rec.calls[0]?.record.trialRefs).toHaveLength(FILE_FINDING_MAX_TRIAL_REFS); + expect(rec.calls[0]?.record.evidenceRefs).toHaveLength(FILE_FINDING_MAX_EVIDENCE_REFS); + }); + + test('measures limits after trimming, so padded at-limit text is accepted', async () => { + const rec = recordingPort(createdEcho); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookupFrom(() => true).port, + newId: () => 'id-trim', + now: () => FIXED_EPOCH_MS, + }); + + const res = await tool.execute({ + ...validArgs, + title: ` ${'T'.repeat(FILE_FINDING_MAX_TITLE_LENGTH)} `, + }); + + expect(res.isError).toBeUndefined(); + expect(rec.calls[0]?.record.title).toHaveLength(FILE_FINDING_MAX_TITLE_LENGTH); + }); + + test('validation errors never echo submitted text, refs, or keys', async () => { + const sentinel = 'HOLDOUT_OBSERVATION_SENTINEL_0x5f3'; + const rec = recordingPort(createdEcho); + const tool = createFileFindingTool({ + port: rec.port, + trialLookup: lookupFrom(() => true).port, + newId: () => 'id-v', + now: () => FIXED_EPOCH_MS, + }); + + const cases: readonly Record[] = [ + { ...validArgs, summary: `${sentinel} `.repeat(FILE_FINDING_MAX_SUMMARY_LENGTH) }, + { ...validArgs, title: sentinel.repeat(20) }, + { ...validArgs, trialRefs: [sentinel.repeat(10)] }, + { ...validArgs, evidenceRefs: [sentinel.repeat(10)] }, + { ...validArgs, idempotencyKey: sentinel.repeat(5) }, + { ...validArgs, kind: sentinel }, + { ...validArgs, [sentinel]: 1.2345 }, + { ...validArgs, observations: [{ date: '2025-09-01', value: sentinel }] }, + ]; + + for (const args of cases) { + const res = await tool.execute(args); + expect(res.isError).toBe(true); + expect(res.content[0]?.text).not.toContain(sentinel); + } + expect(rec.calls).toHaveLength(0); + }); + + test('concurrent same-key filings across two tool instances store one row (promise barrier, no timers)', async () => { + const stored: FiledFindingRecord[] = []; + const byKey = new Map(); + let releaseFirst: () => void = () => undefined; + const firstHeld = new Promise(resolve => { + releaseFirst = resolve; + }); + let secondArrived: () => void = () => undefined; + const secondReached = new Promise(resolve => { + secondArrived = resolve; + }); + let callIndex = 0; + + const port: FindingWritePort = { + async appendFinding(record, key) { + callIndex += 1; + const mine = callIndex; + // Atomic compare-and-append (no await between read and write). + let outcome: AppendFindingResult; + const existing = key === undefined ? undefined : byKey.get(key); + if (existing === undefined) { + stored.push(record); + if (key !== undefined) { + byKey.set(key, record); + } + outcome = { status: 'created', id: record.id, createdAt: record.createdAt }; + } else if (areFiledFindingPayloadsEqual(existing, record)) { + outcome = { status: 'replayed', id: existing.id, createdAt: existing.createdAt }; + } else { + outcome = { status: 'conflict' }; + } + if (mine === 1) { + await firstHeld; + } else { + secondArrived(); + } + return outcome; + }, + }; + const lookup = lookupFrom(() => true).port; + const toolA = createFileFindingTool({ + port, + trialLookup: lookup, + newId: () => 'inst-a', + now: () => FIXED_EPOCH_MS, + }); + const toolB = createFileFindingTool({ + port, + trialLookup: lookup, + newId: () => 'inst-b', + now: () => FIXED_EPOCH_MS + 1_000, + }); + const args = { ...validArgs, idempotencyKey: 'concurrent' }; + + const pendingA = toolA.execute(args); + const pendingB = toolB.execute(args); + await secondReached; + releaseFirst(); + const [resA, resB] = await Promise.all([pendingA, pendingB]); + + expect(stored).toHaveLength(1); + expect(parseReceipt(resA.content[0]?.text)).toEqual({ + id: 'inst-a', + createdAt: new Date(FIXED_EPOCH_MS).toISOString(), + created: true, + }); + expect(parseReceipt(resB.content[0]?.text)).toEqual({ + id: 'inst-a', + createdAt: new Date(FIXED_EPOCH_MS).toISOString(), + created: false, + }); + }); + + test('payload equality helper ignores server metadata and is order-sensitive on normalized refs', () => { + const base = { + kind: 'finding' as const, + title: 't', + summary: 's', + trialRefs: ['a', 'b'], + evidenceRefs: [], + }; + expect( + areFiledFindingPayloadsEqual( + { ...base, id: 'x', createdAt: '1', status: 'pending_review' } as FiledFindingRecord, + { ...base, id: 'y', createdAt: '2', status: 'pending_review' } as FiledFindingRecord + ) + ).toBe(true); + expect(areFiledFindingPayloadsEqual(base, { ...base, trialRefs: ['a'] })).toBe(false); + expect(areFiledFindingPayloadsEqual(base, { ...base, evidenceRefs: ['e'] })).toBe(false); + expect(areFiledFindingPayloadsEqual(base, { ...base, title: 'T' })).toBe(false); + }); +});