
AI coding agents default to text search even when a structural knowledge graph of the repository is available, because instructions in CLAUDE.md or rules files are suggestions rather than guarantees. A documented real-world review found Claude Code bypassing an installed Graphify integration entirely, reasoning that a small feature did not warrant a graph lookup. The reliable enforcement point sits at the tool-call boundary: a pre-execution hook that intercepts grep, ripgrep, and find commands and decides, per invocation, whether the graph should answer first. This article examines the smart-grep-hook decision ladder — an ordered, first-match-wins set of routing rules with a deliberate escalation from teaching to enforcement. It covers the ladder's silent-pass conditions, the --graph-tried escape hatch, wiring for Claude Code, Cursor, and other agentic tools, and the MCP serving layer that makes inline answers cheap. The intended audience is developers integrating Graphify into a daily agent workflow who already have, or plan to build, a repository graph.

A public review of Graphify documented a concrete failure mode: during a real feature‑building session, Claude Code bypassed the installed Graphify integration, opened source files directly, and when asked explicitly admitted it had not consulted the graph because the feature was small and it already knew the target files【5†content】. The reviewer observed the same pattern across several projects and ultimately uninstalled Graphify from all of them【5†content】.
The root cause lies in the way most coding‑agent scaffolds are built. A taxonomy of 13 popular agents shows that eight of them—including SWE‑agent, OpenHands, Codex CLI, Gemini CLI, Cline, and others—follow the LLM‑as‑Navigator paradigm: they expose generic shell tools such as grep, find, or ripgrep and leave all code‑understanding to the language model itself【1†content】. Because the scaffold provides no built‑in repository map or AST analysis, the model decides which files to read and which searches to run, making prompt‑embedded instructions (e.g., CLAUDE.md, AGENTS.md) merely suggestions that the model can ignore.
Harness‑engineering literature stresses that this separation is intentional: hooks enforce policy at the tool‑call boundary, while instruction files reside only in the model’s context and are therefore ignorable【6†content】. When enforcement is placed inside the model’s reasoning loop, the same “policy‑as‑prompt” problem reappears, exactly the scenario where agents skip the graph.
Claude Code already implements a fine‑grained permission system that gates roughly 40 discrete tool capabilities through an ordered allow/deny/ask chain, with the first matching rule winning【7†content】. This mechanism, originally designed for safety, can be repurposed to route retrieval: a pre‑execution hook intercepts every grep/rg/find request, checks the graph first, and decides whether to allow the raw search or return a graph‑derived answer.
Recommendation: treat graph‑access policy as a harness configuration rather than as prompt text. Define the smart‑grep‑hook ladder in the hook layer (e.g., silent passes for non‑code targets, --graph‑tried escape, first‑grep lessons) and rely on the agent’s existing allow/deny chain to enforce it. This shifts the guarantee from “the model was told to use the graph” to “the system will not let the model read files without consulting the graph first,” eliminating the documented bypass.

