Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ CODEBASE_CONTEXT_ASCII=1 node /path/to/codebase-context/dist/index.js patterns
- `refs --symbol <name>` — concrete reference evidence
- `cycles` — circular dependency detection
- `status` — index status/progress
- `relationships --file <path>` — 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`)
Expand All @@ -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 <name>` 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
Expand Down
46 changes: 44 additions & 2 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -42,6 +42,7 @@ const _CLI_COMMANDS = [
'style-guide',
'patterns',
'refs',
'relationships',
'cycles',
'init',
'map'
Expand All @@ -50,7 +51,7 @@ const _CLI_COMMANDS = [
type CliCommand = (typeof _CLI_COMMANDS)[number];

const CLI_COMMAND_SET: ReadonlySet<string> = 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);
}

Expand Down Expand Up @@ -82,6 +83,10 @@ function printUsage(): void {
console.log(' style-guide [--query <q>] [--category <c>] Style guide rules');
console.log(' patterns [--category all|di|state|testing|libraries] Team patterns');
console.log(' refs --symbol <name> [--limit <n>] Symbol references');
console.log(
' relationships --file <path> Verified imports/re-exports (not runtime calls)'
);
console.log(' [--direction outgoing|incoming] [--max-hops 1..3] [--max-nodes 1..100]');
console.log(' cycles [--scope <path>] Circular dependency detection');
console.log(' init [--client <name>] [--yes] Detect and configure coding tools');
console.log(' map [--json] [--pretty] Conventions map (indexes first if needed)');
Expand Down Expand Up @@ -294,6 +299,7 @@ export async function handleCliCommand(argv: string[]): Promise<void> {
| { 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 = {
Expand All @@ -307,6 +313,12 @@ export async function handleCliCommand(argv: string[]): Promise<void> {
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;
Expand Down Expand Up @@ -425,6 +437,36 @@ export async function handleCliCommand(argv: string[]): Promise<void> {
};
break;
}
case 'relationships': {
const usage =
'codebase-context relationships --file <path> [--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 <path>]';
const scope = optionalStringFlag(flags, 'scope', usage);
Expand Down
21 changes: 4 additions & 17 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
Expand All @@ -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');
Expand Down Expand Up @@ -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);
Expand Down
124 changes: 78 additions & 46 deletions src/tools/search-codebase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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([
Expand Down Expand Up @@ -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<string, string>; why: string }> {
const hops: Array<{ tool: string; args?: Record<string, string>; 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);
Expand Down Expand Up @@ -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<SearchResultItem, 'signaturePreview' | 'previewRange' | 'readRange'> {
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) => ({
Expand All @@ -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) {
Expand All @@ -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,
Expand All @@ -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))
})
Expand Down
26 changes: 26 additions & 0 deletions src/tools/search-payload-budget.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
Expand Down
Loading
Loading