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(mcp): file-scope blast radius aggregates symbol edges; schema + note polish
Shrish Dwivedib6e81e7cceef
diff --git a/src/ask/ask.ts b/src/ask/ask.tsindex e8ea755e..12cadfe8 100644--- a/src/ask/ask.ts+++ b/src/ask/ask.ts@@ -560,11 +560,15 @@ export function formatAsk(r: AskResult): string {// The note prints as its own prominent line(s) right under the header —// above every hit — so a loud structural-fallthrough note (or the// no-structural-edges / no-lexical-match note) can never be missed by only- // being embedded inline in the header parenthetical.+ // being embedded inline in the header parenthetical. Only a genuine+ // fallthrough/warning line (from `fallthroughNoteFor`, always prefixed+ // "structural index:") gets the ⚠ marker; the benign structural header note+ // ("callers / references of X" / "outgoing edges from X") prints plain —+ // it's informational, not a warning.const noteBlock = r.note? r.note.split("\n")- .map((l) => `⚠ ${l}`)+ .map((l) => (l.startsWith("structural index:") ? `⚠ ${l}` : l)).join("\n"): "";if (r.hits.length === 0) {diff --git a/src/graph/traverse.ts b/src/graph/traverse.tsindex aa06899e..9a7e7539 100644--- a/src/graph/traverse.ts+++ b/src/graph/traverse.ts@@ -133,6 +133,24 @@ export function calleesOf(graph: GraphV1, symbol: NodeV1): EdgeHit[] {* dependency graph counts its convergence node exactly once).*/export function impactOf(graph: GraphV1, symbol: NodeV1, maxDepth = 2): EdgeHit[] {+ return impactOfMany(graph, [symbol], maxDepth);+}++/**+ * BFS over INCOMING walk-relation edges from *multiple* seed nodes at once —+ * the multi-seed generalization of {@link impactOf} (`impactOf(g, n, d)` is+ * exactly `impactOfMany(g, [n], d)`). Used when one logical unit spans several+ * graph node ids — e.g. a file plus every symbol defined in it, since a+ * `calls`/`references`/etc. edge from another file always targets the SYMBOL+ * id, never the FILE id, so walking the file node alone misses dependents that+ * call into it rather than merely importing it.+ *+ * Every seed is pre-marked visited (so a seed can never appear as its own+ * hit, and an edge between two seeds is never reported), then the walk+ * proceeds exactly like `impactOf`'s: each reached node deduped by id and+ * reported once, at the depth it was first reached from *any* seed.+ */+export function impactOfMany(graph: GraphV1, seeds: NodeV1[], maxDepth = 2): EdgeHit[] {const byId = new Map(graph.nodes.map((n) => [n.id, n]));// target id → incoming {source, relation} pairs, restricted to walk relations.@@ -145,9 +163,9 @@ export function impactOf(graph: GraphV1, symbol: NodeV1, maxDepth = 2): EdgeHit[else incoming.set(e.target, [entry]);}- const visited = new Set<string>([symbol.id]);+ const visited = new Set<string>(seeds.map((s) => s.id));const hits: EdgeHit[] = [];- let frontier = [symbol.id];+ let frontier = [...visited];for (let depth = 1; depth <= maxDepth && frontier.length > 0; depth++) {const next: string[] = [];@@ -164,3 +182,22 @@ export function impactOf(graph: GraphV1, symbol: NodeV1, maxDepth = 2): EdgeHit[return hits;}++/** Every non-file node whose `path` equals `fileNode.path` — the symbols+ * defined in that file. */+function symbolsInFile(graph: GraphV1, fileNode: NodeV1): NodeV1[] {+ return graph.nodes.filter((n) => n.kind !== "file" && n.path === fileNode.path);+}++/**+ * `impactOf`, generalized for a `kind: 'file'` seed: aggregates the BFS over+ * the file node AND every symbol node defined in that file (via+ * {@link impactOfMany} — dedup by id, min depth, seeds excluded). Fixes a file+ * query silently dropping dependents that `calls`/`references`/etc. into a+ * symbol the file defines, rather than merely `imports`-ing the file itself —+ * see this module's header and `impactOfMany`'s doc for why. Symbol-kind+ * queries keep using plain `impactOf`; this is only for file-kind matches.+ */+export function impactOfFile(graph: GraphV1, fileNode: NodeV1, maxDepth = 2): EdgeHit[] {+ return impactOfMany(graph, [fileNode, ...symbolsInFile(graph, fileNode)], maxDepth);+}diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex e6ed8ca5..4bfa0d1a 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -8,7 +8,7 @@ import { formatCheckReport } from '../context/check.js';import { formatGraphCheckReport } from '../graph/check.js';import { loadGraphCached } from '../graph/load.js';import { contextDirFor } from '../context/node-file.js';-import { resolveSymbol, callersOf, calleesOf, impactOf, type EdgeHit } from '../graph/traverse.js';+import { resolveSymbol, callersOf, calleesOf, impactOf, impactOfFile, type EdgeHit } from '../graph/traverse.js';import { headerOf, hitLine, looseNoteFor, type TraverseKind } from '../graph/traverse-cli.js';import type { NodeV1 } from '../graph/types.js';@@ -54,6 +54,7 @@ export const TOOLS: ToolDef[] = [type: 'object',properties: {file: { type: 'string', description: 'repo-relative file path, or a symbol name (bare, qualified, or package-qualified)' },+ symbol: { type: 'string', description: 'alternative to `file` — a symbol name (bare, qualified, or package-qualified)' },depth: { type: 'number', description: 'max BFS depth (default 2)' },},required: ['file'],@@ -135,7 +136,15 @@ export function callTool(? args.depth: DEFAULT_BLAST_DEPTH;// impactOf's BFS is over incoming edges — same wording family as "callers".- const text = renderMatches('impact', matches, (m) => impactOf(w, m, depth));+ // A file-kind match must aggregate impact over the file node AND every+ // symbol it defines: a `calls`/`references`/etc. edge into a function+ // defined in the file targets the SYMBOL id, never the FILE id, so+ // walking the file node alone silently drops dependents that call+ // into it rather than merely importing it. Symbol-kind matches keep+ // the plain single-seed walk.+ const text = renderMatches('impact', matches, (m) =>+ m.kind === 'file' ? impactOfFile(w, m, depth) : impactOf(w, m, depth),+ );return { text, isError: false };}case 'graft_callers':diff --git a/test/graph-traverse.test.ts b/test/graph-traverse.test.tsindex ba677ea7..5a41ea64 100644--- a/test/graph-traverse.test.ts+++ b/test/graph-traverse.test.ts@@ -9,7 +9,7 @@*/import { test } from "node:test";import assert from "node:assert/strict";-import { resolveSymbol, callersOf, calleesOf, impactOf } from "../src/graph/traverse.js";+import { resolveSymbol, callersOf, calleesOf, impactOf, impactOfMany, impactOfFile } from "../src/graph/traverse.js";import type { EdgeV1, GraphV1, NodeV1, Relation } from "../src/graph/types.js";function nodeStub(partial: Partial<NodeV1> & { id: string }): NodeV1 {@@ -211,3 +211,66 @@ test("impactOf: no incoming edges → empty array", () => {const g = baseGraph();assert.deepEqual(impactOf(g, hashFn), []);});++// ── impactOfMany / impactOfFile ─────────────────────────────────────────────++/** b.ts imports a.ts (file-level `imports` edge, target = the FILE id) AND+ * calls `helper`, a function defined in a.ts (`calls` edge, target = the+ * SYMBOL id) — the exact shape that regresses a file-scope blast radius that+ * only walks the file node: the `calls` edge is invisible from there. */+function fileAndSymbolGraph() {+ const fileA = nodeStub({ id: "src/a.ts", name: "a.ts", kind: "file", path: "src/a.ts" });+ const helper = nodeStub({ id: "src/a.ts#helper", name: "helper", kind: "function", path: "src/a.ts" });+ const fileB = nodeStub({ id: "src/b.ts", name: "b.ts", kind: "file", path: "src/b.ts" });+ const useB = nodeStub({ id: "src/b.ts#useB", name: "useB", kind: "function", path: "src/b.ts" });+ const graph = graphOf(+ [fileA, helper, fileB, useB],+ [edge("src/b.ts", "src/a.ts", "imports"), edge("src/b.ts#useB", "src/a.ts#helper", "calls")],+ );+ return { fileA, helper, fileB, useB, graph };+}++test("impactOfMany: aggregating over [file, symbol] seeds finds both the importing file and the calling symbol", () => {+ const { fileA, helper, graph } = fileAndSymbolGraph();++ // Walking the file node alone (today's behavior for a file-kind match) sees+ // only the file-level `imports` edge — the `calls` edge targets the symbol+ // id, so it's invisible from here. This is the regression.+ const fileOnly = impactOf(graph, fileA);+ assert.deepEqual(fileOnly.map((h) => h.id), ["src/b.ts"]);++ // impactOfMany over [file, symbol] recovers both dependents.+ const hits = impactOfMany(graph, [fileA, helper], 2);+ assert.deepEqual(hits.map((h) => h.id).sort(), ["src/b.ts", "src/b.ts#useB"]);+ const byId = new Map(hits.map((h) => [h.id, h]));+ assert.equal(byId.get("src/b.ts")?.relation, "imports");+ assert.equal(byId.get("src/b.ts#useB")?.relation, "calls");+});++test("impactOfMany: seeds are excluded from their own results and cross-seed convergence dedups at the min depth", () => {+ const A = nodeStub({ id: "A", name: "A" });+ const B = nodeStub({ id: "B", name: "B" });+ const C = nodeStub({ id: "C", name: "C" });+ // C calls into both A and B — a hit reached from two different seeds at the+ // same depth must still be reported once.+ const g = graphOf([A, B, C], [edge("C", "A", "calls"), edge("C", "B", "calls")]);+ const hits = impactOfMany(g, [A, B], 2);+ assert.deepEqual(hits.map((h) => h.id), ["C"]);+ assert.equal(hits[0].depth, 1);+});++test("impactOfMany: impactOf(g, n, d) is the single-seed special case", () => {+ const { node: X, graph } = diamondGraph();+ assert.deepEqual(impactOfMany(graph, [X], 2), impactOf(graph, X, 2));+});++test("impactOfFile: aggregates over the file node and every symbol node it defines", () => {+ const { fileA, graph } = fileAndSymbolGraph();+ const hits = impactOfFile(graph, fileA, 2);+ assert.deepEqual(hits.map((h) => h.id).sort(), ["src/b.ts", "src/b.ts#useB"]);+});++test("impactOfFile: with no symbol nodes in the file, behaves exactly like impactOf on the file node", () => {+ const g = baseGraph();+ assert.deepEqual(impactOfFile(g, fileNode, 2), impactOf(g, fileNode, 2));+});diff --git a/test/mcp-tools.test.ts b/test/mcp-tools.test.tsindex 980c4732..de19e43e 100644--- a/test/mcp-tools.test.ts+++ b/test/mcp-tools.test.ts@@ -32,6 +32,21 @@ function chainRepo(): string {return d;}+/** b.ts imports a.ts AND calls a function (`helper`) defined in a.ts. The+ * `imports` edge targets a.ts's FILE id; the `calls` edge targets `helper`'s+ * SYMBOL id — two different node ids, both "in" a.ts from a human's view. */+function fileScopeRepo(): string {+ const d = mkdtempSync(join(tmpdir(), 'graft-mcptools-filescope-'));+ mkdirSync(join(d, 'src'), { recursive: true });+ writeFileSync(join(d, 'src', 'a.ts'), 'export function helper(): number {\n return 42;\n}\n');+ writeFileSync(+ join(d, 'src', 'b.ts'),+ "import { helper } from './a';\n\nexport function useB(): number {\n return helper();\n}\n",+ );+ execFileSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', 'build', d], { stdio: 'pipe' });+ return d;+}+test('TOOLS lists all five tools with schemas', () => {assert.deepEqual(TOOLS.map((t) => t.name), ['graft_ask',@@ -44,6 +59,11 @@ test('TOOLS lists all five tools with schemas', () => {assert.ok(t.description.length > 0);assert.equal((t.inputSchema as { type: string }).type, 'object');}+ // graft_blast_radius accepts `symbol` as an alternative to `file` (callTool+ // does `args.symbol ?? args.file`) — the schema must document it too.+ const blastRadius = TOOLS.find((t) => t.name === 'graft_blast_radius')!;+ const props = (blastRadius.inputSchema as { properties: Record<string, unknown> }).properties;+ assert.ok('symbol' in props, 'graft_blast_radius schema should document `symbol`');});test('graft_ask returns ranked hits for a built repo', () => {@@ -136,6 +156,17 @@ test('graft_blast_radius: depth param is honored (default 2 reaches further thanassert.match(deeper.text, /\[depth 2\]/);});+test('graft_blast_radius: file-scope match aggregates dependents that call into a symbol the file defines, not just file-level imports', () => {+ const d = fileScopeRepo();+ const r = callTool(d, 'graft_blast_radius', { file: 'src/a.ts' });+ assert.equal(r.isError, false);+ // Old behavior (walking only the FILE node's incoming edges) found b.ts via+ // `imports` but silently dropped it via `calls`, since a `calls` edge+ // targets the SYMBOL id (`src/a.ts#helper`), never the FILE id.+ assert.match(r.text, /imports ← b\.ts \(src\/b\.ts/);+ assert.match(r.text, /calls ← useB \(src\/b\.ts/);+});+test('graft_blast_radius: unknown symbol is a soft isError with the check-spelling message', () => {const d = builtRepo();const r = callTool(d, 'graft_blast_radius', { file: 'noSuchSymbolAnywhere' });