import { describe, expect, test } from 'bun:test'; import { type AppendFindingResult, FILE_FINDING_ERROR_FILING_FAILED, FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, FILE_FINDING_INITIAL_STATUS, type FileFindingResultPayload, type FiledFindingRecord, type FindingWritePort, PostgresTrialRefError, type TrialRefExecutor, createFileFindingTool, createMcpServer, createPostgresTrialRefLookupPort, } from '../src/mcp/index'; import { utcDateOf } from '../src/mcp/tools/vault-fenced-input'; interface RecordedCall { readonly text: string; readonly params: readonly unknown[] | undefined; } function createFakeExecutor(rows: readonly Record[] = []): { readonly calls: RecordedCall[]; readonly executor: TrialRefExecutor; } { const calls: RecordedCall[] = []; const executor: TrialRefExecutor = { async query>( text: string, params?: readonly unknown[] ): Promise<{ readonly rows: readonly Row[] }> { calls.push({ text, params }); return { rows: rows as readonly Row[] }; }, }; return { calls, executor }; } function createFakeWritePort(): { readonly appended: FiledFindingRecord[]; readonly port: FindingWritePort; } { const appended: FiledFindingRecord[] = []; const port: FindingWritePort = { async appendFinding(record: FiledFindingRecord): Promise { appended.push(record); return { status: 'created', id: record.id, createdAt: record.createdAt, }; }, }; return { appended, port }; } const CUTOFF_MIDNIGHT_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0); // 2025-06-30T00:00:00.000Z describe('createPostgresTrialRefLookupPort', () => { test('rejects missing or non-callable executor with INVALID_EXECUTOR', () => { const invalidOptions: unknown[] = [ null, undefined, {}, { executor: null, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }, { executor: {}, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }, { executor: { query: 'not-a-fn' }, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }, ]; for (const opts of invalidOptions) { let caught: unknown; try { createPostgresTrialRefLookupPort( opts as Parameters[0] ); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(PostgresTrialRefError); expect(caught).toBeInstanceOf(RangeError); expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR'); } }); test('rejects invalid schema names with INVALID_SCHEMA before any query', () => { const fake = createFakeExecutor([]); const badSchemas: unknown[] = [ '', 'Bad-Schema', 'a;drop', '1schema', 'bad.name', 'space name', 'public"; DROP TABLE trial_ledger; --', 123, null, ]; for (const schema of badSchemas) { let caught: unknown; try { createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS, schema: schema as string, }); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(PostgresTrialRefError); expect((caught as PostgresTrialRefError).code).toBe('INVALID_SCHEMA'); } expect(fake.calls).toHaveLength(0); }); test('rejects invalid or extended-year vaultCutoffTs with INVALID_VAULT_CUTOFF', () => { const fake = createFakeExecutor([]); const badCutoffs: unknown[] = [ Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, '2025-06-30', null, undefined, 123.45, Date.parse('+010000-01-01T00:00:00.000Z'), Date.parse('-000001-01-01T00:00:00.000Z'), Date.parse('0000-01-01T00:00:00.000Z'), ]; for (const vaultCutoffTs of badCutoffs) { let caught: unknown; try { createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: vaultCutoffTs as number, }); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(PostgresTrialRefError); expect((caught as PostgresTrialRefError).code).toBe('INVALID_VAULT_CUTOFF'); } expect(fake.calls).toHaveLength(0); }); test('returns true for a visible trial with one parameterized read-only SELECT and exact params', async () => { const fake = createFakeExecutor([{ visible: 1 }]); const port = createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); const visible = await port.hasResearchVisibleTrial('42'); expect(visible).toBe(true); expect(fake.calls).toHaveLength(1); const call = fake.calls[0]!; expect(call.text.trimStart().startsWith('SELECT')).toBe(true); expect(call.text).not.toContain(';'); expect(call.text).not.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i); expect(call.text).toContain('FROM trial_ledger'); expect(call.text).toContain('trial_id = $1::bigint'); expect(call.text).toContain('sample_end < $2::date'); expect(call.text).toContain('LIMIT 1'); expect(call.params).toEqual(['42', '2025-06-30']); expect(typeof call.params?.[0]).toBe('string'); }); test('returns false when the executor returns empty rows (unknown or Vault-only trial)', async () => { const fake = createFakeExecutor([]); const port = createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); const visible = await port.hasResearchVisibleTrial('42'); expect(visible).toBe(false); expect(fake.calls).toHaveLength(1); expect(fake.calls[0]!.params).toEqual(['42', '2025-06-30']); }); test('maps midnight and non-midnight UTC vaultCutoffTs to the same UTC date as utcDateOf', async () => { const nonMidnightTs = Date.UTC(2025, 5, 30, 23, 59, 59, 999); const nextDayTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0); const fakeSameDay = createFakeExecutor([{ visible: 1 }]); const sameDayPort = createPostgresTrialRefLookupPort({ executor: fakeSameDay.executor, vaultCutoffTs: nonMidnightTs, }); await sameDayPort.hasResearchVisibleTrial('7'); expect(fakeSameDay.calls[0]!.params).toEqual(['7', utcDateOf(nonMidnightTs)]); expect(fakeSameDay.calls[0]!.params?.[1]).toBe('2025-06-30'); const fakeNextDay = createFakeExecutor([{ visible: 1 }]); const nextDayPort = createPostgresTrialRefLookupPort({ executor: fakeNextDay.executor, vaultCutoffTs: nextDayTs, }); await nextDayPort.hasResearchVisibleTrial('7'); expect(fakeNextDay.calls[0]!.params).toEqual(['7', '2025-07-01']); }); test('returns false with zero executor calls for malformed, injection-shaped, overflowing, and non-string refs', async () => { const fake = createFakeExecutor([{ visible: 1 }]); const port = createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); const invalidRefs: unknown[] = [ '', ' 42', '42 ', '042', '0', '-1', '+1', '1.0', '1e3', '0x10', '42; DROP TABLE trial_ledger', '9223372036854775808', '10000000000000000000', 42, 42n, null, undefined, {}, ]; for (const ref of invalidRefs) { const result = await port.hasResearchVisibleTrial(ref as string); expect(result).toBe(false); } expect(fake.calls).toHaveLength(0); }); test('queries the maximum signed 64-bit BIGINT verbatim as a string without numeric coercion', async () => { const maxBigIntRef = '9223372036854775807'; const fake = createFakeExecutor([{ visible: 1 }]); const port = createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); const visible = await port.hasResearchVisibleTrial(maxBigIntRef); expect(visible).toBe(true); expect(fake.calls).toHaveLength(1); expect(fake.calls[0]!.text).not.toContain(maxBigIntRef); expect(fake.calls[0]!.params).toEqual([maxBigIntRef, '2025-06-30']); }); test('quotes validated optional schema and leaves table unqualified when omitted', async () => { const fakeDefault = createFakeExecutor([]); const defaultPort = createPostgresTrialRefLookupPort({ executor: fakeDefault.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); await defaultPort.hasResearchVisibleTrial('1'); expect(fakeDefault.calls[0]!.text).toContain('FROM trial_ledger '); const fakeScoped = createFakeExecutor([]); const scopedPort = createPostgresTrialRefLookupPort({ executor: fakeScoped.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS, schema: 'research_x', }); await scopedPort.hasResearchVisibleTrial('1'); expect(fakeScoped.calls[0]!.text).toContain('FROM "research_x".trial_ledger '); }); test('propagates executor rejections unchanged without retrying', async () => { const failure = new Error('postgres connection lost'); let attempts = 0; const executor: TrialRefExecutor = { async query() { attempts += 1; throw failure; }, }; const port = createPostgresTrialRefLookupPort({ executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); await expect(port.hasResearchVisibleTrial('42')).rejects.toBe(failure); expect(attempts).toBe(1); }); test('accepts a pg.Pool-shaped executor with query on its prototype', async () => { class PoolLikeExecutor { readonly calls: RecordedCall[] = []; async query>( text: string, params?: readonly unknown[] ): Promise<{ readonly rows: readonly Row[] }> { this.calls.push({ text, params }); return { rows: [{ visible: 1 }] as unknown as readonly Row[] }; } } const executor = new PoolLikeExecutor(); const port = createPostgresTrialRefLookupPort({ executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); expect(await port.hasResearchVisibleTrial('99')).toBe(true); expect(executor.calls).toHaveLength(1); }); }); describe('createPostgresTrialRefLookupPort wired into createFileFindingTool', () => { async function callFileFinding( executor: TrialRefExecutor, trialRefs: readonly string[] ): Promise<{ readonly appended: FiledFindingRecord[]; readonly result: { readonly content: readonly { type: string; text: string }[]; readonly isError?: boolean }; }> { const trialLookup = createPostgresTrialRefLookupPort({ executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); const { appended, port } = createFakeWritePort(); const tool = createFileFindingTool({ port, trialLookup, newId: () => 'finding-0001', now: () => Date.UTC(2025, 5, 29, 12, 0, 0, 0), }); const server = createMcpServer({ name: 'test-copilot', version: '0.1.0', tools: [tool], }); const rawResponse = await server.handleMessage( JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'file_finding', arguments: { kind: 'finding', title: 'Pre-vault momentum signal', summary: 'Observed stable rank IC across US equities prior to cutoff.', trialRefs, }, }, }) ); const parsed = JSON.parse(rawResponse!) as { readonly result: { readonly content: readonly { type: string; text: string }[]; readonly isError?: boolean; }; }; return { appended, result: parsed.result }; } test('files a pending_review finding and returns a created receipt when the trial is visible', async () => { const fake = createFakeExecutor([{ visible: 1 }]); const { appended, result } = await callFileFinding(fake.executor, ['42']); expect(result.isError).toBeUndefined(); const payload = JSON.parse(result.content[0]!.text) as FileFindingResultPayload; expect(payload).toEqual({ id: 'finding-0001', createdAt: '2025-06-29T12:00:00.000Z', created: true, }); expect(appended).toHaveLength(1); expect(appended[0]).toEqual({ id: 'finding-0001', kind: 'finding', title: 'Pre-vault momentum signal', status: FILE_FINDING_INITIAL_STATUS, createdAt: '2025-06-29T12:00:00.000Z', summary: 'Observed stable rank IC across US equities prior to cutoff.', trialRefs: ['42'], evidenceRefs: [], }); expect(fake.calls).toHaveLength(1); expect(fake.calls[0]!.params).toEqual(['42', '2025-06-30']); }); test('returns FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF with zero appends when executor returns no rows', async () => { const fake = createFakeExecutor([]); const { appended, result } = await callFileFinding(fake.executor, ['42']); expect(result.isError).toBe(true); expect(result.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); expect(appended).toHaveLength(0); expect(fake.calls).toHaveLength(1); }); test('returns FILE_FINDING_ERROR_FILING_FAILED with zero appends when executor rejects', async () => { const executor: TrialRefExecutor = { async query() { throw new Error('database unavailable'); }, }; const { appended, result } = await callFileFinding(executor, ['42']); expect(result.isError).toBe(true); expect(result.content[0]!.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); expect(appended).toHaveLength(0); }); }); describe('createPostgresTrialRefLookupPort (QA edge cases)', () => { test('queries in-range 19-digit refs and rejects 19-digit refs above the signed BIGINT max', async () => { const fake = createFakeExecutor([{ visible: 1 }]); const port = createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); expect(await port.hasResearchVisibleTrial('1000000000000000000')).toBe(true); expect(await port.hasResearchVisibleTrial('9223372036854775806')).toBe(true); expect(await port.hasResearchVisibleTrial('9223372036854775900')).toBe(false); expect(await port.hasResearchVisibleTrial('9999999999999999999')).toBe(false); expect(fake.calls.map(c => c.params?.[0])).toEqual([ '1000000000000000000', '9223372036854775806', ]); }); test('rejects trailing-newline, tab, fullwidth-digit, and boxed-String refs without querying', async () => { const fake = createFakeExecutor([{ visible: 1 }]); const port = createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); for (const ref of ['42\n', '\n42', '4\t2', '42', '42\u0000', new String('42')] as unknown[]) { expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false); } expect(fake.calls).toHaveLength(0); }); test('accepts the four-digit PostgreSQL calendar bounds 0001-01-01 and 9999-12-31 as cutoff dates', async () => { const earliest = Date.parse('0001-01-01T00:00:00.000Z'); const latest = Date.parse('9999-12-31T23:59:59.999Z'); for (const [ts, expected] of [ [earliest, '0001-01-01'], [latest, '9999-12-31'], [Date.UTC(1969, 11, 31, 23, 59, 59, 999), '1969-12-31'], ] as const) { const fake = createFakeExecutor([]); const port = createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: ts }); await port.hasResearchVisibleTrial('5'); expect(fake.calls[0]!.params).toEqual(['5', expected]); } let caught: unknown; try { createPostgresTrialRefLookupPort({ executor: createFakeExecutor().executor, vaultCutoffTs: latest + 1, }); } catch (err) { caught = err; } expect((caught as PostgresTrialRefError).code).toBe('INVALID_VAULT_CUTOFF'); }); test('freezes the cutoff date and SQL text at construction across repeated lookups', async () => { const fake = createFakeExecutor([]); const options = { executor: fake.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }; const port = createPostgresTrialRefLookupPort(options); await port.hasResearchVisibleTrial('1'); (options as { vaultCutoffTs: number }).vaultCutoffTs = Date.UTC(2030, 0, 1); await port.hasResearchVisibleTrial('2'); expect(fake.calls).toHaveLength(2); expect(fake.calls[0]!.text).toBe(fake.calls[1]!.text); expect(fake.calls[1]!.params).toEqual(['2', '2025-06-30']); }); test('returns true for multiple matching rows and rejects (not false) on a malformed executor response', async () => { const many = createFakeExecutor([{ visible: 1 }, { visible: 1 }]); const manyPort = createPostgresTrialRefLookupPort({ executor: many.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); expect(await manyPort.hasResearchVisibleTrial('3')).toBe(true); for (const response of [null, {}, { rows: 'x' }, { rows: null }]) { const executor: TrialRefExecutor = { async query() { return response as unknown as { readonly rows: readonly never[] }; }, }; const port = createPostgresTrialRefLookupPort({ executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }); await expect(port.hasResearchVisibleTrial('3')).rejects.toBeInstanceOf(TypeError); } }); test('propagates a synchronous executor throw as a rejection with the same error', async () => { const failure = new Error('pool exhausted'); const executor = { query() { throw failure; }, } as unknown as TrialRefExecutor; const port = createPostgresTrialRefLookupPort({ executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }); await expect(port.hasResearchVisibleTrial('42')).rejects.toBe(failure); }); });