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
feat(graph): traversal core — symbol resolution + callers/callees/impact
Shrish Dwivedib685d6ec0a46
diff --git a/src/graph/traverse.ts b/src/graph/traverse.tsnew file mode 100644index 00000000..aa06899e--- /dev/null+++ b/src/graph/traverse.ts@@ -0,0 +1,166 @@+/**+ * Pure graph-traversal core shared by `graft callers` / `callees` / `impact`,+ * their MCP equivalents, and `ask`'s structural intent path.+ *+ * Centralizes the symbol-resolution contract (bare name, qualified id-suffix,+ * last-segment fallback, `--in` narrowing) so all three surfaces agree on what+ * a query like `Cache.get` or `hashstructure.Hash` means, and the depth-1+ * (callers/callees) and BFS (impact) edge walks over the wiring graph.+ *+ * No I/O here: callers pass in an already-loaded `GraphV1` (via+ * `loadGraphCached`), which keeps this module trivially unit-testable against+ * hand-built fixture graphs.+ */+import type { EdgeV1, GraphV1, NodeV1, Relation } from "./types.js";++/** A resolved symbol-search hit. Reserved for future disambiguation metadata+ * (e.g. why a query matched); today it wraps the node 1:1. */+export interface SymbolMatch {+ node: NodeV1;+}++export interface ResolveSymbolOptions {+ /** Narrow candidates to nodes whose `path` contains this substring. */+ in?: string;+}++/**+ * Edges that carry meaning-flow for a walk. `contains` is deliberately+ * excluded — see graphrank.ts's identical WALK_RELATIONS for why (a file+ * "contains" every symbol in it, which would make the file a false hub).+ */+const WALK_RELATIONS = new Set<Relation>([+ "calls",+ "references",+ "imports",+ "implements",+ "extends",+]);++/**+ * Resolve a query string to every matching node in the graph.+ *+ * Matching, in order:+ * 1. Non-file nodes whose `name` equals the query case-insensitively, OR+ * whose `id` ends with `#<query>` or `.<query>` case-insensitively — this+ * is what makes a qualified name like `Cache.get` resolve against an id+ * like `src/cache.ts#Cache.get`.+ * 2. If that yields nothing and the query contains a `.`, retry with just+ * the last dot-segment as a bare name (`hashstructure.Hash` → `Hash`) —+ * covers package-qualified names (e.g. Go) whose id never contains the+ * package prefix.+ * 3. If *that* still yields nothing and the query looks like a filename+ * (contains `.`, no `#`), fall back to `kind: 'file'` nodes matched by+ * name or path.+ *+ * `opts.in` then filters whichever candidate set was produced, by path+ * substring. Multiple matches are not an error — every match is returned.+ */+export function resolveSymbol(graph: GraphV1, query: string, opts: ResolveSymbolOptions = {}): NodeV1[] {+ const lowerQuery = query.toLowerCase();+ const looksLikeFilename = query.includes(".") && !query.includes("#");++ let matches = symbolMatches(graph.nodes, lowerQuery);++ if (matches.length === 0 && query.includes(".")) {+ const lastSegment = query.slice(query.lastIndexOf(".") + 1).toLowerCase();+ if (lastSegment) {+ matches = graph.nodes.filter((n) => n.kind !== "file" && n.name.toLowerCase() === lastSegment);+ }+ }++ if (matches.length === 0 && looksLikeFilename) {+ matches = graph.nodes.filter(+ (n) =>+ n.kind === "file" &&+ (n.name.toLowerCase() === lowerQuery ||+ n.path.toLowerCase() === lowerQuery ||+ n.path.toLowerCase().endsWith("/" + lowerQuery)),+ );+ }++ if (opts.in) matches = matches.filter((n) => n.path.includes(opts.in!));+ return matches;+}++function symbolMatches(nodes: NodeV1[], lowerQuery: string): NodeV1[] {+ const suffixHash = "#" + lowerQuery;+ const suffixDot = "." + lowerQuery;+ return nodes.filter((n) => {+ if (n.kind === "file") return false;+ if (n.name.toLowerCase() === lowerQuery) return true;+ const lowerId = n.id.toLowerCase();+ return lowerId.endsWith(suffixHash) || lowerId.endsWith(suffixDot);+ });+}++/** One traversed edge. `node` is null when the edge's other endpoint isn't a+ * real node in the graph (e.g. an unresolved import module string) — such+ * hits are kept, labeled by the raw id, rather than dropped. */+export interface EdgeHit {+ node: NodeV1 | null;+ id: string;+ relation: Relation;+ depth: number;+}++/** Depth-1: nodes with a walk-relation edge whose target is `symbol`. */+export function callersOf(graph: GraphV1, symbol: NodeV1): EdgeHit[] {+ const byId = new Map(graph.nodes.map((n) => [n.id, n]));+ const hits: EdgeHit[] = [];+ for (const e of graph.edges as EdgeV1[]) {+ if (!WALK_RELATIONS.has(e.relation) || e.target !== symbol.id) continue;+ hits.push({ node: byId.get(e.source) ?? null, id: e.source, relation: e.relation, depth: 1 });+ }+ return hits;+}++/** Depth-1: walk-relation edges whose source is `symbol`. */+export function calleesOf(graph: GraphV1, symbol: NodeV1): EdgeHit[] {+ const byId = new Map(graph.nodes.map((n) => [n.id, n]));+ const hits: EdgeHit[] = [];+ for (const e of graph.edges as EdgeV1[]) {+ if (!WALK_RELATIONS.has(e.relation) || e.source !== symbol.id) continue;+ hits.push({ node: byId.get(e.target) ?? null, id: e.target, relation: e.relation, depth: 1 });+ }+ return hits;+}++/**+ * BFS over INCOMING walk-relation edges from `symbol`, up to `maxDepth` hops+ * — "who breaks if this changes". Each reached node is deduped by id and+ * reported once, at the depth it was first reached (a diamond-shaped+ * dependency graph counts its convergence node exactly once).+ */+export function impactOf(graph: GraphV1, symbol: 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.+ const incoming = new Map<string, { source: string; relation: Relation }[]>();+ for (const e of graph.edges as EdgeV1[]) {+ if (!WALK_RELATIONS.has(e.relation)) continue;+ const arr = incoming.get(e.target);+ const entry = { source: e.source, relation: e.relation };+ if (arr) arr.push(entry);+ else incoming.set(e.target, [entry]);+ }++ const visited = new Set<string>([symbol.id]);+ const hits: EdgeHit[] = [];+ let frontier = [symbol.id];++ for (let depth = 1; depth <= maxDepth && frontier.length > 0; depth++) {+ const next: string[] = [];+ for (const current of frontier) {+ for (const { source, relation } of incoming.get(current) ?? []) {+ if (visited.has(source)) continue;+ visited.add(source);+ hits.push({ node: byId.get(source) ?? null, id: source, relation, depth });+ next.push(source);+ }+ }+ frontier = next;+ }++ return hits;+}diff --git a/test/graph-traverse.test.ts b/test/graph-traverse.test.tsnew file mode 100644index 00000000..ba677ea7--- /dev/null+++ b/test/graph-traverse.test.ts@@ -0,0 +1,213 @@+/**+ * Tests for the pure graph-traversal core: symbol resolution (bare name,+ * qualified id-suffix, last-segment fallback, `--in` filtering) and+ * callers/callees/impact edge walking.+ *+ * Uses a hand-built fixture graph (nodeStub/graphOf helpers, same pattern as+ * test/graphrank.test.ts) rather than a built repo, so the resolution+ * contract can be pinned down precisely without touching the filesystem.+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import { resolveSymbol, callersOf, calleesOf, impactOf } from "../src/graph/traverse.js";+import type { EdgeV1, GraphV1, NodeV1, Relation } from "../src/graph/types.js";++function nodeStub(partial: Partial<NodeV1> & { id: string }): NodeV1 {+ return {+ name: partial.id,+ kind: "function",+ path: partial.id.split("#")[0],+ span: "L1-L1",+ signature: null,+ exported: true,+ origin: "ast",+ body_hash: partial.id,+ summary_state: "pending",+ summary: null,+ crux: null,+ ...partial,+ };+}++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: ["ts"] },+ nodes,+ edges,+ };+}++// ── Fixture ──────────────────────────────────────────────────────────────++const cacheGet = nodeStub({ id: "src/cache.ts#Cache.get", name: "get", kind: "method", path: "src/cache.ts" });+const widgetRender = nodeStub({+ id: "src/widget.ts#Widget.render",+ name: "render",+ kind: "method",+ path: "src/widget.ts",+});+const otherGet = nodeStub({ id: "src/other.ts#get", name: "get", kind: "function", path: "src/other.ts" });+const hashFn = nodeStub({ id: "pkg/hash.go#Hash", name: "Hash", kind: "function", path: "pkg/hash.go" });+const fileNode = nodeStub({ id: "src/file.ts", name: "file.ts", kind: "file", path: "src/file.ts" });++function baseGraph(): GraphV1 {+ return graphOf(+ [cacheGet, widgetRender, otherGet, hashFn, fileNode],+ [+ edge("src/cache.ts", "src/cache.ts#Cache.get", "contains"),+ edge("src/cache.ts#Cache.get", "src/widget.ts#Widget.render", "calls"),+ edge("src/cache.ts#Cache.get", "npm:lodash", "imports"),+ ],+ );+}++// ── resolveSymbol ────────────────────────────────────────────────────────++test("resolveSymbol: bare name match is case-insensitive", () => {+ const g = baseGraph();+ const matches = resolveSymbol(g, "RENDER");+ assert.deepEqual(matches.map((n) => n.id), ["src/widget.ts#Widget.render"]);+});++test("resolveSymbol: qualified Class.method resolves via id suffix", () => {+ const g = baseGraph();+ const matches = resolveSymbol(g, "Cache.get");+ assert.deepEqual(matches.map((n) => n.id), ["src/cache.ts#Cache.get"]);+});++test("resolveSymbol: last-segment fallback for a dotted package-qualified name", () => {+ const g = baseGraph();+ // "hashstructure.Hash" has no id-suffix match anywhere in the fixture — falls+ // back to matching the last dot-segment ("Hash") as a bare name.+ const matches = resolveSymbol(g, "hashstructure.Hash");+ assert.deepEqual(matches.map((n) => n.id), ["pkg/hash.go#Hash"]);+});++test("resolveSymbol: multi-match returns all matching nodes", () => {+ const g = baseGraph();+ const matches = resolveSymbol(g, "get");+ assert.deepEqual(+ matches.map((n) => n.id).sort(),+ ["src/cache.ts#Cache.get", "src/other.ts#get"].sort(),+ );+});++test("resolveSymbol: --in filters candidates by path substring", () => {+ const g = baseGraph();+ const matches = resolveSymbol(g, "get", { in: "cache" });+ assert.deepEqual(matches.map((n) => n.id), ["src/cache.ts#Cache.get"]);+});++test("resolveSymbol: kind:'file' nodes are excluded when a symbol matches", () => {+ const g = baseGraph();+ // "file.ts" also happens to be the file node's name; "ts" isn't a symbol name+ // so it should not spuriously match anything, but the point being tested is+ // that when a real symbol match exists, file nodes never surface. Use a+ // symbol query instead to keep the assertion about exclusion meaningful:+ const matches = resolveSymbol(g, "render");+ assert.ok(matches.every((n) => n.kind !== "file"));+});++test("resolveSymbol: file nodes are matched as a last resort for filename-shaped queries", () => {+ const g = baseGraph();+ const matches = resolveSymbol(g, "file.ts");+ assert.deepEqual(matches.map((n) => n.id), ["src/file.ts"]);+});++test("resolveSymbol: unknown symbol returns empty array", () => {+ const g = baseGraph();+ assert.deepEqual(resolveSymbol(g, "NoSuchSymbol"), []);+});++// ── callersOf / calleesOf ────────────────────────────────────────────────++test("calleesOf: walks outgoing walk-relation edges, keeping unresolved targets", () => {+ const g = baseGraph();+ const hits = calleesOf(g, cacheGet);+ const byId = new Map(hits.map((h) => [h.id, h]));++ assert.equal(hits.length, 2);+ assert.equal(byId.get("src/widget.ts#Widget.render")?.node?.id, "src/widget.ts#Widget.render");+ assert.equal(byId.get("src/widget.ts#Widget.render")?.relation, "calls");+ assert.equal(byId.get("src/widget.ts#Widget.render")?.depth, 1);++ const unresolved = byId.get("npm:lodash");+ assert.ok(unresolved, "unresolved import target is kept");+ assert.equal(unresolved!.node, null);+ assert.equal(unresolved!.relation, "imports");+ assert.equal(unresolved!.depth, 1);+});++test("callersOf: finds incoming walk-relation edges, excludes 'contains'", () => {+ const g = baseGraph();+ const hits = callersOf(g, widgetRender);+ assert.equal(hits.length, 1);+ assert.equal(hits[0].id, "src/cache.ts#Cache.get");+ assert.equal(hits[0].node?.id, "src/cache.ts#Cache.get");+ assert.equal(hits[0].relation, "calls");+ assert.equal(hits[0].depth, 1);++ // The file that "contains" cacheGet must never show up as a caller.+ const containsCallers = callersOf(g, cacheGet);+ assert.deepEqual(containsCallers, []);+});++test("callersOf / calleesOf: no edges → empty array", () => {+ const g = baseGraph();+ assert.deepEqual(callersOf(g, hashFn), []);+ assert.deepEqual(calleesOf(g, hashFn), []);+});++// ── impactOf ─────────────────────────────────────────────────────────────++function diamondGraph(): GraphV1 {+ const X = nodeStub({ id: "X", name: "X" });+ const A = nodeStub({ id: "A", name: "A" });+ const B = nodeStub({ id: "B", name: "B" });+ const C = nodeStub({ id: "C", name: "C" });+ return {+ node: X,+ graph: graphOf(+ [X, A, B, C],+ [edge("A", "X", "calls"), edge("B", "X", "calls"), edge("C", "A", "calls"), edge("C", "B", "calls")],+ ),+ } as unknown as { node: NodeV1; graph: GraphV1 };+}++test("impactOf: BFS over incoming edges, diamond converges to one hit, deduped at min depth", () => {+ const { node: X, graph } = diamondGraph();+ const hits = impactOf(graph, X, 2);+ const byId = new Map(hits.map((h) => [h.id, h]));++ assert.equal(hits.length, 3, "A, B at depth 1, C once at depth 2 — not twice");+ assert.equal(byId.get("A")?.depth, 1);+ assert.equal(byId.get("B")?.depth, 1);+ assert.equal(byId.get("C")?.depth, 2);+});++test("impactOf: depth cap is respected", () => {+ const { node: X, graph } = diamondGraph();+ const hits = impactOf(graph, X, 1);+ assert.deepEqual(+ hits.map((h) => h.id).sort(),+ ["A", "B"],+ );+});++test("impactOf: default maxDepth is 2", () => {+ const { node: X, graph } = diamondGraph();+ const hits = impactOf(graph, X);+ assert.deepEqual(+ hits.map((h) => h.id).sort(),+ ["A", "B", "C"],+ );+});++test("impactOf: no incoming edges → empty array", () => {+ const g = baseGraph();+ assert.deepEqual(impactOf(g, hashFn), []);+});