When an agent decides to invoke a tool—e.g., grep "TODO" src/**/*.js—the request is already serialized as a concrete command line with arguments. A pre‑tool‑use hook can therefore examine the full payload before any external process is launched. The hook runs synchronously, returns a decision, and only then is the command handed to the OS. Because the decision point is inside the agent harness, a model‑level prompt injection cannot bypass it.
| Agent / Framework | Hook name | Production status |
|---|---|---|
| Claude Code | PreToolUse | Production |
| Cursor | beforeShellExecution | Production |
| OpenClaw | before_tool_call plugin | Production |
| LangChain | on_tool_start callback | Production |
| CrewAI | @before_tool_call decorator | Production |
These hook points are defined in the Open Agent Passport reference implementation, which standardises the “blocking hook” pattern across 5+ platforms【source 7】.
The smart‑grep‑hook registers the three search‑tool names it cares about—grep, rg (ripgrep) and find. Each time one of these commands is about to run, the hook:
--graph-tried).nodes_fts). The index lookup runs in sub‑millisecond on‑CPU, requires no external process, and never touches the network. If the FTS query returns nothing, the hook falls back to a cheap LIKE scan on the same table.Because the entire decision chain stays on the developer’s machine, latency is negligible and no data leaves the host—an essential property for a per‑command gate.
The hook returns one of three vocabularies, deliberately mirroring classic allow/block/escalate governance models but extended for graph‑first workflows:
| Outcome | Behaviour | Why it matters |
|---|---|---|
| Silent allow | The command proceeds unchanged. Used when no graph is available or the user explicitly forces a raw search with --graph-tried. | |
| Deny with answer inline | The tool is blocked and the hook injects a concise answer derived from the graph (e.g., “no matches – the symbol lives in module X”). | Prevents unnecessary I/O and provides the agent with immediate, structured context. |
| Allow with graph context injected | The original grep/ripgrep/find runs after the hook prepends the graph‑derived snippet to the agent’s prompt. | This “allow‑with‑context” path is the pattern’s distinguishing move: it keeps the tool usable while still biasing the model toward graph‑based reasoning. |
The decision ladder follows a first‑match‑wins order (see the detailed table in the smart‑grep‑hook review)【source 6】, ensuring that the most specific rule (e.g., an explicit override flag) wins over broader defaults. Implementations must guard against API changes; for example, Claude Code moved the PreToolUse hook from settings.json to a separate skill.md file in version 2.3, and LangChain renamed on_tool_start to on_tool_execute in its 0.2 release. Keeping the hook registration code version‑aware is therefore a required maintenance step.

The smart‑grep‑hook follows a first‑match‑wins ladder whose explicit design goal is zero false positives: a graph lookup is performed only when the hook can be sure it will improve the answer, otherwise the command proceeds silently. The ladder is ordered from permissive to restrictive, so early rungs keep the hook invisible when the graph cannot help, and later rungs enforce a one‑shot teaching moment before blocking redundant greps.
| Rung | Condition | Behaviour |
|---|---|---|
| 1 | No graph file (.code-review-graph/graph.db) in the current repository and no sibling repos registered in the multi‑repo registry. | Silent pass – the hook does nothing, avoiding noise. |
| 2 | The grep pattern targets non‑code files (*.md, *.json, *.log, *.jsonl). | Silent pass – the AST‑based graph indexes only source code, so plain text search is correct. |
| 3 | The command contains the --graph‑tried escape (usually as a comment). | Silent pass – the agent explicitly tells the hook that the graph has already been consulted or that it should be skipped. |
| 4 | Grep is run on an absolute path outside the working directory and the target directory contains a graph. | The hook queries that remote graph, injects the result as inline context, then allows the grep to run. |
| 5 | Absolute‑path grep with no graph found in the target hierarchy. | Silent pass – the hook falls back to the original grep. |
| 6 | No local graph, but a registered sibling repository matches the search pattern. | The sibling’s graph result is shown as context, and the grep proceeds. |
| 7 | First grep of the session that hits a local graph. | Both the graph answer and the grep output are returned – a one‑time lesson that lets the agent compare the two sources. |
| 8 | First grep of the session with no graph hit. | Grep runs normally, and the hook suggests using the MCP (multi‑repo cache proxy) tool for future look‑ups. |
| 9 | Any subsequent grep in the same session that hits a graph. | The command is denied; the graph answer is returned inline, so the agent incurs no retry cost. |
The escalation philosophy is therefore teach once, then enforce: rungs 1–6 keep the hook transparent, rungs 7–8 provide a teaching moment, and rung 9 blocks repetition that would otherwise waste compute cycles.
When a graph lookup is required, the hook resolves the source in three ordered steps (see the reference implementation) ¹:
.code-review-graph/graph.db file inside the current working directory..code-review-graph/ directory is found.code-review-graph repos) that merges graphs from all registered sibling repositories, optionally backed by a merged global graph (e.g., ~/obsidian-vault/merged-graph.json).If a lookup succeeds at a higher‑priority level, lower levels are never consulted.
Agents can bypass the hook by appending # --graph‑tried to the command line ². The comment is detected by the hook and treated as an explicit override, ensuring that legitimate greps are never more than one retry away.
Note: Directory names (
.code-review-graph/), registry commands, and rung ordering reflect the documented setup at the time of writing. Verify against the currentsmart-grep-hookscript before relying on them.

