diff --git a/README.md b/README.md index e583e076d..28890cd3b 100644 --- a/README.md +++ b/README.md @@ -253,7 +253,7 @@ 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`. -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). A Grep over a directory needs no indexed-file match; a Grep pinned to a single file is denied only when the graph indexes that file, as with Read. 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. +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). A Grep over a directory needs no indexed-file match; a Grep pinned to a single file is denied only when the graph indexes that file, as with Read. 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. Soft nudges are capped per session (`GRAPHIFY_HOOK_NUDGE_CAP`, default 5). After a context compaction, a `SessionStart` hook (matcher `compact`) resets that budget, the subagents' budgets and the strict denial, since the compacted context no longer holds the earlier nudges. Pi has no `PreToolUse` hook, so `graphify pi guard install` registers a native Pi extension (via Pi's own `pi install `) 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 `` 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 `. diff --git a/graphify/cli.py b/graphify/cli.py index e4b48d7d5..6d0312863 100644 --- a/graphify/cli.py +++ b/graphify/cli.py @@ -55,6 +55,20 @@ _READ_NUDGE_STALE = json.dumps({ ), } }, ensure_ascii=False, separators=(",", ":")) + "\n" +# Claude Code SessionStart (matcher "compact") output: compaction dropped the +# earlier nudges from the model's context, so restate the one fact they carried. +# SessionStart accepts hookSpecificOutput.additionalContext. +_COMPACT_CONTEXT = json.dumps({ + "hookSpecificOutput": { + "hookEventName": "SessionStart", + "additionalContext": ( + 'graphify: this project has a knowledge graph at graphify-out/graph.json. ' + '`graphify query ""`, `graphify explain ""` and ' + '`graphify path "" ""` show which files and lines matter, usually ' + 'in far fewer tokens than reading or grepping raw files.' + ), + } +}, ensure_ascii=False, separators=(",", ":")) + "\n" # Strict-mode block (opt-in). Claude Code PreToolUse honors # hookSpecificOutput.permissionDecision == "deny" and shows permissionDecisionReason # to the model. Fires at most once per session (see _mark_session_denied) so it can @@ -1030,7 +1044,10 @@ def _nudge_allowed(payload: dict) -> bool: disables the cap), counted in a marker next to the strict-mode ones. Calls without a session id cannot be counted: only the stamp applies. - Fail-open: on a marker error, only the stamp applies. + Fail-open: on a marker error, only the stamp applies. Compaction keeps the + session id but drops the earlier nudges from the model's context, so + ``hook-guard compact`` (Claude Code SessionStart, source "compact") deletes + the session's counters, see _reset_hook_session. """ from graphify.paths import out_path, write_text_atomic import hashlib @@ -1080,6 +1097,33 @@ def _gc_hook_session_markers(d: "Path") -> None: pass +def _reset_hook_session(session_id: str) -> None: + """Give a compacted Claude Code session its hook budget back. + + After compaction the session id stays the same, but the model no longer + sees the nudges it was given, and _nudge_allowed has already spent the cap. + Deletes the session's nudge counter, the counter of every subagent of it + (``-<16 hex>``, the per-agent key _nudge_allowed builds) and the + strict-mode deny marker, so the next qualifying call nudges again and strict + mode can redirect once more. Other sessions' markers are untouched. Errors + propagate: the caller fails open. + """ + from graphify.paths import out_path + key = re.sub(r"[^A-Za-z0-9_-]", "_", str(session_id or ""))[:64] + if not key: + return + d = out_path("cache", "hook_sessions") + if not d.is_dir(): + return + own = re.compile(re.escape(key) + r"(?:-[0-9a-f]{16})?\.nudges|" + re.escape(key) + r"\.denied") + for entry in os.scandir(d): + if own.fullmatch(entry.name): + try: + os.unlink(entry.path) + except FileNotFoundError: + pass + + def _mark_session_denied(session_id: str) -> bool: """Atomically claim a one-time strict block for this session. Returns True only on the FIRST call for a given session id (O_EXCL create wins once); every later @@ -1413,6 +1457,20 @@ def _run_hook_guard(kind: str, strict: bool = False) -> None: return if not isinstance(d, dict): return + # Claude Code SessionStart with matcher "compact": reset this session's + # nudge budget and restate the graph. Other sources (startup, resume, + # clear, fork) keep their counters. + if kind == "compact": + try: + if d.get("hook_event_name", "SessionStart") != "SessionStart" \ + or d.get("source") != "compact": + return + _reset_hook_session(str(d.get("session_id") or "")) + if out_path("graph.json").is_file(): + sys.stdout.write(_nudge_for_out(_COMPACT_CONTEXT)) + except Exception: + pass + return t = d.get("tool_input", d) if not isinstance(t, dict): return @@ -3287,6 +3345,8 @@ def dispatch_command(cmd: str) -> None: # strict mode (opt-in, `hook-guard --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. + # `hook-guard compact` is the SessionStart (matcher "compact") hook that + # resets the session's nudge budget after a context compaction. _run_hook_guard( sys.argv[2] if len(sys.argv) > 2 else "", strict="--strict" in sys.argv[3:], diff --git a/graphify/install.py b/graphify/install.py index b40087b7c..c9bbfadb4 100644 --- a/graphify/install.py +++ b/graphify/install.py @@ -593,6 +593,23 @@ def _claude_pretooluse_hooks(strict: bool = False, project: bool = False) -> "li {"matcher": "Read|Glob", "hooks": [{"type": "command", "command": read_cmd, "timeout": 10}]}, ] +def _claude_sessionstart_hooks(project: bool = False) -> "list[dict]": + """graphify's Claude Code SessionStart hook: matcher "compact" only. + + Claude Code fires SessionStart with source "compact" after an auto or manual + compaction, keeping the session id. The model has lost the earlier nudges by + then, but their per-session budget is spent, so `hook-guard compact` resets + it (and the strict-mode deny marker) and restates the graph in one line. + Same command form and timeout as _claude_pretooluse_hooks; the command + carries "hook-guard", so the install/uninstall filters recognise it. + """ + exe = _resolve_graphify_exe(project=project) + if " " in exe and not exe.startswith('"'): + exe = f'"{exe}"' + return [ + {"matcher": "compact", + "hooks": [{"type": "command", "command": f"{exe} hook-guard compact", "timeout": 10}]}, + ] # Tokens that only ever appear in a command graphify itself writes: its # `hook-guard ` and `hook-check` subcommands. Legacy # (pre-#522) installs shipped an inline POSIX bash guard instead, whose command @@ -2341,11 +2358,18 @@ def _install_claude_hook(project_dir: Path, strict: bool = False, project: bool if not isinstance(pre_tool, list): _refuse_to_modify(settings_path) + session_start = hooks.setdefault("SessionStart", []) + if not isinstance(session_start, list): + _refuse_to_modify(settings_path) + hooks["PreToolUse"] = _strip_graphify_hooks(pre_tool) hooks["PreToolUse"].extend(_claude_pretooluse_hooks(strict=strict, project=project)) + hooks["SessionStart"] = _strip_graphify_hooks(session_start) + hooks["SessionStart"].extend(_claude_sessionstart_hooks(project=project)) _write_settings_with_backup(settings_path, settings) _mode = " (strict)" if strict else "" print(f" .claude/settings.json -> PreToolUse hooks registered (Bash|Grep search + Read/Glob){_mode}") + print(" .claude/settings.json -> SessionStart hook registered (compact: resets the nudge budget)") def _uninstall_claude_hook(project_dir: Path) -> None: """Remove the graphify PreToolUse hook from .claude/settings.json and its local-only sibling .claude/settings.local.json. @@ -2357,22 +2381,31 @@ def _uninstall_claude_hook(project_dir: Path) -> None: for name in ("settings.json", "settings.local.json"): _strip_graphify_hook(claude_dir / name) def _strip_graphify_hook(settings_path: Path) -> None: - """Drop graphify PreToolUse hooks from a single Claude settings file, if present.""" + """Drop graphify PreToolUse and SessionStart hooks from a single Claude + settings file, if present.""" if not settings_path.exists(): return try: settings = json.loads(settings_path.read_text(encoding="utf-8")) except json.JSONDecodeError: return - pre_tool = settings.get("hooks", {}).get("PreToolUse", []) - if not isinstance(pre_tool, list): + hooks = settings.get("hooks", {}) + if not isinstance(hooks, dict): return - filtered = _strip_graphify_hooks(pre_tool) - if filtered == pre_tool: + removed = [] + for event in ("PreToolUse", "SessionStart"): + groups = hooks.get(event, []) + if not isinstance(groups, list): + continue + filtered = _strip_graphify_hooks(groups) + if filtered != groups: + hooks[event] = filtered + removed.append(event) + if not removed: return - settings["hooks"]["PreToolUse"] = filtered _write_settings_with_backup(settings_path, settings) - print(f" .claude/{settings_path.name} -> PreToolUse hook removed") + for event in removed: + print(f" .claude/{settings_path.name} -> {event} hook removed") def _unsafe_purge_reason(out: Path, project_dir: Path) -> str | None: diff --git a/tests/test_hook_compact.py b/tests/test_hook_compact.py new file mode 100644 index 000000000..0bbaa391b --- /dev/null +++ b/tests/test_hook_compact.py @@ -0,0 +1,287 @@ +"""The nudge budget comes back after a Claude Code context compaction. + +_nudge_allowed counts nudges per session (and per subagent) and stops at +GRAPHIFY_HOOK_NUDGE_CAP (#3435). Compaction keeps the session id but drops the +earlier nudges from the model's context, so with the budget spent the rest of a +long session never heard about the graph again. Claude Code fires SessionStart +with source "compact" after compaction; graphify installs a SessionStart hook +with matcher "compact" that runs `graphify hook-guard compact`, which resets the +session's counters, its subagents' counters and the strict-mode deny marker. + +The guard is driven the way Claude Code drives it: a subprocess with the hook +JSON on stdin. +""" +from __future__ import annotations + +import json +import os +import subprocess +import sys +import time + +import pytest + +from graphify import install as install_mod + +SID = "9f1c2d3e-4b5a-6789-abcd-ef0123456789" + + +def _project(tmp_path): + src = tmp_path / "src" + src.mkdir() + f = src / "mod.py" + f.write_text("def x():\n return 1\n", encoding="utf-8") + out = tmp_path / "graphify-out" + out.mkdir() + (out / "manifest.json").write_text(json.dumps({"src/mod.py": {"mtime": 1}}), encoding="utf-8") + time.sleep(0.02) + (out / "graph.json").write_text('{"nodes":[],"links":[]}', encoding="utf-8") + return f + + +def _env(tmp_path): + 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(tmp_path) + return e + + +def _guard(kind, payload, tmp_path, *, strict=False): + args = [sys.executable, "-m", "graphify", "hook-guard", kind] + (["--strict"] if strict else []) + data = payload if isinstance(payload, str) else json.dumps(payload) + r = subprocess.run(args, input=data, capture_output=True, text=True, cwd=tmp_path, env=_env(tmp_path)) + assert r.returncode == 0, r.stderr + return r.stdout + + +def _read(f, tmp_path, *, sid=SID, agent=None, strict=False): + payload = { + "session_id": sid, + "transcript_path": f"/home/u/.claude/projects/p/{sid}.jsonl", + "cwd": str(tmp_path), + "permission_mode": "default", + "hook_event_name": "PreToolUse", + "tool_name": "Read", + "tool_input": {"file_path": str(f)}, + "tool_use_id": "toolu_01", + } + if agent: + payload["agent_id"] = agent + payload["agent_type"] = "Explore" + return _guard("read", payload, tmp_path, strict=strict) + + +def _session_start(source, tmp_path, *, sid=SID): + return _guard("compact", { + "session_id": sid, + "transcript_path": f"/home/u/.claude/projects/p/{sid}.jsonl", + "cwd": str(tmp_path), + "hook_event_name": "SessionStart", + "source": source, + "model": "claude-opus-4-1", + }, tmp_path) + + +def _kind(out): + if not out.strip(): + return "silent" + hso = json.loads(out)["hookSpecificOutput"] + return "deny" if hso.get("permissionDecision") == "deny" else "nudge" + + +def _markers(tmp_path): + d = tmp_path / "graphify-out" / "cache" / "hook_sessions" + return sorted(p.name for p in d.iterdir()) if d.is_dir() else [] + + +def test_compact_restores_the_nudge_budget_for_session_and_subagent(tmp_path): + f = _project(tmp_path) + assert [_kind(_read(f, tmp_path)) for _ in range(5)] == ["nudge"] * 5 + assert _kind(_read(f, tmp_path)) == "silent", "cap of 5 reached" + assert [_kind(_read(f, tmp_path, agent="a1")) for _ in range(5)] == ["nudge"] * 5 + assert _kind(_read(f, tmp_path, agent="a1")) == "silent", "subagent cap reached" + # Another session's spent budget must survive this session's compaction. + other = "11111111-2222-3333-4444-555555555555" + for _ in range(5): + _read(f, tmp_path, sid=other) + assert _kind(_read(f, tmp_path, sid=other)) == "silent" + + out = _session_start("compact", tmp_path) + hso = json.loads(out)["hookSpecificOutput"] + assert hso["hookEventName"] == "SessionStart" + assert "graphify query" in hso["additionalContext"] + assert set(hso) == {"hookEventName", "additionalContext"} + + assert _kind(_read(f, tmp_path)) == "nudge", "budget back after compaction" + assert _kind(_read(f, tmp_path, agent="a1")) == "nudge", "subagent budget back too" + assert _kind(_read(f, tmp_path, sid=other)) == "silent", "other session untouched" + + +def test_compact_rearms_the_strict_deny(tmp_path): + f = _project(tmp_path) + assert _kind(_read(f, tmp_path, strict=True)) == "deny" + assert _kind(_read(f, tmp_path, strict=True)) == "nudge", "deny fires once per session" + assert f"{SID}.denied" in _markers(tmp_path) + _session_start("compact", tmp_path) + assert f"{SID}.denied" not in _markers(tmp_path) + assert _kind(_read(f, tmp_path, strict=True)) == "deny", "strict redirects once more" + assert _kind(_read(f, tmp_path, strict=True)) == "nudge" + + +@pytest.mark.parametrize("source", ["startup", "resume", "clear", "fork", None]) +def test_other_session_start_sources_do_not_reset(source, tmp_path): + f = _project(tmp_path) + assert _kind(_read(f, tmp_path, strict=True)) == "deny" + for _ in range(5): + _read(f, tmp_path, strict=True) + _read(f, tmp_path, agent="a1") + before = _markers(tmp_path) + payload = {"session_id": SID, "hook_event_name": "SessionStart", "cwd": str(tmp_path)} + if source is not None: + payload["source"] = source + assert _guard("compact", payload, tmp_path) == "" + assert _markers(tmp_path) == before + assert _kind(_read(f, tmp_path, strict=True)) == "silent" + # Control: the same session does get its budget back on "compact". + _session_start("compact", tmp_path) + assert _kind(_read(f, tmp_path, strict=True)) == "deny" + + +def test_compact_on_another_event_does_nothing(tmp_path): + f = _project(tmp_path) + for _ in range(6): + _read(f, tmp_path) + before = _markers(tmp_path) + out = _guard("compact", {"session_id": SID, "hook_event_name": "PreCompact", "source": "compact"}, tmp_path) + assert out == "" and _markers(tmp_path) == before + _session_start("compact", tmp_path) # control: the real event resets + assert _kind(_read(f, tmp_path)) == "nudge" + + +def test_compact_without_markers_or_graph_is_quiet(tmp_path): + # No graph: nothing to restate. No markers: nothing to delete. Never an error. + assert _session_start("compact", tmp_path) == "" + _project(tmp_path) + assert _kind(_session_start("compact", tmp_path)) == "nudge" + + +@pytest.mark.parametrize("stdin", ["", "not json", "[]", '"compact"', '{"source": ["compact"]}']) +def test_compact_fails_open_on_bad_input(stdin, tmp_path): + f = _project(tmp_path) + for _ in range(6): + _read(f, tmp_path) + before = _markers(tmp_path) + assert _guard("compact", stdin, tmp_path) == "" + assert _markers(tmp_path) == before + _session_start("compact", tmp_path) # control: valid input still resets + assert _kind(_read(f, tmp_path)) == "nudge" + + +def test_compact_fails_open_when_the_reset_raises(tmp_path, monkeypatch): + # Root ignores file permissions, so force the error in-process. + import io + import graphify.cli as cli + f = _project(tmp_path) + _read(f, tmp_path) + monkeypatch.chdir(tmp_path) + + def boom(*_a, **_k): + raise PermissionError("denied") + + def run(): + class _Stdin: + buffer = io.BytesIO(json.dumps({"session_id": SID, "hook_event_name": "SessionStart", + "source": "compact"}).encode()) + monkeypatch.setattr(sys, "stdin", _Stdin()) + buf = io.StringIO() + monkeypatch.setattr(sys, "stdout", buf) + cli._run_hook_guard("compact") + return buf.getvalue() + + with monkeypatch.context() as m: + m.setattr(cli.os, "scandir", boom) + assert run() == "" + assert _kind(run()) == "nudge", "control: without the error the reminder prints" + + +def test_compact_respects_graphify_out(tmp_path): + f = _project(tmp_path) + (tmp_path / "graphify-out").rename(tmp_path / "alt-out") + env = _env(tmp_path) + env["GRAPHIFY_OUT"] = "alt-out" + + def run(kind, payload): + return subprocess.run([sys.executable, "-m", "graphify", "hook-guard", kind], input=json.dumps(payload), + capture_output=True, text=True, cwd=tmp_path, env=env).stdout + + read = {"session_id": SID, "tool_name": "Read", "tool_input": {"file_path": str(f)}} + for _ in range(5): + run("read", read) + assert run("read", read) == "" + out = run("compact", {"session_id": SID, "hook_event_name": "SessionStart", "source": "compact"}) + assert "alt-out/graph.json" in out + assert run("read", read) != "" + + +# ------------------------------------------------------------------ install + + +def _settings(project): + return json.loads((project / ".claude" / "settings.json").read_text(encoding="utf-8")) + + +def _ours(groups): + return [g for g in groups if any(install_mod._is_graphify_hook_entry(e) for e in g.get("hooks", []))] + + +def test_install_adds_one_compact_session_start_hook(tmp_path): + install_mod._install_claude_hook(tmp_path) + install_mod._install_claude_hook(tmp_path) # re-install must not duplicate + groups = _settings(tmp_path)["hooks"]["SessionStart"] + ours = _ours(groups) + assert len(ours) == 1 + assert ours[0]["matcher"] == "compact" + (entry,) = ours[0]["hooks"] + assert entry["type"] == "command" and entry["command"].endswith("hook-guard compact") + assert 0 < entry["timeout"] <= 30 + + +def test_project_install_uses_the_bare_command(tmp_path): + install_mod._install_claude_hook(tmp_path, project=True) + (group,) = _ours(_settings(tmp_path)["hooks"]["SessionStart"]) + assert group["hooks"][0]["command"] == "graphify hook-guard compact" + + +def test_install_and_uninstall_keep_the_users_session_start_hooks(tmp_path): + settings_path = tmp_path / ".claude" / "settings.json" + settings_path.parent.mkdir(parents=True) + user_group = {"matcher": "startup", "hooks": [{"type": "command", "command": "echo hello"}]} + shared = {"matcher": "compact", "hooks": [{"type": "command", "command": "./notify.sh"}]} + settings_path.write_text(json.dumps({"hooks": {"SessionStart": [user_group, shared]}}), encoding="utf-8") + + install_mod._install_claude_hook(tmp_path) + groups = _settings(tmp_path)["hooks"]["SessionStart"] + assert groups[:2] == [user_group, shared] + assert len(_ours(groups)) == 1 + + install_mod._uninstall_claude_hook(tmp_path) + hooks = _settings(tmp_path)["hooks"] + assert hooks["SessionStart"] == [user_group, shared] + assert _ours(hooks["PreToolUse"]) == [] + + +def test_uninstall_removes_the_session_start_hook(tmp_path): + install_mod._install_claude_hook(tmp_path) + install_mod._uninstall_claude_hook(tmp_path) + hooks = _settings(tmp_path)["hooks"] + assert _ours(hooks["SessionStart"]) == [] and _ours(hooks["PreToolUse"]) == [] + + +def test_uninstall_cleans_session_start_from_settings_local(tmp_path): + local = tmp_path / ".claude" / "settings.local.json" + local.parent.mkdir(parents=True) + local.write_text(json.dumps({"hooks": {"SessionStart": install_mod._claude_sessionstart_hooks()}}), + encoding="utf-8") + install_mod._uninstall_claude_hook(tmp_path) + assert json.loads(local.read_text(encoding="utf-8"))["hooks"]["SessionStart"] == []