word the hook reminders as facts so agents stop reading them as prompt injection
(cherry picked from commit 08a4c448c8)
This commit is contained in:
1 parent
0ba0ed1dbe
commit
59b01dcd3a
5 files changed
+81
-31
No files matched your search
+16
-13
@@ -15,14 +15,19 @@ from graphify.paths import GRAPHIFY_OUT as _GRAPHIFY_OUT
|
||||
from pathlib import Path, PurePosixPath, PureWindowsPath
|
||||
|
||||
|
||||
# Hook reminders arrive inside the agent's tool-result stream, where commands
|
||||
# ("MANDATORY", "You MUST", "include this in every subagent prompt") read like a
|
||||
# prompt injection and get ignored or flagged (#2202). State facts instead; the
|
||||
# per-agent budget in _nudge_allowed already gives each subagent its own nudge.
|
||||
_SEARCH_NUDGE = json.dumps({
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "PreToolUse",
|
||||
"additionalContext": (
|
||||
'MANDATORY: graphify-out/graph.json exists. You MUST run '
|
||||
'`graphify query "<question>"` before grepping raw files. Grep raw '
|
||||
'files only once you know the exact file and lines you need, from the '
|
||||
'graph or an earlier read.'
|
||||
'graphify: this project has a knowledge graph at graphify-out/graph.json. '
|
||||
'`graphify query "<question>"` returns the files and relations that '
|
||||
'matter for a question, usually in far fewer tokens than grepping raw '
|
||||
'files. Grep works best once the graph or an earlier read has pointed '
|
||||
'to the exact file and lines.'
|
||||
),
|
||||
}
|
||||
}, ensure_ascii=False, separators=(",", ":")) + "\n"
|
||||
@@ -30,13 +35,12 @@ _READ_NUDGE = json.dumps({
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "PreToolUse",
|
||||
"additionalContext": (
|
||||
'MANDATORY: graphify-out/graph.json exists. You MUST run graphify '
|
||||
'before reading source files. Use: `graphify query "<question>"` '
|
||||
'(scoped subgraph), `graphify explain "<concept>"`, or '
|
||||
'`graphify path "<A>" "<B>"`. Read raw files only once graphify has '
|
||||
'shown you the exact file and lines you need. This rule applies to '
|
||||
'subagents too — include it in every subagent prompt involving code '
|
||||
'exploration.'
|
||||
'graphify: this project has a knowledge graph at graphify-out/graph.json. '
|
||||
'`graphify query "<question>"` (scoped subgraph), '
|
||||
'`graphify explain "<concept>"` and `graphify path "<A>" "<B>"` show '
|
||||
'which files and lines matter — usually in far fewer tokens than reading '
|
||||
'source files one by one. Reading a file directly works best once the '
|
||||
'graph has pointed to the exact lines.'
|
||||
),
|
||||
}
|
||||
}, ensure_ascii=False, separators=(",", ":")) + "\n"
|
||||
@@ -64,8 +68,7 @@ _READ_DENY = json.dumps({
|
||||
'this file. Run `graphify query "<your question>"` (or `graphify explain` / '
|
||||
'`graphify path`) FIRST to orient yourself, then re-issue this Read — it '
|
||||
'will be allowed. This block fires at most once per session; after one '
|
||||
'query, read raw files for the exact lines the graph pointed you to. Apply the '
|
||||
'same rule in any subagent prompt that explores code.'
|
||||
'query, read raw files for the exact lines the graph pointed you to.'
|
||||
),
|
||||
}
|
||||
}, ensure_ascii=False, separators=(",", ":")) + "\n"
|
||||
|
||||
+12
-12
@@ -260,7 +260,7 @@ def test_fresh_query_stamp_silences_nudges_after_the_first(tmp_path, monkeypatch
|
||||
_fresh_stamp(tmp_path)
|
||||
# The stamp is project-wide and cannot tell which agent queried, so each
|
||||
# agent still gets its first nudge; later ones are silenced.
|
||||
assert "MANDATORY" in _invoke("read", _read_payload(), tmp_path, monkeypatch)
|
||||
assert "knowledge graph at" in _invoke("read", _read_payload(), tmp_path, monkeypatch)
|
||||
assert _invoke("read", _read_payload(), tmp_path, monkeypatch) == ""
|
||||
assert _invoke("search", _search_payload(), tmp_path, monkeypatch) == ""
|
||||
|
||||
@@ -275,34 +275,34 @@ def test_subagents_get_their_own_nudge_budget(tmp_path, monkeypatch):
|
||||
# Claude Code subagents share the parent's session_id and differ by agent_id.
|
||||
monkeypatch.setenv("GRAPHIFY_HOOK_NUDGE_CAP", "1")
|
||||
sid = "s" * 64 # long ids must not truncate distinct agents into one key
|
||||
assert "MANDATORY" in _invoke("read", _read_payload(sid), tmp_path, monkeypatch)
|
||||
assert "knowledge graph at" in _invoke("read", _read_payload(sid), tmp_path, monkeypatch)
|
||||
assert _invoke("read", _read_payload(sid), tmp_path, monkeypatch) == ""
|
||||
assert "MANDATORY" in _invoke("read", _read_payload(sid, "agent-a"), tmp_path, monkeypatch)
|
||||
assert "knowledge graph at" in _invoke("read", _read_payload(sid, "agent-a"), tmp_path, monkeypatch)
|
||||
assert _invoke("read", _read_payload(sid, "agent-a"), tmp_path, monkeypatch) == ""
|
||||
assert "MANDATORY" in _invoke("read", _read_payload(sid, "agent-b"), tmp_path, monkeypatch)
|
||||
assert "knowledge graph at" in _invoke("read", _read_payload(sid, "agent-b"), tmp_path, monkeypatch)
|
||||
|
||||
|
||||
def test_subagent_first_nudge_survives_parent_query(tmp_path, monkeypatch):
|
||||
assert "MANDATORY" in _invoke("read", _read_payload(), tmp_path, monkeypatch)
|
||||
assert "knowledge graph at" in _invoke("read", _read_payload(), tmp_path, monkeypatch)
|
||||
_fresh_stamp(tmp_path) # parent queried
|
||||
assert _invoke("read", _read_payload(), tmp_path, monkeypatch) == ""
|
||||
assert "MANDATORY" in _invoke("read", _read_payload(agent="agent-a"), tmp_path, monkeypatch)
|
||||
assert "knowledge graph at" in _invoke("read", _read_payload(agent="agent-a"), tmp_path, monkeypatch)
|
||||
|
||||
|
||||
def test_nudges_capped_per_session(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("GRAPHIFY_HOOK_NUDGE_CAP", "3")
|
||||
outs = [_invoke("read", _read_payload("cap"), tmp_path, monkeypatch) for _ in range(3)]
|
||||
assert all("MANDATORY" in o for o in outs)
|
||||
assert all("knowledge graph at" in o for o in outs)
|
||||
assert _invoke("read", _read_payload("cap"), tmp_path, monkeypatch) == ""
|
||||
assert _invoke("search", _search_payload("cap"), tmp_path, monkeypatch) == ""
|
||||
# Another session has its own budget.
|
||||
assert "MANDATORY" in _invoke("read", _read_payload("other"), tmp_path, monkeypatch)
|
||||
assert "knowledge graph at" in _invoke("read", _read_payload("other"), tmp_path, monkeypatch)
|
||||
|
||||
|
||||
def test_read_and_search_nudges_share_the_session_budget(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("GRAPHIFY_HOOK_NUDGE_CAP", "2")
|
||||
assert "MANDATORY" in _invoke("search", _search_payload("mix"), tmp_path, monkeypatch)
|
||||
assert "MANDATORY" in _invoke("read", _read_payload("mix"), tmp_path, monkeypatch)
|
||||
assert "knowledge graph at" in _invoke("search", _search_payload("mix"), tmp_path, monkeypatch)
|
||||
assert "knowledge graph at" in _invoke("read", _read_payload("mix"), tmp_path, monkeypatch)
|
||||
assert _invoke("search", _search_payload("mix"), tmp_path, monkeypatch) == ""
|
||||
|
||||
|
||||
@@ -316,14 +316,14 @@ def test_nudge_cap_default_is_five(tmp_path, monkeypatch):
|
||||
def test_nudge_cap_disabled(value, tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("GRAPHIFY_HOOK_NUDGE_CAP", value)
|
||||
outs = [_invoke("read", _read_payload("nocap"), tmp_path, monkeypatch) for _ in range(8)]
|
||||
assert all("MANDATORY" in o for o in outs)
|
||||
assert all("knowledge graph at" in o for o in outs)
|
||||
|
||||
|
||||
def test_nudges_without_session_id_are_not_counted(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("GRAPHIFY_HOOK_NUDGE_CAP", "1")
|
||||
payload = {"tool_name": "Read", "tool_input": {"file_path": "src/app.py"}}
|
||||
outs = [_invoke("read", payload, tmp_path, monkeypatch) for _ in range(3)]
|
||||
assert all("MANDATORY" in o for o in outs)
|
||||
assert all("knowledge graph at" in o for o in outs)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"""#2202 - hook reminders arrive in the agent's tool-result stream. Phrased as
|
||||
commands ("MANDATORY", "You MUST", "include it in every subagent prompt") they
|
||||
read like a prompt injection, and agents flag or ignore them. They must state
|
||||
facts instead.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from graphify import cli
|
||||
|
||||
_COMMANDING = re.compile(r"MANDATORY|\bMUST\b|every subagent prompt|subagent prompt", re.I)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["_SEARCH_NUDGE", "_READ_NUDGE", "_READ_NUDGE_STALE"])
|
||||
def test_nudges_state_facts_not_commands(name):
|
||||
text = json.loads(getattr(cli, name))["hookSpecificOutput"]["additionalContext"]
|
||||
assert not _COMMANDING.search(text), text
|
||||
|
||||
|
||||
def test_strict_deny_does_not_ask_to_spread_itself_to_subagents():
|
||||
reason = json.loads(cli._READ_DENY)["hookSpecificOutput"]["permissionDecisionReason"]
|
||||
assert "subagent" not in reason.lower()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind, tool_input", [
|
||||
("search", {"command": "grep -rn foo src/"}),
|
||||
("read", {"file_path": "src/app.py"}),
|
||||
])
|
||||
def test_emitted_reminder_has_no_commands(tmp_path, monkeypatch, kind, tool_input):
|
||||
(tmp_path / "graphify-out").mkdir()
|
||||
(tmp_path / "graphify-out" / "graph.json").write_text("{}", encoding="utf-8")
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(tmp_path))
|
||||
payload = json.dumps({"session_id": "s1", "tool_input": tool_input}).encode()
|
||||
monkeypatch.setattr(sys, "stdin", io.TextIOWrapper(io.BytesIO(payload)))
|
||||
out = io.StringIO()
|
||||
monkeypatch.setattr(sys, "stdout", out)
|
||||
cli._run_hook_guard(kind)
|
||||
text = json.loads(out.getvalue())["hookSpecificOutput"]["additionalContext"]
|
||||
assert "graphify query" in text
|
||||
assert not _COMMANDING.search(text), text
|
||||
@@ -152,12 +152,12 @@ def test_driveless_rooted_path_outside_the_project_is_silent(tmp_path, monkeypat
|
||||
def test_in_project_relative_path_still_nudges(tmp_path, monkeypatch):
|
||||
"""The guard must keep firing for the paths it exists to catch."""
|
||||
_project(tmp_path)
|
||||
assert "MANDATORY" in _invoke(tmp_path, monkeypatch, "src/mod.py")
|
||||
assert "knowledge graph at" in _invoke(tmp_path, monkeypatch, "src/mod.py")
|
||||
|
||||
|
||||
def test_in_project_absolute_path_still_nudges(tmp_path, monkeypatch):
|
||||
f = _project(tmp_path)
|
||||
assert "MANDATORY" in _invoke(tmp_path, monkeypatch, f)
|
||||
assert "knowledge graph at" in _invoke(tmp_path, monkeypatch, f)
|
||||
|
||||
|
||||
def test_absolute_path_outside_the_project_is_still_silent(tmp_path, monkeypatch):
|
||||
|
||||
@@ -70,7 +70,7 @@ def test_strict_first_read_denies_then_nudges(tmp_path, monkeypatch):
|
||||
assert (tmp_path / "graphify-out" / "cache" / "hook_sessions" / "s1.denied").exists()
|
||||
# same session again -> soft nudge, not a second deny
|
||||
out2 = _invoke("read", _read(f), tmp_path, monkeypatch, strict=True)
|
||||
assert not _is_deny(out2) and "MANDATORY" in out2
|
||||
assert not _is_deny(out2) and "knowledge graph at" in out2
|
||||
|
||||
|
||||
def test_strict_new_session_denies_again(tmp_path, monkeypatch):
|
||||
@@ -88,7 +88,7 @@ def test_fresh_query_stamp_suppresses_deny(tmp_path, monkeypatch):
|
||||
out = _invoke("read", _read(f), tmp_path, monkeypatch, strict=True)
|
||||
# Recently oriented: no block. This session's first nudge still fires, since
|
||||
# the project-wide stamp cannot tell which agent queried (#3435).
|
||||
assert not _is_deny(out) and "MANDATORY" in out
|
||||
assert not _is_deny(out) and "knowledge graph at" in out
|
||||
assert _invoke("read", _read(f), tmp_path, monkeypatch, strict=True) == ""
|
||||
|
||||
|
||||
@@ -106,7 +106,7 @@ def test_expired_query_stamp_still_denies(tmp_path, monkeypatch):
|
||||
def test_soft_mode_never_denies(tmp_path, monkeypatch):
|
||||
f = _fixture(tmp_path)
|
||||
out = _invoke("read", _read(f), tmp_path, monkeypatch, strict=False)
|
||||
assert not _is_deny(out) and "MANDATORY" in out
|
||||
assert not _is_deny(out) and "knowledge graph at" in out
|
||||
|
||||
|
||||
def test_env_forces_strict_on(tmp_path, monkeypatch):
|
||||
@@ -133,7 +133,7 @@ def test_stale_graph_softens_never_denies(tmp_path, monkeypatch):
|
||||
f = _fixture(tmp_path, fresh=False) # source newer than graph
|
||||
out = _invoke("read", _read(f), tmp_path, monkeypatch, strict=True)
|
||||
assert not _is_deny(out)
|
||||
assert "stale" in out.lower() and "MANDATORY" not in out
|
||||
assert "stale" in out.lower() and "knowledge graph at" not in out
|
||||
|
||||
|
||||
def test_needs_update_flag_softens(tmp_path, monkeypatch):
|
||||
|
||||
Reference in new issue
Block a user