fix(hooks): include dedicated Grep in the strict orientation gate

Share Read’s existing one-denial-per-session gate with dedicated Grep, respecting the query stamp and project/output boundaries. Bash and Glob remain advisory. Pass --strict through installed search hooks and document both-mode silence for irrelevant targets.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 6f38228510)
This commit is contained in:
Andre Brait authored and safishamsi committed 2026-11-03 21:36:55 +00:00
1 parent cb408949e1
commit 2a5d442632
5 files changed
+218 -33

No files matched your search

+3 -1
View File
@@ -253,7 +253,9 @@ Codex users also need `multi_agent = true` under `[features]` in `~/.codex/confi
`--platform agents` (alias `--platform skills`) targets the generic cross-framework [Agent-Skills](https://github.com/anthropics/skills) locations: the spec's user-global `~/.agents/skills/` (read by `npx skills` and spec-compliant frameworks) for a global install, and `./.agents/skills/` for a project (`--project`) install. The bare `graphify install` stays single-platform (Claude Code) by design: use the named `agents` platform when you want the skill discoverable by any framework that reads `.agents/skills`.
Pi has no `PreToolUse` hook, so `graphify pi guard install` registers a native Pi extension (via Pi's own `pi install <package directory>`) that runs the installed `graphify hook-guard` before Pi's `read`, `grep`, `find` and search-style `bash` calls. Fresh/stale graph decisions and the `GRAPHIFY_HOOK_STRICT=1` once-per-session indexed-read denial come from that same policy, so Pi matches Claude Code's hook behavior; guidance arrives as a `<system-reminder source="graphify">` steering message. It needs Pi 0.58.4 or newer: earlier versions let a steering message skip the rest of a parallel tool-call batch. The package ships inside the Graphify installation, so install Graphify persistently (`uv tool install graphifyy` or `pipx install graphifyy`, not `uvx`), restart Pi after installing or upgrading, and remove it with `graphify pi guard uninstall`. Only local file targets are inspected; the hook needs `graphify` on an absolute `PATH` entry outside the project, is bounded to a two-second, 256 KiB-in/64 KiB-out call, and fails open. The same package also loads in [Oh My Pi](https://github.com/can1357/oh-my-pi): `omp plugin install "$(graphify pi guard path)"`. The registered path contains the Python version and venv, so re-run `graphify pi guard install` after changing either, and remove the old entry with `pi remove <old path>`.
Claude Code's `graphify install --project --strict` makes Read and dedicated Grep share one denial per session unless a recent graph query has oriented the agent (default 30 minutes). Grep may target a directory; it does not need an indexed-file match. External and graph-output Grep targets produce neither a deny nor a nudge, in soft mode as well as strict mode, matching Read's scope. A graph marked `needs_update` never triggers a Grep denial. Bash searches and Glob stay advisory. `GRAPHIFY_HOOK_STRICT=1` enables the policy without reinstalling; `GRAPHIFY_HOOK_STRICT=0` disables it even when installed with `--strict`. Existing strict installs need a reinstall to add the search hook's `--strict` flag, or the environment override.
Pi has no `PreToolUse` hook, so `graphify pi guard install` registers a native Pi extension (via Pi's own `pi install <package directory>`) that runs the installed `graphify hook-guard` before Pi's `read`, `grep`, `find` and search-style `bash` calls. Fresh/stale graph decisions and the `GRAPHIFY_HOOK_STRICT=1` once-per-session denial shared by indexed Read and dedicated Grep come from that same policy, so Pi matches Claude Code's hook behavior; Bash and file listing remain advisory. Guidance arrives as a `<system-reminder source="graphify">` steering message. It needs Pi 0.58.4 or newer: earlier versions let a steering message skip the rest of a parallel tool-call batch. The package ships inside the Graphify installation, so install Graphify persistently (`uv tool install graphifyy` or `pipx install graphifyy`, not `uvx`), restart Pi after installing or upgrading, and remove it with `graphify pi guard uninstall`. Only local file targets are inspected; the hook needs `graphify` on an absolute `PATH` entry outside the project, is bounded to a two-second, 256 KiB-in/64 KiB-out call, and fails open. The same package also loads in [Oh My Pi](https://github.com/can1357/oh-my-pi): `omp plugin install "$(graphify pi guard path)"`. The registered path contains the Python version and venv, so re-run `graphify pi guard install` after changing either, and remove the old entry with `pi remove <old path>`.
> Codex uses `$graphify` instead of `/graphify`.
+52 -21
View File
@@ -72,6 +72,18 @@ _READ_DENY = json.dumps({
),
}
}, ensure_ascii=False, separators=(",", ":")) + "\n"
_SEARCH_DENY = json.dumps({
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": (
'graphify strict mode: this project has a knowledge graph. Run '
'`graphify query "<your question>"` (or `graphify explain` / '
'`graphify path`) FIRST to orient yourself, then re-issue this Grep — '
'it will be allowed. This block fires at most once per session.'
),
}
}, ensure_ascii=False, separators=(",", ":")) + "\n"
_HOOK_SOURCE_EXTS = (
'.py', '.js', '.cjs', '.ts', '.tsx', '.jsx', '.astro', '.vue', '.svelte', '.ejs', '.go',
'.rs', '.java', '.rb', '.c', '.h', '.cpp', '.hpp', '.cc', '.cs', '.kt',
@@ -969,7 +981,7 @@ def _touch_query_stamp(graph_path: "Path") -> None:
def _query_stamp_fresh() -> bool:
"""True if a query/explain/path ran within GRAPHIFY_HOOK_STRICT_TTL (default
1800s) — recent orientation, so strict mode does not block this read."""
1800s) — recent orientation, so strict mode does not block raw Read/Grep."""
from graphify.paths import out_path
try:
ttl = float(os.environ.get("GRAPHIFY_HOOK_STRICT_TTL", "1800"))
@@ -1176,14 +1188,12 @@ def _run_hook_guard(kind: str, strict: bool = False) -> None:
Fails open everywhere: any error, or a non-matching tool call, prints nothing
and the caller exits 0, so a legitimate tool call is never blocked by a bug.
In strict mode (opt-in, Claude Code Read only) the FIRST raw read of indexed,
in-project, fresh code per session is DENIED with a redirect to `graphify query`
(permissionDecision), then downgrades to the soft nudge — it fires at most once
per session and can never strand the agent. Search (Bash) and Glob stay
nudge-only: a compound shell command has no single parseable target and blocking
file listing would strand navigation. #1840: reads of out-of-project files are
ignored, and a graph that is stale for the target file softens to a non-mandatory
nudge instead of blocking or demanding.
In strict mode (opt-in), the FIRST raw Read of indexed, fresh code or dedicated
Grep in the project is DENIED with a redirect to `graphify query`, then
downgrades to the soft nudge. The two tools share one block per session.
Bash and Glob stay nudge-only: a compound shell command has no single
parseable target and blocking file listing would strand navigation.
Out-of-project and graph-output targets are ignored; stale graphs never block.
"""
from graphify.paths import out_path
# Gemini's BeforeTool hook takes no stdin and must ALWAYS return a decision so
@@ -1213,16 +1223,37 @@ def _run_hook_guard(kind: str, strict: bool = False) -> None:
# Two input shapes reach this guard (matcher "Bash|Grep", #1986):
# the Bash tool carries `command`, while Claude Code's dedicated
# Grep tool carries `pattern` (plus optional path/glob) and no
# command — a Grep call IS a content search by definition, so it
# nudges whenever a graph exists. For Bash, decide on the
# command's EXECUTED tokens (#3121): the old whole-string
# substring scan fired on quoted prose ('add flag support'
# contains "ag ") and on heredoc bodies that merely mention
# grep. Nudge-only, even in strict mode — see the docstring.
is_grep_tool = not cmd_str and bool(t.get("pattern"))
# command. Grep is scoped below to the project's source targets.
# Bash searches remain advisory: compound shell commands have no
# single reliable target.
pattern = t.get("pattern")
is_grep_tool = not cmd_str and isinstance(pattern, str) and bool(pattern) \
and d.get("tool_name") in (None, "Grep")
is_bash_search = bool(cmd_str) and _bash_invokes_search(cmd_str)
if (is_grep_tool or is_bash_search) and out_path("graph.json").is_file() \
and _nudge_allowed(d):
if not (is_grep_tool or is_bash_search) or not out_path("graph.json").is_file():
return
if is_grep_tool:
path = t.get("path", ".")
if not isinstance(path, str):
return
root = Path(os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()).resolve()
target = Path(path.replace("\\", "/"))
if _is_cwd_relative(path):
target = root / target
target = target.resolve()
if not target.is_relative_to(root):
return
for output in (out_path(), root / "graphify-out"):
if _is_cwd_relative(str(output)):
output = root / output
if target.is_relative_to(output.resolve()):
return
if _hook_strict_enabled(strict) and not out_path("needs_update").exists() \
and not _query_stamp_fresh() \
and _mark_session_denied(str(d.get("session_id") or "")):
sys.stdout.write(_with_hint(_SEARCH_DENY, terms=_search_hint_terms(t)))
return
if _nudge_allowed(d):
sys.stdout.write(_with_hint(_nudge_for_out(_SEARCH_NUDGE), terms=_search_hint_terms(t)))
elif kind == "read":
vals = [str(t.get("file_path") or ""), str(t.get("pattern") or ""), str(t.get("path") or "")]
@@ -3004,9 +3035,9 @@ def dispatch_command(cmd: str) -> None:
# Shell-agnostic Claude/Codebuddy PreToolUse guard (#522). Replaces the old
# inline-bash hooks that failed on Windows. Prints an additionalContext nudge
# toward graphify when a fresh in-project graph exists; always exits 0. In
# strict mode (opt-in, `hook-guard read --strict`) it blocks the first raw
# read per session via the JSON permissionDecision payload — never via exit
# code — and downgrades to the nudge thereafter.
# strict mode (opt-in, `hook-guard <read|search> --strict`) it blocks the
# first raw Read or dedicated Grep per session via the JSON permissionDecision
# payload — never via exit code — and downgrades to the nudge thereafter.
_run_hook_guard(
sys.argv[2] if len(sys.argv) > 2 else "",
strict="--strict" in sys.argv[3:],
+11 -8
View File
@@ -488,9 +488,9 @@ def _claude_pretooluse_hooks(strict: bool = False, project: bool = False) -> "li
content search through its dedicated Grep tool, not Bash (#1986) — a
Bash-only matcher never fired on the agent's primary search path.
When ``strict`` is set, the read hook carries ``--strict`` so it blocks the
first raw read per session (Claude Code only). The ``GRAPHIFY_HOOK_STRICT`` env
var can force it on or off at runtime without a reinstall.
When ``strict`` is set, both hooks carry ``--strict`` so Read and dedicated
Grep share one block per session; Bash and Glob remain advisory. The
``GRAPHIFY_HOOK_STRICT`` env var can force it on or off without a reinstall.
Each entry carries a ``timeout`` (#3314): unset, Claude Code defaults a
command hook to 600s, so a single wedged guard (a stuck filesystem, a
@@ -504,9 +504,10 @@ def _claude_pretooluse_hooks(strict: bool = False, project: bool = False) -> "li
if " " in exe and not exe.startswith('"'):
exe = f'"{exe}"'
read_cmd = f"{exe} hook-guard read" + (" --strict" if strict else "")
search_cmd = f"{exe} hook-guard search" + (" --strict" if strict else "")
return [
{"matcher": "Bash|Grep",
"hooks": [{"type": "command", "command": f"{exe} hook-guard search", "timeout": 10}]},
"hooks": [{"type": "command", "command": search_cmd, "timeout": 10}]},
{"matcher": "Read|Glob",
"hooks": [{"type": "command", "command": read_cmd, "timeout": 10}]},
]
@@ -1028,8 +1029,9 @@ def _print_install_usage() -> None:
platforms = ", ".join([*_PLATFORM_CONFIG, "gemini", "cursor"])
print("Usage: graphify install [--project] [--strict] [--platform P|P]")
print(f"Platforms: {platforms}")
print(" --strict block the first raw file read per session until one "
"`graphify query` runs (Claude Code project hook only; needs --project)")
print(" --strict block the first raw Read or dedicated Grep per session "
"unless recently oriented with `graphify query` "
"(Claude Code project hooks only; needs --project; Bash/Glob stay advisory)")
_CLAUDE_MD_MARKER = "## graphify"
_CODEBUDDY_MD_MARKER = "## graphify"
_AGENTS_MD_MARKER = "## graphify"
@@ -2236,8 +2238,9 @@ def claude_install(project_dir: Path | None = None, strict: bool = False, projec
print("Claude Code will now check the knowledge graph before answering")
print("codebase questions and rebuild it after code changes.")
if strict:
print("Strict mode: the first raw file read per session is blocked until")
print("one `graphify query` runs (toggle with GRAPHIFY_HOOK_STRICT=0).")
print("Strict mode: Read and dedicated Grep share one block per session")
print("unless recently oriented with `graphify query`; Bash/Glob stay advisory.")
print("Toggle with GRAPHIFY_HOOK_STRICT=0.")
def _install_claude_hook(project_dir: Path, strict: bool = False, project: bool = False) -> None:
"""Add graphify PreToolUse hook to .claude/settings.json.
+4 -3
View File
@@ -207,9 +207,10 @@ def test_install_hook_carries_strict_flag():
read_strict = next(h for h in strict if h["matcher"] == "Read|Glob")["hooks"][0]["command"]
assert read_soft.endswith("hook-guard read")
assert read_strict.endswith("hook-guard read --strict")
# search hook is unchanged either way
for hooks in (soft, strict):
assert next(h for h in hooks if h["matcher"] == "Bash|Grep")["hooks"][0]["command"].endswith("hook-guard search")
search_soft = next(h for h in soft if h["matcher"] == "Bash|Grep")["hooks"][0]["command"]
search_strict = next(h for h in strict if h["matcher"] == "Bash|Grep")["hooks"][0]["command"]
assert search_soft.endswith("hook-guard search")
assert search_strict.endswith("hook-guard search --strict")
def test_strict_deny_shows_the_files_graph_nodes(tmp_path, monkeypatch):
+148
View File
@@ -0,0 +1,148 @@
"""Dedicated Grep shares Read's once-per-session strict orientation gate."""
import io
import json
import time
import pytest
from tests.test_hook_strict import _fixture, _invoke, _is_deny, _read
def _grep(path=None, sid="s1"):
tool_input = {"pattern": "load_config"}
if path is not None:
tool_input["path"] = str(path)
return {"session_id": sid, "tool_name": "Grep", "tool_input": tool_input}
def test_first_grep_denies_then_nudges(tmp_path, monkeypatch):
_fixture(tmp_path, indexed=False) # directory searches need no manifest match
payload = _grep(tmp_path / "src")
first = _invoke("search", payload, tmp_path, monkeypatch, strict=True)
assert _is_deny(first)
reason = json.loads(first)["hookSpecificOutput"]["permissionDecisionReason"]
assert "graphify query" in reason and "Grep" in reason and "Read" not in reason
second = _invoke("search", payload, tmp_path, monkeypatch, strict=True)
assert not _is_deny(second) and "knowledge graph at" in second
def test_fresh_query_bypasses_grep_deny(tmp_path, monkeypatch):
_fixture(tmp_path)
stamp = tmp_path / "graphify-out" / "cache" / "last_query_stamp"
stamp.parent.mkdir(parents=True)
stamp.write_text(str(time.time()), encoding="utf-8")
out = _invoke("search", _grep(), tmp_path, monkeypatch, strict=True)
assert not _is_deny(out) and "knowledge graph at" in out
assert _invoke("search", _grep(), tmp_path, monkeypatch, strict=True) == ""
@pytest.mark.parametrize("strict,env,denied", [
(False, {}, False),
(True, {}, True),
(False, {"GRAPHIFY_HOOK_STRICT": "1"}, True),
(True, {"GRAPHIFY_HOOK_STRICT": "0"}, False),
])
def test_grep_strict_flag_and_environment(tmp_path, monkeypatch, strict, env, denied):
_fixture(tmp_path)
out = _invoke("search", _grep(), tmp_path, monkeypatch, strict=strict, env=env)
assert _is_deny(out) is denied
assert "graphify query" in out
@pytest.mark.parametrize("first_kind", ["read", "search"])
def test_read_and_grep_share_one_deny(tmp_path, monkeypatch, first_kind):
f = _fixture(tmp_path)
calls = [("read", _read(f)), ("search", _grep())]
if first_kind == "search":
calls.reverse()
first, second = calls
assert _is_deny(_invoke(*first, tmp_path, monkeypatch, strict=True))
out = _invoke(*second, tmp_path, monkeypatch, strict=True)
assert not _is_deny(out) and "knowledge graph at" in out
@pytest.mark.parametrize("target", ["external", "../outside", "graphify-out", "graphify-out/graph.json"])
def test_grep_external_and_output_paths_bypass(tmp_path, monkeypatch, target):
_fixture(tmp_path)
path = tmp_path.parent / "outside" if target == "external" else target
assert _invoke("search", _grep(path), tmp_path, monkeypatch, strict=True) == ""
# Bypassed searches must not consume the session's deny.
assert _is_deny(_invoke("search", _grep(), tmp_path, monkeypatch, strict=True))
@pytest.mark.parametrize("target", ["external", "../outside", "graphify-out", "graphify-out/graph.json"])
def test_soft_grep_suppresses_irrelevant_path_nudges(tmp_path, monkeypatch, target):
_fixture(tmp_path)
path = tmp_path.parent / "outside" if target == "external" else target
assert _invoke("search", _grep(path), tmp_path, monkeypatch, strict=False) == ""
assert "knowledge graph at" in _invoke("search", _grep("src"), tmp_path, monkeypatch, strict=False)
def test_grep_custom_output_bypasses(tmp_path, monkeypatch):
from graphify import paths
_fixture(tmp_path)
custom = tmp_path / "artifacts" / "graphify"
custom.mkdir(parents=True)
(custom / "graph.json").write_text('{"nodes":[],"links":[]}', encoding="utf-8")
monkeypatch.setattr(paths, "GRAPHIFY_OUT", str(custom))
assert _invoke("search", _grep("artifacts/graphify"), tmp_path, monkeypatch, strict=True) == ""
assert _invoke("search", _grep("graphify-out"), tmp_path, monkeypatch, strict=True) == ""
assert _is_deny(_invoke("search", _grep("src"), tmp_path, monkeypatch, strict=True))
@pytest.mark.parametrize("state", ["no_session", "no_graph", "needs_update", "marker_error"])
def test_grep_safe_without_gate_prerequisites(tmp_path, monkeypatch, state):
_fixture(tmp_path)
payload = _grep()
out_dir = tmp_path / "graphify-out"
if state == "no_session":
payload.pop("session_id")
elif state == "no_graph":
(out_dir / "graph.json").unlink()
elif state == "needs_update":
(out_dir / "needs_update").touch()
else:
(out_dir / "cache").write_text("not a directory", encoding="utf-8")
out = _invoke("search", payload, tmp_path, monkeypatch, strict=True)
assert not _is_deny(out)
assert not (out_dir / "cache" / "hook_sessions" / "s1.denied").exists()
@pytest.mark.parametrize("payload", [
b"{not json", [], {"tool_input": []},
{"session_id": "s1", "tool_name": "Grep", "tool_input": {"pattern": ["foo"]}},
{"session_id": "s1", "tool_name": "Grep", "tool_input": {"pattern": "foo", "path": ["src"]}},
])
def test_grep_bad_payload_fails_open(tmp_path, monkeypatch, payload):
_fixture(tmp_path)
out = _invoke("search", payload, tmp_path, monkeypatch, strict=True)
assert not _is_deny(out)
def test_non_grep_tool_with_a_pattern_cannot_consume_the_deny(tmp_path, monkeypatch):
_fixture(tmp_path)
payload = _grep()
payload["tool_name"] = "Bash"
assert _invoke("search", payload, tmp_path, monkeypatch, strict=True) == ""
assert _is_deny(_invoke("search", _grep(), tmp_path, monkeypatch, strict=True))
@pytest.mark.parametrize("command", ["grep -rn foo .", "rg foo .", "git grep foo"])
def test_bash_search_stays_advisory_without_consuming_deny(tmp_path, monkeypatch, command):
_fixture(tmp_path)
payload = {"session_id": "s1", "tool_name": "Bash", "tool_input": {"command": command}}
out = _invoke("search", payload, tmp_path, monkeypatch, strict=True)
assert not _is_deny(out) and "knowledge graph at" in out
assert _is_deny(_invoke("search", _grep(), tmp_path, monkeypatch, strict=True))
def test_cli_search_passes_strict_flag(tmp_path, monkeypatch, capsys):
import graphify.cli as cli
import sys
_fixture(tmp_path)
monkeypatch.chdir(tmp_path)
monkeypatch.setattr(sys, "argv", ["graphify", "hook-guard", "search", "--strict"])
monkeypatch.setattr(sys, "stdin", io.TextIOWrapper(io.BytesIO(json.dumps(_grep()).encode())))
with pytest.raises(SystemExit) as exc:
cli.dispatch_command("hook-guard")
assert exc.value.code == 0 and _is_deny(capsys.readouterr().out)