diff --git a/docs/cli.md b/docs/cli.md index bbae502..08e350c 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -43,6 +43,7 @@ CODEBASE_CONTEXT_ASCII=1 node /path/to/codebase-context/dist/index.js patterns - `refs --symbol ` — concrete reference evidence - `cycles` — circular dependency detection - `status` — index status/progress +- `relationships --file ` — verified imports/re-exports; `--direction incoming|outgoing`, `--max-hops 1..3`, `--max-nodes 1..100` - `reindex` — rebuild index (full or incremental) - `style-guide` — find style guide sections in docs - `memory list|add|remove` — manage team memory (stored in `.codebase-context/memory.json`) @@ -67,6 +68,20 @@ The built candidate also supports `--version` and builds a missing index when yo ## First use +Compact JSON search results include a `signaturePreview` of up to seven contiguous +source lines, bounded to 480 serialized UTF-8 bytes per preview. `previewRange` +identifies those exact lines in the result file; `readRange`, when present, identifies +the indexed source span to open for omitted context. A preview is an excerpt, not a +complete control-flow analysis. An oversized source line is omitted rather than cut. +Compact `searchQuality.hint` directs source reads when context is omitted and states +that selected results cannot prove absence or repository-wide behavior. +Search `nextHops` retain the MCP operation and include a CLI argument array (`cli`) +to pass after the executable. They follow the results, require a confident search +and an indexed import edge, and choose outgoing or incoming traversal accordingly. +`relationships` uses the same verified import/re-export +tool as MCP and does not prove runtime calls. `refs --symbol ` uses the existing +current-source reference finder for symbol-level continuation. + Run these candidate commands from the project root. A fresh index defaults to keyword-only mode without an embedding or reranker download. An existing index keeps its recorded mode, which may use embeddings. Indexing time depends on the repository and machine; no cold-start timing is promised here. Then inspect the map and search: ```bash diff --git a/src/cli.ts b/src/cli.ts index 2121e73..1bc653b 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -2,7 +2,7 @@ import { resolveIndexArtifact } from './core/index-generation.js'; /** * CLI subcommands for codebase-context. * Memory list/add/remove — vendor-neutral access without any AI agent. - * search/metadata/status/reindex/style-guide/patterns/refs/cycles — human-facing wrappers over core read/query tools. + * search/metadata/status/reindex/style-guide/patterns/refs/relationships/cycles — wrappers over read/query tools. */ import path from 'path'; @@ -42,6 +42,7 @@ const _CLI_COMMANDS = [ 'style-guide', 'patterns', 'refs', + 'relationships', 'cycles', 'init', 'map' @@ -50,7 +51,7 @@ const _CLI_COMMANDS = [ type CliCommand = (typeof _CLI_COMMANDS)[number]; const CLI_COMMAND_SET: ReadonlySet = new Set(_CLI_COMMANDS); -function isCliCommand(value: string): value is CliCommand { +export function isCliCommand(value: string): value is CliCommand { return CLI_COMMAND_SET.has(value); } @@ -82,6 +83,10 @@ function printUsage(): void { console.log(' style-guide [--query ] [--category ] Style guide rules'); console.log(' patterns [--category all|di|state|testing|libraries] Team patterns'); console.log(' refs --symbol [--limit ] Symbol references'); + console.log( + ' relationships --file Verified imports/re-exports (not runtime calls)' + ); + console.log(' [--direction outgoing|incoming] [--max-hops 1..3] [--max-nodes 1..100]'); console.log(' cycles [--scope ] Circular dependency detection'); console.log(' init [--client ] [--yes] Detect and configure coding tools'); console.log(' map [--json] [--pretty] Conventions map (indexes first if needed)'); @@ -294,6 +299,7 @@ export async function handleCliCommand(argv: string[]): Promise { | { toolName: 'get_style_guide'; toolArgs: StyleGuideToolArgs } | { toolName: 'get_team_patterns'; toolArgs: TeamPatternsToolArgs } | { toolName: 'get_symbol_references'; toolArgs: SymbolReferencesToolArgs } + | { toolName: 'get_code_relationships'; toolArgs: RelationshipToolArgs } | { toolName: 'detect_circular_dependencies'; toolArgs: DetectCircularDependenciesToolArgs }; type SearchToolArgs = { @@ -307,6 +313,12 @@ export async function handleCliCommand(argv: string[]): Promise { type StyleGuideToolArgs = { query?: string; category?: string }; type TeamPatternsToolArgs = { category?: TeamPatternCategory }; type SymbolReferencesToolArgs = { symbol: string; limit?: number }; + type RelationshipToolArgs = { + file: string; + direction?: 'outgoing' | 'incoming'; + max_hops?: number; + max_nodes?: number; + }; type DetectCircularDependenciesToolArgs = { scope?: string }; let dispatch: DispatchSpec; @@ -425,6 +437,36 @@ export async function handleCliCommand(argv: string[]): Promise { }; break; } + case 'relationships': { + const usage = + 'codebase-context relationships --file [--direction outgoing|incoming] [--max-hops 1..3] [--max-nodes 1..100]'; + const file = requireStringFlag(flags, 'file', usage); + const direction = optionalStringFlag(flags, 'direction', usage); + if (direction !== undefined && direction !== 'incoming' && direction !== 'outgoing') { + exitWithError(`Error: --direction must be incoming or outgoing\nUsage: ${usage}`); + } + const boundedInt = (key: string, maximum: number): number | undefined => { + const value = optionalStringFlag(flags, key, usage); + if (value === undefined) return undefined; + const number = Number(value); + if (!Number.isInteger(number) || number < 1 || number > maximum) { + exitWithError(`Error: --${key} must be an integer from 1 to ${maximum}\nUsage: ${usage}`); + } + return number; + }; + const maxHops = boundedInt('max-hops', 3); + const maxNodes = boundedInt('max-nodes', 100); + dispatch = { + toolName: 'get_code_relationships', + toolArgs: { + file, + ...(direction ? { direction } : {}), + ...(maxHops !== undefined ? { max_hops: maxHops } : {}), + ...(maxNodes !== undefined ? { max_nodes: maxNodes } : {}) + } + }; + break; + } case 'cycles': { const usage = 'codebase-context cycles [--scope ]'; const scope = optionalStringFlag(flags, 'scope', usage); diff --git a/src/index.ts b/src/index.ts index 4a2de3f..04ad1d8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -25,7 +25,7 @@ import { IndexSignalSchema, type IndexSignal } from './core/index-signal.js'; export type { IndexSignal } from './core/index-signal.js'; import { IndexCorruptedError } from './errors/index.js'; import { appendMemoryFile } from './memory/store.js'; -import { handleCliCommand } from './cli.js'; +import { handleCliCommand, isCliCommand } from './cli.js'; import { startFileWatcher } from './core/file-watcher.js'; import { parseGitLogLineToMemory } from './memory/git-memory.js'; import { @@ -97,20 +97,6 @@ const KNOWN_FLAGS = new Set([ '--version', '-v' ]); -const CLI_SUBCOMMANDS = [ - 'memory', - 'search', - 'metadata', - 'status', - 'reindex', - 'style-guide', - 'patterns', - 'refs', - 'cycles', - 'init', - 'map', - 'help' -]; function canonicalEntrypointPath(filePath: string | undefined): string | undefined { if (!filePath) return undefined; @@ -131,7 +117,8 @@ const directSubcommand = process.argv[2]; const isDirectCliSubcommand = isDirectRun && typeof directSubcommand === 'string' && - (CLI_SUBCOMMANDS.includes(directSubcommand) || + (isCliCommand(directSubcommand) || + directSubcommand === 'help' || directSubcommand === '--help' || directSubcommand === '--version' || directSubcommand === '-v'); @@ -2123,7 +2110,7 @@ if (isDirectRun) { if (subcommand === '--version' || subcommand === '-v') { console.log(PKG_VERSION); process.exit(0); - } else if (CLI_SUBCOMMANDS.includes(subcommand) || subcommand === '--help') { + } else if (isCliCommand(subcommand) || subcommand === 'help' || subcommand === '--help') { handleCliCommand(process.argv.slice(2)).catch((error) => { console.error('Error:', error instanceof Error ? error.message : String(error)); process.exit(1); diff --git a/src/tools/search-codebase.ts b/src/tools/search-codebase.ts index 4182734..b2cc66b 100644 --- a/src/tools/search-codebase.ts +++ b/src/tools/search-codebase.ts @@ -3,7 +3,13 @@ import { withToolIndexSnapshot } from './index-snapshot.js'; import type { Tool } from '@modelcontextprotocol/sdk/types.js'; import { promises as fs } from 'fs'; import path from 'path'; -import type { ToolContext, ToolResponse, DecisionCard } from './types.js'; +import type { + ToolContext, + ToolResponse, + DecisionCard, + SearchNextHop, + SearchResultItem +} from './types.js'; import { presentSourceCoverage } from '../core/source-coverage-action.js'; import { CodebaseSearcher } from '../core/search.js'; import type { SearchIntentProfile, SearchSourceCoverage } from '../core/search.js'; @@ -29,7 +35,7 @@ import { indexHealthByFile, normalizeHealthLookupKey, readHealthFile } from '../ import { InternalFileGraph } from '../utils/usage-tracker.js'; import type { FileExport } from '../utils/usage-tracker.js'; import { RELATIONSHIPS_FILENAME } from '../constants/codebase-context.js'; -import { finalizeSearchPayloadText } from './search-payload-budget.js'; +import { boundSearchPreview, finalizeSearchPayloadText } from './search-payload-budget.js'; // Stop words for compact-mode memory relevance filter (mirrors QUERY_STOP_WORDS in search.ts) const COMPACT_STOP_WORDS = new Set([ @@ -841,32 +847,29 @@ async function handlePinned( return undefined; } - // Build up to 2 dynamic next-hop suggestions (compact mode) - function buildNextHops( - compactResults: SearchResult[], - sq: { status: string } - ): Array<{ tool: string; args?: Record; why: string }> { - const hops: Array<{ tool: string; args?: Record; why: string }> = []; - // Only advertise tools this MCP server actually supplies. Source reads belong - // to the host; returned result paths already identify what to open there. - if (compactResults.length > 0) { - const relativeFile = path.relative(ctx.rootPath, compactResults[0].filePath); - if ( - !path.isAbsolute(relativeFile) && - relativeFile !== '..' && - !relativeFile.startsWith(`..${path.sep}`) - ) { - hops.push({ - tool: 'get_code_relationships', - args: { file: relativeFile.replace(/\\/g, '/'), direction: 'outgoing' }, - why: - sq.status === 'low_confidence' - ? 'Follow current import evidence while continuing source discovery' - : 'Follow verified imports to related implementation files' - }); + // Recommend an indexed edge only after source discovery has a confident result. + function buildNextHops(compactResults: SearchResult[], sq: { status: string }): SearchNextHop[] { + if (sq.status === 'low_confidence') return []; + for (const result of compactResults) { + const relativeFile = canonicalRootRelativePath(normalizeGraphPath(result.filePath)); + if (!relativeFile) continue; + const direction = getImportsGraph()?.[relativeFile]?.length + ? 'outgoing' + : reverseImports.get(relativeFile)?.length + ? 'incoming' + : undefined; + if (direction) { + return [ + { + tool: 'get_code_relationships', + args: { file: relativeFile, direction }, + cli: ['relationships', '--file', relativeFile, '--direction', direction, '--json'], + why: 'After reading the result source, follow indexed imports/re-exports, not runtime calls.' + } + ]; } } - return hops.slice(0, 2); + return []; } const searchQuality = assessSearchQuality(queryStr, results); @@ -1240,10 +1243,24 @@ async function handlePinned( // Compact mode (default): bounded response with light graph context const isCompact = mode !== 'full'; - function buildSignaturePreview(snippet: string | undefined): string | undefined { - if (!snippet) return undefined; - - const lines = snippet.replace(/^\r?\n+/, '').split('\n'); + function buildSignaturePreview( + result: SearchResult + ): Pick { + const readRange = { startLine: result.startLine, endLine: result.endLine }; + if (!result.snippet) return { readRange }; + // Snippets are source prefixes. Keep their offsets, but never present the + // searcher's synthetic truncation footer as source evidence. + const lines = result.snippet.replace(/\r\n/g, '\n').split('\n'); + if ( + lines.length === 22 && + lines[20] === '' && + /^\.\.\. \[\d+ more lines\]$/.test(lines[21]) && + result.endLine - result.startLine + 1 > 20 + ) + lines.splice(20); + while (lines.length && !lines[lines.length - 1].trim()) lines.pop(); + const leading = lines.findIndex((line) => line.trim()); + if (leading < 0) return { readRange }; const previewTerms = [...new Set(queryTerms.filter((term) => term.length > 3))]; const strongestMatch = lines .map((line, index) => ({ @@ -1253,17 +1270,22 @@ async function handlePinned( .filter((entry) => entry.matches > 0) .sort((a, b) => b.matches - a.matches || a.index - b.index)[0]; - let previewLines = lines.slice(0, 3); - if (strongestMatch) { - const windowLength = Math.min(3, lines.length); - const windowStart = Math.max( - 0, - Math.min(strongestMatch.index - 1, lines.length - windowLength) - ); - previewLines = lines.slice(windowStart, windowStart + windowLength); - } - - return previewLines.join('\n').trim() || undefined; + const selected = boundSearchPreview( + lines.slice(leading), + Math.max(0, (strongestMatch?.index ?? leading) - leading) + ); + if (!selected) return { readRange }; + const previewRange = { + startLine: result.startLine + leading + selected.start, + endLine: result.startLine + leading + selected.end - 1 + }; + return { + signaturePreview: selected.text, + previewRange, + ...(previewRange.startLine > result.startLine || previewRange.endLine < result.endLine + ? { readRange } + : {}) + }; } if (isCompact) { @@ -1272,22 +1294,31 @@ async function handlePinned( const patternSummary = buildPatternSummary(); const bestExample = getBestExample(compactResults); const nextHops = buildNextHops(compactResults, searchQuality); + const previews = compactResults.map(buildSignaturePreview); + const evidenceHint = [ + searchQualityBlock.hint, + 'Selected search results are not exhaustive: they do not prove absence or repository-wide behavior.', + previews.some((preview) => preview.readRange) + ? 'Read each readRange in the host before inferring behavior; previewRange covers only the displayed excerpt.' + : undefined + ] + .filter(Boolean) + .join(' '); const payloadText = finalizeSearchPayloadText( { status: 'success', ...(sourceCoverage.status === 'partial' && { sourceCoverage }), - searchQuality: searchQualityBlock, + searchQuality: { ...searchQualityBlock, hint: evidenceHint }, budget: { mode: 'compact', resultCount: compactResults.length }, ...(preflightPayload && { preflight: preflightPayload }), ...(patternSummary && { patternSummary }), ...(bestExample && { bestExample }), - ...(nextHops.length > 0 && { nextHops }), - results: compactResults.map((r) => { + results: compactResults.map((r, index) => { const importedByCount = getImportedByCount(r); const topExports = getTopExports(r.filePath); const scope = buildScopeHeader(r.metadata); const health = getResultHealth(r.filePath); - const signaturePreview = buildSignaturePreview(r.snippet); + const preview = previews[index]; return { file: `${r.filePath}:${r.startLine}-${r.endLine}`, summary: r.summary, @@ -1306,9 +1337,10 @@ async function handlePinned( ...(r.metadata?.symbolKind && { symbolKind: r.metadata.symbolKind }), ...(scope && { scope }), ...(health && { health }), - ...(signaturePreview && { signaturePreview }) + ...preview }; }), + ...(nextHops.length > 0 && { nextHops }), ...(strongMemories.length > 0 && { relatedMemories: strongMemories.map((m) => formatMemoryForOutput(m)) }) diff --git a/src/tools/search-payload-budget.ts b/src/tools/search-payload-budget.ts index 74ee28a..b3cfb85 100644 --- a/src/tools/search-payload-budget.ts +++ b/src/tools/search-payload-budget.ts @@ -1,5 +1,31 @@ type SearchPayloadMode = 'compact' | 'full'; +/** Whole contiguous source lines only; never cut a condition/effect mid-line. */ +export function boundSearchPreview( + lines: string[], + anchor: number +): { text: string; start: number; end: number } | undefined { + const maximumLines = 7; + const maximumSerializedBytes = 480; + let start = Math.max(0, Math.min(anchor - 2, lines.length - maximumLines)); + let end = Math.min(lines.length, start + maximumLines); + while (start < end) { + const text = lines.slice(start, end).join('\n'); + // Include the field key and JSON escaping, with room for the surrounding + // result object's indentation and comma (compact results serialize pretty). + if ( + Buffer.byteLength(JSON.stringify({ signaturePreview: text }, null, 2), 'utf8') + 8 <= + maximumSerializedBytes + ) { + return text.trim() ? { text, start, end } : undefined; + } + // Retain the matched line, removing the furthest context line first. + if (anchor - start > end - 1 - anchor) start += 1; + else end -= 1; + } + return undefined; +} + function isPlainRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } diff --git a/src/tools/types.ts b/src/tools/types.ts index 43cabb8..b50e122 100644 --- a/src/tools/types.ts +++ b/src/tools/types.ts @@ -96,6 +96,7 @@ export interface SearchNextHop { tool: string; why: string; args?: Record; + cli?: string[]; } export interface SearchBudget { @@ -125,6 +126,8 @@ export interface SearchResultItem { symbolKind?: string; scope?: string; signaturePreview?: string; + previewRange?: { startLine: number; endLine: number }; + readRange?: { startLine: number; endLine: number }; imports?: string[]; exports?: string[]; complexity?: number; diff --git a/tests/cli-entrypoint-runtime.test.ts b/tests/cli-entrypoint-runtime.test.ts index 314ad8e..19c9b60 100644 --- a/tests/cli-entrypoint-runtime.test.ts +++ b/tests/cli-entrypoint-runtime.test.ts @@ -19,6 +19,24 @@ type MapJson = { }; describe('CLI entrypoint runtime', () => { + it('runs relationships through the executable CLI route without starting MCP', async () => { + const projectRoot = await mkdtemp(join(tmpdir(), 'cbc-cli-relationships-')); + try { + const help = runCli(['relationships', '--help'], projectRoot); + expect(help.status, help.stderr).toBe(0); + expect(help.stdout).toContain('relationships --file '); + const result = runCli(['relationships', '--file', 'missing.ts', '--json'], projectRoot); + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + status: 'not_indexed_or_outside_root', + file: 'missing.ts' + }); + expect(await readdir(projectRoot)).toEqual([]); + } finally { + await rm(projectRoot, { recursive: true, force: true }); + } + }, 120_000); + function runCli(args: string[], projectRoot = root) { return spawnSync( process.execPath, diff --git a/tests/cli.test.ts b/tests/cli.test.ts index 2debe67..213eade 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -149,6 +149,48 @@ describe('CLI', () => { expect(toolMocks.dispatchTool).not.toHaveBeenCalled(); }); + it('relationships follows the existing verified import tool with bounded options', async () => { + const payload = { status: 'success', paths: [], note: 'Imports never imply runtime calls.' }; + toolMocks.dispatchTool.mockResolvedValue({ + content: [{ type: 'text', text: JSON.stringify(payload) }] + }); + await handleCliCommand([ + 'relationships', + '--file', + 'src/session.ts', + '--direction', + 'incoming', + '--max-hops', + '3', + '--max-nodes', + '12', + '--json' + ]); + expect(toolMocks.dispatchTool).toHaveBeenCalledWith( + 'get_code_relationships', + { + file: 'src/session.ts', + direction: 'incoming', + max_hops: 3, + max_nodes: 12 + }, + expect.objectContaining({ rootPath: expect.any(String) }) + ); + expect(logSpy).toHaveBeenCalledWith(JSON.stringify(payload)); + }); + + it.each([ + ['--file'], + ['--file', 'src/a.ts', '--direction', 'callers'], + ['--file', 'src/a.ts', '--max-hops', '4'], + ['--file', 'src/a.ts', '--max-hops', '1.5'], + ['--file', 'src/a.ts', '--max-nodes', '101'], + ['--file', 'src/a.ts', '--max-nodes', '0'] + ])('rejects invalid relationship options %j before dispatch', async (...args) => { + await expect(handleCliCommand(['relationships', ...args])).rejects.toThrow(/process\.exit:1/); + expect(toolMocks.dispatchTool).not.toHaveBeenCalled(); + }); + it('status renders human output (not raw JSON)', async () => { const originalAscii = process.env.CODEBASE_CONTEXT_ASCII; process.env.CODEBASE_CONTEXT_ASCII = '1'; diff --git a/tests/search-compact-mode.test.ts b/tests/search-compact-mode.test.ts index 267db28..959e164 100644 --- a/tests/search-compact-mode.test.ts +++ b/tests/search-compact-mode.test.ts @@ -339,6 +339,17 @@ describe('search_codebase compact/full mode', () => { expect(payload.nextHops?.length ?? 0).toBeGreaterThan(0); expect(payload.nextHops?.some((hop) => hop.tool === 'read_file')).toBe(false); expect(payload.nextHops?.[0].tool).toBe('get_code_relationships'); + expect(payload.nextHops?.[0].cli).toEqual([ + 'relationships', + '--file', + 'src/auth/auth.service.ts', + '--direction', + 'incoming', + '--json' + ]); + expect(response.content[0].text.indexOf('"results"')).toBeLessThan( + response.content[0].text.indexOf('"nextHops"') + ); }); it('does not recommend an unrelated golden example for a different source result', async () => { @@ -363,7 +374,35 @@ describe('search_codebase compact/full mode', () => { }); const payload = parseSearchResponse(response.content[0].text); expect(payload.bestExample).toBeUndefined(); - expect(payload.nextHops?.some((hop) => hop.tool === 'read_file')).toBe(false); + expect(payload.nextHops).toBeUndefined(); + }); + + it('offers outgoing traversal only for a result with indexed imports', async () => { + searchMocks.search.mockResolvedValueOnce([ + makeResult({ filePath: path.join(tempRoot!, 'src/app/app.module.ts') }) + ]); + const { server } = await import('../src/index.js'); + const handler = ( + server as { + _requestHandlers?: Map< + string, + (request: unknown) => Promise<{ content: Array<{ type: string; text: string }> }> + >; + } + )._requestHandlers?.get('tools/call'); + if (!handler) throw new Error('Expected tools/call handler'); + const response = await handler({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name: 'search_codebase', arguments: { query: 'auth service' } } + }); + const payload = parseSearchResponse(response.content[0].text); + expect(payload.nextHops?.[0].args).toEqual({ + file: 'src/app/app.module.ts', + direction: 'outgoing' + }); + expect(payload.nextHops?.[0].why).toContain('not runtime calls'); }); it('omits stale pattern examples from summaries, advice, and evidence', async () => { @@ -461,9 +500,9 @@ describe('search_codebase compact/full mode', () => { it('suppresses grounded pattern advice when search quality requires abstention', async () => { searchMocks.search.mockResolvedValueOnce([ - makeResult({ score: 0.2 }), - makeResult({ filePath: 'src/auth/auth.service2.ts', score: 0.19 }), - makeResult({ filePath: 'src/auth/auth.service3.ts', score: 0.18 }) + makeResult({ filePath: path.join(tempRoot!, 'src/auth/auth.service.ts'), score: 0.2 }), + makeResult({ filePath: path.join(tempRoot!, 'src/auth/auth.service2.ts'), score: 0.19 }), + makeResult({ filePath: path.join(tempRoot!, 'src/auth/auth.service3.ts'), score: 0.18 }) ]); const { server } = await import('../src/index.js'); @@ -490,6 +529,9 @@ describe('search_codebase compact/full mode', () => { expect(payload.searchQuality?.status).toBe('low_confidence'); expect(payload.preflight?.abstain).toBe(true); expect(payload.preflight?.patterns).toBeUndefined(); + expect(payload.nextHops).toBeUndefined(); + expect(payload.searchQuality.hint).toContain('Low confidence'); + expect(payload.searchQuality.hint).toContain('not exhaustive'); }); it('compact mode serializes symbol intelligence fields from chunk metadata', async () => { @@ -529,7 +571,7 @@ describe('search_codebase compact/full mode', () => { expect(payload.results[0].symbolKind).toBe('class'); expect(payload.results[0].scope).toBe('AuthModule.AuthService'); expect(payload.results[0].signaturePreview).toBe( - 'export class AuthService {\n getToken() {\n return tokenStore.read();' + 'export class AuthService {\n getToken() {\n return tokenStore.read();\n }\n}\nconst ignored = true;' ); }); @@ -586,7 +628,7 @@ describe('search_codebase compact/full mode', () => { const preview = payload.results[0]?.signaturePreview; expect(preview).toContain(marker); - expect((preview ?? '').split('\n').length).toBeLessThanOrEqual(3); + expect((preview ?? '').split('\n').length).toBeLessThanOrEqual(7); }); it('keeps compact preview lines contiguous around the strongest source match', async () => { @@ -628,12 +670,118 @@ describe('search_codebase compact/full mode', () => { expect(previewLines).toContain('finishImport(saved);'); expect(previewLines.length).toBeGreaterThan(0); - expect(previewLines.length).toBeLessThanOrEqual(3); + expect(previewLines.length).toBeLessThanOrEqual(7); expect(sourceLines.slice(previewStart, previewStart + previewLines.length)).toEqual( previewLines ); }); + it('keeps a condition and its effect with exact source lines in compact evidence', async () => { + const lines = [ + '', + 'function expireSession(expiry) {', + ' const now = Date.now();', + ' if (expiry <= now) {', + ' revokeSession();', + ' return false;', + ' }', + ' return true;', + '}' + ]; + searchMocks.search.mockResolvedValueOnce([ + makeResult({ snippet: lines.join('\r\n'), startLine: 40, endLine: 48 }) + ]); + const { server } = await import('../src/index.js'); + const handler = ( + server as { + _requestHandlers?: Map< + string, + (request: unknown) => Promise<{ content: Array<{ type: string; text: string }> }> + >; + } + )._requestHandlers?.get('tools/call'); + if (!handler) throw new Error('Expected tools/call handler'); + const response = await handler({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name: 'search_codebase', arguments: { query: 'expireSession expiry' } } + }); + const payload = parseSearchResponse(response.content[0].text); + const result = payload.results[0]; + expect(result.signaturePreview).toContain('if (expiry <= now) {'); + expect(result.signaturePreview).toContain('revokeSession();'); + expect(result.signaturePreview).toContain('return false;'); + expect(result.previewRange).toEqual({ startLine: 41, endLine: 47 }); + expect(result.signaturePreview).toBe(lines.slice(1, 8).join('\n')); + expect(result.readRange).toEqual({ startLine: 40, endLine: 48 }); + const emittedPreview = response.content[0].text.match( + /"signaturePreview"\s*:\s*"(?:\\.|[^"\\])*"/ + )?.[0]; + expect(emittedPreview).toBeDefined(); + expect(Buffer.byteLength(emittedPreview ?? '', 'utf8')).toBeLessThanOrEqual(480); + expect(payload.searchQuality.tokenEstimate).toBe( + Math.ceil(response.content[0].text.length / 4) + ); + }); + + it.each([ + { snippet: 'function selected() {\n return first();\n}', endLine: 35 }, + { snippet: undefined, endLine: 35 }, + { snippet: '界'.repeat(200), endLine: 1 } + ])('directs source follow-through when compact evidence omits source: %j', async (source) => { + searchMocks.search.mockResolvedValueOnce([ + makeResult({ ...source, startLine: 1, filePath: path.join(tempRoot!, 'src/selected.ts') }) + ]); + const { server } = await import('../src/index.js'); + const handler = ( + server as { + _requestHandlers?: Map< + string, + (request: unknown) => Promise<{ content: Array<{ type: string; text: string }> }> + >; + } + )._requestHandlers?.get('tools/call'); + if (!handler) throw new Error('Expected tools/call handler'); + const response = await handler({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name: 'search_codebase', arguments: { query: 'selected' } } + }); + const payload = parseSearchResponse(response.content[0].text); + expect(payload.results[0].readRange).toEqual({ startLine: 1, endLine: source.endLine }); + expect(payload.searchQuality.hint).toContain('readRange'); + expect(payload.searchQuality.hint).toContain('not exhaustive'); + expect(payload.searchQuality.hint).toContain('behavior'); + }); + + it('does not present complete excerpts as exhaustive repository evidence', async () => { + searchMocks.search.mockResolvedValueOnce([ + makeResult({ snippet: 'function selected() {}', startLine: 1, endLine: 1 }) + ]); + const { server } = await import('../src/index.js'); + const handler = ( + server as { + _requestHandlers?: Map< + string, + (request: unknown) => Promise<{ content: Array<{ type: string; text: string }> }> + >; + } + )._requestHandlers?.get('tools/call'); + if (!handler) throw new Error('Expected tools/call handler'); + const response = await handler({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name: 'search_codebase', arguments: { query: 'selected' } } + }); + const payload = parseSearchResponse(response.content[0].text); + expect(payload.results[0].readRange).toBeUndefined(); + expect(payload.searchQuality.hint).toContain('not exhaustive'); + expect(payload.searchQuality.hint).not.toContain('readRange'); + }); + it('adds an exact tokenEstimate advisory to compact responses', async () => { searchMocks.search.mockResolvedValueOnce([makeResult()]); diff --git a/tests/search-preview-budget.test.ts b/tests/search-preview-budget.test.ts new file mode 100644 index 0000000..aa74910 --- /dev/null +++ b/tests/search-preview-budget.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'vitest'; +import { boundSearchPreview } from '../src/tools/search-payload-budget.js'; + +describe('bounded compact source evidence', () => { + it('retains the condition, cleanup and return as whole contiguous source lines', () => { + const lines = [ + 'def release(item):', + ' now = clock()', + ' if item.deadline < now:', + ' close(item)', + ' remove(item)', + ' return False', + ' return True', + '# next' + ]; + const preview = boundSearchPreview(lines, 2); + expect(preview).toEqual({ text: lines.slice(0, 7).join('\n'), start: 0, end: 7 }); + }); + + it('keeps an interior match and exact offsets instead of joining disconnected lines', () => { + const lines = Array.from({ length: 30 }, (_, i) => `statement_${i}();`); + const preview = boundSearchPreview(lines, 17); + expect(preview).toEqual({ text: lines.slice(15, 22).join('\n'), start: 15, end: 22 }); + }); + + it('bounds serialized UTF-8 bytes including JSON escaping without slicing source lines', () => { + const lines = ['prefix', '"\\'.repeat(80), ' cleanup("你好");', 'tail', '好'.repeat(180)]; + const preview = boundSearchPreview(lines, 2); + expect(preview).toBeDefined(); + if (!preview) throw new Error('Expected cleanup evidence'); + expect(preview.text).toContain(' cleanup("你好");'); + expect(preview.text).toBe(lines.slice(preview.start, preview.end).join('\n')); + const serialized = JSON.stringify( + { results: [{ signaturePreview: preview.text, score: 1 }] }, + null, + 2 + ); + const field = serialized + .split('\n') + .find((line) => line.trimStart().startsWith('"signaturePreview":')); + expect(field).toBeDefined(); + expect(Buffer.byteLength(field ?? '', 'utf8')).toBeLessThanOrEqual(480); + }); + + it('omits an oversized matched line so the caller can supply a read range', () => { + expect(boundSearchPreview(['before', '界'.repeat(200), 'after'], 1)).toBeUndefined(); + }); + + it.each([[], [''], [' ']])('omits empty evidence %j', (...lines) => { + expect(boundSearchPreview(lines, 0)).toBeUndefined(); + }); +});