# --graph‑tried as a CommentThe smart‑grep‑hook decides whether a greppable command should be answered by the repository graph or fall back to a traditional text search. When the agent has already consulted the graph—or when the request targets data the AST‑based graph cannot represent (raw string literals, configuration values, log entries, or code in an unindexed language)—the hook allows an explicit override. The convention is to append # --graph‑tried as a shell comment to the original command, e.g.:
grep -rn "TODO" src/ # --graph‑tried
ugrep on macOS) reject unknown flags and abort the command. A comment is ignored by the shell and passes through unchanged, guaranteeing that the underlying grep still runs.| Situation | Hook response |
|---|---|
| The agent has previously queried the graph for the same term. | Recognises # --graph‑tried and lets grep execute (the graph‑first path has already been taken). |
| The query addresses content outside the graph’s scope (e.g., literal strings, config files, logs). | Same override applies; the graph cannot index such items, so a direct file search is appropriate. |
A hard denial would terminate the command, forcing the agent into a retry loop that wastes tokens and latency. By contrast, the escape hatch permits one‑shot greps after a graph lookup, preserving throughput while keeping the graph‑first policy as the default. This “soft‑block” model reduces friction and encourages agents to attempt the graph first without risking permanent failure.
The hook records the first‑grep allowance in an hourly bucket under a cache directory, e.g.:
~/.cache/claude-graph-hook/first-grep-<repo-hash>-<YYYYMMDDHH>
The allowance resets each hour, ensuring that teaching opportunities are short‑lived and do not accumulate indefinitely.
Every bypass is written to bypass.log, creating a lightweight audit trail. Repeated patterns in this log highlight queries that consistently miss the graph, signalling gaps in coverage. Teams can regularly review the log and promote high‑frequency misses into custom graph indexes or documented FAQs, turning what would be a policy leak into a constructive feedback loop [source].
By embedding # --graph‑tried into the tool‑call contract, developers retain the safety of a graph‑first strategy while granting agents a precise, low‑overhead escape when the graph is not the right tool.

