import { describe, expect, test } from 'bun:test'; import type { MarketDataStore } from '../src/market-data-store'; import { MarketDataStoreNotImplementedError } from '../src/market-data-store-duckdb'; import { type FindingQuery, type FindingRecord, type KnowledgePort, type LibraryCardQuery, type LibraryCardRecord, type ProviderCaveatQuery, type ProviderCaveatRecord, READ_KNOWLEDGE_DEFAULT_LIMIT, READ_KNOWLEDGE_MAX_LIMIT, READ_KNOWLEDGE_MAX_QUERY_LENGTH, READ_KNOWLEDGE_MAX_TEXT_LENGTH, READ_KNOWLEDGE_SOURCES, type ReadKnowledgeResultPayload, type SymbolSearchPort, createAnalyzeSignalTool, createEventStudyTool, createMcpServer, createQueryDataTool, createReadKnowledgeTool, createSearchSymbolsTool, readKnowledgeInputSchema, } from '../src/mcp/index'; import type { TrialLedgerExecutor } from '../src/trial-ledger'; const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); function makeLibraryCard( overrides: Partial & { readonly id: string } ): LibraryCardRecord { return { id: overrides.id, title: overrides.title ?? `Card ${overrides.id}`, tags: overrides.tags ?? ['methodology'], summary: overrides.summary ?? `Summary for ${overrides.id}`, body: overrides.body ?? `Body for ${overrides.id}`, }; } function makeFinding(overrides: Partial & { readonly id: string }): FindingRecord { return { id: overrides.id, title: overrides.title ?? `Finding ${overrides.id}`, status: overrides.status ?? 'confirmed', createdAt: overrides.createdAt ?? '2025-01-15T12:00:00.000Z', summary: overrides.summary ?? `Finding summary for ${overrides.id}`, trialRefs: overrides.trialRefs ?? [`trial-${overrides.id}`], evidenceRefs: overrides.evidenceRefs ?? [`ev-${overrides.id}`], }; } function makeCaveat( overrides: Partial & { readonly id: string } ): ProviderCaveatRecord { return { id: overrides.id, provider: overrides.provider ?? 'eodhd', dataset: overrides.dataset ?? `Dataset ${overrides.id}`, caveat: overrides.caveat ?? `Caveat text for ${overrides.id}`, createdAt: overrides.createdAt ?? '2025-01-20T08:30:00.000Z', }; } interface FakePortState { readonly libraryCalls: LibraryCardQuery[]; readonly findingsCalls: FindingQuery[]; readonly caveatsCalls: ProviderCaveatQuery[]; readonly invokedMethods: string[]; readonly port: KnowledgePort; } function createFakeKnowledgePort(options?: { readonly libraryCards?: readonly LibraryCardRecord[]; readonly findings?: readonly FindingRecord[]; readonly providerCaveats?: readonly ProviderCaveatRecord[]; readonly libraryError?: unknown; readonly findingsError?: unknown; readonly caveatsError?: unknown; readonly applySelectors?: boolean; }): FakePortState { const libraryCalls: LibraryCardQuery[] = []; const findingsCalls: FindingQuery[] = []; const caveatsCalls: ProviderCaveatQuery[] = []; const invokedMethods: string[] = []; const libraryCards = options?.libraryCards ?? []; const findings = options?.findings ?? []; const providerCaveats = options?.providerCaveats ?? []; const applySelectors = options?.applySelectors === true; const rawPort: KnowledgePort = { async listLibraryCards(q: LibraryCardQuery): Promise { libraryCalls.push({ ...q }); if (options?.libraryError !== undefined) { throw options.libraryError; } if (!applySelectors) { return [...libraryCards]; } return libraryCards.filter(card => { if (q.id !== undefined && card.id !== q.id) { return false; } if (q.tags !== undefined) { const cardTags = new Set(card.tags.map(t => t.toLowerCase())); if (!q.tags.every(t => cardTags.has(t.toLowerCase()))) { return false; } } if (q.query !== undefined) { const needle = q.query.toLowerCase(); const inText = card.title.toLowerCase().includes(needle) || card.summary.toLowerCase().includes(needle) || card.tags.some(t => t.toLowerCase().includes(needle)); if (!inText) { return false; } } return true; }); }, async listFindings(q: FindingQuery): Promise { findingsCalls.push({ ...q }); if (options?.findingsError !== undefined) { throw options.findingsError; } if (!applySelectors) { return [...findings]; } return findings.filter(finding => { if (q.id !== undefined && finding.id !== q.id) { return false; } if (q.query !== undefined) { const needle = q.query.toLowerCase(); const inText = finding.title.toLowerCase().includes(needle) || finding.summary.toLowerCase().includes(needle); if (!inText) { return false; } } return true; }); }, async listProviderCaveats(q: ProviderCaveatQuery): Promise { caveatsCalls.push({ ...q }); if (options?.caveatsError !== undefined) { throw options.caveatsError; } if (!applySelectors) { return [...providerCaveats]; } return providerCaveats.filter(caveat => { if (q.id !== undefined && caveat.id !== q.id) { return false; } if (q.provider !== undefined && caveat.provider.toLowerCase() !== q.provider.toLowerCase()) { return false; } if (q.query !== undefined) { const needle = q.query.toLowerCase(); const inText = caveat.provider.toLowerCase().includes(needle) || caveat.dataset.toLowerCase().includes(needle) || caveat.caveat.toLowerCase().includes(needle); if (!inText) { return false; } } return true; }); }, }; const port = new Proxy(rawPort, { get(target, prop, receiver) { const value: unknown = Reflect.get(target, prop, receiver); if (typeof value === 'function' && typeof prop === 'string') { return (...args: unknown[]) => { invokedMethods.push(prop); return (value as (...a: unknown[]) => unknown).apply(target, args); }; } return value; }, }); return { libraryCalls, findingsCalls, caveatsCalls, invokedMethods, port, }; } function createMinimalStore(): MarketDataStore { return { bars() { return { async *[Symbol.asyncIterator]() { // empty stream }, }; }, async universe() { return []; }, crossSection() { throw new MarketDataStoreNotImplementedError('crossSection'); }, fundamentalsAsOf() { throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); }, events() { throw new MarketDataStoreNotImplementedError('events'); }, shortsAsOf() { throw new MarketDataStoreNotImplementedError('shortsAsOf'); }, macroAsOf() { throw new MarketDataStoreNotImplementedError('macroAsOf'); }, fx() { throw new MarketDataStoreNotImplementedError('fx'); }, }; } function createMinimalLedger(): TrialLedgerExecutor { return { async query() { return { rows: [] }; }, }; } function createMinimalSymbolPort(): SymbolSearchPort { return { async searchSymbols() { return []; }, }; } async function callReadKnowledge( fake: FakePortState, args: Record ): Promise<{ readonly isError: boolean; readonly text: string; readonly payload: ReadKnowledgeResultPayload | null; }> { const server = createMcpServer({ name: 'stock-bot-research', version: '0.1.0', tools: [createReadKnowledgeTool({ port: fake.port })], }); const raw = await server.handleMessage( JSON.stringify({ jsonrpc: '2.0', id: 'rk-1', method: 'tools/call', params: { name: 'read_knowledge', arguments: args, }, }) ); expect(raw).not.toBeNull(); const parsed = JSON.parse(raw as string) as { result: { isError?: boolean; content: { type: string; text: string }[]; }; }; const isError = parsed.result.isError === true; const text = parsed.result.content[0]?.text ?? ''; return { isError, text, payload: isError ? null : (JSON.parse(text) as ReadKnowledgeResultPayload), }; } describe('MCP read_knowledge tool', () => { test('registers alongside existing MCP tools, exposes strict schema via tools/list, and executes via tools/call', async () => { const store = createMinimalStore(); const ledger = createMinimalLedger(); const fake = createFakeKnowledgePort({ libraryCards: [ makeLibraryCard({ id: 'card-cpcv', title: 'Combinatorial Purged Cross-Validation', tags: ['validation', 'overfitting'], summary: 'Purge and embargo overlapping labels across folds.', body: 'Detailed CPCV methodology card body.', }), ], findings: [ makeFinding({ id: 'find-01', title: 'Earnings drift decay post-2023', status: 'confirmed', createdAt: '2025-02-01T10:00:00.000Z', summary: 'Post-earnings drift attenuates within 3 sessions.', trialRefs: ['trial-101'], evidenceRefs: ['ev-202'], }), ], providerCaveats: [ makeCaveat({ id: 'cav-01', provider: 'eodhd', dataset: 'eodPrices', caveat: 'Backward split adjustments must be un-adjusted before research.', createdAt: '2025-02-05T09:00:00.000Z', }), ], }); const server = createMcpServer({ name: 'stock-bot-research', version: '0.1.0', tools: [ createQueryDataTool({ store, vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, }), createAnalyzeSignalTool({ store, ledger, vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, principalId: 'operator', }), createEventStudyTool({ store, ledger, vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, principalId: 'operator', resolveExchangeCalendars: () => ({}), }), createSearchSymbolsTool({ port: createMinimalSymbolPort(), vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, }), createReadKnowledgeTool({ port: fake.port }), ], }); const listRaw = await server.handleMessage( JSON.stringify({ jsonrpc: '2.0', id: 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([ 'query_data', 'analyze_signal', 'event_study', 'search_symbols', 'read_knowledge', ]); const tool = listParsed.result.tools.find(t => t.name === 'read_knowledge'); expect(tool).toBeDefined(); expect(tool?.inputSchema.type).toBe('object'); expect(tool?.inputSchema.additionalProperties).toBe(false); expect(tool?.inputSchema.required).toBeUndefined(); expect(tool?.inputSchema.properties.source).toMatchObject({ type: 'string', enum: [...READ_KNOWLEDGE_SOURCES], default: 'all', }); expect(tool?.inputSchema.properties.query).toMatchObject({ type: 'string', minLength: 1, maxLength: READ_KNOWLEDGE_MAX_QUERY_LENGTH, }); expect(tool?.inputSchema.properties.id).toMatchObject({ type: 'string', minLength: 1, }); expect(tool?.inputSchema.properties.tags).toMatchObject({ type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, }); expect(tool?.inputSchema.properties.provider).toMatchObject({ type: 'string', minLength: 1, }); expect(tool?.inputSchema.properties.limit).toMatchObject({ type: 'integer', minimum: 1, maximum: READ_KNOWLEDGE_MAX_LIMIT, default: READ_KNOWLEDGE_DEFAULT_LIMIT, }); expect(tool?.inputSchema.properties.scope).toBeUndefined(); expect(tool?.inputSchema.properties.vault_evaluation_only).toBeUndefined(); expect(tool?.inputSchema.properties.vaultCutoffTs).toBeUndefined(); // Execute tools/call end-to-end on the multi-tool server. const callRaw = await server.handleMessage( JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'read_knowledge', arguments: { id: 'card-cpcv' }, }, }) ); expect(callRaw).not.toBeNull(); const callParsed = JSON.parse(callRaw as string) as { result: { isError?: boolean; content: { type: string; text: string }[] }; }; expect(callParsed.result.isError).toBeUndefined(); const payload = JSON.parse(callParsed.result.content[0]?.text ?? '') as ReadKnowledgeResultPayload; expect(payload).toEqual({ rowCount: 1, sources: { library: 1, findings: 0, provider_caveats: 0, }, rows: [ { source: 'library', id: 'card-cpcv', title: 'Combinatorial Purged Cross-Validation', tags: ['validation', 'overfitting'], summary: 'Purge and embargo overlapping labels across folds.', body: 'Detailed CPCV methodology card body.', truncated: false, }, ], }); expect(new Set(fake.invokedMethods)).toEqual( new Set(['listLibraryCards', 'listFindings', 'listProviderCaveats']) ); }); test('invokes only the selected source port methods with applicable parsed selectors', async () => { const libraryCard = makeLibraryCard({ id: 'lib-1', tags: ['alpha'] }); const finding = makeFinding({ id: 'fin-1' }); const caveat = makeCaveat({ id: 'cav-1', provider: 'eodhd' }); // source: 'library' const libFake = createFakeKnowledgePort({ libraryCards: [libraryCard], findings: [finding], providerCaveats: [caveat], }); const libRes = await callReadKnowledge(libFake, { source: 'library', query: ' lib-1 ', tags: [' alpha '], provider: 'eodhd', }); expect(libRes.isError).toBe(false); expect(libFake.invokedMethods).toEqual(['listLibraryCards']); expect(libFake.libraryCalls).toEqual([{ query: 'lib-1', tags: ['alpha'] }]); expect(libFake.findingsCalls).toHaveLength(0); expect(libFake.caveatsCalls).toHaveLength(0); expect(libRes.payload?.sources).toEqual({ library: 1, findings: 0, provider_caveats: 0 }); // source: 'findings' const finFake = createFakeKnowledgePort({ libraryCards: [libraryCard], findings: [finding], providerCaveats: [caveat], }); const finRes = await callReadKnowledge(finFake, { source: 'findings', query: ' fin-1 ', tags: ['alpha'], provider: 'eodhd', }); expect(finRes.isError).toBe(false); expect(finFake.invokedMethods).toEqual(['listFindings']); expect(finFake.findingsCalls).toEqual([{ query: 'fin-1' }]); expect(finFake.libraryCalls).toHaveLength(0); expect(finFake.caveatsCalls).toHaveLength(0); expect(finRes.payload?.sources).toEqual({ library: 0, findings: 1, provider_caveats: 0 }); // source: 'provider_caveats' const cavFake = createFakeKnowledgePort({ libraryCards: [libraryCard], findings: [finding], providerCaveats: [caveat], }); const cavRes = await callReadKnowledge(cavFake, { source: 'provider_caveats', query: ' cav-1 ', tags: ['alpha'], provider: ' EODHD ', }); expect(cavRes.isError).toBe(false); expect(cavFake.invokedMethods).toEqual(['listProviderCaveats']); expect(cavFake.caveatsCalls).toEqual([{ query: 'cav-1', provider: 'EODHD' }]); expect(cavFake.libraryCalls).toHaveLength(0); expect(cavFake.findingsCalls).toHaveLength(0); expect(cavRes.payload?.sources).toEqual({ library: 0, findings: 0, provider_caveats: 1 }); // source: 'all' (explicit) and omitted source for (const args of [ { source: 'all', id: ' shared-id ', tags: [' beta '], provider: ' polygon ' }, { id: ' shared-id ', tags: [' beta '], provider: ' polygon ' }, ]) { const allFake = createFakeKnowledgePort(); const allRes = await callReadKnowledge(allFake, args); expect(allRes.isError).toBe(false); expect(allFake.libraryCalls).toEqual([{ id: 'shared-id', tags: ['beta'] }]); expect(allFake.findingsCalls).toEqual([{ id: 'shared-id' }]); expect(allFake.caveatsCalls).toEqual([{ id: 'shared-id', provider: 'polygon' }]); expect(allFake.invokedMethods).toEqual([ 'listLibraryCards', 'listFindings', 'listProviderCaveats', ]); } }); test('supports exact case-sensitive id precedence over query, missing id, and explicit field projection', async () => { const extraCard = { ...makeLibraryCard({ id: 'Exact-Id', title: 'Unrelated Title', summary: 'Unrelated summary', }), internalSecret: 'must-not-leak', } as unknown as LibraryCardRecord; const fake = createFakeKnowledgePort({ libraryCards: [extraCard, makeLibraryCard({ id: 'exact-id', title: 'Lowercase ID' })], findings: [makeFinding({ id: 'Exact-Id', title: 'Matching Finding ID' })], providerCaveats: [makeCaveat({ id: 'Exact-Id', dataset: 'Matching Caveat ID' })], }); // id takes precedence over non-matching query and is case-sensitive const exactRes = await callReadKnowledge(fake, { id: ' Exact-Id ', query: 'nonexistent-query-text', }); expect(exactRes.isError).toBe(false); expect(exactRes.payload?.rowCount).toBe(3); expect(exactRes.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 1 }); expect(exactRes.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ 'library:Exact-Id', 'findings:Exact-Id', 'provider_caveats:Exact-Id', ]); expect('internalSecret' in (exactRes.payload?.rows[0] ?? {})).toBe(false); // Missing id returns empty result with zero counts const missingRes = await callReadKnowledge(fake, { id: 'does-not-exist' }); expect(missingRes.isError).toBe(false); expect(missingRes.payload).toEqual({ rowCount: 0, sources: { library: 0, findings: 0, provider_caveats: 0 }, rows: [], }); }); test('omits query from port selectors when id is supplied so selector-filtering ports return exact matches', async () => { const filteringFake = createFakeKnowledgePort({ applySelectors: true, libraryCards: [ makeLibraryCard({ id: 'card-cpcv', title: 'Combinatorial Purged Cross-Validation', tags: ['validation'], summary: 'Purge and embargo overlapping labels across folds.', }), ], findings: [ makeFinding({ id: 'card-cpcv', title: 'CPCV split stability', summary: 'No mention of unrelated factors.', }), ], providerCaveats: [ makeCaveat({ id: 'card-cpcv', provider: 'eodhd', dataset: 'eodPrices', caveat: 'Backward split adjustments only.', }), ], }); const res = await callReadKnowledge(filteringFake, { id: 'card-cpcv', query: 'momentum', tags: ['validation'], provider: 'eodhd', }); expect(res.isError).toBe(false); expect(filteringFake.libraryCalls).toEqual([{ id: 'card-cpcv', tags: ['validation'] }]); expect(filteringFake.findingsCalls).toEqual([{ id: 'card-cpcv' }]); expect(filteringFake.caveatsCalls).toEqual([{ id: 'card-cpcv', provider: 'eodhd' }]); expect(res.payload?.rowCount).toBe(3); expect(res.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 1 }); expect(res.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ 'library:card-cpcv', 'findings:card-cpcv', 'provider_caveats:card-cpcv', ]); }); test('does not grant exact-ID priority to free-text query matches and stays invariant to query capitalization', async () => { const fake = createFakeKnowledgePort({ libraryCards: [ makeLibraryCard({ id: 'momentum', title: 'Factor Crowding Notes', tags: ['risk'], summary: 'Discusses momentum drawdown regimes.', }), makeLibraryCard({ id: 'z-card', title: 'Momentum Basics', tags: ['factor'], summary: 'Introductory overview.', }), ], findings: [ makeFinding({ id: 'momentum', title: 'Regime Decay', summary: 'Observed momentum turnover costs.', }), makeFinding({ id: 'z-finding', title: 'Momentum Persistence', summary: 'Observed over 2015–2024.', }), ], providerCaveats: [ makeCaveat({ id: 'momentum', provider: 'eodhd', dataset: 'eodPrices', caveat: 'Affects momentum backtests.', }), makeCaveat({ id: 'z-caveat', provider: 'eodhd', dataset: 'momentum_signals', caveat: 'Adjusted series.', }), ], }); for (const source of ['library', 'findings', 'provider_caveats'] as const) { const lowerTop = await callReadKnowledge(fake, { source, query: 'momentum', limit: 1 }); const upperTop = await callReadKnowledge(fake, { source, query: 'MOMENTUM', limit: 1 }); expect(lowerTop.isError).toBe(false); expect(upperTop.isError).toBe(false); expect(lowerTop.payload).toEqual(upperTop.payload); const expectedId = source === 'library' ? 'z-card' : source === 'findings' ? 'z-finding' : 'z-caveat'; expect(lowerTop.payload?.rows.map(r => r.id)).toEqual([expectedId]); } }); test('filters case-insensitively across titles, tags, summaries, caveats, and source-specific filters', async () => { const fake = createFakeKnowledgePort({ libraryCards: [ makeLibraryCard({ id: 'lib-tag', title: 'Factor Neutrality', tags: ['Momentum', 'Neutrality'], summary: 'Dollar neutral weighting.', }), makeLibraryCard({ id: 'lib-summary', title: 'Execution Slippage', tags: ['Microstructure'], summary: 'Models MOMENTUM crowding impact.', }), makeLibraryCard({ id: 'lib-only-one-tag', title: 'Momentum Basics', tags: ['Momentum'], summary: 'Single tag card.', }), ], findings: [ makeFinding({ id: 'fin-match', title: 'Cross-sectional Momentum', summary: 'Observed decay in 2024.', }), makeFinding({ id: 'fin-other', title: 'Value Spread', summary: 'Unrelated finding.', }), ], providerCaveats: [ makeCaveat({ id: 'cav-eodhd', provider: 'EODHD', dataset: 'eodPrices', caveat: 'Momentum backtests need un-adjusted closes.', }), makeCaveat({ id: 'cav-polygon', provider: 'Polygon', dataset: 'intraday1m', caveat: 'Momentum bars omit odd lots.', }), ], }); // With source: 'all', tags filters only library (all-tag match) and provider filters only caveats const combinedRes = await callReadKnowledge(fake, { query: ' momentum ', tags: [' MOMENTUM ', 'neutrality'], provider: ' eodhd ', }); expect(combinedRes.isError).toBe(false); expect(combinedRes.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ 'findings:fin-match', 'provider_caveats:cav-eodhd', 'library:lib-tag', ]); expect(combinedRes.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 1, }); // Empty result when query matches nothing const emptyRes = await callReadKnowledge(fake, { query: 'zzz-no-match' }); expect(emptyRes.isError).toBe(false); expect(emptyRes.payload).toEqual({ rowCount: 0, sources: { library: 0, findings: 0, provider_caveats: 0 }, rows: [], }); }); test('ranks deterministically across shuffled fixtures: exact id > title/dataset > other > ascending id > source order', async () => { const libraryCards: LibraryCardRecord[] = [ makeLibraryCard({ id: 'tie-id', title: 'Alpha title match', tags: ['misc'], summary: 'summary', }), makeLibraryCard({ id: 'a-other', title: 'Unrelated', tags: ['alpha'], summary: 'summary', }), makeLibraryCard({ id: 'B-other', title: 'Unrelated', tags: ['misc'], summary: 'Contains alpha in summary', }), ]; const findings: FindingRecord[] = [ makeFinding({ id: 'tie-id', title: 'Alpha finding title', summary: 'summary', }), makeFinding({ id: 'z-summary', title: 'Unrelated finding', summary: 'Mentions alpha here', }), ]; const providerCaveats: ProviderCaveatRecord[] = [ makeCaveat({ id: 'tie-id', provider: 'eodhd', dataset: 'alpha_dataset', caveat: 'caveat text', }), makeCaveat({ id: 'c-provider', provider: 'alpha-feed', dataset: 'bars', caveat: 'ordinary text', }), makeCaveat({ id: 'd-caveat', provider: 'other', dataset: 'bars', caveat: 'mentions alpha inside caveat', }), ]; const resA = await callReadKnowledge( createFakeKnowledgePort({ libraryCards, findings, providerCaveats }), { query: 'alpha' } ); const resB = await callReadKnowledge( createFakeKnowledgePort({ libraryCards: [...libraryCards].reverse(), findings: [...findings].reverse(), providerCaveats: [...providerCaveats].reverse(), }), { query: 'alpha' } ); expect(resA.isError).toBe(false); expect(resB.isError).toBe(false); expect(resA.payload).toEqual(resB.payload); // Title/dataset matches first (all have id 'tie-id', broken by library -> findings -> provider_caveats), // then other text matches ordered by ASCII/code-unit id ('B-other' < 'a-other' < 'c-provider' < 'd-caveat' < 'z-summary'). expect(resA.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ 'library:tie-id', 'findings:tie-id', 'provider_caveats:tie-id', 'library:B-other', 'library:a-other', 'provider_caveats:c-provider', 'provider_caveats:d-caveat', 'findings:z-summary', ]); }); test('enforces default limit 20, hard max 100, late best match, and post-limit source counts', async () => { // 25 eligible records (22 library + 3 findings) with default limit 20: // Findings have title matches so they rank ahead of library summary matches, pushing 5 library rows out. const lib22: LibraryCardRecord[] = []; for (let i = 1; i <= 22; i += 1) { lib22.push( makeLibraryCard({ id: `lib-${String(i).padStart(2, '0')}`, title: 'Generic Card', summary: 'Contains needle in summary', }) ); } const fin3: FindingRecord[] = [ makeFinding({ id: 'fin-01', title: 'Needle Title 1', summary: 's' }), makeFinding({ id: 'fin-02', title: 'Needle Title 2', summary: 's' }), makeFinding({ id: 'fin-03', title: 'Needle Title 3', summary: 's' }), ]; const defaultRes = await callReadKnowledge( createFakeKnowledgePort({ libraryCards: lib22, findings: fin3 }), { query: 'needle' } ); expect(defaultRes.isError).toBe(false); expect(defaultRes.payload?.rowCount).toBe(20); expect(defaultRes.payload?.rows).toHaveLength(20); expect(defaultRes.payload?.sources).toEqual({ library: 17, findings: 3, provider_caveats: 0, }); // Hard max 100 with 115 eligible records and the best match placed last in the fixture const lib115: LibraryCardRecord[] = []; for (let i = 1; i <= 114; i += 1) { lib115.push( makeLibraryCard({ id: `rec-${String(i).padStart(3, '0')}`, title: 'Other', summary: 'Contains signal in summary', }) ); } lib115.push( makeLibraryCard({ id: 'zzz-best-late', title: 'Signal Title Match Placed Last', summary: 'summary', }) ); const maxRes = await callReadKnowledge(createFakeKnowledgePort({ libraryCards: lib115 }), { source: 'library', query: 'signal', limit: READ_KNOWLEDGE_MAX_LIMIT, }); expect(maxRes.isError).toBe(false); expect(maxRes.payload?.rowCount).toBe(100); expect(maxRes.payload?.rows).toHaveLength(100); expect(maxRes.payload?.rows[0]?.id).toBe('zzz-best-late'); expect(maxRes.payload?.sources).toEqual({ library: 100, findings: 0, provider_caveats: 0, }); }); test('truncates body, summary, and caveat independently at 4096 chars after matching', async () => { const exactCap = 'x'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH); const overCapWithTailNeedle = `${'y'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH)}NEEDLE`; const overCapOne = 'z'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 1); const fake = createFakeKnowledgePort({ libraryCards: [ makeLibraryCard({ id: 'lib-exact', title: 'Exact Cap Card', summary: exactCap, body: exactCap, }), makeLibraryCard({ id: 'lib-over-body', title: 'Over Cap Body', summary: 'short summary', body: overCapOne, }), makeLibraryCard({ id: 'lib-over-summary-needle', title: 'Late Match Summary', summary: overCapWithTailNeedle, body: 'short body', }), ], findings: [ makeFinding({ id: 'fin-exact', title: 'Exact Finding', summary: exactCap, }), makeFinding({ id: 'fin-over-needle', title: 'Late Match Finding', summary: overCapWithTailNeedle, }), ], providerCaveats: [ makeCaveat({ id: 'cav-exact', dataset: 'exact_ds', caveat: exactCap, }), makeCaveat({ id: 'cav-over-needle', dataset: 'over_ds', caveat: overCapWithTailNeedle, }), ], }); // Exact cap rows are not truncated for (const id of ['lib-exact', 'fin-exact', 'cav-exact']) { const res = await callReadKnowledge(fake, { id }); expect(res.isError).toBe(false); expect(res.payload?.rows).toHaveLength(1); const row = res.payload?.rows[0]; expect(row?.truncated).toBe(false); if (row?.source === 'library') { expect(row.summary).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); expect(row.body).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); } else if (row?.source === 'findings') { expect(row.summary).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); } else if (row?.source === 'provider_caveats') { expect(row.caveat).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); } } // Library body 1 char over cap is truncated independently while short summary is untouched const overBodyRes = await callReadKnowledge(fake, { id: 'lib-over-body' }); expect(overBodyRes.isError).toBe(false); const bodyRow = overBodyRes.payload?.rows[0]; expect(bodyRow?.source).toBe('library'); if (bodyRow?.source === 'library') { expect(bodyRow.truncated).toBe(true); expect(bodyRow.summary).toBe('short summary'); expect(bodyRow.body).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); } // Query matching text beyond char 4096 still matches, then caps output to 4096 with truncated: true const needleRes = await callReadKnowledge(fake, { query: 'needle' }); expect(needleRes.isError).toBe(false); expect(needleRes.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ 'provider_caveats:cav-over-needle', 'findings:fin-over-needle', 'library:lib-over-summary-needle', ]); for (const row of needleRes.payload?.rows ?? []) { expect(row.truncated).toBe(true); if (row.source === 'library') { expect(row.summary).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); expect(row.body).toBe('short body'); } else if (row.source === 'findings') { expect(row.summary).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); } else { expect(row.caveat).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); } } }); test('rejects strict input violations before invoking any port method', async () => { const invalidInputs: Record[] = [ { scope: 'vault_evaluation_only' }, { vault_evaluation_only: true }, { vaultCutoffTs: VAULT_CUTOFF_TS }, { unexpectedKey: 'nope' }, { query: 'A'.repeat(READ_KNOWLEDGE_MAX_QUERY_LENGTH + 1) }, { query: '' }, { query: ' \t\n ' }, { id: '' }, { id: ' ' }, { provider: '' }, { provider: ' ' }, { tags: [] }, { tags: ['valid', ' '] }, { source: 'vault' }, { source: 'LIBRARY' }, { limit: 0 }, { limit: -5 }, { limit: READ_KNOWLEDGE_MAX_LIMIT + 1 }, { limit: 1.5 }, { limit: '10' }, ]; for (const args of invalidInputs) { expect(readKnowledgeInputSchema.safeParse(args).success).toBe(false); const fake = createFakeKnowledgePort({ libraryCards: [makeLibraryCard({ id: 'c1' })], }); const res = await callReadKnowledge(fake, args); expect(res.isError).toBe(true); expect(res.text).toContain('Invalid arguments for tool "read_knowledge"'); expect(fake.invokedMethods).toHaveLength(0); } }); test('returns sanitized isError without leaking connection strings or stack traces when port rejects', async () => { const secretError = new Error( 'postgres://admin:super-secret@10.0.0.51:5432/trading_bot connection refused' ); secretError.stack = 'Error: postgres://admin:super-secret@10.0.0.51:5432/trading_bot\n at internalQuery (/srv/secret/db.ts:42:9)'; // Single source failure const singleFake = createFakeKnowledgePort({ libraryError: secretError }); const singleRes = await callReadKnowledge(singleFake, { source: 'library', query: 'alpha' }); expect(singleRes.isError).toBe(true); expect(singleRes.text).toBe('Error: Tool execution failed.'); expect(singleRes.text).not.toContain('super-secret'); expect(singleRes.text).not.toContain('10.0.0.51'); expect(singleRes.text).not.toContain('trading_bot'); expect(singleRes.text).not.toContain('/srv/secret/db.ts'); // Partial failure under source: 'all' when other selected sources succeed const partialFake = createFakeKnowledgePort({ libraryCards: [makeLibraryCard({ id: 'ok-1', title: 'Alpha' })], findingsError: secretError, providerCaveats: [makeCaveat({ id: 'ok-2', dataset: 'Alpha' })], }); const partialRes = await callReadKnowledge(partialFake, { source: 'all', query: 'alpha' }); expect(partialRes.isError).toBe(true); expect(partialRes.text).toBe('Error: Tool execution failed.'); expect(partialRes.text).not.toContain('super-secret'); expect(partialRes.text).not.toContain('10.0.0.51'); expect(partialRes.text).not.toContain('db.ts'); }); test('factory throws on missing or invalid port options', () => { expect(() => createReadKnowledgeTool(null as unknown as Parameters[0]) ).toThrow(); expect(() => createReadKnowledgeTool({ port: null as unknown as KnowledgePort }) ).toThrow(); expect(() => createReadKnowledgeTool({ port: {} as unknown as KnowledgePort }) ).toThrow(); }); });