Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

feat(graph): graft map — token-budgeted repo orientation from the wiring graph

Shrish Dwivediea5e7097751b
diff --git a/src/cli.ts b/src/cli.ts
index 1bd4ac4b..9e4041a3 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -9,6 +9,7 @@
* mcp serve the graph over MCP (stdio) for coding agents.
* callers / callees / impact precise graph traversal for a symbol ($0, no LLM).
* grep regex search over indexed files, grouped by enclosing symbol, ranked by coupling ($0, no LLM).
+ * map token-budgeted repo orientation — dir clusters, hubs, hotspots ($0, no LLM).
* init set up the Claude Code integration (.claude/ statusline + hooks) in this repo.
*
* Git is the sync: commit graft/ and anyone who clones the repo has the
@@ -301,6 +302,32 @@ program
},
);
+program
+ .command("map")
+ .description(
+ "Token-budgeted repo orientation — directory clusters, per-directory hubs, and global hotspots from the wiring graph ($0, no LLM)",
+ )
+ .argument("[dir]", "repository root", ".")
+ .option("--json", "output as JSON")
+ .action(async (dir: string, opts: { json?: boolean }) => {
+ const { buildRepoMap, formatRepoMap } = await import("./graph/map.js");
+ const root = resolve(dir);
+ const globalOpts = program.opts<{ dir?: string }>();
+ const contextDir = contextDirFor(root, globalOpts.dir);
+ const graph = loadGraphCached(contextDir);
+ if (!graph) {
+ console.error("✗ no graph — run graft build first");
+ process.exit(1);
+ return;
+ }
+ const map = buildRepoMap(graph);
+ if (opts.json) {
+ console.log(JSON.stringify(map, null, 2));
+ return;
+ }
+ process.stdout.write(formatRepoMap(map));
+ });
+
program
.command("init")
.description("Wire Graft into the AI coding agents used with this repo (instruction files; full hooks + statusline for Claude Code)")
diff --git a/src/graph/map.ts b/src/graph/map.ts
new file mode 100644
index 00000000..cb844a5a
--- /dev/null
+++ b/src/graph/map.ts
@@ -0,0 +1,223 @@
+/**
+ * `graft map` core: a deterministic, token-budgeted repo orientation —
+ * directory clusters, per-directory hubs, and global hotspots — computed
+ * purely from the wiring graph (no LLM, no I/O beyond the already-loaded
+ * `GraphV1`).
+ *
+ * Grouping is by first path segment (`src/cache.ts` → `src`), so a coding
+ * agent gets the same top-level shape a human sees in a file tree. When one
+ * segment swallows most of the repo (a flat `src/` with everything under
+ * it), that single group would be useless as an orientation aid, so it gets
+ * one refinement pass: split one level deeper (`src` → `src/ask`,
+ * `src/graph`, …). Hubs and hotspots rank by incoming `WALK_RELATIONS`
+ * edges (shared with `graphrank.ts`/`grep.ts`, so "important" means the same
+ * thing everywhere in graft) — never by lines of code or heuristics that
+ * drift from the actual wiring.
+ *
+ * Pure and synchronous: same fixture-testable shape as `grep.ts` — no CLI or
+ * MCP concerns live here. `cli.ts` and `mcp/tools.ts` both call
+ * `buildRepoMap` + `formatRepoMap` directly.
+ */
+import type { GraphV1, NodeV1 } from "./types.js";
+import { languageOf } from "./extract.js";
+import { WALK_RELATIONS } from "./relations.js";
+
+export interface Hub {
+ name: string;
+ kind: string;
+ path: string;
+ span: string;
+ inDegree: number;
+}
+
+export interface DirEntry {
+ path: string;
+ files: number;
+ symbols: number;
+ languages: string[];
+ hubs: Hub[];
+}
+
+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. */
+ hotspots: Hub[];
+ /** Directory groups beyond the `maxDirs` cap — never silently dropped. */
+ dropped: number;
+}
+
+export interface BuildRepoMapOptions {
+ /** Max directory entries kept (the rest are counted into `dropped`). Default 16. */
+ maxDirs?: number;
+ /** Max hubs listed per directory. Default 3. */
+ hubsPerDir?: number;
+ /** Max global hotspots. Default 12. */
+ hotspots?: number;
+}
+
+const DEFAULT_MAX_DIRS = 16;
+const DEFAULT_HUBS_PER_DIR = 3;
+const DEFAULT_HOTSPOTS = 12;
+/** A single group must not exceed this share of all file nodes, or it's
+ * refined one path-segment deeper — see the module doc. */
+const SPLIT_THRESHOLD = 0.6;
+
+/** First `depth` path segments, joined back with `/`. Files with fewer
+ * segments than `depth` (e.g. a root-level file at depth 2) just use every
+ * segment they have — there's nothing deeper to split into. */
+function dirKey(path: string, depth: number): string {
+ const segments = path.split("/");
+ return segments.slice(0, Math.min(depth, segments.length)).join("/");
+}
+
+/** Incoming WALK_RELATIONS edge count per target id — the same "coupling"
+ * metric `grep.ts` uses, so a hub in `graft map` means the same thing as a
+ * high-inDegree group in `graft grep`. */
+function computeInDegree(graph: GraphV1): Map<string, number> {
+ const deg = new Map<string, number>();
+ for (const e of graph.edges) {
+ if (!WALK_RELATIONS.has(e.relation)) continue;
+ deg.set(e.target, (deg.get(e.target) ?? 0) + 1);
+ }
+ 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. */
+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))
+ .slice(0, cap);
+}
+
+function sortedLanguages(paths: string[]): string[] {
+ const set = new Set<string>();
+ for (const p of paths) {
+ const lang = languageOf(p);
+ if (lang) set.add(lang);
+ }
+ return [...set].sort();
+}
+
+/**
+ * Build the repo map from an already-loaded `GraphV1`. Deterministic: same
+ * graph in → byte-identical `RepoMap` out (modulo insertion order, which is
+ * never observed — everything meaningful is sorted).
+ */
+export function buildRepoMap(graph: GraphV1, opts: BuildRepoMapOptions = {}): RepoMap {
+ const maxDirs = opts.maxDirs ?? DEFAULT_MAX_DIRS;
+ const hubsPerDir = opts.hubsPerDir ?? DEFAULT_HUBS_PER_DIR;
+ const hotspotsN = opts.hotspots ?? DEFAULT_HOTSPOTS;
+
+ const fileNodes = graph.nodes.filter((n) => n.kind === "file");
+ const totalFiles = fileNodes.length;
+
+ // Pass 1: depth-1 file counts, to find (at most one) group over the
+ // split threshold — two groups can't both exceed 60% of the same total.
+ const depth1FileCounts = new Map<string, number>();
+ for (const n of fileNodes) {
+ const key = dirKey(n.path, 1);
+ depth1FileCounts.set(key, (depth1FileCounts.get(key) ?? 0) + 1);
+ }
+ let splitSegment: string | null = null;
+ if (totalFiles > 0) {
+ for (const [seg, count] of depth1FileCounts) {
+ if (count / totalFiles > SPLIT_THRESHOLD) {
+ splitSegment = seg;
+ break;
+ }
+ }
+ }
+
+ const depthFor = (path: string): number => (splitSegment !== null && dirKey(path, 1) === splitSegment ? 2 : 1);
+
+ // Pass 2: assign every node (file and symbol alike) to its group.
+ const groups = new Map<string, { files: NodeV1[]; symbols: NodeV1[] }>();
+ for (const n of graph.nodes) {
+ const key = dirKey(n.path, depthFor(n.path));
+ let g = groups.get(key);
+ if (!g) {
+ g = { files: [], symbols: [] };
+ groups.set(key, g);
+ }
+ if (n.kind === "file") g.files.push(n);
+ else g.symbols.push(n);
+ }
+
+ const inDegree = computeInDegree(graph);
+
+ const dirEntries: DirEntry[] = [...groups.entries()].map(([path, g]) => ({
+ path,
+ files: g.files.length,
+ symbols: g.symbols.length,
+ languages: sortedLanguages(g.files.map((f) => f.path)),
+ hubs: topHubs(g.symbols, inDegree, hubsPerDir),
+ }));
+
+ dirEntries.sort((a, b) => b.symbols - a.symbols || a.path.localeCompare(b.path));
+ const dropped = Math.max(0, dirEntries.length - maxDirs);
+ const dirs = dirEntries.slice(0, maxDirs);
+
+ const allSymbols = graph.nodes.filter((n) => n.kind !== "file");
+ const hotspots = topHubs(allSymbols, inDegree, hotspotsN);
+
+ return {
+ totals: {
+ files: totalFiles,
+ symbols: allSymbols.length,
+ edges: graph.edges.length,
+ languages: sortedLanguages(fileNodes.map((f) => f.path)),
+ },
+ dirs,
+ hotspots,
+ dropped,
+ };
+}
+
+const DIR_COL_WIDTH = 20;
+
+function basenameOf(path: string): string {
+ const i = path.lastIndexOf("/");
+ return i >= 0 ? path.slice(i + 1) : path;
+}
+
+function formatDirHub(h: Hub): string {
+ return `${h.name} (${basenameOf(h.path)}, ${h.inDegree}←)`;
+}
+
+function formatDirLine(d: DirEntry): string {
+ const label = `${d.path}/`.padEnd(DIR_COL_WIDTH);
+ const counts = `${d.files} files · ${d.symbols} symbols`;
+ const hubs = d.hubs.length ? ` hubs: ${d.hubs.map(formatDirHub).join(", ")}` : "";
+ return `${label}${counts}${hubs}`;
+}
+
+function formatHotspot(h: Hub): string {
+ return `${h.name} · ${h.kind} · ${h.path}:${h.span} · ${h.inDegree}←`;
+}
+
+/**
+ * Render a `RepoMap` as the human report. Deterministic (same map in → same
+ * string out) and targets <= 6000 chars for a typical repo (the `maxDirs`/
+ * `hubsPerDir`/`hotspots` caps in `buildRepoMap` are what keep it bounded on
+ * very large graphs).
+ */
+export function formatRepoMap(map: RepoMap): string {
+ const { totals } = map;
+ const header = `repo map — ${totals.files} files · ${totals.symbols} symbols · ${totals.edges} edges · ${totals.languages.join(", ")}`;
+
+ 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("");
+ lines.push(`hotspots: ${map.hotspots.map(formatHotspot).join(" ")}`);
+
+ return lines.join("\n") + "\n";
+}
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index b2bbc8f1..0bb2ff98 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -12,6 +12,7 @@ import { resolveSymbol, callersOf, calleesOf, impactOf, impactOfFile, type EdgeH
import { headerOf, hitLine, looseNoteFor, type TraverseKind } from '../graph/traverse-cli.js';
import { grepGraph } from '../search/grep.js';
import { formatGrepResult, zeroHitNote } from '../search/grep-cli.js';
+import { buildRepoMap, formatRepoMap } from '../graph/map.js';
import type { NodeV1 } from '../graph/types.js';
export interface ToolDef {
@@ -101,6 +102,12 @@ export const TOOLS: ToolDef[] = [
required: ['pattern'],
},
},
+ {
+ 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: {} },
+ },
];
/** Render every resolved match's header + edge report (or the loud zero-edge
@@ -192,6 +199,12 @@ export function callTool(
if (result.totalHits === 0) return { text: zeroHitNote(result), isError: false };
return { text: formatGrepResult(result), isError: false };
}
+ case 'graft_map': {
+ const w = loadGraphCached(contextDirFor(root, dirOverride));
+ if (!w) return { text: NO_GRAPH, isError: true };
+ const map = buildRepoMap(w);
+ return { text: formatRepoMap(map), isError: false };
+ }
default:
return { text: `unknown tool: ${name}`, isError: true };
}
diff --git a/test/graph-map.test.ts b/test/graph-map.test.ts
new file mode 100644
index 00000000..f9447b14
--- /dev/null
+++ b/test/graph-map.test.ts
@@ -0,0 +1,257 @@
+/**
+ * Tests for `graft map`'s pure core: {@link buildRepoMap} + {@link formatRepoMap}.
+ *
+ * All fixtures are hand-built `GraphV1` graphs (no real repo, no `buildGraph`)
+ * — same `nodeStub`/`graphOf` pattern as test/graphrank.test.ts, extended
+ * with a `path`/`kind`/`span` so directory grouping and hub ranking have
+ * something to chew on.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { buildRepoMap, formatRepoMap } from "../src/graph/map.js";
+import type { GraphV1, NodeV1, EdgeV1, Kind, Relation } from "../src/graph/types.js";
+
+let counter = 0;
+
+function fileNode(path: string): NodeV1 {
+ return {
+ id: path,
+ name: path.slice(path.lastIndexOf("/") + 1),
+ kind: "file",
+ path,
+ span: "L1-L1",
+ signature: null,
+ exported: true,
+ origin: "ast",
+ body_hash: `h${counter++}`,
+ summary_state: "pending",
+ summary: null,
+ crux: null,
+ };
+}
+
+function symNode(path: string, name: string, opts: { kind?: Kind; span?: string } = {}): NodeV1 {
+ const id = `${path}#${name}`;
+ return {
+ id,
+ name,
+ kind: opts.kind ?? "function",
+ path,
+ span: opts.span ?? "L1-L10",
+ signature: `${name}()`,
+ exported: true,
+ origin: "ast",
+ body_hash: `h${counter++}`,
+ summary_state: "pending",
+ summary: null,
+ crux: null,
+ };
+}
+
+function edge(source: string, target: string, relation: Relation = "calls"): EdgeV1 {
+ return { source, target, relation, confidence: "extracted" };
+}
+
+function graphOf(nodes: NodeV1[], edges: EdgeV1[]): GraphV1 {
+ return {
+ meta: { version: 1, nodeCount: nodes.length, edgeCount: edges.length, languages: [] },
+ nodes,
+ edges,
+ };
+}
+
+// ── totals ────────────────────────────────────────────────────────────────
+
+test("buildRepoMap: totals count files, symbols, edges, and languages across the whole graph", () => {
+ const nodes = [
+ fileNode("src/a.ts"),
+ symNode("src/a.ts", "fnA"),
+ fileNode("docs/readme.py"), // deliberately mixed languages
+ symNode("docs/readme.py", "fnB"),
+ ];
+ const edges = [edge("src/a.ts#fnA", "docs/readme.py#fnB")];
+ const map = buildRepoMap(graphOf(nodes, edges));
+
+ assert.equal(map.totals.files, 2);
+ assert.equal(map.totals.symbols, 2);
+ assert.equal(map.totals.edges, 1);
+ assert.deepEqual(map.totals.languages, ["python", "typescript"]);
+});
+
+test("buildRepoMap: dirs are grouped by first path segment and sorted by symbol count desc", () => {
+ const nodes = [
+ fileNode("alpha/a.ts"),
+ symNode("alpha/a.ts", "one"),
+ fileNode("beta/b.ts"),
+ symNode("beta/b.ts", "two"),
+ symNode("beta/b.ts", "three"),
+ ];
+ const map = buildRepoMap(graphOf(nodes, []));
+
+ assert.deepEqual(map.dirs.map((d) => d.path), ["beta", "alpha"], "beta has more symbols, sorts first");
+ const beta = map.dirs.find((d) => d.path === "beta")!;
+ assert.equal(beta.files, 1);
+ assert.equal(beta.symbols, 2);
+});
+
+// ── >60% split refinement ────────────────────────────────────────────────
+
+test("buildRepoMap: a segment holding >60% of file nodes is split one level deeper", () => {
+ // 7 of 10 files under src/ (70% > 60%) → src/ask, src/graph split out.
+ // tests/ (3 files, 30%) stays a single depth-1 group.
+ const nodes = [
+ fileNode("src/ask/a1.ts"),
+ fileNode("src/ask/a2.ts"),
+ fileNode("src/ask/a3.ts"),
+ fileNode("src/ask/a4.ts"),
+ fileNode("src/graph/g1.ts"),
+ fileNode("src/graph/g2.ts"),
+ fileNode("src/graph/g3.ts"),
+ fileNode("tests/t1.ts"),
+ fileNode("tests/t2.ts"),
+ fileNode("tests/t3.ts"),
+ ];
+ const map = buildRepoMap(graphOf(nodes, []));
+ const paths = map.dirs.map((d) => d.path);
+
+ assert.ok(!paths.includes("src"), "the over-threshold group itself must not survive unsplit");
+ assert.ok(paths.includes("src/ask"), "split refines src into its sub-segments");
+ assert.ok(paths.includes("src/graph"));
+ assert.ok(paths.includes("tests"), "a group under threshold is untouched");
+
+ const ask = map.dirs.find((d) => d.path === "src/ask")!;
+ assert.equal(ask.files, 4);
+ const graphDir = map.dirs.find((d) => d.path === "src/graph")!;
+ assert.equal(graphDir.files, 3);
+});
+
+test("buildRepoMap: a segment at or below 60% is not split", () => {
+ const nodes = [
+ fileNode("src/a.ts"),
+ fileNode("src/b.ts"),
+ fileNode("src/c.ts"), // src: 3/5 = 60%, not > 60%
+ fileNode("tests/t1.ts"),
+ fileNode("tests/t2.ts"),
+ ];
+ const map = buildRepoMap(graphOf(nodes, []));
+ assert.ok(map.dirs.some((d) => d.path === "src"), "60% exactly must not trigger the split");
+});
+
+// ── hub ordering ─────────────────────────────────────────────────────────
+
+test("buildRepoMap: hubs within a dir are ranked by inDegree desc, ties broken by name asc", () => {
+ const nodes = [
+ fileNode("lib/x.ts"),
+ symNode("lib/x.ts", "zebra", { kind: "function" }),
+ symNode("lib/x.ts", "apple", { kind: "function" }),
+ symNode("lib/x.ts", "mango", { kind: "function" }),
+ // An unrelated dir so "lib" doesn't trivially hold 100% of file nodes
+ // and trip the >60% split refinement this test isn't exercising.
+ fileNode("other/y.ts"),
+ ];
+ const edges = [
+ // zebra: 2 inbound; apple: 2 inbound (tie, name asc must put apple first); mango: 1 inbound.
+ edge("lib/x.ts#caller1", "lib/x.ts#zebra"),
+ edge("lib/x.ts#caller2", "lib/x.ts#zebra"),
+ edge("lib/x.ts#caller1", "lib/x.ts#apple"),
+ edge("lib/x.ts#caller2", "lib/x.ts#apple"),
+ edge("lib/x.ts#caller1", "lib/x.ts#mango"),
+ ];
+ const map = buildRepoMap(graphOf(nodes, edges));
+ const lib = map.dirs.find((d) => d.path === "lib")!;
+
+ assert.deepEqual(
+ lib.hubs.map((h) => h.name),
+ ["apple", "zebra", "mango"],
+ "tied inDegree (apple, zebra) breaks by name asc; mango (lower inDegree) last",
+ );
+ assert.equal(lib.hubs[0].inDegree, 2);
+});
+
+test("buildRepoMap: hotspots rank globally by inDegree, ties broken by name asc, capped by opts.hotspots", () => {
+ const nodes = [fileNode("a/x.ts"), fileNode("b/y.ts")];
+ const names = ["zeta", "beta", "gamma", "alpha"];
+ for (const n of names) nodes.push(symNode("a/x.ts", n));
+ const edges: EdgeV1[] = [];
+ // Every symbol gets exactly 1 inbound edge (tie) except "beta" which gets 2.
+ for (const n of names) edges.push(edge("b/y.ts#caller", `a/x.ts#${n}`));
+ edges.push(edge("b/y.ts#caller2", "a/x.ts#beta"));
+
+ const map = buildRepoMap(graphOf(nodes, edges), { hotspots: 2 });
+ assert.equal(map.hotspots.length, 2, "capped by opts.hotspots");
+ assert.equal(map.hotspots[0].name, "beta", "beta has the highest inDegree");
+ assert.equal(map.hotspots[1].name, "alpha", "remaining tie broken by name 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, []));
+ const lib = map.dirs.find((d) => d.path === "lib")!;
+ assert.equal(lib.hubs.length, 0);
+ assert.equal(map.hotspots.length, 0);
+});
+
+// ── dropped-dirs cap ─────────────────────────────────────────────────────
+
+test("buildRepoMap: dirs beyond maxDirs are capped and counted into dropped", () => {
+ const nodes: NodeV1[] = [];
+ for (const dir of ["a", "b", "c", "d", "e"]) {
+ nodes.push(fileNode(`${dir}/x.ts`));
+ }
+ const map = buildRepoMap(graphOf(nodes, []), { maxDirs: 2 });
+ assert.equal(map.dirs.length, 2);
+ assert.equal(map.dropped, 3);
+});
+
+// ── formatRepoMap ────────────────────────────────────────────────────────
+
+/** 60-node-ish fixture: a handful of dirs, each with several hub-worthy
+ * symbols, enough edges to build up inDegree without exploding sizes. */
+function bigFixture(): GraphV1 {
+ const nodes: NodeV1[] = [];
+ const edges: EdgeV1[] = [];
+ const dirs = ["alpha", "beta", "gamma", "delta"];
+ for (const dir of dirs) {
+ for (let f = 0; f < 3; f++) {
+ const path = `${dir}/file${f}.ts`;
+ nodes.push(fileNode(path));
+ for (let s = 0; s < 4; s++) {
+ const name = `${dir}Sym${f}_${s}`;
+ nodes.push(symNode(path, name));
+ // Give the first symbol in each file a bunch of callers so it's a hub.
+ if (s === 0) {
+ for (let c = 0; c < 5; c++) edges.push(edge(`${dir}/caller${c}.ts#c`, `${path}#${name}`));
+ }
+ }
+ }
+ }
+ return graphOf(nodes, edges);
+}
+
+test("formatRepoMap: stays under the 6000-char budget and surfaces hub names", () => {
+ const map = buildRepoMap(bigFixture());
+ const text = formatRepoMap(map);
+
+ assert.ok(text.length <= 6000, `formatted map is ${text.length} chars, expected <= 6000`);
+ assert.match(text, /^repo map — \d+ files · \d+ symbols · \d+ edges/);
+ for (const d of map.dirs) {
+ for (const h of d.hubs) {
+ assert.ok(text.includes(h.name), `hub name "${h.name}" must appear in the rendered map`);
+ }
+ }
+});
+
+test("formatRepoMap: notes dropped directories beyond the cap", () => {
+ 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/);
+});
+
+test("formatRepoMap: an empty repo map still renders a well-formed header", () => {
+ const map = buildRepoMap(graphOf([], []));
+ const text = formatRepoMap(map);
+ assert.match(text, /^repo map — 0 files · 0 symbols · 0 edges ·\s*$/m);
+ assert.match(text, /^hotspots:\s*$/m);
+});
diff --git a/test/mcp-server.test.ts b/test/mcp-server.test.ts
index 3f439fc3..615d3b18 100644
--- a/test/mcp-server.test.ts
+++ b/test/mcp-server.test.ts
@@ -52,6 +52,7 @@ test('initialize → tools/list → tools/call round-trip', async () => {
'graft_callers',
'graft_callees',
'graft_grep',
+ 'graft_map',
]);
const call = rs.find((r) => r.id === 3);
assert.equal(call.result.isError, true); // unbuilt repo → soft error content
diff --git a/test/mcp-tools.test.ts b/test/mcp-tools.test.ts
index b853bc11..42e82a6b 100644
--- a/test/mcp-tools.test.ts
+++ b/test/mcp-tools.test.ts
@@ -59,7 +59,7 @@ function fileScopeRepo(): string {
return d;
}
-test('TOOLS lists all six tools with schemas', () => {
+test('TOOLS lists all seven tools with schemas', () => {
assert.deepEqual(TOOLS.map((t) => t.name), [
'graft_ask',
'graft_check',
@@ -67,6 +67,7 @@ test('TOOLS lists all six tools with schemas', () => {
'graft_callers',
'graft_callees',
'graft_grep',
+ 'graft_map',
]);
for (const t of TOOLS) {
assert.ok(t.description.length > 0);
@@ -216,6 +217,22 @@ test('graft_grep: missing pattern and unbuilt repo are soft errors', () => {
assert.match(r2.text, /graft build/);
});
+test('graft_map round-trips a repo orientation on the built fixture', () => {
+ const d = builtRepo();
+ const r = callTool(d, 'graft_map', {});
+ assert.equal(r.isError, false);
+ assert.match(r.text, /^repo map — \d+ files · \d+ symbols · \d+ edges/);
+ assert.match(r.text, /src/);
+ assert.match(r.text, /hotspots:/);
+});
+
+test('graft_map: unbuilt repo is a soft isError with the no-graph message', () => {
+ const bare = mkdtempSync(join(tmpdir(), 'graft-mcptools-map-bare-'));
+ const r = callTool(bare, 'graft_map', {});
+ assert.equal(r.isError, true);
+ assert.match(r.text, /graft build/);
+});
+
test('callTool honors a dirOverride for a graph built in a non-default dir', () => {
const { repo, graphDir } = customDirRepo();