| File (git status) | Purpose | Typical contents |
|---|---|---|
.claude/settings.json (committed) | Holds only permissions – no hooks, so teammates who lack Graphify won’t be forced to run them. | json\n{ "permissions": { "allow": ["read", "write"] } }\n |
.claude/settings.example.json (committed) | Serves as a reference that documents the complete hook structure (SessionStart, PreToolUse, Stop). Team members copy it when they set up the project. | json\n{ "hooks": { "SessionStart": [], "PreToolUse": [], "Stop": [] } }\n |
.claude/settings.local.json (git‑ignored) | The runtime file where the actual hooks live. Copied from the example on first setup and then edited with personal paths, environment variables, or secret keys. | (contains the concrete hook objects – see below) |
This layout keeps the repository clean: the committed files define the contract, while the local file activates the behavior only for developers who have installed Graphify. Individual hooks can be lifted into the global ~/.claude/settings.json to reuse them across projects.
Add a SessionStart entry to settings.local.json that injects ~150 tokens at the start of every Claude Code session iff a graph exists. The payload typically includes:
| Pattern | Graphify CLI | Example |
|---|---|---|
where‑is‑X | graphify query "<X>" | where‑is‑payment → graphify query "payment" |
who‑calls‑X | graphify query "callers_of X" | |
pre‑refactor‑blast | graphify impact‑radius X | |
cluster‑questions | graphify community X | |
review‑context | graphify review‑context X | |
misses | graphify query-cli | |
A‑to‑B | graphify path A B |
--graph-tried escape hatch flag that agents can append to a tool call to bypass the graph for a particular invocation.{
"hooks": {
"SessionStart": [
{
"type": "inject",
"content": "Graphify graph available: 12 k nodes, 45 k edges. Use the query‑to‑tool map (where‑is‑X → graphify query, who‑calls‑X → graphify query \"callers_of …\", …). Files in .gitignore are skipped. Append --graph‑tried to any grep/rg/find to skip the graph."
}
]
}
}
{
"hooks": {
"PreToolUse": [
{
"toolPattern": "(grep|rg|find|glob)",
"action": "inject",
"content": "graphify: Knowledge graph exists. Read GRAPH_REPORT.md and run the appropriate graphify query before searching raw files."
}
]
}
}
The hook fires once per session and decides, based on the --graph-tried flag or the skip list, whether the graph should answer first.
| Command | What it does |
|---|---|
graphify claude install | Writes a minimal set of rules to CLAUDE.md and adds a PreToolUse hook that injects the graph prompt before every Glob/Grep call【3†source】. |
graphify install --project --strict | Enables strict mode: the first raw source read of a session is blocked and redirected to the graph, then the system falls back to the soft‑nudge. The hook fires at most once per session and never wedges【3†source】. |
| Runtime toggle | GRAPHIFY_HOOK_STRICT=1 enables strict mode; 0 disables it. This allows per‑run experimentation without reinstalling. |
settings.json with a different whitespace or ordering, causing Claude Code to ignore the PreToolUse block. Verify that the file still contains the exact hook objects and, if needed, copy the original structure from Graphify’s skill documentation【1†source】.GRAPHIFY_SKIP, GRAPHIFY_TRIED) and the exact environment‑variable name (GRAPHIFY_HOOK_STRICT) have changed between Graphify v2.1 and v2.3; always consult the release notes or the installer output for the version you are using.By committing the example and permission‑only settings, providing a local runtime file with the SessionStart cheatsheet and PreToolUse enforcement, and using Graphify’s installer‑generated hooks, teams can reliably route Claude Code’s search operations through the repository graph while keeping the configuration portable and safe for collaborators who have not yet installed the tooling.

