Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
fix(map): real --max-dirs escape hatch + fully deterministic hub ordering
Shrish Dwivedi808e70465d83
diff --git a/src/cli.ts b/src/cli.tsindex 9e4041a3..4f320a95 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -308,8 +308,9 @@ program"Token-budgeted repo orientation — directory clusters, per-directory hubs, and global hotspots from the wiring graph ($0, no LLM)",).argument("[dir]", "repository root", ".")+ .option("--max-dirs <n>", "max directory entries shown, rest counted into dropped (default 16)").option("--json", "output as JSON")- .action(async (dir: string, opts: { json?: boolean }) => {+ .action(async (dir: string, opts: { json?: boolean; maxDirs?: string }) => {const { buildRepoMap, formatRepoMap } = await import("./graph/map.js");const root = resolve(dir);const globalOpts = program.opts<{ dir?: string }>();@@ -320,7 +321,17 @@ programprocess.exit(1);return;}- const map = buildRepoMap(graph);+ let maxDirs: number | undefined;+ if (opts.maxDirs !== undefined) {+ const n = parseInt(opts.maxDirs, 10);+ if (!Number.isFinite(n) || n <= 0) {+ console.error(`✗ --max-dirs must be a positive integer, got "${opts.maxDirs}"`);+ process.exit(1);+ return;+ }+ maxDirs = n;+ }+ const map = buildRepoMap(graph, { maxDirs });if (opts.json) {console.log(JSON.stringify(map, null, 2));return;diff --git a/src/graph/map.ts b/src/graph/map.tsindex cb844a5a..eb579566 100644--- a/src/graph/map.ts+++ b/src/graph/map.ts@@ -42,7 +42,7 @@ export interface RepoMap {totals: { files: number; symbols: number; edges: number; languages: string[] };/** Sorted by symbol count desc (ties by path asc), capped at `maxDirs`. */dirs: DirEntry[];- /** Global top hubs by inDegree, ties by name asc. */+ /** Global top hubs by inDegree, ties by name asc then path asc. */hotspots: Hub[];/** Directory groups beyond the `maxDirs` cap — never silently dropped. */dropped: number;@@ -84,14 +84,14 @@ function computeInDegree(graph: GraphV1): Map<string, number> {return deg;}-/** Top `cap` nodes by inDegree (ties broken by name asc for determinism),- * dropping anything with zero inbound edges — a hub with no callers isn't a- * hub. */+/** Top `cap` nodes by inDegree (ties broken by name asc, then path asc, for+ * full determinism regardless of the input nodes' array order), dropping+ * anything with zero inbound edges — a hub with no callers isn't a hub. */function topHubs(nodes: NodeV1[], inDegree: Map<string, number>, cap: number): Hub[] {return nodes.map((n) => ({ name: n.name, kind: n.kind, path: n.path, span: n.span, inDegree: inDegree.get(n.id) ?? 0 })).filter((h) => h.inDegree > 0)- .sort((a, b) => b.inDegree - a.inDegree || a.name.localeCompare(b.name))+ .sort((a, b) => b.inDegree - a.inDegree || a.name.localeCompare(b.name) || a.path.localeCompare(b.path)).slice(0, cap);}@@ -214,7 +214,7 @@ export function formatRepoMap(map: RepoMap): string {const lines: string[] = [header, ""];for (const d of map.dirs) lines.push(formatDirLine(d));if (map.dropped > 0) {- lines.push(`… +${map.dropped} more director${map.dropped === 1 ? "y" : "ies"} not shown (raise --max-dirs or use --json)`);+ lines.push(`… +${map.dropped} more director${map.dropped === 1 ? "y" : "ies"} not shown (raise max-dirs to see more)`);}lines.push("");lines.push(`hotspots: ${map.hotspots.map(formatHotspot).join(" ")}`);diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex 0bb2ff98..91a124e1 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -106,7 +106,12 @@ export const TOOLS: ToolDef[] = [name: 'graft_map',description:'Token-budgeted repo orientation — directory clusters, per-directory hubs, and global hotspots computed purely from the wiring graph ($0, no LLM). Use this to get oriented in an unfamiliar repo before diving into files.',- inputSchema: { type: 'object', properties: {} },+ inputSchema: {+ type: 'object',+ properties: {+ max_dirs: { type: 'number', description: 'max directory entries shown, rest counted into dropped (default 16)' },+ },+ },},];@@ -202,7 +207,8 @@ export function callTool(case 'graft_map': {const w = loadGraphCached(contextDirFor(root, dirOverride));if (!w) return { text: NO_GRAPH, isError: true };- const map = buildRepoMap(w);+ const maxDirs = typeof args.max_dirs === 'number' && Number.isFinite(args.max_dirs) && args.max_dirs > 0 ? args.max_dirs : undefined;+ const map = buildRepoMap(w, { maxDirs });return { text: formatRepoMap(map), isError: false };}default:diff --git a/test/graph-map.test.ts b/test/graph-map.test.tsindex f9447b14..e1524eee 100644--- a/test/graph-map.test.ts+++ b/test/graph-map.test.ts@@ -183,6 +183,36 @@ test("buildRepoMap: hotspots rank globally by inDegree, ties broken by name asc,assert.equal(map.hotspots[1].name, "alpha", "remaining tie broken by name asc");});+test("buildRepoMap: hub/hotspot order is identical regardless of node array order (final path-asc tie-break)", () => {+ // Two symbols, same name, same inDegree, different paths — a same-name/+ // same-inDegree tie that `name asc` alone can't resolve deterministically;+ // without a final `path asc` tie-break the reported order depends on+ // whichever happened to come first in `graph.nodes`.+ const fileA = fileNode("alpha/a.ts");+ const fileB = fileNode("beta/b.ts");+ const symInAlpha = symNode("alpha/a.ts", "dup");+ const symInBeta = symNode("beta/b.ts", "dup");+ const callerFile = fileNode("callers/c.ts");+ const edges = [+ edge("callers/c.ts#caller1", "alpha/a.ts#dup"),+ edge("callers/c.ts#caller2", "beta/b.ts#dup"),+ ];++ const forward = buildRepoMap(+ graphOf([fileA, symInAlpha, fileB, symInBeta, callerFile], edges),+ );+ const reversed = buildRepoMap(+ graphOf([callerFile, fileB, symInBeta, fileA, symInAlpha], edges),+ );++ assert.deepEqual(forward.hotspots, reversed.hotspots, "hotspot order must not depend on node array order");+ assert.deepEqual(+ forward.hotspots.map((h) => h.path),+ ["alpha/a.ts", "beta/b.ts"],+ "tied name+inDegree hotspots break the tie by path asc",+ );+});+test("buildRepoMap: symbols with zero inbound edges are never listed as hubs or hotspots", () => {const nodes = [fileNode("lib/x.ts"), symNode("lib/x.ts", "lonely"), fileNode("other/y.ts")];const map = buildRepoMap(graphOf(nodes, []));@@ -241,12 +271,32 @@ test("formatRepoMap: stays under the 6000-char budget and surfaces hub names", (}});-test("formatRepoMap: notes dropped directories beyond the cap", () => {+test("formatRepoMap: notes dropped directories beyond the cap, pointing only at options that actually exist", () => {const nodes: NodeV1[] = [];for (const dir of ["a", "b", "c", "d"]) nodes.push(fileNode(`${dir}/x.ts`));const map = buildRepoMap(graphOf(nodes, []), { maxDirs: 1 });const text = formatRepoMap(map);assert.match(text, /\+3 more directories not shown/);+ // Regression: the old note said "raise --max-dirs or use --json" — no+ // --max-dirs flag existed, and --json is capped identically (both go+ // through the same `maxDirs`-sliced RepoMap), so dropped dirs were+ // unreachable either way. The reworded note only promises a real escape+ // hatch (the now-real `maxDirs` option) and drops the dead --json mention.+ assert.match(text, /max-dirs/);+ assert.doesNotMatch(text, /--json/);+});++test("buildRepoMap: a raised maxDirs opt actually surfaces previously-dropped dirs (the real --max-dirs escape hatch)", () => {+ const nodes: NodeV1[] = [];+ for (const dir of ["a", "b", "c", "d", "e"]) nodes.push(fileNode(`${dir}/x.ts`));++ const capped = buildRepoMap(graphOf(nodes, []), { maxDirs: 2 });+ assert.equal(capped.dirs.length, 2);+ assert.equal(capped.dropped, 3);++ const raised = buildRepoMap(graphOf(nodes, []), { maxDirs: 10 });+ assert.equal(raised.dirs.length, 5, "raising maxDirs surfaces every dir");+ assert.equal(raised.dropped, 0);});test("formatRepoMap: an empty repo map still renders a well-formed header", () => {diff --git a/test/mcp-tools.test.ts b/test/mcp-tools.test.tsindex 42e82a6b..05f472a4 100644--- a/test/mcp-tools.test.ts+++ b/test/mcp-tools.test.ts@@ -59,6 +59,19 @@ function fileScopeRepo(): string {return d;}+/** Five top-level dirs, one file each — enough groups that a small `max_dirs`+ * actually drops some, so the `graft_map` `max_dirs` arg has something to+ * prove it's wired through to `buildRepoMap`. */+function multiDirRepo(): string {+ const d = mkdtempSync(join(tmpdir(), 'graft-mcptools-multidir-'));+ for (const dir of ['aaa', 'bbb', 'ccc', 'ddd', 'eee']) {+ mkdirSync(join(d, dir), { recursive: true });+ writeFileSync(join(d, dir, 'x.ts'), `export function ${dir}Fn(): number {\n return 1;\n}\n`);+ }+ execFileSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', 'build', d], { stdio: 'pipe' });+ return d;+}+test('TOOLS lists all seven tools with schemas', () => {assert.deepEqual(TOOLS.map((t) => t.name), ['graft_ask',@@ -233,6 +246,18 @@ test('graft_map: unbuilt repo is a soft isError with the no-graph message', () =assert.match(r.text, /graft build/);});+test('graft_map: max_dirs arg is honored — the MCP escape hatch for dropped dirs', () => {+ const d = multiDirRepo();++ const capped = callTool(d, 'graft_map', { max_dirs: 1 });+ assert.equal(capped.isError, false);+ assert.match(capped.text, /\+4 more directories not shown/);++ const raised = callTool(d, 'graft_map', { max_dirs: 10 });+ assert.equal(raised.isError, false);+ assert.doesNotMatch(raised.text, /more directories? not shown/);+});+test('callTool honors a dirOverride for a graph built in a non-default dir', () => {const { repo, graphDir } = customDirRepo();