Skip to content

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

feat(cli): graft callers / callees / impact commands

Shrish Dwivedi24cdf2d09c0f
diff --git a/src/cli.ts b/src/cli.ts
index 3a363072..a855c6c3 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -7,6 +7,7 @@
* check fail if graft/ has drifted from the code — for CI.
* viz serve the interactive graph viewer.
* mcp serve the graph over MCP (stdio) for coding agents.
+ * callers / callees / impact precise graph traversal for a symbol ($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
@@ -197,6 +198,42 @@ program
startMcpServer(resolve(dir));
});
+function traverseAction(kind: import("./graph/traverse-cli.js").TraverseKind) {
+ return async (symbol: string, dir: string, opts: { in?: string; json?: boolean; depth?: string }) => {
+ const { runTraverseCommand } = await import("./graph/traverse-cli.js");
+ const globalOpts = program.opts<{ dir?: string }>();
+ runTraverseCommand(kind, symbol, dir, { in: opts.in, json: opts.json, depth: opts.depth, globalDir: globalOpts.dir });
+ };
+}
+
+program
+ .command("callers")
+ .description("Who calls/references/imports/implements/extends a symbol ($0, no LLM)")
+ .argument("<symbol>", "bare name, qualified (Class.method), or package-qualified (pkg.Fn)")
+ .argument("[dir]", "repository root", ".")
+ .option("--in <path>", "narrow matches to nodes whose path contains this substring")
+ .option("--json", "output as JSON")
+ .action(traverseAction("callers"));
+
+program
+ .command("callees")
+ .description("What a symbol calls/references/imports/implements/extends ($0, no LLM)")
+ .argument("<symbol>", "bare name, qualified (Class.method), or package-qualified (pkg.Fn)")
+ .argument("[dir]", "repository root", ".")
+ .option("--in <path>", "narrow matches to nodes whose path contains this substring")
+ .option("--json", "output as JSON")
+ .action(traverseAction("callees"));
+
+program
+ .command("impact")
+ .description("BFS over incoming edges — who breaks if this symbol changes ($0, no LLM)")
+ .argument("<symbol>", "bare name, qualified (Class.method), or package-qualified (pkg.Fn)")
+ .argument("[dir]", "repository root", ".")
+ .option("-d, --depth <n>", "max BFS depth (default 2)")
+ .option("--in <path>", "narrow matches to nodes whose path contains this substring")
+ .option("--json", "output as JSON")
+ .action(traverseAction("impact"));
+
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/traverse-cli.ts b/src/graph/traverse-cli.ts
new file mode 100644
index 00000000..e87c4b76
--- /dev/null
+++ b/src/graph/traverse-cli.ts
@@ -0,0 +1,139 @@
+/**
+ * CLI wiring for `graft callers` / `callees` / `impact`.
+ *
+ * The three commands are one implementation with a direction flag: they all
+ * resolve a symbol via `resolveSymbol`, walk edges via `callersOf` /
+ * `calleesOf` / `impactOf`, and share the same resolve-or-die flow, human
+ * formatter, and --json shape. Kept out of cli.ts so that file stays thin
+ * (argument wiring only) and this logic stays unit-testable without shelling
+ * out to the CLI on every case.
+ */
+import { resolve } from "node:path";
+import { contextDirFor } from "../context/node-file.js";
+import { loadGraphCached } from "./load.js";
+import { resolveSymbol, callersOf, calleesOf, impactOf, type EdgeHit } from "./traverse.js";
+import type { GraphV1, NodeV1 } from "./types.js";
+
+export type TraverseKind = "callers" | "callees" | "impact";
+
+export interface TraverseCliOptions {
+ in?: string;
+ json?: boolean;
+ /** impact only: max BFS depth, as the raw --depth string (validated here). */
+ depth?: string;
+ /** the top-level `--dir` override, so this command respects it like every other. */
+ globalDir?: string;
+}
+
+const ARROW: Record<TraverseKind, "←" | "→"> = { callers: "←", impact: "←", callees: "→" };
+const DEFAULT_IMPACT_DEPTH = 2;
+
+function edgesFor(kind: TraverseKind, graph: GraphV1, node: NodeV1, depth: number): EdgeHit[] {
+ if (kind === "callers") return callersOf(graph, node);
+ if (kind === "callees") return calleesOf(graph, node);
+ return impactOf(graph, node, depth);
+}
+
+function headerOf(n: NodeV1): string {
+ return `${n.name} · ${n.kind} · ${n.path}:${n.span}`;
+}
+
+function hitLine(kind: TraverseKind, hit: EdgeHit): string {
+ const arrow = ARROW[kind];
+ const depthTag = kind === "impact" ? ` [depth ${hit.depth}]` : "";
+ const label = hit.node ? `${hit.node.name} (${hit.node.path}:${hit.node.span})` : `${hit.id} (unresolved import)`;
+ return ` ${hit.relation} ${arrow} ${label}${depthTag}`;
+}
+
+/** Loud, actionable empty-result note — never a bare empty list. `callers` and
+ * `impact` both walk incoming edges, so they share the "callers" wording. */
+function looseNoteFor(kind: TraverseKind, name: string): string {
+ const label = kind === "callees" ? "callees" : "callers";
+ const direction = kind === "callees" ? "outgoing" : "incoming";
+ return ` no indexed ${label} — the graph has no ${direction} call/reference edges for this symbol; try grep -rn "${name}"`;
+}
+
+interface SymbolJson {
+ id: string;
+ name: string;
+ kind: string;
+ path: string;
+ span: string;
+}
+
+interface HitJson {
+ id: string;
+ name?: string;
+ kind?: string;
+ path?: string;
+ span?: string;
+ relation: string;
+ depth: number;
+}
+
+function symbolJson(n: NodeV1): SymbolJson {
+ return { id: n.id, name: n.name, kind: n.kind, path: n.path, span: n.span };
+}
+
+function hitJson(hit: EdgeHit): HitJson {
+ const out: HitJson = { id: hit.id, relation: hit.relation, depth: hit.depth };
+ if (hit.node) {
+ out.name = hit.node.name;
+ out.kind = hit.node.kind;
+ out.path = hit.node.path;
+ out.span = hit.node.span;
+ }
+ return out;
+}
+
+/**
+ * Resolve `query` in the graph at `dir` (respecting `--dir`/`--in`), walk
+ * edges per `kind`, and print either the human report or `--json`. Exits the
+ * process (code 1) when there's no graph at all or the symbol is unknown —
+ * both are caller-facing mistakes, not recoverable states.
+ */
+export function runTraverseCommand(kind: TraverseKind, query: string, dir: string, opts: TraverseCliOptions): void {
+ const root = resolve(dir);
+ const contextDir = contextDirFor(root, opts.globalDir);
+ const graph = loadGraphCached(contextDir);
+ if (!graph) {
+ console.error(`✗ no graph found at ${contextDir} — run \`graft build\` first`);
+ process.exit(1);
+ }
+
+ const matches = resolveSymbol(graph, query, opts.in ? { in: opts.in } : {});
+ if (matches.length === 0) {
+ console.error(`✗ no symbol "${query}" in the graph — check spelling or run graft build`);
+ process.exit(1);
+ }
+
+ let depth = DEFAULT_IMPACT_DEPTH;
+ if (kind === "impact" && opts.depth !== undefined) {
+ const d = Number(opts.depth);
+ if (!Number.isFinite(d) || d < 1) {
+ console.error(`✗ --depth must be a positive number, got "${opts.depth}"`);
+ process.exit(1);
+ }
+ depth = d;
+ }
+
+ const results = matches.map((symbol) => ({ symbol, hits: edgesFor(kind, graph, symbol, depth) }));
+
+ if (opts.json) {
+ const payload = {
+ query,
+ matches: results.map((r) => ({ symbol: symbolJson(r.symbol), hits: r.hits.map(hitJson) })),
+ };
+ console.log(JSON.stringify(payload, null, 2));
+ return;
+ }
+
+ const lines: string[] = [];
+ for (const { symbol, hits } of results) {
+ lines.push(headerOf(symbol));
+ if (hits.length === 0) lines.push(looseNoteFor(kind, symbol.name));
+ else for (const h of hits) lines.push(hitLine(kind, h));
+ lines.push("");
+ }
+ process.stdout.write(lines.join("\n").replace(/\n+$/, "\n"));
+}
diff --git a/test/graph-traverse-cli.test.ts b/test/graph-traverse-cli.test.ts
new file mode 100644
index 00000000..b2b30a9a
--- /dev/null
+++ b/test/graph-traverse-cli.test.ts
@@ -0,0 +1,110 @@
+/**
+ * CLI tests for `graft callers` / `callees` / `impact` — the three commands
+ * that wire src/graph/traverse.ts's pure resolver + edge-walkers into the
+ * `graft` binary. Runs the real CLI via execFileSync (same pattern as
+ * test/mcp-tools.test.ts's `builtRepo` helper) against a built fixture repo,
+ * so these tests exercise the actual process boundary: exit codes, stdout vs
+ * stderr, and --json shape.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { execFileSync } from 'node:child_process';
+
+function builtRepo(): string {
+ const d = mkdtempSync(join(tmpdir(), 'graft-traversecli-'));
+ mkdirSync(join(d, 'src'), { recursive: true });
+ writeFileSync(
+ join(d, 'src', 'math.ts'),
+ 'export function add(a: number, b: number): number {\n return a + b;\n}\n' +
+ 'export function sub(a: number, b: number): number {\n return add(a, -b);\n}\n' +
+ 'export function compute(a: number, b: number): number {\n return sub(a, b);\n}\n',
+ );
+ execFileSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', 'build', d], { stdio: 'pipe' });
+ return d;
+}
+
+function runCli(args: string[]): { stdout: string; stderr: string; status: number } {
+ try {
+ const stdout = execFileSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', ...args], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ return { stdout, stderr: '', status: 0 };
+ } catch (err) {
+ const e = err as { stdout?: string; stderr?: string; status?: number };
+ return { stdout: e.stdout ?? '', stderr: e.stderr ?? '', status: e.status ?? 1 };
+ }
+}
+
+test('graft callers: happy path shows header and the caller hit', () => {
+ const d = builtRepo();
+ const r = runCli(['callers', 'add', d]);
+ assert.equal(r.status, 0);
+ assert.match(r.stdout, /add · function · src\/math\.ts:/);
+ assert.match(r.stdout, /calls ← sub \(src\/math\.ts:/);
+});
+
+test('graft callers --json: shape matches {query, matches:[{symbol,hits}]}', () => {
+ const d = builtRepo();
+ const r = runCli(['callers', 'add', d, '--json']);
+ assert.equal(r.status, 0);
+ const parsed = JSON.parse(r.stdout);
+ assert.equal(parsed.query, 'add');
+ assert.equal(parsed.matches.length, 1);
+ const m = parsed.matches[0];
+ assert.equal(m.symbol.name, 'add');
+ assert.equal(m.symbol.kind, 'function');
+ assert.ok(m.symbol.path.endsWith('math.ts'));
+ assert.ok(m.symbol.id);
+ assert.ok(m.symbol.span);
+ assert.equal(m.hits.length, 1);
+ assert.equal(m.hits[0].name, 'sub');
+ assert.equal(m.hits[0].relation, 'calls');
+ assert.equal(m.hits[0].depth, 1);
+});
+
+test('graft callers: unknown symbol exits 1 with a stderr message', () => {
+ const d = builtRepo();
+ const r = runCli(['callers', 'noSuchSymbolAnywhere', d]);
+ assert.equal(r.status, 1);
+ assert.match(r.stderr, /no symbol "noSuchSymbolAnywhere" in the graph/);
+ assert.match(r.stderr, /graft build/);
+ assert.equal(r.stdout, '');
+});
+
+test('graft callees: zero-edge symbol prints a loud note and still exits 0', () => {
+ const d = builtRepo();
+ // `add` calls nothing, so its callees are empty — must not be a silent list.
+ const r = runCli(['callees', 'add', d]);
+ assert.equal(r.status, 0);
+ assert.match(r.stdout, /add · function · src\/math\.ts:/);
+ assert.match(r.stdout, /no indexed callees/);
+ assert.match(r.stdout, /grep -rn "add"/);
+});
+
+test('graft impact -d: depth flag limits the BFS, default reaches further', () => {
+ const d = builtRepo();
+ // compute -> sub -> add: impact of `add` at depth 1 is just `sub`;
+ // the default depth (2) also reaches `compute`.
+ const shallow = runCli(['impact', 'add', d, '-d', '1']);
+ assert.equal(shallow.status, 0);
+ assert.match(shallow.stdout, /← sub \(/);
+ assert.doesNotMatch(shallow.stdout, /compute/);
+
+ const deeper = runCli(['impact', 'add', d]);
+ assert.equal(deeper.status, 0);
+ assert.match(deeper.stdout, /← sub \(/);
+ assert.match(deeper.stdout, /\[depth 1\]/);
+ assert.match(deeper.stdout, /← compute \(/);
+ assert.match(deeper.stdout, /\[depth 2\]/);
+});
+
+test('graft callers: no graph at all is a stderr error, exit 1', () => {
+ const bare = mkdtempSync(join(tmpdir(), 'graft-traversecli-bare-'));
+ const r = runCli(['callers', 'add', bare]);
+ assert.equal(r.status, 1);
+ assert.match(r.stderr, /graft build/);
+});