The smart‑grep‑hook pattern relies on a pre‑execution interception that can decide, before a grep, rg, or find runs, whether the repository graph should answer first. Different agents expose this interception under distinct API names, but they all share the same semantics of a blocking hook that returns a decision before the tool is invoked. The Open Agent Passport (OAP) reference lists the production‑grade equivalents as 【1†L1-L9】:
| Agent | Hook name | Status |
|---|---|---|
| Claude Code | PreToolUse | Production |
| Cursor | beforeShellExecution | Production |
| OpenClaw | before_tool_call plugin | Production |
| LangChain | on_tool_start callback | Production |
| CrewAI | @before_tool_call decorator | Production |
If an assistant does not expose a hook, the only reachable control surface is an instruction file that is concatenated into the system prompt. Examples include AGENTS.md for terminal‑based agents, CLAUDE.md for Anthropic, and .cursorrules (with an alwaysApply flag) for Cursor. These files are nudges—the model may ignore them, which is the exact weakness the ladder is designed to close.
Agents such as Aider, Trae, and similar platforms lack a pre‑tool hook. The recommended workaround is to codify the ladder’s “silent‑pass” rules directly in the instruction file (e.g., AGENTS.md or a .cursorrules file). The file should state, in plain prose, that the agent must skip graph lookup for pure configuration files, prefer scoped queries for code, and use the --graph-tried comment convention to signal a failed graph attempt. Because these are prompt‑only controls, compliance depends on the model faithfully following the directives.
The graphify-mcp-tools package provides a single entry point that adapts the ladder to each supported editor/agent. The command syntax is:
graphify-mcp-tools install --target <editor> [--graph <path>]
--target (required) selects one of opencode, cursor, claude, or vscode.--graph (optional) points to the graphify-out/ directory; it defaults to ./graphify-out.Running the installer performs four coordinated actions for the chosen target 【2†L1-L9】:
graphify-mcp-tools.yml manifest that records paths and version metadata.| Target | MCP config | Hook / Rule | Skill location | Manifest |
|---|---|---|---|---|
| Cursor | .cursor/mcp.json | .cursor/rules/graphify-mcp-tools.mdc (alwaysApply) | Embedded in the rule file | .cursor/graphify-mcp-tools.yml |
| Claude | Manual claude mcp add (CLI) | .claude/settings.json (PreToolUse) | .claude/skills/graphify-mcp-tools/SKILL.md | .claude/graphify-mcp-tools.yml |
| VS Code | .vscode/mcp.json | Copilot‑Chat instruction markdown | Embedded in the instruction file | .vscode/graphify-mcp-tools.yml |
| OpenCode | .opencode/opencode.json | .opencode/plugins/graphify-mcp-tools.js | .opencode/skills/graphify-mcp-tools/SKILL.md | .opencode/graphify-mcp-tools.yml |
The installer automatically detects 17 supported assistants and applies the appropriate layout 【3†L1-L9】, making the process version‑sensitive: a future release that adds or removes an assistant will change the generated files.
When only instruction files are available:
*.md, *.yaml, or *.toml.”--graph-tried comment: after a failed graph lookup, the agent should append # --graph-tried to the command line, allowing downstream tooling to recognize that the graph was consulted.Because these are prompt‑only controls, the enforcement point is weaker than a true pre‑tool hook. Teams should monitor compliance (e.g., via log analysis) and consider migrating to an assisted platform once a native hook becomes available.

The Graphify build process can launch an MCP server directly from the emitted graph.json:
python -m graphify.serve graphify-out/graph.json # stdio (default)
python -m graphify.serve graphify-out/graph.json \
--transport http --port 8080 \
--host 0.0.0.0 --api-key "$GRAPHIFY_API_KEY"
stdio runs locally for a single developer; http exposes the same set of tools to a whole team behind a self‑hosted endpoint.graphify package; no external services are involved.query_graphget_nodeget_neighborsshortest_pathlist_prsget_pr_impacttriage_prsThese tools give agents precise, low‑token answers instead of scanning the repository with grep. The built‑in server is documented on the Graphify GitHub repository ➡️.
For environments that prefer a pure‑JavaScript runtime, the companion package provides an MCP server with a richer feature set:
graph.json is imported into an in‑memory SQLite database via the sql.js WebAssembly engine.| Tool | What it does |
|---|---|
graph_search | Indexed text search with type and repository filters |
graph_impact | BFS blast‑radius analysis (up/downstream dependents) |
graph_path | Weighted Dijkstra shortest‑path with edge‑type filters |
graph_explain | Node detail plus community membership and centrality metrics |
graph_community | Ranked listing of community members |
graph_hotspots | “God‑node” detection using degree, in/out‑degree, betweenness |
graph_outline | Tree‑sitter generated code outlines (functions, classes, signatures) |
graph_status | Metadata about node/edge counts, repos, build timestamp |
The architecture diagram and API surface are described in the graphify-mcp-tools documentation ➡️.
Graphify’s own data sheet reports a 60‑80 % reduction in token consumption when agents query the graph instead of raw files ➡️.
Typical MCP‑tool responses fall in the range of 70–170 tokens (e.g., impact‑radius, callers‑of, importers, review‑context, community listings). By contrast, a full‑graph CLI query can exceed 1 500 tokens, making it appropriate only for occasional deep‑dive investigations. The cheap, inline answers produced by the smart‑grep‑hook therefore stay well within model context windows and keep cost low.
Both servers are self‑hosted: the vendor never touches your graph data.
stdio mode – serves a single machine, ideal for local development.http mode – runs behind your firewall, allowing multiple agents (Claude Code, Cursor, etc.) to share a common endpoint.Choosing between the Python built‑in server and the Node.js companion depends on your existing stack and the need for advanced analyses such as indexed search or centrality‑based hotspot detection. Either option provides the cheap, precise query surface that the smart‑grep‑hook relies on to replace blind text searches with graph‑driven answers.

