fix(hook): give Bash file reads (cat, head, sed -n, ...) the read nudge
The Read|Glob matcher gives the read nudge, but Bash goes to `hook-guard
search`, which only reacted to search commands. `cat src/app.py`,
`head -50 src/app.py`, `tail`, `nl`, `less`, `more` and `bat` read indexed
code with no nudge at all, and `sed -n 1,80p src/app.py` got the generic
search nudge without the file's symbols. Claude Code reads files this way a
lot, especially with the Bash tool in auto mode.
`hook-guard search` now checks Bash commands for a file reader in an executed
position (the #3121 parsing, factored out of _bash_invokes_search into
_bash_commands so both use it) naming an existing in-project code file. Such a
call goes through the Read path: the same Read nudge with the file hint, the
stale variant, and the same per-agent budget. It is never denied, also in
strict mode. Targets outside the project or inside the graph output are
skipped (#1840, #4961), as are docs (`cat README.md` stays silent, as the
existing tests pin), non-graphed extensions, writes (`cat > x.py`, a stdout
redirect, `sed -i`), stdin reads (`echo x | cat`) and paths with shell
expansion. sed counts as a reader only with -n/--quiet/--silent; without it a
sed on a file stays a search, as before.
Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 13d133ea68)
This commit is contained in:
1 parent
82bde2b35b
commit
fd1ee64528
3 files changed
+397
-38
No files matched your search
@@ -305,7 +305,7 @@ Run `graphify <platform> install` once in your project, for example `graphify cl
|
||||
|
||||
This writes a small config file that tells your assistant to consult the knowledge graph for codebase questions, preferring scoped queries like `graphify query "<question>"` over reading the full report or grepping raw files.
|
||||
|
||||
- **Hook platforms** (Claude Code, Gemini CLI): a hook fires automatically before search-style tool calls (and, on Claude Code, before reading source files one by one via the Read/Glob tools) and nudges your assistant toward the graph path.
|
||||
- **Hook platforms** (Claude Code, Gemini CLI): a hook fires automatically before search-style tool calls (and, on Claude Code, before reading source files one by one via the Read/Glob tools, or via `cat`, `head`, `tail`, `sed -n` and similar readers in Bash) and nudges your assistant toward the graph path.
|
||||
- **Instruction-file platforms** (Codex, OpenCode, Cursor, etc.): persistent instruction files (`AGENTS.md`, `.cursor/rules/`, etc.) provide the same query-first guidance.
|
||||
|
||||
`GRAPH_REPORT.md` is still available for broad architecture review.
|
||||
|
||||
+156
-37
@@ -1113,23 +1113,17 @@ _COMMAND_WRAPPERS = frozenset({
|
||||
_HEREDOC_OPEN_RE = re.compile(r"<<-?\s*(['\"]?)(\w+)\1")
|
||||
|
||||
|
||||
def _bash_invokes_search(cmd_str: str) -> bool:
|
||||
"""Whether a Bash command actually RUNS a search tool (#3121).
|
||||
def _bash_commands(cmd_str: str):
|
||||
"""Yield ``(name, args, piped)`` for each command a Bash string executes.
|
||||
|
||||
The old test was a plain substring scan over the whole command string,
|
||||
including quoted arguments and heredoc bodies - so `git commit -m "add
|
||||
flag support"` fired ("flag " contains "ag "), prose containing "find "
|
||||
fired, and a design doc written via heredoc fired if its body mentioned
|
||||
grep. Every false positive injects a nudge where graphify has nothing to
|
||||
contribute and trains the agent to skim the line.
|
||||
|
||||
Decide on the command's executed tokens instead: drop heredoc bodies and
|
||||
quoted spans, split on shell operators, and match the executable at each
|
||||
command position (wrappers like sudo/xargs/env skipped; `git grep` and
|
||||
`VAR=x grep ...` still count; a search-tool name inside prose does not).
|
||||
`sed` and `awk` count too when they open a file themselves: run on files, they
|
||||
are a grep or a read of the codebase by another name. Reading a pipe, editing
|
||||
in place, or naming no file (a program alone reads stdin) does not count.
|
||||
The command parsing behind _bash_invokes_search (#3121): heredoc bodies are
|
||||
dropped, quoted spans become one placeholder word ``Q``, and the string is
|
||||
split at shell operators and substitution boundaries. In each segment the
|
||||
executable is the first token after ``VAR=value`` prefixes and wrappers
|
||||
(sudo/xargs/env and their flags). ``name`` is its basename, lowercased, with
|
||||
any ``.exe`` removed; ``args`` are the tokens after it; ``piped`` says the
|
||||
segment reads a pipe. A word in prose, a quoted argument or a heredoc body is
|
||||
never yielded as a command.
|
||||
"""
|
||||
text = cmd_str
|
||||
# Drop heredoc bodies: from the line after `<<WORD` through the line that
|
||||
@@ -1179,28 +1173,142 @@ def _bash_invokes_search(cmd_str: str) -> bool:
|
||||
while i < len(tokens) and tokens[i].startswith("-"):
|
||||
i += 1
|
||||
continue
|
||||
if name in _SEARCH_COMMANDS:
|
||||
return True
|
||||
if name == "git" and any(
|
||||
t2 == "grep" for t2 in tokens[i + 1:i + 4] if not t2.startswith("-")
|
||||
):
|
||||
return True
|
||||
if name in ("sed", "awk") and not segment_piped:
|
||||
rest = tokens[i + 1:]
|
||||
in_place = any(
|
||||
t2.startswith("--in-place")
|
||||
or (t2.startswith("-i") if name == "awk" else
|
||||
t2.startswith("-") and not t2.startswith("--") and "i" in t2)
|
||||
for t2 in rest
|
||||
)
|
||||
# The program and at least one file; `x=1` is an awk assignment.
|
||||
operands = [t2 for t2 in rest if not t2.startswith("-") and "=" not in t2]
|
||||
if not in_place and len(operands) >= 2:
|
||||
return True
|
||||
yield name, tokens[i + 1:], segment_piped
|
||||
break # first real token decides this segment
|
||||
|
||||
|
||||
def _bash_invokes_search(cmd_str: str) -> bool:
|
||||
"""Whether a Bash command actually RUNS a search tool (#3121).
|
||||
|
||||
The old test was a plain substring scan over the whole command string,
|
||||
including quoted arguments and heredoc bodies - so `git commit -m "add
|
||||
flag support"` fired ("flag " contains "ag "), prose containing "find "
|
||||
fired, and a design doc written via heredoc fired if its body mentioned
|
||||
grep. Every false positive injects a nudge where graphify has nothing to
|
||||
contribute and trains the agent to skim the line.
|
||||
|
||||
Decide on the command's executed tokens instead: drop heredoc bodies and
|
||||
quoted spans, split on shell operators, and match the executable at each
|
||||
command position (wrappers like sudo/xargs/env skipped; `git grep` and
|
||||
`VAR=x grep ...` still count; a search-tool name inside prose does not).
|
||||
`sed` and `awk` count too when they open a file themselves: run on files, they
|
||||
are a grep or a read of the codebase by another name. Reading a pipe, editing
|
||||
in place, or naming no file (a program alone reads stdin) does not count.
|
||||
"""
|
||||
for name, args, piped in _bash_commands(cmd_str):
|
||||
if name in _SEARCH_COMMANDS:
|
||||
return True
|
||||
if name == "git" and any(
|
||||
t2 == "grep" for t2 in args[:3] if not t2.startswith("-")
|
||||
):
|
||||
return True
|
||||
if name in ("sed", "awk") and not piped:
|
||||
# The program and at least one file; `x=1` is an awk assignment.
|
||||
operands = [t2 for t2 in args if not t2.startswith("-") and "=" not in t2]
|
||||
if not _sed_awk_in_place(name, args) and len(operands) >= 2:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _sed_awk_in_place(name: str, args: "list[str]") -> bool:
|
||||
"""Whether sed/awk edits its files in place (`-i`, `--in-place`, `-Ei`)."""
|
||||
return any(
|
||||
t2.startswith("--in-place")
|
||||
or (t2.startswith("-i") if name == "awk" else
|
||||
t2.startswith("-") and not t2.startswith("--") and "i" in t2)
|
||||
for t2 in args
|
||||
)
|
||||
|
||||
|
||||
# Bash commands that print a file for the agent to read. `sed` counts only with
|
||||
# -n/--quiet/--silent (it prints the lines asked for); without it, a sed run on
|
||||
# a file stays a search (see _bash_invokes_search).
|
||||
_BASH_READERS = frozenset({"cat", "head", "tail", "sed", "nl", "less", "more", "bat"})
|
||||
# Docs are graphed and nudge on the Read tool, but `cat README.md` in a shell is
|
||||
# orientation, not a walk through the code, so Bash reads nudge on code only.
|
||||
_BASH_READ_SKIP_EXTS = (".md", ".rst", ".txt", ".mdx")
|
||||
|
||||
|
||||
def _bash_read_target(cmd_str: str, cwd: str = "") -> "str | None":
|
||||
"""The in-project source file a Bash command prints, as an absolute path.
|
||||
|
||||
The Read tool gets the read nudge; `cat src/app.py`, `sed -n 1,80p
|
||||
src/app.py`, `head -50 src/app.py` and the like read the same code through
|
||||
Bash and got nothing (#3121's parser only looked for searches). Uses
|
||||
_bash_commands, so only executed commands count, never a reader named in
|
||||
prose, quotes or a heredoc body.
|
||||
|
||||
A file counts when a reader names it as an operand (or `< file`), it exists,
|
||||
its extension is a graphed code extension, it resolves inside the project
|
||||
(CLAUDE_PROJECT_DIR or cwd) and outside the graph output (#1840, #4961).
|
||||
Relative paths resolve against the Bash tool's ``cwd`` from the hook payload
|
||||
when it is inside the project. Writes are not reads: a stdout redirect
|
||||
(`cat > x.py`, `sed -n 1p a.py > b.py`) or `sed -i` disqualifies the
|
||||
command, and a reader with no file operand (`echo x | cat`) reads stdin.
|
||||
Paths with shell expansion are skipped. None when nothing qualifies.
|
||||
"""
|
||||
from graphify.paths import out_path
|
||||
try:
|
||||
root = Path(os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()).resolve()
|
||||
base = root
|
||||
if cwd and not _is_cwd_relative(cwd):
|
||||
c = Path(cwd).resolve()
|
||||
if c.is_relative_to(root):
|
||||
base = c
|
||||
outs = []
|
||||
for o in (out_path(), Path("graphify-out")):
|
||||
outs.append((root / o if _is_cwd_relative(str(o)) else o).resolve())
|
||||
except (OSError, RuntimeError, ValueError):
|
||||
return None
|
||||
for name, args, _piped in _bash_commands(cmd_str):
|
||||
if name not in _BASH_READERS:
|
||||
continue
|
||||
if name == "sed" and (_sed_awk_in_place(name, args) or not any(
|
||||
a in ("--quiet", "--silent") or (a.startswith("-") and not a.startswith("--") and "n" in a)
|
||||
for a in args)):
|
||||
continue
|
||||
files: "list[str]" = []
|
||||
it = iter(args)
|
||||
for tok in it:
|
||||
if ">" in tok:
|
||||
if tok.split(">", 1)[0] in ("", "1", "&"):
|
||||
files = []
|
||||
break # stdout goes to a file: a write, not a read
|
||||
if tok.endswith(">"):
|
||||
next(it, None) # `2> err.log`
|
||||
continue
|
||||
if tok.startswith("<<"):
|
||||
if tok in ("<<", "<<-", "<<<"):
|
||||
next(it, None)
|
||||
continue
|
||||
if tok == "<":
|
||||
tok = next(it, "")
|
||||
elif tok.startswith("<"):
|
||||
tok = tok[1:]
|
||||
elif name == "sed" and tok in ("-e", "-f", "--expression", "--file"):
|
||||
next(it, None) # the program, not a file
|
||||
continue
|
||||
elif tok.startswith("-"):
|
||||
continue
|
||||
files.append(tok)
|
||||
for f in files:
|
||||
if not f or re.search(r"[$`~*?\[\]{}]", f):
|
||||
continue
|
||||
seg = f.lower().replace("\\", "/").rsplit("/", 1)[-1]
|
||||
ext = "." + seg.rsplit(".", 1)[-1]
|
||||
if "." not in seg or ext not in _HOOK_SOURCE_EXTS or ext in _BASH_READ_SKIP_EXTS:
|
||||
continue
|
||||
try:
|
||||
p = Path(f.replace("\\", "/"))
|
||||
p = (base / p if _is_cwd_relative(str(p)) else p).resolve()
|
||||
if p.is_file() and p.is_relative_to(root) \
|
||||
and not any(p.is_relative_to(o) for o in outs):
|
||||
return str(p)
|
||||
except (OSError, RuntimeError, ValueError):
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _search_is_outside_project(tool_input: dict) -> bool:
|
||||
"""Skip only searches whose literal targets are all outside the project.
|
||||
|
||||
@@ -1280,7 +1388,10 @@ def _run_hook_guard(kind: str, strict: bool = False) -> None:
|
||||
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.
|
||||
parseable target and blocking file listing would strand navigation. A Bash
|
||||
command that prints an in-project code file (cat/head/tail/sed -n/nl/less/
|
||||
more/bat, see _bash_read_target) gets the Read nudge for that file, through
|
||||
the same budget, and is never denied.
|
||||
Out-of-project and graph-output targets are ignored; stale graphs never block.
|
||||
"""
|
||||
from graphify.paths import out_path
|
||||
@@ -1306,6 +1417,14 @@ def _run_hook_guard(kind: str, strict: bool = False) -> None:
|
||||
if not isinstance(t, dict):
|
||||
return
|
||||
try:
|
||||
# A Bash file read is a Read by another name: route it through the read
|
||||
# guard below with the file as its target. A reader wins over a search
|
||||
# in the same command, since the read nudge names the file's symbols.
|
||||
bash_read = False
|
||||
if kind == "search" and d.get("tool_name") in (None, "Bash"):
|
||||
target = _bash_read_target(str(t.get("command", "") or ""), str(d.get("cwd") or ""))
|
||||
if target:
|
||||
kind, t, bash_read = "read", {"file_path": target}, True
|
||||
if kind == "search":
|
||||
cmd_str = str(t.get("command", "") or "")
|
||||
# Two input shapes reach this guard (matcher "Bash|Grep", #1986):
|
||||
@@ -1462,9 +1581,9 @@ def _run_hook_guard(kind: str, strict: bool = False) -> None:
|
||||
sys.stdout.write(_nudge_for_out(_READ_NUDGE_STALE))
|
||||
return
|
||||
# Strict block: Read tool only, first time per session, not recently
|
||||
# oriented, and the file is demonstrably indexed.
|
||||
# oriented, and the file is demonstrably indexed. Bash stays advisory.
|
||||
tool_name = d.get("tool_name")
|
||||
if _hook_strict_enabled(strict) and tool_name in (None, "Read") \
|
||||
if not bash_read and _hook_strict_enabled(strict) and tool_name in (None, "Read") \
|
||||
and not _query_stamp_fresh() \
|
||||
and _target_is_indexed(fp, root) \
|
||||
and _mark_session_denied(str(d.get("session_id") or "")):
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Reading code with cat/sed/head/tail/... in Bash gets the Read nudge.
|
||||
|
||||
The Read|Glob matcher gives the read nudge, but Bash goes to `hook-guard
|
||||
search`, which only reacted to search commands (_bash_invokes_search, #3121).
|
||||
`cat src/app.py`, `head -50 src/app.py` or `nl src/app.py` read indexed code
|
||||
with no nudge at all, and `sed -n 1,80p src/app.py` got the generic search
|
||||
nudge without the file's symbols. Now a Bash command that prints an in-project
|
||||
code file gets the same Read nudge (with the file hint) through the same
|
||||
per-agent budget, and is never denied, strict mode included.
|
||||
|
||||
Driven the way Claude Code drives it: `graphify hook-guard search` in a
|
||||
subprocess with the PreToolUse JSON on stdin.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
SID = "3e1f0c2a-7b6d-4e5f-9a8b-1c2d3e4f5a6b"
|
||||
GRAPH = {
|
||||
"nodes": [
|
||||
{"id": "app", "label": "app.py", "source_file": "src/app.py", "source_location": "L1"},
|
||||
{"id": "app_run", "label": "run()", "source_file": "src/app.py", "source_location": "L3"},
|
||||
],
|
||||
"links": [],
|
||||
}
|
||||
|
||||
|
||||
def _project(tmp_path):
|
||||
proj = tmp_path / "proj"
|
||||
(proj / "src").mkdir(parents=True)
|
||||
(proj / "src" / "app.py").write_text("import os\n\ndef run():\n return os.getcwd()\n", encoding="utf-8")
|
||||
(proj / "README.md").write_text("# demo\n", encoding="utf-8")
|
||||
(proj / "package.json").write_text("{}\n", encoding="utf-8")
|
||||
(proj / "logo.png").write_bytes(b"\x89PNG")
|
||||
out = proj / "graphify-out"
|
||||
out.mkdir()
|
||||
(out / "GRAPH_REPORT.md").write_text("# report\n", encoding="utf-8")
|
||||
(out / "graph.json").write_text(json.dumps(GRAPH), encoding="utf-8")
|
||||
outside = tmp_path / "elsewhere"
|
||||
outside.mkdir()
|
||||
(outside / "other.py").write_text("x = 1\n", encoding="utf-8")
|
||||
return proj
|
||||
|
||||
|
||||
def _env(proj, **extra):
|
||||
e = dict(os.environ)
|
||||
for k in ("GRAPHIFY_OUT", "GRAPHIFY_HOOK_STRICT", "GRAPHIFY_HOOK_NUDGE_CAP", "GRAPHIFY_HOOK_STRICT_TTL"):
|
||||
e.pop(k, None)
|
||||
e["CLAUDE_PROJECT_DIR"] = str(proj)
|
||||
e.update(extra)
|
||||
return e
|
||||
|
||||
|
||||
def _bash(command, proj, *, sid=SID, agent=None, strict=False, tool_name="Bash", env=None):
|
||||
payload = {
|
||||
"session_id": sid,
|
||||
"transcript_path": f"/home/u/.claude/projects/p/{sid}.jsonl",
|
||||
"cwd": str(proj),
|
||||
"permission_mode": "auto",
|
||||
"hook_event_name": "PreToolUse",
|
||||
"tool_name": tool_name,
|
||||
"tool_input": {"command": command, "description": "Read the file"},
|
||||
"tool_use_id": "toolu_01",
|
||||
}
|
||||
if tool_name is None:
|
||||
del payload["tool_name"]
|
||||
if agent:
|
||||
payload["agent_id"] = agent
|
||||
args = [sys.executable, "-m", "graphify", "hook-guard", "search"] + (["--strict"] if strict else [])
|
||||
r = subprocess.run(args, input=json.dumps(payload), capture_output=True, text=True,
|
||||
cwd=proj, env=env or _env(proj))
|
||||
assert r.returncode == 0, r.stderr
|
||||
return r.stdout
|
||||
|
||||
|
||||
def _read_tool(path, proj, *, sid=SID):
|
||||
payload = {"session_id": sid, "hook_event_name": "PreToolUse", "tool_name": "Read",
|
||||
"cwd": str(proj), "tool_input": {"file_path": str(path)}}
|
||||
r = subprocess.run([sys.executable, "-m", "graphify", "hook-guard", "read"], input=json.dumps(payload),
|
||||
capture_output=True, text=True, cwd=proj, env=_env(proj))
|
||||
return r.stdout
|
||||
|
||||
|
||||
def _is_read_nudge(out):
|
||||
hso = json.loads(out)["hookSpecificOutput"]
|
||||
ctx = hso.get("additionalContext", "")
|
||||
return (hso["hookEventName"] == "PreToolUse" and "permissionDecision" not in hso
|
||||
and "reading source files one by one" in ctx)
|
||||
|
||||
|
||||
def _nudges(proj):
|
||||
d = proj / "graphify-out" / "cache" / "hook_sessions"
|
||||
return {p.name: p.read_text() for p in d.glob("*.nudges")} if d.is_dir() else {}
|
||||
|
||||
|
||||
READERS = [
|
||||
"cat src/app.py",
|
||||
"cat -n src/app.py",
|
||||
"sed -n 1,80p src/app.py",
|
||||
"sed -n '/def run/,/^$/p' src/app.py",
|
||||
"head -50 src/app.py",
|
||||
"head -n 20 src/app.py",
|
||||
"tail src/app.py",
|
||||
"tail -n +3 src/app.py",
|
||||
"nl -ba src/app.py",
|
||||
"less src/app.py",
|
||||
"more src/app.py",
|
||||
"bat --paging=never src/app.py",
|
||||
"cat < src/app.py",
|
||||
"cat src/app.py | grep run",
|
||||
"sudo cat ./src/app.py",
|
||||
"git status && cat src/app.py",
|
||||
"cat src/app.py 2>/dev/null",
|
||||
"head -50 src/app.py 2>&1",
|
||||
"cat {proj}/src/app.py",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("command", READERS)
|
||||
def test_bash_reader_gets_the_read_nudge_with_the_file_hint(command, tmp_path):
|
||||
proj = _project(tmp_path)
|
||||
out = _bash(command.format(proj=proj), proj)
|
||||
assert out.count("\n") == 1, "exactly one nudge"
|
||||
assert _is_read_nudge(out), out
|
||||
ctx = json.loads(out)["hookSpecificOutput"]["additionalContext"]
|
||||
assert 'Start with: `graphify explain "app.py"`' in ctx
|
||||
assert "- run() (src/app.py L3)" in ctx
|
||||
assert _nudges(proj) == {f"{SID}.nudges": "1"}
|
||||
|
||||
|
||||
SILENT = [
|
||||
"cat README.md", # docs: orientation, not a code walk
|
||||
"cat package.json", # not a graphed extension
|
||||
"cat logo.png",
|
||||
"cat src/missing.py", # no such file
|
||||
"cat > src/new.py", # writes
|
||||
"cat >> src/app.py",
|
||||
"cat src/app.py > /tmp/copy.py",
|
||||
"cat <<'EOF' > src/new.py\nimport os\nEOF",
|
||||
"sed -i 's/a/b/' src/app.py", # edits in place
|
||||
"sed -ni 's/a/b/p' src/app.py",
|
||||
"echo x | cat", # stdin, no file
|
||||
"git diff | head -50",
|
||||
"cat -",
|
||||
'echo "cat src/app.py"', # prose, not an executed reader
|
||||
"# cat src/app.py",
|
||||
"cat ../elsewhere/other.py", # outside the project (#1840)
|
||||
"cat {tmp}/elsewhere/other.py",
|
||||
"cat graphify-out/GRAPH_REPORT.md", # graph output (#4961)
|
||||
"head graphify-out/graph.json",
|
||||
"cat $HOME/src/app.py", # shell expansion: target unknown
|
||||
"cat src/*.py",
|
||||
"python src/app.py", # runs code, does not print it
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("command", SILENT)
|
||||
def test_non_reads_stay_silent(command, tmp_path):
|
||||
proj = _project(tmp_path)
|
||||
assert _bash(command.format(tmp=tmp_path), proj) == ""
|
||||
assert _nudges(proj) == {}, "a silent call spends no budget"
|
||||
# Control in the same project and session: a real read nudges.
|
||||
assert _is_read_nudge(_bash("cat src/app.py", proj))
|
||||
|
||||
|
||||
def test_bash_reads_share_the_read_budget(tmp_path):
|
||||
proj = _project(tmp_path)
|
||||
outs = [_bash("cat src/app.py", proj), _read_tool(proj / "src" / "app.py", proj),
|
||||
_bash("head -50 src/app.py", proj), _bash("sed -n 1,9p src/app.py", proj),
|
||||
_read_tool(proj / "src" / "app.py", proj)]
|
||||
assert all(outs) and _is_read_nudge(outs[0])
|
||||
assert _bash("tail src/app.py", proj) == "", "cap of 5 shared with the Read tool"
|
||||
sub = _bash("cat src/app.py", proj, agent="agent-7")
|
||||
assert _is_read_nudge(sub), "a subagent has its own budget (#3435)"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tool_name", ["Bash", None])
|
||||
def test_strict_mode_never_blocks_a_bash_read(tool_name, tmp_path):
|
||||
proj = _project(tmp_path)
|
||||
(proj / "graphify-out" / "manifest.json").write_text(json.dumps({"src/app.py": {"mtime": 1}}),
|
||||
encoding="utf-8")
|
||||
os.utime(proj / "src" / "app.py", (1, 1)) # older than the graph: fresh, indexed
|
||||
for env in (None, _env(proj, GRAPHIFY_HOOK_STRICT="1")):
|
||||
out = _bash("cat src/app.py", proj, sid=f"strict-{env is None}", strict=True,
|
||||
tool_name=tool_name, env=env)
|
||||
assert _is_read_nudge(out), out
|
||||
assert not list((proj / "graphify-out" / "cache" / "hook_sessions").glob("*.denied"))
|
||||
# The Read tool on the same file is still denied once.
|
||||
out = _read_tool(proj / "src" / "app.py", proj)
|
||||
assert out # soft mode here (no --strict): the nudge
|
||||
r = subprocess.run([sys.executable, "-m", "graphify", "hook-guard", "read", "--strict"],
|
||||
input=json.dumps({"session_id": "r", "tool_name": "Read",
|
||||
"tool_input": {"file_path": str(proj / "src" / "app.py")}}),
|
||||
capture_output=True, text=True, cwd=proj, env=_env(proj))
|
||||
assert json.loads(r.stdout)["hookSpecificOutput"]["permissionDecision"] == "deny"
|
||||
|
||||
|
||||
def test_relative_path_resolves_against_the_bash_cwd(tmp_path):
|
||||
proj = _project(tmp_path)
|
||||
payload = {"session_id": SID, "tool_name": "Bash", "cwd": str(proj / "src"),
|
||||
"tool_input": {"command": "cat app.py"}}
|
||||
r = subprocess.run([sys.executable, "-m", "graphify", "hook-guard", "search"], input=json.dumps(payload),
|
||||
capture_output=True, text=True, cwd=proj, env=_env(proj))
|
||||
assert _is_read_nudge(r.stdout)
|
||||
assert "- run() (src/app.py L3)" in r.stdout
|
||||
|
||||
|
||||
def test_stale_file_gets_the_stale_read_nudge(tmp_path):
|
||||
proj = _project(tmp_path)
|
||||
(proj / "graphify-out" / "needs_update").write_text("1", encoding="utf-8")
|
||||
out = _bash("cat src/app.py", proj)
|
||||
assert "may be STALE" in json.loads(out)["hookSpecificOutput"]["additionalContext"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("command", [
|
||||
"grep -rn run src",
|
||||
"rg run src/app.py",
|
||||
"sed 's/a/b/' src/app.py", # no -n: still counts as a search
|
||||
"awk '/run/' src/app.py",
|
||||
])
|
||||
def test_searches_keep_the_search_nudge(command, tmp_path):
|
||||
proj = _project(tmp_path)
|
||||
out = _bash(command, proj)
|
||||
ctx = json.loads(out)["hookSpecificOutput"]["additionalContext"]
|
||||
assert "Finding where something lives is what the graph answers" in ctx
|
||||
# Control: the same session's read gets the read nudge.
|
||||
assert _is_read_nudge(_bash("cat src/app.py", proj))
|
||||
|
||||
|
||||
def test_no_graph_no_nudge(tmp_path):
|
||||
proj = _project(tmp_path)
|
||||
(proj / "graphify-out" / "graph.json").unlink()
|
||||
assert _bash("cat src/app.py", proj) == ""
|
||||
(proj / "graphify-out" / "graph.json").write_text(json.dumps(GRAPH), encoding="utf-8")
|
||||
assert _is_read_nudge(_bash("cat src/app.py", proj))
|
||||
Reference in new issue
Block a user