import { describe, expect, test } from 'bun:test'; import * as rootResearchExports from '../src/index'; import { type AppendFindingResult, FILE_FINDING_ERROR_FILING_FAILED, FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT, FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, FILE_FINDING_ERROR_UNKNOWN_KEYS, FILE_FINDING_INITIAL_STATUS, FILE_FINDING_KINDS, 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 FindingQuery, type FindingRecord, type FindingWritePort, type KnowledgePort, type ReadKnowledgeResultPayload, type TrialRefLookupPort, areFiledFindingPayloadsEqual, createFileFindingTool, createMcpServer, createReadKnowledgeTool, fileFindingInputSchema, } from '../src/mcp/index'; interface SharedFindingsFakeOptions { readonly failNextAppendError?: unknown; readonly alwaysAppendError?: unknown; readonly delayFirstAppendMs?: number; readonly attachExtraReceiptField?: boolean; } interface SharedFindingsFake { readonly stored: FiledFindingRecord[]; readonly appendCalls: { readonly record: FiledFindingRecord; readonly idempotencyKey?: string; }[]; readonly writePort: FindingWritePort; readonly knowledgePort: KnowledgePort; readonly invokedWriteMethods: string[]; } function createSharedFindingsFake(options?: SharedFindingsFakeOptions): SharedFindingsFake { const stored: FiledFindingRecord[] = []; const byIdempotencyKey = new Map(); const appendCalls: { readonly record: FiledFindingRecord; readonly idempotencyKey?: string }[] = []; const invokedWriteMethods: string[] = []; let failOnceError: unknown = options?.failNextAppendError; let firstCallSeen = false; const rawWritePort: FindingWritePort = { async appendFinding( record: FiledFindingRecord, idempotencyKey?: string ): Promise { appendCalls.push({ record, idempotencyKey }); if (options?.alwaysAppendError !== undefined) { throw options.alwaysAppendError; } if (failOnceError !== undefined) { const err = failOnceError; failOnceError = undefined; throw err; } // Atomic compare-and-append before any async yield so concurrent calls with // the same idempotencyKey cannot both insert. let outcome: AppendFindingResult; if (idempotencyKey !== undefined) { const existing = byIdempotencyKey.get(idempotencyKey); if (existing !== undefined) { if (areFiledFindingPayloadsEqual(existing, record)) { outcome = { status: 'replayed', id: existing.id, createdAt: existing.createdAt, }; } else { outcome = { status: 'conflict' }; } } else { const copy: FiledFindingRecord = { ...record, trialRefs: [...record.trialRefs], evidenceRefs: [...record.evidenceRefs], }; stored.push(copy); byIdempotencyKey.set(idempotencyKey, copy); outcome = { status: 'created', id: copy.id, createdAt: copy.createdAt, }; } } else { const copy: FiledFindingRecord = { ...record, trialRefs: [...record.trialRefs], evidenceRefs: [...record.evidenceRefs], }; stored.push(copy); outcome = { status: 'created', id: copy.id, createdAt: copy.createdAt, }; } if (!firstCallSeen && options?.delayFirstAppendMs !== undefined) { firstCallSeen = true; await new Promise(resolve => setTimeout(resolve, options.delayFirstAppendMs)); } if (options?.attachExtraReceiptField === true && outcome.status !== 'conflict') { return { ...outcome, internalDsn: 'postgres://leaked:pass@127.0.0.1:5432/trading_bot', } as unknown as AppendFindingResult; } return outcome; }, }; const writePort = new Proxy(rawWritePort, { get(target, prop, receiver) { const value: unknown = Reflect.get(target, prop, receiver); if (typeof value === 'function' && typeof prop === 'string') { return (...args: unknown[]) => { invokedWriteMethods.push(prop); return (value as (...a: unknown[]) => unknown).apply(target, args); }; } return value; }, }); const knowledgePort: KnowledgePort = { async listLibraryCards() { return []; }, async listFindings(q: FindingQuery): Promise { return stored.filter(item => { if (q.id !== undefined && item.id !== q.id) { return false; } if (q.query !== undefined) { const needle = q.query.toLowerCase(); return ( item.title.toLowerCase().includes(needle) || item.summary.toLowerCase().includes(needle) ); } return true; }); }, async listProviderCaveats() { return []; }, }; return { stored, appendCalls, writePort, knowledgePort, invokedWriteMethods, }; } interface FakeTrialLookup { readonly queriedRefs: string[]; readonly port: TrialRefLookupPort; } function createFakeTrialLookup(options?: { readonly researchVisibleRefs?: readonly string[]; readonly vaultOnlyRefs?: readonly string[]; readonly throwError?: unknown; }): FakeTrialLookup { const visibleSet = new Set( options?.researchVisibleRefs ?? ['trial-101', 'trial-102', '9007199254740993123'] ); const vaultOnlySet = new Set(options?.vaultOnlyRefs ?? ['trial-vault-999']); const queriedRefs: string[] = []; const port: TrialRefLookupPort = { async hasResearchVisibleTrial(trialRef: string): Promise { queriedRefs.push(trialRef); if (options?.throwError !== undefined) { throw options.throwError; } if (vaultOnlySet.has(trialRef)) { return false; } return visibleSet.has(trialRef); }, }; return { queriedRefs, port }; } function createFixedClock(startIso = '2025-03-01T12:00:00.000Z', stepMs = 60_000) { let current = Date.parse(startIso); let calls = 0; return { get calls() { return calls; }, now: () => { calls += 1; const value = current; current += stepMs; return value; }, }; } function createFixedIdGenerator(prefix = 'find') { let counter = 0; return { get calls() { return counter; }, newId: () => { counter += 1; return `${prefix}-${String(counter).padStart(4, '0')}`; }, }; } async function callTool( server: ReturnType, toolName: string, args: Record, id: string | number = 'req-1' ): Promise<{ readonly isError: boolean; readonly text: string; readonly payload: TPayload | null; }> { const raw = await server.handleMessage( JSON.stringify({ jsonrpc: '2.0', id, method: 'tools/call', params: { name: toolName, arguments: args, }, }) ); expect(raw).not.toBeNull(); const parsed = JSON.parse(raw as string) as { error?: unknown; result: { isError?: boolean; content: { type: string; text: string }[]; }; }; expect(parsed.error).toBeUndefined(); const isError = parsed.result.isError === true; const text = parsed.result.content[0]?.text ?? ''; return { isError, text, payload: isError ? null : (JSON.parse(text) as TPayload), }; } describe('MCP file_finding tool', () => { test('files both finding and dead_end with fixed server metadata, normalization, and explicit receipt projection', async () => { const fake = createSharedFindingsFake({ attachExtraReceiptField: true }); const trialLookup = createFakeTrialLookup(); const clock = createFixedClock('2025-03-01T10:00:00.000Z', 60_000); const idGen = createFixedIdGenerator('finding'); const server = createMcpServer({ name: 'stock-bot-research', version: '0.1.0', tools: [ createFileFindingTool({ port: fake.writePort, trialLookup: trialLookup.port, newId: idGen.newId, now: clock.now, }), ], }); const findingRes = await callTool(server, 'file_finding', { kind: 'finding', title: ' Post-earnings drift decays after day 3 ', summary: ' Cross-sectional CAR flattens after session +3 across 2015-2024. ', trialRefs: [' trial-102 ', '9007199254740993123', 'trial-102', 'trial-101'], evidenceRefs: [' snap-b ', 'snap-a', 'snap-b', 'Snap-A'], }); expect(findingRes.isError).toBe(false); expect(findingRes.payload).toEqual({ id: 'finding-0001', createdAt: '2025-03-01T10:00:00.000Z', created: true, }); expect(Object.keys(findingRes.payload as unknown as Record).sort()).toEqual([ 'created', 'createdAt', 'id', ]); expect(fake.stored[0]).toEqual({ id: 'finding-0001', kind: 'finding', title: 'Post-earnings drift decays after day 3', status: FILE_FINDING_INITIAL_STATUS, createdAt: '2025-03-01T10:00:00.000Z', summary: 'Cross-sectional CAR flattens after session +3 across 2015-2024.', trialRefs: ['9007199254740993123', 'trial-101', 'trial-102'], evidenceRefs: ['Snap-A', 'snap-a', 'snap-b'], }); const deadEndRes = await callTool(server, 'file_finding', { kind: 'dead_end', title: 'Short-interest 1d reversal', summary: 'No net edge after realistic borrow and spread costs.', trialRefs: ['trial-101'], }); expect(deadEndRes.isError).toBe(false); expect(deadEndRes.payload).toEqual({ id: 'finding-0002', createdAt: '2025-03-01T10:01:00.000Z', created: true, }); expect(fake.stored[1]).toEqual({ id: 'finding-0002', kind: 'dead_end', title: 'Short-interest 1d reversal', status: 'pending_review', createdAt: '2025-03-01T10:01:00.000Z', summary: 'No net edge after realistic borrow and spread costs.', trialRefs: ['trial-101'], evidenceRefs: [], }); expect(fake.invokedWriteMethods).toEqual(['appendFinding', 'appendFinding']); }); test('rejects invalid inputs, blank or over-length fields, raw array limits, unknown fields, and metadata overrides with zero writes', async () => { const fake = createSharedFindingsFake(); const trialLookup = createFakeTrialLookup(); const clock = createFixedClock(); const idGen = createFixedIdGenerator(); const server = createMcpServer({ name: 'stock-bot-research', version: '0.1.0', tools: [ createFileFindingTool({ port: fake.writePort, trialLookup: trialLookup.port, newId: idGen.newId, now: clock.now, }), ], }); const validBase = { kind: 'finding', title: 'Valid title', summary: 'Valid research-visible summary', trialRefs: ['trial-101'], }; const invalidCases: readonly { readonly label: string; readonly args: Record; readonly forbiddenSubstring?: string; }[] = [ { label: 'missing trialRefs', args: { kind: 'finding', title: 'T', summary: 'S' } }, { label: 'empty trialRefs', args: { ...validBase, trialRefs: [] } }, { label: 'blank trialRef', args: { ...validBase, trialRefs: [' '] } }, { label: 'blank evidenceRef', args: { ...validBase, evidenceRefs: [' '] } }, { label: 'blank title', args: { ...validBase, title: ' ' } }, { label: 'blank summary', args: { ...validBase, summary: '\t\n ' } }, { label: 'blank idempotencyKey', args: { ...validBase, idempotencyKey: ' ' } }, { label: 'over-length title', args: { ...validBase, title: 'a'.repeat(FILE_FINDING_MAX_TITLE_LENGTH + 1) }, }, { label: 'over-length summary', args: { ...validBase, summary: 's'.repeat(FILE_FINDING_MAX_SUMMARY_LENGTH + 1) }, }, { label: 'over-length trialRef', args: { ...validBase, trialRefs: ['r'.repeat(FILE_FINDING_MAX_REF_LENGTH + 1)] }, }, { label: 'over-length evidenceRef', args: { ...validBase, evidenceRefs: ['e'.repeat(FILE_FINDING_MAX_REF_LENGTH + 1)] }, }, { label: 'over-length idempotencyKey', args: { ...validBase, idempotencyKey: 'k'.repeat(FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH + 1), }, }, { label: 'raw trialRefs exceeds 32 even with duplicates', args: { ...validBase, trialRefs: Array.from({ length: FILE_FINDING_MAX_TRIAL_REFS + 1 }, () => 'trial-101'), }, }, { label: 'raw evidenceRefs exceeds 32 even with duplicates', args: { ...validBase, evidenceRefs: Array.from( { length: FILE_FINDING_MAX_EVIDENCE_REFS + 1 }, () => 'snap-01' ), }, }, { label: 'invalid kind does not echo caller value', args: { ...validBase, kind: 'vault_secret_kind_sentinel' }, forbiddenSubstring: 'vault_secret_kind_sentinel', }, { label: 'invalid title type', args: { ...validBase, title: 123 } }, { label: 'invalid trialRefs type', args: { ...validBase, trialRefs: 'trial-101' } }, { label: 'caller-supplied id rejected', args: { ...validBase, id: 'attacker-id' }, forbiddenSubstring: 'attacker-id', }, { label: 'caller-supplied status rejected', args: { ...validBase, status: 'confirmed' }, forbiddenSubstring: 'confirmed', }, { label: 'caller-supplied createdAt rejected', args: { ...validBase, createdAt: '2020-01-01T00:00:00.000Z' }, forbiddenSubstring: '2020-01-01', }, { label: 'holdout scope rejected without echoing key', args: { ...validBase, scope: 'vault_evaluation_only' }, forbiddenSubstring: 'scope', }, { label: 'holdout vault_evaluation_only rejected without echoing key', args: { ...validBase, vault_evaluation_only: true }, forbiddenSubstring: 'vault_evaluation_only', }, { label: 'holdout vaultCutoffTs rejected without echoing key', args: { ...validBase, vaultCutoffTs: 1_700_000_000_000 }, forbiddenSubstring: 'vaultCutoffTs', }, { label: 'unknown-key sentinel rejected without echoing sentinel', args: { ...validBase, vaultHoldoutKeySentinel_XYZ: 'secret-value' }, forbiddenSubstring: 'vaultHoldoutKeySentinel_XYZ', }, ]; for (const testCase of invalidCases) { const res = await callTool(server, 'file_finding', testCase.args); expect(res.isError).toBe(true); if (testCase.forbiddenSubstring !== undefined) { expect(res.text).not.toContain(testCase.forbiddenSubstring); } if ( testCase.label.includes('unknown-key') || testCase.label.includes('holdout') || testCase.label.includes('caller-supplied') ) { expect(res.text).toContain(FILE_FINDING_ERROR_UNKNOWN_KEYS); } } expect(fake.stored).toHaveLength(0); expect(fake.appendCalls).toHaveLength(0); expect(trialLookup.queriedRefs).toHaveLength(0); expect(idGen.calls).toBe(0); expect(clock.calls).toBe(0); // Raw 32 duplicate entries are accepted (bounds applied before dedup). const maxRawRes = await callTool(server, 'file_finding', { ...validBase, trialRefs: Array.from({ length: FILE_FINDING_MAX_TRIAL_REFS }, () => 'trial-101'), evidenceRefs: Array.from({ length: FILE_FINDING_MAX_EVIDENCE_REFS }, () => 'snap-1'), }); expect(maxRawRes.isError).toBe(false); expect(fake.stored).toHaveLength(1); expect(fake.stored[0]?.trialRefs).toEqual(['trial-101']); expect(fake.stored[0]?.evidenceRefs).toEqual(['snap-1']); }); test('rejects unknown and Vault-only trial refs identically with zero writes and zero metadata generation', async () => { const fake = createSharedFindingsFake(); const trialLookup = createFakeTrialLookup({ researchVisibleRefs: ['trial-101'], vaultOnlyRefs: ['trial-vault-only-secret'], }); const clock = createFixedClock(); const idGen = createFixedIdGenerator(); const server = createMcpServer({ name: 'stock-bot-research', version: '0.1.0', tools: [ createFileFindingTool({ port: fake.writePort, trialLookup: trialLookup.port, newId: idGen.newId, now: clock.now, }), ], }); const unknownRes = await callTool(server, 'file_finding', { kind: 'finding', title: 'Mixed valid and unknown ref', summary: 'Should fail before writing.', trialRefs: ['trial-101', 'trial-unknown-secret-ref'], }); const vaultRes = await callTool(server, 'file_finding', { kind: 'finding', title: 'Mixed valid and Vault-only ref', summary: 'Should fail identically to unknown ref.', trialRefs: ['trial-101', 'trial-vault-only-secret'], }); expect(unknownRes.isError).toBe(true); expect(vaultRes.isError).toBe(true); expect(unknownRes.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); expect(vaultRes.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); expect(unknownRes.text).not.toContain('trial-unknown-secret-ref'); expect(vaultRes.text).not.toContain('trial-vault-only-secret'); expect(fake.stored).toHaveLength(0); expect(fake.appendCalls).toHaveLength(0); expect(idGen.calls).toBe(0); expect(clock.calls).toBe(0); }); test('sanitizes lookup and append exceptions so DSNs and stack markers never leak', async () => { const fakeDsn = 'postgres://writer:supersecret@10.0.0.51:5432/trading_bot'; const stackMarker = 'at internalPgPoolQuery (/srv/stock-bot/secret-adapter.ts:91:13)'; const lookupErr = new Error(`Lookup failed on ${fakeDsn}\n ${stackMarker}`); lookupErr.name = 'PgConnectionError'; const lookupFake = createSharedFindingsFake(); const failingLookup = createFakeTrialLookup({ throwError: lookupErr }); const lookupServer = createMcpServer({ name: 'stock-bot-research', version: '0.1.0', tools: [ createFileFindingTool({ port: lookupFake.writePort, trialLookup: failingLookup.port, newId: createFixedIdGenerator().newId, now: createFixedClock().now, }), ], }); const lookupRes = await callTool(lookupServer, 'file_finding', { kind: 'finding', title: 'Lookup failure test', summary: 'Summary text', trialRefs: ['trial-101'], }); expect(lookupRes.isError).toBe(true); expect(lookupRes.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); expect(lookupRes.text).not.toContain(fakeDsn); expect(lookupRes.text).not.toContain(stackMarker); expect(lookupRes.text).not.toContain('PgConnectionError'); expect(lookupFake.appendCalls).toHaveLength(0); const appendErr = new Error(`INSERT failed on ${fakeDsn}\n ${stackMarker}`); appendErr.name = 'DatabaseWriteError'; const appendFake = createSharedFindingsFake({ alwaysAppendError: appendErr }); const appendServer = createMcpServer({ name: 'stock-bot-research', version: '0.1.0', tools: [ createFileFindingTool({ port: appendFake.writePort, trialLookup: createFakeTrialLookup().port, newId: createFixedIdGenerator().newId, now: createFixedClock().now, }), ], }); const appendRes = await callTool(appendServer, 'file_finding', { kind: 'finding', title: 'Append failure test', summary: 'Summary text', trialRefs: ['trial-101'], }); expect(appendRes.isError).toBe(true); expect(appendRes.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); expect(appendRes.text).not.toContain(fakeDsn); expect(appendRes.text).not.toContain(stackMarker); expect(appendRes.text).not.toContain('DatabaseWriteError'); }); test('enforces idempotency replays, per-field conflicts, concurrent retries across instances, post-failure retry, and independent unkeyed calls', async () => { const fake = createSharedFindingsFake(); const trialLookup = createFakeTrialLookup(); const clock = createFixedClock('2025-03-01T14:00:00.000Z', 60_000); const idGen = createFixedIdGenerator('idem'); const server = createMcpServer({ name: 'stock-bot-research', version: '0.1.0', tools: [ createFileFindingTool({ port: fake.writePort, trialLookup: trialLookup.port, newId: idGen.newId, now: clock.now, }), ], }); const first = await callTool(server, 'file_finding', { kind: 'finding', title: 'Momentum crowding signal', summary: 'Observed IC decay during high volatility regimes.', trialRefs: ['trial-102', 'trial-101'], idempotencyKey: ' key-001 ', }); expect(first.isError).toBe(false); expect(first.payload).toEqual({ id: 'idem-0001', createdAt: '2025-03-01T14:00:00.000Z', created: true, }); expect(fake.stored).toHaveLength(1); // Replay with whitespace, duplicate/reordered refs, and explicit empty evidenceRefs. const replay = await callTool(server, 'file_finding', { kind: 'finding', title: ' Momentum crowding signal ', summary: ' Observed IC decay during high volatility regimes. ', trialRefs: ['trial-101', ' trial-102 ', 'trial-101'], evidenceRefs: [], idempotencyKey: 'key-001', }); expect(replay.isError).toBe(false); expect(replay.payload).toEqual({ id: 'idem-0001', createdAt: '2025-03-01T14:00:00.000Z', created: false, }); expect(fake.stored).toHaveLength(1); // Changing each normalized payload field in turn causes a conflict with zero extra rows. const conflictPayloads: readonly Record[] = [ { kind: 'dead_end', title: 'Momentum crowding signal', summary: 'Observed IC decay during high volatility regimes.', trialRefs: ['trial-101', 'trial-102'], evidenceRefs: [], idempotencyKey: 'key-001', }, { kind: 'finding', title: 'Different title', summary: 'Observed IC decay during high volatility regimes.', trialRefs: ['trial-101', 'trial-102'], evidenceRefs: [], idempotencyKey: 'key-001', }, { kind: 'finding', title: 'Momentum crowding signal', summary: 'Different summary', trialRefs: ['trial-101', 'trial-102'], evidenceRefs: [], idempotencyKey: 'key-001', }, { kind: 'finding', title: 'Momentum crowding signal', summary: 'Observed IC decay during high volatility regimes.', trialRefs: ['trial-101'], evidenceRefs: [], idempotencyKey: 'key-001', }, { kind: 'finding', title: 'Momentum crowding signal', summary: 'Observed IC decay during high volatility regimes.', trialRefs: ['trial-101', 'trial-102'], evidenceRefs: ['snap-extra'], idempotencyKey: 'key-001', }, ]; for (const conflictArgs of conflictPayloads) { const res = await callTool(server, 'file_finding', conflictArgs); expect(res.isError).toBe(true); expect(res.text).toBe(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT); } expect(fake.stored).toHaveLength(1); // Concurrent same-key calls across two separate tool instances sharing one port. const concurrentFake = createSharedFindingsFake({ delayFirstAppendMs: 10 }); const toolA = createFileFindingTool({ port: concurrentFake.writePort, trialLookup: trialLookup.port, newId: createFixedIdGenerator('instA').newId, now: createFixedClock('2025-03-02T00:00:00.000Z').now, }); const toolB = createFileFindingTool({ port: concurrentFake.writePort, trialLookup: trialLookup.port, newId: createFixedIdGenerator('instB').newId, now: createFixedClock('2025-03-02T05:00:00.000Z').now, }); const concurrentArgs = { kind: 'finding', title: 'Concurrent filing', summary: 'Submitted concurrently by two retries.', trialRefs: ['trial-101'], idempotencyKey: 'concurrent-key', }; const [resA, resB] = await Promise.all([ toolA.execute(concurrentArgs), toolB.execute(concurrentArgs), ]); expect(resA.isError).toBeUndefined(); expect(resB.isError).toBeUndefined(); const payloadA = JSON.parse(resA.content[0]?.text ?? '') as FileFindingResultPayload; const payloadB = JSON.parse(resB.content[0]?.text ?? '') as FileFindingResultPayload; expect(concurrentFake.stored).toHaveLength(1); expect(payloadA.id).toBe(payloadB.id); expect(payloadA.createdAt).toBe(payloadB.createdAt); expect([payloadA.created, payloadB.created].sort()).toEqual([false, true]); // Retry after an injected pre-commit failure succeeds cleanly. const retryFake = createSharedFindingsFake({ failNextAppendError: new Error('transient pre-commit timeout'), }); const retryServer = createMcpServer({ name: 'stock-bot-research', version: '0.1.0', tools: [ createFileFindingTool({ port: retryFake.writePort, trialLookup: trialLookup.port, newId: createFixedIdGenerator('retry').newId, now: createFixedClock('2025-03-03T08:00:00.000Z').now, }), ], }); const failedAttempt = await callTool(retryServer, 'file_finding', { kind: 'dead_end', title: 'Retry after failure', summary: 'First attempt fails before commit.', trialRefs: ['trial-101'], idempotencyKey: 'retry-key', }); expect(failedAttempt.isError).toBe(true); expect(failedAttempt.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); expect(retryFake.stored).toHaveLength(0); const retryAttempt = await callTool(retryServer, 'file_finding', { kind: 'dead_end', title: 'Retry after failure', summary: 'First attempt fails before commit.', trialRefs: ['trial-101'], idempotencyKey: 'retry-key', }); expect(retryAttempt.isError).toBe(false); expect(retryAttempt.payload).toEqual({ id: 'retry-0002', createdAt: '2025-03-03T08:01:00.000Z', created: true, }); expect(retryFake.stored).toHaveLength(1); // Unkeyed calls with identical payloads are independent. const unkeyed1 = await callTool(server, 'file_finding', { kind: 'finding', title: 'Unkeyed entry', summary: 'Independent unkeyed filing.', trialRefs: ['trial-101'], }); const unkeyed2 = await callTool(server, 'file_finding', { kind: 'finding', title: 'Unkeyed entry', summary: 'Independent unkeyed filing.', trialRefs: ['trial-101'], }); expect(unkeyed1.isError).toBe(false); expect(unkeyed2.isError).toBe(false); expect(unkeyed1.payload?.created).toBe(true); expect(unkeyed2.payload?.created).toBe(true); expect(unkeyed1.payload?.id).not.toBe(unkeyed2.payload?.id); expect(fake.stored).toHaveLength(3); }); test('advertises strict schema via tools/list and round-trips filed records through read_knowledge', async () => { const fake = createSharedFindingsFake(); const trialLookup = createFakeTrialLookup(); const clock = createFixedClock('2025-03-04T09:30:00.000Z', 120_000); const idGen = createFixedIdGenerator('kb'); const server = createMcpServer({ name: 'stock-bot-research', version: '0.1.0', tools: [ createFileFindingTool({ port: fake.writePort, trialLookup: trialLookup.port, newId: idGen.newId, now: clock.now, }), createReadKnowledgeTool({ port: fake.knowledgePort, }), ], }); const listRaw = await server.handleMessage( JSON.stringify({ jsonrpc: '2.0', id: 'list-1', method: 'tools/list', }) ); expect(listRaw).not.toBeNull(); const listParsed = JSON.parse(listRaw as string) as { result: { tools: { name: string; description: string; inputSchema: { type: string; properties: Record>; required?: string[]; additionalProperties: boolean; }; }[]; }; }; expect(listParsed.result.tools.map(t => t.name)).toEqual(['file_finding', 'read_knowledge']); const tool = listParsed.result.tools.find(t => t.name === 'file_finding'); expect(tool).toBeDefined(); expect(tool?.inputSchema.type).toBe('object'); expect(tool?.inputSchema.additionalProperties).toBe(false); expect(tool?.inputSchema.required).toEqual(['kind', 'title', 'summary', 'trialRefs']); expect(tool?.inputSchema.properties.kind).toMatchObject({ type: 'string', enum: [...FILE_FINDING_KINDS], }); expect(tool?.inputSchema.properties.title).toMatchObject({ type: 'string', minLength: 1, maxLength: FILE_FINDING_MAX_TITLE_LENGTH, }); expect(tool?.inputSchema.properties.summary).toMatchObject({ type: 'string', minLength: 1, maxLength: FILE_FINDING_MAX_SUMMARY_LENGTH, }); expect(tool?.inputSchema.properties.trialRefs).toMatchObject({ type: 'array', minItems: 1, maxItems: FILE_FINDING_MAX_TRIAL_REFS, items: { type: 'string', minLength: 1, maxLength: FILE_FINDING_MAX_REF_LENGTH }, }); expect(tool?.inputSchema.properties.evidenceRefs).toMatchObject({ type: 'array', maxItems: FILE_FINDING_MAX_EVIDENCE_REFS, default: [], items: { type: 'string', minLength: 1, maxLength: FILE_FINDING_MAX_REF_LENGTH }, }); expect(tool?.inputSchema.properties.idempotencyKey).toMatchObject({ type: 'string', minLength: 1, maxLength: FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, }); expect(tool?.inputSchema.properties.id).toBeUndefined(); expect(tool?.inputSchema.properties.status).toBeUndefined(); expect(tool?.inputSchema.properties.createdAt).toBeUndefined(); expect(tool?.inputSchema.properties.scope).toBeUndefined(); expect(tool?.inputSchema.properties.vault_evaluation_only).toBeUndefined(); expect(tool?.inputSchema.properties.vaultCutoffTs).toBeUndefined(); // File both kinds via tools/call and read each back through read_knowledge. const filedFinding = await callTool( server, 'file_finding', { kind: 'finding', title: ' Event-study drift after SEC 8-K ', summary: ' CAR peaks on session +2 and persists through +5. ', trialRefs: ['trial-102', 'trial-101', 'trial-102'], evidenceRefs: ['ev-html-2', 'ev-html-1'], }, 'call-f1' ); expect(filedFinding.isError).toBe(false); const findingId = filedFinding.payload?.id as string; const filedDeadEnd = await callTool( server, 'file_finding', { kind: 'dead_end', title: 'Intraday gap fade on microcaps', summary: 'Edge disappears once 15 bps slippage is modeled.', trialRefs: ['9007199254740993123'], }, 'call-f2' ); expect(filedDeadEnd.isError).toBe(false); const deadEndId = filedDeadEnd.payload?.id as string; const readFinding = await callTool( server, 'read_knowledge', { source: 'findings', id: findingId }, 'call-r1' ); expect(readFinding.isError).toBe(false); expect(readFinding.payload).toEqual({ rowCount: 1, sources: { library: 0, findings: 1, provider_caveats: 0 }, rows: [ { source: 'findings', id: findingId, title: 'Event-study drift after SEC 8-K', status: 'pending_review', createdAt: '2025-03-04T09:30:00.000Z', summary: 'CAR peaks on session +2 and persists through +5.', trialRefs: ['trial-101', 'trial-102'], evidenceRefs: ['ev-html-1', 'ev-html-2'], truncated: false, }, ], }); expect(fake.stored.find(r => r.id === findingId)?.kind).toBe('finding'); const readDeadEnd = await callTool( server, 'read_knowledge', { source: 'findings', id: deadEndId }, 'call-r2' ); expect(readDeadEnd.isError).toBe(false); expect(readDeadEnd.payload).toEqual({ rowCount: 1, sources: { library: 0, findings: 1, provider_caveats: 0 }, rows: [ { source: 'findings', id: deadEndId, title: 'Intraday gap fade on microcaps', status: 'pending_review', createdAt: '2025-03-04T09:32:00.000Z', summary: 'Edge disappears once 15 bps slippage is modeled.', trialRefs: ['9007199254740993123'], evidenceRefs: [], truncated: false, }, ], }); expect(fake.stored.find(r => r.id === deadEndId)?.kind).toBe('dead_end'); }); test('produces bit-identical receipts, stored records, and read-backs across deterministic replays', async () => { async function runReplay() { const fake = createSharedFindingsFake(); const trialLookup = createFakeTrialLookup(); const server = createMcpServer({ name: 'stock-bot-research', version: '0.1.0', tools: [ createFileFindingTool({ port: fake.writePort, trialLookup: trialLookup.port, newId: createFixedIdGenerator('rep').newId, now: createFixedClock('2025-03-05T00:00:00.000Z', 30_000).now, }), createReadKnowledgeTool({ port: fake.knowledgePort }), ], }); const r1 = await callTool(server, 'file_finding', { kind: 'finding', title: 'Replay finding', summary: 'Deterministic summary.', trialRefs: ['trial-102', 'trial-101'], evidenceRefs: ['ev-b', 'ev-a'], idempotencyKey: 'rep-key-1', }); const r2 = await callTool(server, 'file_finding', { kind: 'finding', title: 'Replay finding', summary: 'Deterministic summary.', trialRefs: ['trial-101', 'trial-102'], evidenceRefs: ['ev-a', 'ev-b'], idempotencyKey: 'rep-key-1', }); const r3 = await callTool(server, 'read_knowledge', { source: 'findings', }); return { receipts: [r1.payload, r2.payload], stored: fake.stored, knowledge: r3.payload, }; } const firstRun = await runReplay(); const secondRun = await runReplay(); expect(secondRun).toEqual(firstRun); }); test('validates factory options eagerly and keeps MCP symbols out of browser-safe root export', () => { const validPort = createSharedFindingsFake().writePort; const validLookup = createFakeTrialLookup().port; const validNewId = () => 'id-1'; const validNow = () => Date.UTC(2025, 2, 1); expect(() => createFileFindingTool(null as never)).toThrow(/options/i); expect(() => createFileFindingTool({ port: {} as never, trialLookup: validLookup, newId: validNewId, now: validNow, }) ).toThrow(/port/i); expect(() => createFileFindingTool({ port: validPort, trialLookup: {} as never, newId: validNewId, now: validNow, }) ).toThrow(/trialLookup/i); expect(() => createFileFindingTool({ port: validPort, trialLookup: validLookup, newId: 'not-a-fn' as never, now: validNow, }) ).toThrow(/newId/i); expect(() => createFileFindingTool({ port: validPort, trialLookup: validLookup, newId: validNewId, now: 'not-a-fn' as never, }) ).toThrow(/now/i); expect( fileFindingInputSchema.safeParse({ kind: 'finding', title: 'Schema export sanity check', summary: 'Direct schema parse works.', trialRefs: ['trial-101'], }).success ).toBe(true); expect(Object.keys(rootResearchExports)).not.toContain('createFileFindingTool'); }); });