A stale graph is more damaging than no graph at all: when the graph returns an answer that no longer matches the source, the agent learns to bypass the hook entirely. The hook’s reliability therefore hinges on keeping the lightweight graph in sync with each turn while relegating the heavyweight full‑repo rebuild to background Git hooks.
| Trigger | What updates | Typical latency | Guarding |
|---|---|---|---|
Claude Code Stop hook | Light‑weight graph (AST + symbol index) | ≈ 0.4 s | PID‑file guard ensures a single update per turn; fires once after the AI finishes all edits |
PostToolUse | Same lightweight update (if misused) | – | Fires after every file edit; the guard’s millisecond race window fails under concurrent edits, leading to dozens of spawned processes, load‑average > 12 and memory saturation (observed in production) |
Git post‑commit / post‑checkout | Full graphify update (full rebuild) | 10 s + on a real monorepo | Runs as a background nohup process; smart diff logic: ≤ 5 changed files → incremental update, > 5 or branch change → full rebuild |
The lightweight update is safe to run on every turn because it touches only the changed symbols and finishes before the next turn begins. The heavyweight update, which re‑processes the entire codebase, would block the session if run inside a turn hook; therefore it belongs in Git hooks where it can run asynchronously without affecting the agent’s responsiveness.
“
PostToolUsefires after every individual file edit … the result is multiple CRG Python processes piling up, load average hits 12+, RAM saturates …Stopfires once … zero pile‑up by design.” – dev.to article
A benchmark on a 1336‑node TypeScript monorepo measured token consumption for different retrieval strategies:
| Query type | Grep + read (tokens) | Graphify query (tokens) |
|---|---|---|
Simple symbol lookup (e.g., createThread) | ~ 594 | ~ 1532 (CRG semantic answer ≈ 115) |
| Multi‑file pattern (e.g., UI state layer) | ~ 1069 | ~ 1552 (semantic miss → graph → grep) |
| Exact string in config / logs | 114 | 1538 (graph not needed) |
| Import‑graph traversal | ~ 437 | ~ 1563 (semantic answer ≈ 80) |
| Error handling snippet | 2220 chars (≈ >2 k tokens) | ~ 1538 (semantic answer ≈ 477 chars) |
The hidden cost of grep is the subsequent file read; a typical grep‑plus‑read scenario totals 1 300 – 2 500 tokens per question. By contrast, a CRR (graph‑first) answer can be delivered as a file:line pair, eliminating the follow‑up read and capping the token budget at 80 – 170 tokens for the same question.
“After a grep hit the model usually reads the matched file — a typical grep + follow‑up read costs 1300–2500 tokens per question.” – dev.to benchmark
Exact‑string searches (e.g., looking for a literal JSON key, a log line, or a configuration flag) are still faster with traditional grep/rg. The smart‑grep‑hook provides an explicit escape hatch (--graph-tried) that developers can attach to such commands, ensuring the hook bypasses the graph and runs the raw search without penalty.
Embedding‑based semantic search can miss precise symbol names; the documented case study recorded misses on two concrete symbols. The prescribed resolution chain is:
The session cheatsheet should prominently list this order so developers know when to promote a missed grep into an indexed graph entry.
--graph-tried flags or repeated grep invocations; these indicate patterns where the graph is either stale or insufficient.By keeping the lightweight graph fresh each turn, relegating full rebuilds to background Git hooks, and continuously auditing token budgets, you close the feedback loop that prevents agents from learning to distrust the smart‑grep‑hook pattern.