Skip to content

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

feat(search): graft grep — matches grouped by enclosing symbol, ranked by coupling

Shrish Dwivedi41257f20ae19
diff --git a/src/ask/graphrank.ts b/src/ask/graphrank.ts
index 73326207..e984fb88 100644
--- a/src/ask/graphrank.ts
+++ b/src/ask/graphrank.ts
@@ -14,21 +14,8 @@
* graph disposes." Deterministic, $0, no embeddings — a lexical-seed →
* graph-rank pipeline, the established alternative to vector search for code.
*/
-import type { GraphV1, Relation } from "../graph/types.js";
-
-/**
- * Edges that carry meaning-flow for the walk. `contains` is deliberately
- * excluded: a file node contains every symbol defined in it, so walking it
- * would make every same-file symbol a neighbour and let a file act as a hub
- * that connects otherwise-unrelated code — the flooding a graph walk must avoid.
- */
-const WALK_RELATIONS = new Set<Relation>([
- "calls",
- "references",
- "imports",
- "implements",
- "extends",
-]);
+import type { GraphV1 } from "../graph/types.js";
+import { WALK_RELATIONS } from "../graph/relations.js";
export interface PageRankOptions {
/** Restart probability — the mass that teleports back to the seed set each
diff --git a/src/cli.ts b/src/cli.ts
index 5363deb9..1bd4ac4b 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -8,6 +8,7 @@
* 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).
+ * grep regex search over indexed files, grouped by enclosing symbol, ranked by coupling ($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
@@ -273,6 +274,33 @@ program
.option("--json", "output as JSON")
.action(traverseAction("impact"));
+program
+ .command("grep")
+ .description("Regex search over indexed files, hits grouped by enclosing symbol and ranked by coupling ($0, no LLM)")
+ .argument("<pattern>", "regex pattern (or literal string with --fixed)")
+ .argument("[dir]", "repository root", ".")
+ .option("-i, --ignore-case", "case-insensitive match")
+ .option("--fixed", "treat pattern as a literal string, not a regex")
+ .option("--in <path>", "narrow to files whose path contains this substring")
+ .option("--json", "output as JSON")
+ .action(
+ async (
+ pattern: string,
+ dir: string,
+ opts: { ignoreCase?: boolean; fixed?: boolean; in?: string; json?: boolean },
+ ) => {
+ const { runGrepCommand } = await import("./search/grep-cli.js");
+ const globalOpts = program.opts<{ dir?: string }>();
+ runGrepCommand(pattern, dir, {
+ ignoreCase: opts.ignoreCase,
+ fixed: opts.fixed,
+ in: opts.in,
+ json: opts.json,
+ globalDir: globalOpts.dir,
+ });
+ },
+ );
+
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/relations.ts b/src/graph/relations.ts
new file mode 100644
index 00000000..7d2c493e
--- /dev/null
+++ b/src/graph/relations.ts
@@ -0,0 +1,20 @@
+/**
+ * Edges that carry dependency meaning for a graph walk/rank: `calls`,
+ * `references`, `imports`, `implements`, `extends`. `contains` is deliberately
+ * excluded — a file "contains" every symbol defined in it, so walking it
+ * would make every same-file symbol a neighbour and let a file act as a false
+ * hub, flooding a walk that must stay confined to genuine dependency wiring.
+ *
+ * Shared by `traverse.ts` (callers/callees/impact edge walks), `graphrank.ts`
+ * (personalized PageRank), and `search/grep.ts` (in-degree ranking) so every
+ * surface agrees on what counts as a dependency edge.
+ */
+import type { Relation } from "./types.js";
+
+export const WALK_RELATIONS: ReadonlySet<Relation> = new Set<Relation>([
+ "calls",
+ "references",
+ "imports",
+ "implements",
+ "extends",
+]);
diff --git a/src/graph/traverse.ts b/src/graph/traverse.ts
index 9a7e7539..2f4cb885 100644
--- a/src/graph/traverse.ts
+++ b/src/graph/traverse.ts
@@ -12,6 +12,7 @@
* hand-built fixture graphs.
*/
import type { EdgeV1, GraphV1, NodeV1, Relation } from "./types.js";
+import { WALK_RELATIONS } from "./relations.js";
/** A resolved symbol-search hit. Reserved for future disambiguation metadata
* (e.g. why a query matched); today it wraps the node 1:1. */
@@ -24,19 +25,6 @@ export interface ResolveSymbolOptions {
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.
*
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index 1d71d350..b2bbc8f1 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -10,6 +10,8 @@ import { loadGraphCached } from '../graph/load.js';
import { contextDirFor } from '../context/node-file.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 { grepGraph } from '../search/grep.js';
+import { formatGrepResult, zeroHitNote } from '../search/grep-cli.js';
import type { NodeV1 } from '../graph/types.js';
export interface ToolDef {
@@ -84,6 +86,21 @@ export const TOOLS: ToolDef[] = [
required: ['symbol'],
},
},
+ {
+ name: 'graft_grep',
+ description:
+ 'Regex search over the graph\'s indexed files, hits grouped by innermost enclosing symbol and ranked by incoming-edge count (coupling) — which hit matters, not just where it is.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ pattern: { type: 'string', description: 'regex pattern (or literal string with fixed: true)' },
+ in: { type: 'string', description: 'narrow to files whose path contains this substring' },
+ ignore_case: { type: 'boolean', description: 'case-insensitive match' },
+ fixed: { type: 'boolean', description: 'treat pattern as a literal string, not a regex' },
+ },
+ required: ['pattern'],
+ },
+ },
];
/** Render every resolved match's header + edge report (or the loud zero-edge
@@ -162,6 +179,19 @@ export function callTool(
const text = renderMatches(kind, matches, (m) => walk(w, m));
return { text, isError: false };
}
+ case 'graft_grep': {
+ const pattern = String(args.pattern ?? '');
+ if (!pattern) return { text: 'graft_grep requires a pattern', isError: true };
+ const w = loadGraphCached(contextDirFor(root, dirOverride));
+ if (!w) return { text: NO_GRAPH, isError: true };
+ const result = grepGraph(w, root, pattern, {
+ ignoreCase: typeof args.ignore_case === 'boolean' ? args.ignore_case : undefined,
+ fixed: typeof args.fixed === 'boolean' ? args.fixed : undefined,
+ in: typeof args.in === 'string' && args.in ? args.in : undefined,
+ });
+ if (result.totalHits === 0) return { text: zeroHitNote(result), isError: false };
+ return { text: formatGrepResult(result), isError: false };
+ }
default:
return { text: `unknown tool: ${name}`, isError: true };
}
diff --git a/src/search/grep-cli.ts b/src/search/grep-cli.ts
new file mode 100644
index 00000000..309694d5
--- /dev/null
+++ b/src/search/grep-cli.ts
@@ -0,0 +1,104 @@
+/**
+ * CLI wiring + human formatter for `graft grep`.
+ *
+ * Kept out of cli.ts (argument wiring only) and out of grep.ts (pure core,
+ * unit-testable against hand-built fixture graphs without touching a real
+ * repo root) — same split as traverse.ts/traverse-cli.ts. `formatGrepResult`
+ * is exported so `graft_grep` in `src/mcp/tools.ts` renders the identical
+ * report, rather than re-implementing it.
+ */
+import { resolve } from "node:path";
+import { contextDirFor } from "../context/node-file.js";
+import { loadGraphCached } from "../graph/load.js";
+import { grepGraph, type GrepGroup, type GrepResult } from "./grep.js";
+
+export interface GrepCliOptions {
+ ignoreCase?: boolean;
+ fixed?: boolean;
+ in?: string;
+ json?: boolean;
+ /** the top-level `--dir` override, so this command respects it like every other. */
+ globalDir?: string;
+}
+
+function groupHeader(g: GrepGroup): string {
+ if (g.symbol) return `${g.symbol.name} · ${g.symbol.kind} · ${g.symbol.path}:${g.symbol.span} · ${g.inDegree} in-edges`;
+ return `${g.path} (module level) · ${g.inDegree} in-edges`;
+}
+
+function formatGroup(g: GrepGroup): string {
+ const lines = [groupHeader(g)];
+ for (const h of g.hits) lines.push(` L${h.line}: ${h.text}`);
+ return lines.join("\n");
+}
+
+/** `"<pattern>" — N hits in M symbols across K files (searched T indexed files)` */
+export function formatGrepHeader(result: GrepResult): string {
+ const filesHit = new Set(result.groups.map((g) => g.path)).size;
+ return `"${result.pattern}" — ${result.totalHits} hits in ${result.groups.length} symbols across ${filesHit} files (searched ${result.filesSearched} indexed files)`;
+}
+
+/** Loud truncation note — dropped counts are never silent. */
+function truncationNote(result: GrepResult): string | null {
+ const { files, hits } = result.truncated;
+ if (files === 0 && hits === 0) return null;
+ const parts: string[] = [];
+ if (hits > 0) parts.push(`${hits} more hit${hits === 1 ? "" : "s"} beyond the cap`);
+ if (files > 0) parts.push(`${files} indexed file${files === 1 ? "" : "s"} unreadable`);
+ return `(truncated: ${parts.join(", ")} — narrow with --in or refine the pattern)`;
+}
+
+/** Full human report: header, blank line, then one block per group (header +
+ * indented hit lines), each block separated by a blank line. */
+export function formatGrepResult(result: GrepResult): string {
+ const blocks = [formatGrepHeader(result), "", ...result.groups.map((g) => formatGroup(g) + "\n")];
+ let out = blocks.join("\n").replace(/\n+$/, "\n");
+ const note = truncationNote(result);
+ if (note) out += note + "\n";
+ return out;
+}
+
+/** Loud, actionable zero-hit note (never a bare empty result) — printed to
+ * stderr; the caller still exits 0, since "no hits in the indexed graph" is
+ * not an error, just a reason to fall back to a real grep. */
+export function zeroHitNote(result: GrepResult): string {
+ return `no hits for "${result.pattern}" in ${result.filesSearched} indexed files — unindexed files (docs, configs, new files) aren't searched; try grep -rn "${result.pattern}" for those`;
+}
+
+/**
+ * Resolve the graph at `dir` (respecting `--dir`), run `grepGraph`, and print
+ * either the human report or `--json`. Exits the process (code 1) when
+ * there's no graph at all or the pattern fails to compile as a regex — both
+ * are caller-facing mistakes, not recoverable states. Zero hits is NOT an
+ * error: it prints a loud note to stderr and exits 0.
+ */
+export function runGrepCommand(pattern: string, dir: string, opts: GrepCliOptions): void {
+ const root = resolve(dir);
+ const contextDir = contextDirFor(root, opts.globalDir);
+ const graph = loadGraphCached(contextDir);
+ if (!graph) {
+ console.error("✗ no graph — run graft build first");
+ process.exit(1);
+ }
+
+ let result: GrepResult;
+ try {
+ result = grepGraph(graph, root, pattern, { ignoreCase: opts.ignoreCase, fixed: opts.fixed, in: opts.in });
+ } catch (err) {
+ console.error(`✗ invalid pattern "${pattern}": ${err instanceof Error ? err.message : String(err)}`);
+ process.exit(1);
+ return;
+ }
+
+ if (opts.json) {
+ console.log(JSON.stringify(result, null, 2));
+ return;
+ }
+
+ if (result.totalHits === 0) {
+ console.error(zeroHitNote(result));
+ return;
+ }
+
+ process.stdout.write(formatGrepResult(result));
+}
diff --git a/src/search/grep.ts b/src/search/grep.ts
new file mode 100644
index 00000000..5bbc48b0
--- /dev/null
+++ b/src/search/grep.ts
@@ -0,0 +1,195 @@
+/**
+ * `graft grep` core: regex search over the graph's indexed files, with hits
+ * grouped by their innermost enclosing symbol and ranked by incoming-edge
+ * count (coupling) — a grep that answers "which of these hits matters",
+ * because plain `grep -rn` gives no way to tell a hit inside a
+ * heavily-depended-on function from one inside dead code.
+ *
+ * Pure I/O + regex, no CLI/MCP concerns: `grep-cli.ts` formats this into
+ * human text and wires the CLI command; `mcp/tools.ts` renders the same
+ * shape for the `graft_grep` tool.
+ */
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import type { GraphV1, NodeV1 } from "../graph/types.js";
+import { WALK_RELATIONS } from "../graph/relations.js";
+
+export interface GrepHit {
+ line: number;
+ /** Trimmed line text, capped at 160 chars. */
+ text: string;
+}
+
+export interface GrepSymbolRef {
+ id: string;
+ /** Qualified scope-joined name (e.g. `FastAPI.include_router`), not just
+ * the bare symbol name — the id's segment after the file-path `#`. */
+ name: string;
+ kind: string;
+ path: string;
+ span: string;
+}
+
+export interface GrepGroup {
+ /** null → file-level: the hit lies outside every indexed symbol's span
+ * (module-level code — imports, top-level statements, module constants). */
+ symbol: GrepSymbolRef | null;
+ path: string;
+ /** Incoming WALK_RELATIONS edges targeting the symbol — always 0 for
+ * file-level groups (there's no single symbol id to count edges against). */
+ inDegree: number;
+ hits: GrepHit[];
+}
+
+export interface GrepResult {
+ pattern: string;
+ /** Indexed file nodes considered (after the `in` filter), whether or not
+ * each was actually readable — matches the CLI's "searched N indexed
+ * files" wording. */
+ filesSearched: number;
+ /** Hits actually collected (<= maxHits). */
+ totalHits: number;
+ /** Sorted: inDegree desc, then path asc. */
+ groups: GrepGroup[];
+ /** Dropped counts — never silent. `files`: indexed file nodes that
+ * couldn't be read from disk. `hits`: matches found beyond `maxHits`,
+ * counted but not collected. */
+ truncated: { files: number; hits: number };
+}
+
+export interface GrepOptions {
+ ignoreCase?: boolean;
+ /** Treat `pattern` as a literal string (regex-escaped), not a regex. */
+ fixed?: boolean;
+ /** Narrow to file nodes whose path contains this substring. */
+ in?: string;
+ /** Stop collecting hits after this many; the rest are tallied into
+ * `truncated.hits`. Default 300. */
+ maxHits?: number;
+}
+
+const DEFAULT_MAX_HITS = 300;
+const MAX_HIT_TEXT = 160;
+const SPAN_RE = /^L(\d+)-L(\d+)$/;
+
+function escapeRegExp(s: string): string {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+function spanBounds(span: string): { start: number; end: number } | null {
+ const m = SPAN_RE.exec(span);
+ if (!m) return null;
+ return { start: Number(m[1]), end: Number(m[2]) };
+}
+
+interface SymbolSpan {
+ node: NodeV1;
+ start: number;
+ end: number;
+}
+
+/** The file's symbol nodes, sorted ascending by span start — the order
+ * `enclosingSymbol` scans in to find the innermost containing span. */
+function symbolsOf(graph: GraphV1, path: string): SymbolSpan[] {
+ const out: SymbolSpan[] = [];
+ for (const n of graph.nodes) {
+ if (n.kind === "file" || n.path !== path) continue;
+ const b = spanBounds(n.span);
+ if (b) out.push({ node: n, start: b.start, end: b.end });
+ }
+ out.sort((a, b) => a.start - b.start);
+ return out;
+}
+
+/** Innermost symbol containing `line`: among spans that contain it, the one
+ * with the greatest start line. Symbols are pre-sorted ascending by start,
+ * so the last containing match seen wins, and the scan can stop as soon as
+ * a span starts after `line` — nothing later in the sort can contain it. */
+function enclosingSymbol(symbols: SymbolSpan[], line: number): NodeV1 | null {
+ let found: NodeV1 | null = null;
+ for (const s of symbols) {
+ if (s.start > line) break;
+ if (line <= s.end) found = s.node;
+ }
+ return found;
+}
+
+/** Incoming WALK_RELATIONS edge count per target id — one pass over
+ * `graph.edges`, computed once per call and shared across every hit. */
+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;
+}
+
+function toSymbolRef(n: NodeV1): GrepSymbolRef {
+ const hash = n.id.indexOf("#");
+ return { id: n.id, name: hash >= 0 ? n.id.slice(hash + 1) : n.name, kind: n.kind, path: n.path, span: n.span };
+}
+
+export function grepGraph(graph: GraphV1, repoRoot: string, pattern: string, opts: GrepOptions = {}): GrepResult {
+ const maxHits = opts.maxHits ?? DEFAULT_MAX_HITS;
+ const source = opts.fixed ? escapeRegExp(pattern) : pattern;
+ const regex = new RegExp(source, opts.ignoreCase ? "i" : "");
+
+ const inDegree = computeInDegree(graph);
+ const fileNodes = graph.nodes.filter((n) => n.kind === "file" && (!opts.in || n.path.includes(opts.in)));
+
+ const groups = new Map<string, GrepGroup>();
+ let collected = 0;
+ let truncatedHits = 0;
+ let truncatedFiles = 0;
+
+ for (const file of fileNodes) {
+ let text: string;
+ try {
+ text = readFileSync(join(repoRoot, file.path), "utf8");
+ } catch {
+ truncatedFiles++;
+ continue;
+ }
+
+ const symbols = symbolsOf(graph, file.path);
+ const lines = text.split("\n");
+
+ for (let i = 0; i < lines.length; i++) {
+ const raw = lines[i];
+ if (!regex.test(raw)) continue;
+
+ if (collected >= maxHits) {
+ truncatedHits++;
+ continue;
+ }
+ collected++;
+
+ const lineNo = i + 1;
+ const sym = enclosingSymbol(symbols, lineNo);
+ const key = sym ? sym.id : `file:${file.path}`;
+ let group = groups.get(key);
+ if (!group) {
+ group = {
+ symbol: sym ? toSymbolRef(sym) : null,
+ path: file.path,
+ inDegree: sym ? (inDegree.get(sym.id) ?? 0) : 0,
+ hits: [],
+ };
+ groups.set(key, group);
+ }
+ const trimmed = raw.trim();
+ group.hits.push({ line: lineNo, text: trimmed.length > MAX_HIT_TEXT ? trimmed.slice(0, MAX_HIT_TEXT) : trimmed });
+ }
+ }
+
+ const sortedGroups = [...groups.values()].sort((a, b) => b.inDegree - a.inDegree || a.path.localeCompare(b.path));
+
+ return {
+ pattern,
+ filesSearched: fileNodes.length,
+ totalHits: collected,
+ groups: sortedGroups,
+ truncated: { files: truncatedFiles, hits: truncatedHits },
+ };
+}
diff --git a/test/mcp-server.test.ts b/test/mcp-server.test.ts
index 330dfe03..3f439fc3 100644
--- a/test/mcp-server.test.ts
+++ b/test/mcp-server.test.ts
@@ -51,6 +51,7 @@ test('initialize → tools/list → tools/call round-trip', async () => {
'graft_blast_radius',
'graft_callers',
'graft_callees',
+ 'graft_grep',
]);
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 18585a7c..b853bc11 100644
--- a/test/mcp-tools.test.ts
+++ b/test/mcp-tools.test.ts
@@ -59,13 +59,14 @@ function fileScopeRepo(): string {
return d;
}
-test('TOOLS lists all five tools with schemas', () => {
+test('TOOLS lists all six tools with schemas', () => {
assert.deepEqual(TOOLS.map((t) => t.name), [
'graft_ask',
'graft_check',
'graft_blast_radius',
'graft_callers',
'graft_callees',
+ 'graft_grep',
]);
for (const t of TOOLS) {
assert.ok(t.description.length > 0);
@@ -187,6 +188,34 @@ test('graft_blast_radius: unknown symbol is a soft isError with the check-spelli
assert.match(r.text, /check spelling/);
});
+test('graft_grep round-trips a hit on the built fixture, grouped by enclosing symbol', () => {
+ const d = builtRepo();
+ const r = callTool(d, 'graft_grep', { pattern: 'add' });
+ assert.equal(r.isError, false);
+ assert.match(r.text, /"add" — \d+ hits? in \d+ symbols? across \d+ files? \(searched \d+ indexed files\)/);
+ assert.match(r.text, /src\/math\.ts/);
+});
+
+test('graft_grep: no hits is a soft (non-error) result with the loud fallback note', () => {
+ const d = builtRepo();
+ const r = callTool(d, 'graft_grep', { pattern: 'noSuchPatternAnywhere' });
+ assert.equal(r.isError, false);
+ assert.match(r.text, /no hits for "noSuchPatternAnywhere"/);
+ assert.match(r.text, /grep -rn "noSuchPatternAnywhere"/);
+});
+
+test('graft_grep: missing pattern and unbuilt repo are soft errors', () => {
+ const d = builtRepo();
+ const r1 = callTool(d, 'graft_grep', {});
+ assert.equal(r1.isError, true);
+ assert.match(r1.text, /requires a pattern/);
+
+ const bare = mkdtempSync(join(tmpdir(), 'graft-mcptools-grep-bare-'));
+ const r2 = callTool(bare, 'graft_grep', { pattern: 'add' });
+ assert.equal(r2.isError, true);
+ assert.match(r2.text, /graft build/);
+});
+
test('callTool honors a dirOverride for a graph built in a non-default dir', () => {
const { repo, graphDir } = customDirRepo();
diff --git a/test/search-grep.test.ts b/test/search-grep.test.ts
new file mode 100644
index 00000000..04a64b42
--- /dev/null
+++ b/test/search-grep.test.ts
@@ -0,0 +1,224 @@
+/**
+ * Core tests for `graft grep` (src/search/grep.ts).
+ *
+ * `heavyRarelyRepo()` builds a small real fixture repo (same `builtRepo`
+ * pattern as test/mcp-tools.test.ts) and runs the actual `graft build` CLI,
+ * so inDegree/innermost-symbol attribution are exercised against a genuine
+ * parsed graph, not a hand-rolled one. The narrower fixed/maxHits/zero-hit
+ * assertions use a hand-built GraphV1 (just enough for grepGraph's file-node
+ * iteration + regex/line logic) plus real files on disk, since they don't
+ * need any symbol/edge structure.
+ */
+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';
+import { grepGraph } from '../src/search/grep.js';
+import { WALK_RELATIONS } from '../src/graph/relations.js';
+import { readGraph, wiringPath } from '../src/graph/write.js';
+import type { GraphV1, NodeV1 } from '../src/graph/types.js';
+
+function fileNode(path: string, lines: number): NodeV1 {
+ return {
+ id: path,
+ name: path,
+ kind: 'file',
+ path,
+ span: `L1-L${lines}`,
+ signature: null,
+ exported: true,
+ origin: 'ast',
+ body_hash: '',
+ summary_state: 'pending',
+ summary: null,
+ crux: null,
+ };
+}
+
+function graphOf(nodes: NodeV1[], edges: GraphV1['edges'] = []): GraphV1 {
+ return { meta: { version: 1, nodeCount: nodes.length, edgeCount: edges.length, languages: [] }, nodes, edges };
+}
+
+/** Two TS files: `NEEDLE` appears (a) inside a heavily-called function, (b)
+ * inside a rarely-called one — both in a.ts — and (c) at module level plus
+ * inside a class method in b.ts (the innermost-attribution case: the hit
+ * must map to `Container.method`, not `Container`). Built via the real CLI
+ * so inDegree comes from genuine `calls` edges. */
+function needleRepo(): string {
+ const d = mkdtempSync(join(tmpdir(), 'graft-grep-'));
+ mkdirSync(join(d, 'src'), { recursive: true });
+ writeFileSync(
+ join(d, 'src', 'a.ts'),
+ [
+ 'export function heavilyCalled(): void {',
+ ' console.log("NEEDLE hit in heavilyCalled");',
+ '}',
+ '',
+ 'export function rarelyCalled(): void {',
+ ' console.log("NEEDLE hit in rarelyCalled");',
+ '}',
+ '',
+ 'export function callerOne(): void { heavilyCalled(); }',
+ 'export function callerTwo(): void { heavilyCalled(); }',
+ 'export function callerThree(): void { heavilyCalled(); }',
+ '',
+ ].join('\n'),
+ );
+ writeFileSync(
+ join(d, 'src', 'b.ts'),
+ [
+ 'console.log("NEEDLE at module level");',
+ '',
+ 'export class Container {',
+ ' method(): void {',
+ ' console.log("NEEDLE inside Container.method");',
+ ' }',
+ '}',
+ '',
+ ].join('\n'),
+ );
+ execFileSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', 'build', d], { stdio: 'pipe' });
+ return d;
+}
+
+function loadBuiltGraph(repo: string): GraphV1 {
+ const g = readGraph(wiringPath(join(repo, 'graft')));
+ assert.ok(g, 'expected a built graph.json');
+ return g!;
+}
+
+test('WALK_RELATIONS (shared, src/graph/relations.ts): exactly the five dependency relations', () => {
+ assert.deepEqual(
+ [...WALK_RELATIONS].sort(),
+ ['calls', 'extends', 'implements', 'imports', 'references'].sort(),
+ );
+ // Excluded on purpose: contains is structural (file->symbol), not dependency wiring.
+ assert.equal(WALK_RELATIONS.has('contains' as never), false);
+});
+
+test('grepGraph: groups are ordered by inDegree desc, then path asc', () => {
+ const repo = needleRepo();
+ const graph = loadBuiltGraph(repo);
+ const r = grepGraph(graph, repo, 'NEEDLE');
+
+ assert.equal(r.pattern, 'NEEDLE');
+ assert.equal(r.totalHits, 4);
+ assert.equal(r.groups.length, 4);
+
+ // heavilyCalled has 3 callers -> highest inDegree -> first.
+ const first = r.groups[0];
+ assert.equal(first.symbol?.kind, 'function');
+ assert.match(first.symbol!.name, /heavilyCalled$/);
+ assert.equal(first.inDegree, 3);
+
+ // Every subsequent group has inDegree <= the previous (non-increasing).
+ for (let i = 1; i < r.groups.length; i++) {
+ assert.ok(r.groups[i].inDegree <= r.groups[i - 1].inDegree);
+ }
+ // Ties (inDegree 0) are ordered by path ascending.
+ const zeroDegreeGroups = r.groups.filter((g) => g.inDegree === 0);
+ const paths = zeroDegreeGroups.map((g) => g.path);
+ assert.deepEqual(paths, [...paths].sort((a, b) => a.localeCompare(b)));
+});
+
+test('grepGraph: innermost-symbol attribution — a hit inside a class method maps to the method, not the class', () => {
+ const repo = needleRepo();
+ const graph = loadBuiltGraph(repo);
+ const r = grepGraph(graph, repo, 'NEEDLE');
+
+ const methodGroup = r.groups.find((g) => g.symbol?.kind === 'method');
+ assert.ok(methodGroup, 'expected a group attributed to Container.method');
+ assert.match(methodGroup!.symbol!.name, /Container\.method$/);
+ assert.equal(methodGroup!.symbol!.path, 'src/b.ts');
+ // No group should be attributed to the class itself.
+ assert.equal(r.groups.some((g) => g.symbol?.kind === 'class'), false);
+});
+
+test('grepGraph: rarely-called function has inDegree 0 and is grouped separately from the heavily-called one', () => {
+ const repo = needleRepo();
+ const graph = loadBuiltGraph(repo);
+ const r = grepGraph(graph, repo, 'NEEDLE');
+
+ const rarelyGroup = r.groups.find((g) => g.symbol?.name.endsWith('rarelyCalled'));
+ assert.ok(rarelyGroup);
+ assert.equal(rarelyGroup!.inDegree, 0);
+ assert.equal(rarelyGroup!.hits.length, 1);
+ assert.match(rarelyGroup!.hits[0].text, /NEEDLE hit in rarelyCalled/);
+});
+
+test('grepGraph: a hit outside every symbol span groups as file-level (symbol: null, inDegree 0)', () => {
+ const repo = needleRepo();
+ const graph = loadBuiltGraph(repo);
+ const r = grepGraph(graph, repo, 'NEEDLE');
+
+ const moduleLevel = r.groups.find((g) => g.symbol === null);
+ assert.ok(moduleLevel, 'expected a file-level (symbol: null) group');
+ assert.equal(moduleLevel!.inDegree, 0);
+ assert.equal(moduleLevel!.path, 'src/b.ts');
+ assert.match(moduleLevel!.hits[0].text, /NEEDLE at module level/);
+});
+
+test('grepGraph: `in` filter narrows to matching file paths only', () => {
+ const repo = needleRepo();
+ const graph = loadBuiltGraph(repo);
+ const r = grepGraph(graph, repo, 'NEEDLE', { in: 'a.ts' });
+
+ assert.equal(r.filesSearched, 1);
+ assert.equal(r.totalHits, 2);
+ assert.ok(r.groups.every((g) => g.path === 'src/a.ts'));
+});
+
+test('grepGraph: `fixed` escapes regex metacharacters — "a.b" does not match "axb"', () => {
+ const d = mkdtempSync(join(tmpdir(), 'graft-grep-fixed-'));
+ writeFileSync(join(d, 'x.txt'), 'axb\na.b literal line\n');
+ const graph = graphOf([fileNode('x.txt', 2)]);
+
+ const asRegex = grepGraph(graph, d, 'a.b');
+ assert.equal(asRegex.totalHits, 2); // '.' matches any char -> matches both lines
+
+ const fixed = grepGraph(graph, d, 'a.b', { fixed: true });
+ assert.equal(fixed.totalHits, 1);
+ assert.match(fixed.groups[0].hits[0].text, /a\.b literal line/);
+});
+
+test('grepGraph: maxHits truncation surfaces in truncated.hits, not silently dropped', () => {
+ const d = mkdtempSync(join(tmpdir(), 'graft-grep-maxhits-'));
+ const lines = Array.from({ length: 10 }, (_, i) => `NEEDLE line ${i}`).join('\n') + '\n';
+ writeFileSync(join(d, 'many.txt'), lines);
+ const graph = graphOf([fileNode('many.txt', 10)]);
+
+ const r = grepGraph(graph, d, 'NEEDLE', { maxHits: 5 });
+ assert.equal(r.totalHits, 5);
+ assert.equal(r.truncated.hits, 5);
+ assert.equal(
+ r.groups.reduce((n, g) => n + g.hits.length, 0),
+ 5,
+ );
+});
+
+test('grepGraph: zero-hit result has the documented shape — empty groups, zero counts, non-silent truncated', () => {
+ const d = mkdtempSync(join(tmpdir(), 'graft-grep-zero-'));
+ writeFileSync(join(d, 'x.txt'), 'nothing interesting here\n');
+ const graph = graphOf([fileNode('x.txt', 1)]);
+
+ const r = grepGraph(graph, d, 'NOPE_NOT_PRESENT');
+ assert.equal(r.pattern, 'NOPE_NOT_PRESENT');
+ assert.equal(r.totalHits, 0);
+ assert.deepEqual(r.groups, []);
+ assert.equal(r.filesSearched, 1);
+ assert.deepEqual(r.truncated, { files: 0, hits: 0 });
+});
+
+test('grepGraph: unreadable file is skipped and counted into truncated.files, not silently ignored', () => {
+ const d = mkdtempSync(join(tmpdir(), 'graft-grep-unreadable-'));
+ writeFileSync(join(d, 'real.txt'), 'NEEDLE is here\n');
+ // 'missing.txt' is indexed in the graph but does not exist on disk.
+ const graph = graphOf([fileNode('real.txt', 1), fileNode('missing.txt', 1)]);
+
+ const r = grepGraph(graph, d, 'NEEDLE');
+ assert.equal(r.filesSearched, 2);
+ assert.equal(r.truncated.files, 1);
+ assert.equal(r.totalHits, 1);
+});