From 42dae990bd2fb27052fdcc27caa23e1b3e666ca4 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Sun, 29 Nov 2026 14:42:54 +1300 Subject: [PATCH 01/10] feat(hooks): remind Claude to update the behaviour docs before a turn ends CLAUDE.md asks for README.md's tables and MANIFEST.toml's long_description to change with the behaviour they describe, but only memory enforced it. A Stop hook reads the turn's Edit, Write and MultiEdit calls from the transcript and, for each worktree they touched, blocks the stop once when a tagger script or a plugin file changed but neither doc did. stop_hook_active lets the next stop through, so Claude can say the behaviour didn't change. --- .claude/hooks/behaviour_docs.py | 138 ++++++++++++++++++++++++++ .claude/settings.json | 11 +++ CLAUDE.md | 2 +- tests/test_claude_hooks.py | 169 +++++++++++++++++++++++++++++++- 4 files changed, 318 insertions(+), 2 deletions(-) create mode 100644 .claude/hooks/behaviour_docs.py diff --git a/.claude/hooks/behaviour_docs.py b/.claude/hooks/behaviour_docs.py new file mode 100644 index 0000000..b465f4c --- /dev/null +++ b/.claude/hooks/behaviour_docs.py @@ -0,0 +1,138 @@ +"""Stop hook: remind Claude to update the behaviour docs when a turn changed a tagger script or +the plugin's code but not the docs that describe it. + +CLAUDE.md asks for the README tables and, for a plugin, MANIFEST.toml's long_description to change +in the same change as the behaviour. The hook reads this turn's Edit, Write and MultiEdit calls +from the transcript, since the last prompt the user typed. For each repo root they touched (a +folder holding tools/run_tests.py, so each worktree is judged on its own), a changed +tagger-scripts/*.ptsp needs README.md edited too, and a changed file under plugins// needs +README.md or plugins//MANIFEST.toml. If one doesn't, the hook blocks the stop once, naming the +files; when Claude continues because of it (stop_hook_active), the next stop goes through, so +Claude can answer that the behaviour didn't change. + +Docs edited in an earlier turn, or in a shell command, don't count, and edits made in a shell +command aren't seen at all. An unreadable transcript, or a line it can't parse, is skipped. +""" + +import json +import sys +from pathlib import Path + +EDIT_TOOLS = {"Edit", "Write", "MultiEdit"} +README = ("README.md",) + + +def repo_root(path): + return next( + (d for d in path.parents if (d / "tools" / "run_tests.py").is_file()), None + ) + + +def hook_input(): + """The Stop hook's JSON from stdin, or None.""" + try: + data = json.loads(sys.stdin.buffer.read().decode("utf-8")) + except ValueError: + return None + return data if isinstance(data, dict) else None + + +def is_prompt(entry): + """A message the user typed, not a tool result or a message Claude Code added.""" + if entry.get("type") != "user" or entry.get("isMeta"): + return False + content = (entry.get("message") or {}).get("content") + if isinstance(content, str): + return True + return isinstance(content, list) and not any( + isinstance(item, dict) and item.get("type") == "tool_result" for item in content + ) + + +def edited_paths(entry): + if entry.get("type") != "assistant": + return + content = (entry.get("message") or {}).get("content") + for item in content if isinstance(content, list) else []: + if not isinstance(item, dict) or item.get("type") != "tool_use": + continue + tool_input = item.get("input") + if item.get("name") in EDIT_TOOLS and isinstance(tool_input, dict): + file_path = tool_input.get("file_path") + if isinstance(file_path, str): + yield file_path + + +def turn_edits(transcript): + """The files the Edit tools changed since the user's last prompt.""" + edits = [] + with open(transcript, encoding="utf-8", errors="replace") as lines: + for line in lines: + try: + entry = json.loads(line) + except ValueError: + continue + if not isinstance(entry, dict): + continue + if is_prompt(entry): + edits = [] + edits.extend(edited_paths(entry)) + return edits + + +def undocumented(paths): + """{root: [changed behaviour file, ...]} for each root whose docs this turn left alone.""" + changed = {} + for file_path in paths: + try: + path = Path(file_path).resolve() + except (OSError, ValueError): + continue + root = repo_root(path) + if root is not None: + changed.setdefault(root, set()).add(path.relative_to(root).parts) + missing = {} + for root, parts in changed.items(): + for part in sorted(parts): + name = part[-1].lower() + if ( + len(part) == 2 + and part[0] == "tagger-scripts" + and name.endswith(".ptsp") + ): + docs = {README} + elif len(part) >= 3 and part[0] == "plugins" and name.endswith(".py"): + docs = {README, ("plugins", part[1], "MANIFEST.toml")} + else: + continue + if not docs & parts: + missing.setdefault(root, []).append("/".join(part)) + return missing + + +def main(): + data = hook_input() + if data is None or data.get("stop_hook_active") is True: + return 0 + transcript = data.get("transcript_path") + if not isinstance(transcript, str): + return 0 + try: + missing = undocumented(turn_edits(transcript)) + except OSError: + return 0 + if not missing: + return 0 + files = "; ".join(f"{', '.join(v)} in {root}" for root, v in missing.items()) + reason = ( + f"This turn changed {files} without editing README.md or the plugin's " + "MANIFEST.toml. CLAUDE.md: behaviour is documented in the README tables and " + "MANIFEST.toml long_description, updated in the same change. If the behaviour " + "changed, update them now; if it didn't, say so in a line and stop." + ) + print(json.dumps({"decision": "block", "reason": reason})) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.claude/settings.json b/.claude/settings.json index 1aa3dfa..69f4fbf 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -33,6 +33,17 @@ } ] } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "python -I -c \"import os, runpy; p = os.path.join(os.environ.get('CLAUDE_PROJECT_DIR', ''), '.claude', 'hooks', 'behaviour_docs.py'); os.path.isfile(p) and runpy.run_path(p, run_name='__main__')\"", + "timeout": 10 + } + ] + } ] } } diff --git a/CLAUDE.md b/CLAUDE.md index 41c1882..3de95b2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -18,7 +18,7 @@ uv run python tools/check_min_python.py [file...] # flags stdlib APIs newer tha - `per-file-target-version` in `pyproject.toml` lists the files that run on an older Python than the test venv's 3.14: the `py39` ones (`tools/run_tests.py`, `tools/install.py`, `tools/ci_changes.py`, `.claude/hooks/`) run on the system Python before the venv exists, the plugin (`py310`) runs on Picard's own Python, and `tools/release_plugin.py` (`py311`, for `tomllib`) on the release job's runner Python. Ruff's target version catches newer syntax, and `tools/check_min_python.py` newer stdlib APIs (README's "Lint, format and type check"). Ruff's `FA102` catches an `X | Y` union in a `py39` file's annotations; nothing catches one evaluated at runtime (`isinstance(x, A | B)`, a type alias): check those by hand. A new file of either kind goes in that list. - Edit `.ptsp` and `.py` files with Edit/Write, not a shell command. The PostToolUse hooks in `.claude/settings.json` only see those tools: they check `.ptsp` edits with Picard's parser (this needs the venv from one `run_tests.py` run) and run `ruff format` and `tools/check_min_python.py` on `.py` edits. - Don't run the `mise run install-*` tasks / `tools/install.py` unless asked: they write the user's real Picard config and plugin folder. -- Behaviour is documented in the README tables and, for the plugin, `MANIFEST.toml` `long_description`. Update them in the same change. In self-review of such a change, dispatch the `behaviour-docs-reviewer` agent with the base ref. +- Behaviour is documented in the README tables and, for the plugin, `MANIFEST.toml` `long_description`. Update them in the same change; a Stop hook blocks a turn's end once when its Edit/Write calls changed a script or plugin file but not those docs. In self-review of such a change, dispatch the `behaviour-docs-reviewer` agent with the base ref. - In self-review of a change to `CLAUDE.md` or `.claude/`, or to what they describe (a `PICARD_REF` bump, `pyproject.toml`, `tools/`), dispatch the `instruction-drift-reviewer` agent with the base ref. - Never create a tag Picard reads as a version (`v1.2.3`, `2.0`, `release-1.2`…) or a GitHub release by hand; see README's "Releasing the plugin". - Tagger scripts run in filename order (04 before 05 matters). A script that writes a new tag needs it added to `WRITTEN` in `tests/test_tagger_scripts.py`. diff --git a/tests/test_claude_hooks.py b/tests/test_claude_hooks.py index 43a9f6c..06d7783 100644 --- a/tests/test_claude_hooks.py +++ b/tests/test_claude_hooks.py @@ -881,7 +881,7 @@ def settings_hooks(): """(event, matcher, hook) for every hook in .claude/settings.json.""" settings = json.loads(SETTINGS.read_text(encoding="utf-8")) return [ - (event, group["matcher"], hook) + (event, group.get("matcher", ""), hook) for event, groups in settings["hooks"].items() for group in groups for hook in group["hooks"] @@ -925,6 +925,7 @@ def test_settings_wire_up_every_hook_script(): "NotebookEdit", } assert wired["guards.py"] == ("PreToolUse", shells_and_edits) + assert wired["behaviour_docs.py"] == ("Stop", {""}) def test_settings_command_runs_the_guard(): @@ -1209,3 +1210,169 @@ def test_guards_allow_other_edits(path): def test_guards_ignore_bad_input(stdin): result = run_hook("guards.py", stdin) assert (result.returncode, result.stdout, result.stderr) == (0, "", "") + + +def prompt(text="go"): + return {"type": "user", "message": {"role": "user", "content": text}} + + +def edit(*paths, tool="Edit"): + """An assistant message calling an edit tool on each path.""" + calls = [ + {"type": "tool_use", "name": tool, "input": {"file_path": str(p)}} + for p in paths + ] + return {"type": "assistant", "message": {"role": "assistant", "content": calls}} + + +def tool_result(): + content = [{"type": "tool_result", "tool_use_id": "x", "content": "ok"}] + return {"type": "user", "message": {"role": "user", "content": content}} + + +def stop(tmp_path, *entries, active=False, lines=()): + """Run behaviour_docs.py on a transcript of these entries. Returns its reason or None.""" + transcript = tmp_path / "transcript.jsonl" + text = [json.dumps(e) for e in entries] + list(lines) + transcript.write_text("\n".join(text) + "\n", encoding="utf-8") + payload = { + "hook_event_name": "Stop", + "transcript_path": str(transcript), + "stop_hook_active": active, + } + result = run_hook("behaviour_docs.py", json.dumps(payload)) + assert (result.returncode, result.stderr) == (0, "") + if not result.stdout: + return None + output = json.loads(result.stdout) + assert output["decision"] == "block" + return output["reason"] + + +SCRIPT = Path("tagger-scripts", "01-x.ptsp") +PLUGIN = Path("plugins", "my-plugin", "__init__.py") +MANIFEST = Path("plugins", "my-plugin", "MANIFEST.toml") + + +def test_behaviour_docs_blocks_a_script_change_without_readme(bare_repo, tmp_path): + reason = stop(tmp_path, prompt(), edit(bare_repo / SCRIPT), tool_result()) + assert reason.startswith( + f"This turn changed tagger-scripts/01-x.ptsp in {bare_repo}" + ) + assert "If the behaviour changed, update them now" in reason + + +@pytest.mark.parametrize( + ("changed", "docs"), + [ + (SCRIPT, "README.md"), + (PLUGIN, "README.md"), + (PLUGIN, MANIFEST), + (Path("tagger-scripts", "01-X.PTSP"), "README.md"), + ], +) +def test_behaviour_docs_pass_a_change_with_its_docs(bare_repo, tmp_path, changed, docs): + assert stop(tmp_path, prompt(), edit(bare_repo / changed, bare_repo / docs)) is None + + +@pytest.mark.parametrize( + "changed", + [ + PLUGIN, + Path("plugins", "my-plugin", "sub", "helper.py"), + Path("tagger-scripts", "02-y.PTSP"), + ], +) +def test_behaviour_docs_block_without_the_docs(bare_repo, tmp_path, changed): + reason = stop(tmp_path, prompt(), edit(bare_repo / changed, tool="MultiEdit")) + assert changed.as_posix() in reason + + +def test_behaviour_docs_need_the_changed_plugin_s_own_manifest(bare_repo, tmp_path): + other = Path("plugins", "other", "MANIFEST.toml") + reason = stop(tmp_path, prompt(), edit(bare_repo / PLUGIN, bare_repo / other)) + assert "plugins/my-plugin/__init__.py" in reason + + +@pytest.mark.parametrize( + "changed", + [ + MANIFEST, + Path("plugins", "README.md"), + Path("plugins", "my-plugin", "notes.txt"), + Path("tagger-scripts", "sub", "x.ptsp"), + Path("tagger-scripts", "notes.md"), + Path("tests", "test_tagger_scripts.py"), + Path("tools", "install.py"), + ], +) +def test_behaviour_docs_ignore_other_files(bare_repo, tmp_path, changed): + assert stop(tmp_path, prompt(), edit(bare_repo / changed, tool="Write")) is None + + +def test_behaviour_docs_judge_each_worktree_on_its_own(project, tmp_path): + entries = [prompt(), edit(project / "wt" / SCRIPT, project / "main" / "README.md")] + reason = stop(tmp_path, *entries) + assert f"tagger-scripts/01-x.ptsp in {project / 'wt'}" in reason + assert str(project / "main") not in reason + + +def test_behaviour_docs_read_only_this_turn(bare_repo, tmp_path): + """Edits before the user's last prompt are an earlier turn's; tool results and messages + Claude Code adds don't start a turn.""" + meta = dict(prompt(""), isMeta=True) + listed = prompt([{"type": "text", "text": "and now?"}]) + readme = edit(bare_repo / "README.md") + script = edit(bare_repo / SCRIPT) + assert stop(tmp_path, readme, prompt(), script) is not None + assert stop(tmp_path, script, prompt(), readme) is None + assert stop(tmp_path, script, listed) is None + assert stop(tmp_path, readme, tool_result(), meta, script) is None + + +def test_behaviour_docs_let_claude_stop_after_one_reminder(bare_repo, tmp_path): + assert stop(tmp_path, prompt(), edit(bare_repo / SCRIPT), active=True) is None + + +def test_behaviour_docs_ignore_files_outside_a_repo(tmp_path): + assert stop(tmp_path, prompt(), edit(tmp_path / SCRIPT)) is None + + +def test_behaviour_docs_skip_what_they_cannot_read(bare_repo, tmp_path): + odd = [ + {"type": "assistant", "message": {"content": "text"}}, + {"type": "assistant", "message": None}, + {"type": "assistant", "message": {"content": ["x", {"type": "text"}]}}, + {"type": "assistant", "message": {"content": [{"type": "tool_use"}]}}, + edit(None), + {"type": "user", "message": {"content": None}}, + ["not", "an", "entry"], + ] + bad_path = { + "type": "assistant", + "message": { + "content": [ + {"type": "tool_use", "name": "Edit", "input": {"file_path": "\0"}} + ] + }, + } + lines = ["not json", "{"] + reason = stop( + tmp_path, prompt(), *odd, bad_path, edit(bare_repo / SCRIPT), lines=lines + ) + assert reason.startswith("This turn changed tagger-scripts/01-x.ptsp") + + +@pytest.mark.parametrize( + "stdin", + [ + "not json", + "[]", + "{}", + '{"transcript_path": null}', + '{"transcript_path": "/no/such/transcript.jsonl"}', + ], +) +def test_behaviour_docs_ignore_bad_input(stdin): + result = run_hook("behaviour_docs.py", stdin) + assert (result.returncode, result.stdout, result.stderr) == (0, "", "") From 02e65654ef4e761d186461febd4ede1258065362 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Sun, 29 Nov 2026 15:41:15 +1300 Subject: [PATCH 02/10] test(hooks): cover a non-string file_path and a NUL path in the Stop hook --- .claude/hooks/behaviour_docs.py | 5 ++--- tests/test_claude_hooks.py | 13 ++++++++++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/.claude/hooks/behaviour_docs.py b/.claude/hooks/behaviour_docs.py index b465f4c..20e7907 100644 --- a/.claude/hooks/behaviour_docs.py +++ b/.claude/hooks/behaviour_docs.py @@ -84,10 +84,9 @@ def undocumented(paths): """{root: [changed behaviour file, ...]} for each root whose docs this turn left alone.""" changed = {} for file_path in paths: - try: - path = Path(file_path).resolve() - except (OSError, ValueError): + if "\0" in file_path: # resolve() raises on it on POSIX, but not on Windows continue + path = Path(file_path).resolve() root = repo_root(path) if root is not None: changed.setdefault(root, set()).add(path.relative_to(root).parts) diff --git a/tests/test_claude_hooks.py b/tests/test_claude_hooks.py index 06d7783..90d9236 100644 --- a/tests/test_claude_hooks.py +++ b/tests/test_claude_hooks.py @@ -1344,7 +1344,18 @@ def test_behaviour_docs_skip_what_they_cannot_read(bare_repo, tmp_path): {"type": "assistant", "message": None}, {"type": "assistant", "message": {"content": ["x", {"type": "text"}]}}, {"type": "assistant", "message": {"content": [{"type": "tool_use"}]}}, - edit(None), + { + "type": "assistant", + "message": { + "content": [ + {"type": "tool_use", "name": "Edit", "input": {"file_path": 5}} + ] + }, + }, + { + "type": "assistant", + "message": {"content": [{"type": "tool_use", "name": "Edit"}]}, + }, {"type": "user", "message": {"content": None}}, ["not", "an", "entry"], ] From 7aafea973e8e9f69bab96f39998c90bc2ab6f844 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Mon, 30 Nov 2026 23:22:37 +1300 Subject: [PATCH 03/10] fix(hooks): say only plugin .py files and the root README count, and pin both --- .claude/hooks/behaviour_docs.py | 4 ++-- CLAUDE.md | 2 +- tests/test_claude_hooks.py | 20 ++++++++++++++++++++ 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/.claude/hooks/behaviour_docs.py b/.claude/hooks/behaviour_docs.py index 20e7907..f35ac23 100644 --- a/.claude/hooks/behaviour_docs.py +++ b/.claude/hooks/behaviour_docs.py @@ -5,8 +5,8 @@ in the same change as the behaviour. The hook reads this turn's Edit, Write and MultiEdit calls from the transcript, since the last prompt the user typed. For each repo root they touched (a folder holding tools/run_tests.py, so each worktree is judged on its own), a changed -tagger-scripts/*.ptsp needs README.md edited too, and a changed file under plugins// needs -README.md or plugins//MANIFEST.toml. If one doesn't, the hook blocks the stop once, naming the +tagger-scripts/*.ptsp needs README.md edited too, and a changed .py file under plugins// needs +README.md or plugins//MANIFEST.toml. Only the root README.md counts. If one doesn't, the hook blocks the stop once, naming the files; when Claude continues because of it (stop_hook_active), the next stop goes through, so Claude can answer that the behaviour didn't change. diff --git a/CLAUDE.md b/CLAUDE.md index 3de95b2..b6d0092 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -18,7 +18,7 @@ uv run python tools/check_min_python.py [file...] # flags stdlib APIs newer tha - `per-file-target-version` in `pyproject.toml` lists the files that run on an older Python than the test venv's 3.14: the `py39` ones (`tools/run_tests.py`, `tools/install.py`, `tools/ci_changes.py`, `.claude/hooks/`) run on the system Python before the venv exists, the plugin (`py310`) runs on Picard's own Python, and `tools/release_plugin.py` (`py311`, for `tomllib`) on the release job's runner Python. Ruff's target version catches newer syntax, and `tools/check_min_python.py` newer stdlib APIs (README's "Lint, format and type check"). Ruff's `FA102` catches an `X | Y` union in a `py39` file's annotations; nothing catches one evaluated at runtime (`isinstance(x, A | B)`, a type alias): check those by hand. A new file of either kind goes in that list. - Edit `.ptsp` and `.py` files with Edit/Write, not a shell command. The PostToolUse hooks in `.claude/settings.json` only see those tools: they check `.ptsp` edits with Picard's parser (this needs the venv from one `run_tests.py` run) and run `ruff format` and `tools/check_min_python.py` on `.py` edits. - Don't run the `mise run install-*` tasks / `tools/install.py` unless asked: they write the user's real Picard config and plugin folder. -- Behaviour is documented in the README tables and, for the plugin, `MANIFEST.toml` `long_description`. Update them in the same change; a Stop hook blocks a turn's end once when its Edit/Write calls changed a script or plugin file but not those docs. In self-review of such a change, dispatch the `behaviour-docs-reviewer` agent with the base ref. +- Behaviour is documented in the README tables and, for the plugin, `MANIFEST.toml` `long_description`. Update them in the same change; a Stop hook blocks a turn's end once when its Edit/Write calls changed a tagger script or a plugin `.py` file but not those docs. In self-review of such a change, dispatch the `behaviour-docs-reviewer` agent with the base ref. - In self-review of a change to `CLAUDE.md` or `.claude/`, or to what they describe (a `PICARD_REF` bump, `pyproject.toml`, `tools/`), dispatch the `instruction-drift-reviewer` agent with the base ref. - Never create a tag Picard reads as a version (`v1.2.3`, `2.0`, `release-1.2`…) or a GitHub release by hand; see README's "Releasing the plugin". - Tagger scripts run in filename order (04 before 05 matters). A script that writes a new tag needs it added to `WRITTEN` in `tests/test_tagger_scripts.py`. diff --git a/tests/test_claude_hooks.py b/tests/test_claude_hooks.py index 90d9236..47fbf61 100644 --- a/tests/test_claude_hooks.py +++ b/tests/test_claude_hooks.py @@ -1310,6 +1310,26 @@ def test_behaviour_docs_ignore_other_files(bare_repo, tmp_path, changed): assert stop(tmp_path, prompt(), edit(bare_repo / changed, tool="Write")) is None +def test_behaviour_docs_count_only_edit_tools(bare_repo, tmp_path): + read_script = edit(bare_repo / SCRIPT, tool="Read") + read_readme = edit(bare_repo / "README.md", tool="Read") + assert stop(tmp_path, prompt(), read_script) is None # a read changes nothing + assert stop(tmp_path, prompt(), edit(bare_repo / SCRIPT), read_readme) is not None + + +@pytest.mark.parametrize( + "nested", + [ + Path("plugins", "README.md"), + Path("plugins", "my-plugin", "README.md"), + Path("tagger-scripts", "README.md"), + ], +) +def test_behaviour_docs_need_the_root_readme(bare_repo, tmp_path, nested): + for changed in (SCRIPT, PLUGIN): + assert stop(tmp_path, prompt(), edit(bare_repo / changed, bare_repo / nested)) + + def test_behaviour_docs_judge_each_worktree_on_its_own(project, tmp_path): entries = [prompt(), edit(project / "wt" / SCRIPT, project / "main" / "README.md")] reason = stop(tmp_path, *entries) From 38301519743496e7a9865c1e3b602cf83f7191f5 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Fri, 4 Dec 2026 16:57:28 +1300 Subject: [PATCH 04/10] test(hooks): pin Write and the plugins/ prefix in the Stop hook; reword its docstring --- .claude/hooks/behaviour_docs.py | 7 ++++--- tests/test_claude_hooks.py | 10 ++++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/.claude/hooks/behaviour_docs.py b/.claude/hooks/behaviour_docs.py index f35ac23..b0d7497 100644 --- a/.claude/hooks/behaviour_docs.py +++ b/.claude/hooks/behaviour_docs.py @@ -6,9 +6,10 @@ from the transcript, since the last prompt the user typed. For each repo root they touched (a folder holding tools/run_tests.py, so each worktree is judged on its own), a changed tagger-scripts/*.ptsp needs README.md edited too, and a changed .py file under plugins// needs -README.md or plugins//MANIFEST.toml. Only the root README.md counts. If one doesn't, the hook blocks the stop once, naming the -files; when Claude continues because of it (stop_hook_active), the next stop goes through, so -Claude can answer that the behaviour didn't change. +README.md or plugins//MANIFEST.toml. Only the root README.md counts. If a root's docs weren't +edited, the hook blocks the stop once, naming the files; when Claude continues because of it +(stop_hook_active), the next stop goes through, so Claude can answer that the behaviour didn't +change. Docs edited in an earlier turn, or in a shell command, don't count, and edits made in a shell command aren't seen at all. An unreadable transcript, or a line it can't parse, is skipped. diff --git a/tests/test_claude_hooks.py b/tests/test_claude_hooks.py index 47fbf61..34d2f36 100644 --- a/tests/test_claude_hooks.py +++ b/tests/test_claude_hooks.py @@ -1303,13 +1303,23 @@ def test_behaviour_docs_need_the_changed_plugin_s_own_manifest(bare_repo, tmp_pa Path("tagger-scripts", "sub", "x.ptsp"), Path("tagger-scripts", "notes.md"), Path("tests", "test_tagger_scripts.py"), + Path("tests", "x.ptsp"), Path("tools", "install.py"), + Path("tools", "sub", "x.py"), + Path(".claude", "hooks", "x.py"), ], ) def test_behaviour_docs_ignore_other_files(bare_repo, tmp_path, changed): assert stop(tmp_path, prompt(), edit(bare_repo / changed, tool="Write")) is None +def test_behaviour_docs_count_write(bare_repo, tmp_path): + script = edit(bare_repo / SCRIPT, tool="Write") + readme = edit(bare_repo / "README.md", tool="Write") + assert stop(tmp_path, prompt(), script) is not None + assert stop(tmp_path, prompt(), edit(bare_repo / SCRIPT), readme) is None + + def test_behaviour_docs_count_only_edit_tools(bare_repo, tmp_path): read_script = edit(bare_repo / SCRIPT, tool="Read") read_readme = edit(bare_repo / "README.md", tool="Read") From 53f91941cadac806c880488d828ba3bec6ba01c8 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Fri, 4 Dec 2026 17:11:52 +1300 Subject: [PATCH 05/10] fix(hooks): keep the turn going past compaction summaries and task notifications, and skip failed edits A compaction summary or a background task's notification is a user entry Claude Code adds mid-task; only a typed prompt (origin kind human, or no origin on older transcripts) starts a turn now. An Edit/Write whose tool_result is an error changed nothing, so it no longer counts. Also: a non-dict message is skipped rather than crashing, the NUL-path comment names the Pythons that raise, and the docstring says subagent edits aren't seen. --- .claude/hooks/behaviour_docs.py | 53 ++++++++++++++++++------- tests/test_claude_hooks.py | 69 +++++++++++++++++++++++++++++++-- 2 files changed, 103 insertions(+), 19 deletions(-) diff --git a/.claude/hooks/behaviour_docs.py b/.claude/hooks/behaviour_docs.py index b0d7497..940f2fc 100644 --- a/.claude/hooks/behaviour_docs.py +++ b/.claude/hooks/behaviour_docs.py @@ -3,7 +3,8 @@ CLAUDE.md asks for the README tables and, for a plugin, MANIFEST.toml's long_description to change in the same change as the behaviour. The hook reads this turn's Edit, Write and MultiEdit calls -from the transcript, since the last prompt the user typed. For each repo root they touched (a +from the transcript, since the last prompt the user typed, leaving out calls whose result was an +error. For each repo root they touched (a folder holding tools/run_tests.py, so each worktree is judged on its own), a changed tagger-scripts/*.ptsp needs README.md edited too, and a changed .py file under plugins// needs README.md or plugins//MANIFEST.toml. Only the root README.md counts. If a root's docs weren't @@ -11,8 +12,8 @@ (stop_hook_active), the next stop goes through, so Claude can answer that the behaviour didn't change. -Docs edited in an earlier turn, or in a shell command, don't count, and edits made in a shell -command aren't seen at all. An unreadable transcript, or a line it can't parse, is skipped. +Docs edited in an earlier turn, or in a shell command, don't count. Edits made in a shell command, +or by a subagent (its calls are in its own transcript), aren't seen at all. An unreadable transcript, or a line it can't parse, is skipped. """ import json @@ -38,11 +39,20 @@ def hook_input(): return data if isinstance(data, dict) else None +def content_of(entry, kind): + message = entry.get("message") if entry.get("type") == kind else None + return message.get("content") if isinstance(message, dict) else None + + def is_prompt(entry): - """A message the user typed, not a tool result or a message Claude Code added.""" - if entry.get("type") != "user" or entry.get("isMeta"): + """A message the user typed: not a tool result, a compaction summary or a background + task's notification, which can all arrive in the middle of a task.""" + content = content_of(entry, "user") + if entry.get("isMeta") or entry.get("isCompactSummary"): return False - content = (entry.get("message") or {}).get("content") + origin = entry.get("origin") + if isinstance(origin, dict) and origin.get("kind") != "human": + return False # older transcripts have no origin if isinstance(content, str): return True return isinstance(content, list) and not any( @@ -51,9 +61,8 @@ def is_prompt(entry): def edited_paths(entry): - if entry.get("type") != "assistant": - return - content = (entry.get("message") or {}).get("content") + """(tool_use id, file_path) for each Edit tool call in an assistant message.""" + content = content_of(entry, "assistant") for item in content if isinstance(content, list) else []: if not isinstance(item, dict) or item.get("type") != "tool_use": continue @@ -61,12 +70,21 @@ def edited_paths(entry): if item.get("name") in EDIT_TOOLS and isinstance(tool_input, dict): file_path = tool_input.get("file_path") if isinstance(file_path, str): - yield file_path + tool_id = item.get("id") + yield (tool_id if isinstance(tool_id, str) else object()), file_path + + +def failed_calls(entry): + """The tool_use ids whose results were errors: a failed, denied or refused edit.""" + content = content_of(entry, "user") + for item in content if isinstance(content, list) else []: + if isinstance(item, dict) and item.get("is_error") is True: + yield item.get("tool_use_id") def turn_edits(transcript): """The files the Edit tools changed since the user's last prompt.""" - edits = [] + edits = {} with open(transcript, encoding="utf-8", errors="replace") as lines: for line in lines: try: @@ -76,16 +94,21 @@ def turn_edits(transcript): if not isinstance(entry, dict): continue if is_prompt(entry): - edits = [] - edits.extend(edited_paths(entry)) - return edits + edits = {} + edits.update(edited_paths(entry)) + for tool_id in failed_calls(entry): + if isinstance(tool_id, str): + edits.pop(tool_id, None) + return list(edits.values()) def undocumented(paths): """{root: [changed behaviour file, ...]} for each root whose docs this turn left alone.""" changed = {} for file_path in paths: - if "\0" in file_path: # resolve() raises on it on POSIX, but not on Windows + if ( + "\0" in file_path + ): # resolve() raises on it, except on Windows from Python 3.14 continue path = Path(file_path).resolve() root = repo_root(path) diff --git a/tests/test_claude_hooks.py b/tests/test_claude_hooks.py index 34d2f36..1066de0 100644 --- a/tests/test_claude_hooks.py +++ b/tests/test_claude_hooks.py @@ -1216,17 +1216,26 @@ def prompt(text="go"): return {"type": "user", "message": {"role": "user", "content": text}} -def edit(*paths, tool="Edit"): - """An assistant message calling an edit tool on each path.""" +def edit(*paths, tool="Edit", ids=()): + """An assistant message calling an edit tool on each path, with these tool_use ids.""" calls = [ {"type": "tool_use", "name": tool, "input": {"file_path": str(p)}} for p in paths ] + for call, tool_id in zip(calls, ids): + call["id"] = tool_id return {"type": "assistant", "message": {"role": "assistant", "content": calls}} -def tool_result(): - content = [{"type": "tool_result", "tool_use_id": "x", "content": "ok"}] +def tool_result(tool_id="x", error=False): + content = [ + { + "type": "tool_result", + "tool_use_id": tool_id, + "content": "ok", + "is_error": error, + } + ] return {"type": "user", "message": {"role": "user", "content": content}} @@ -1302,6 +1311,7 @@ def test_behaviour_docs_need_the_changed_plugin_s_own_manifest(bare_repo, tmp_pa Path("plugins", "my-plugin", "notes.txt"), Path("tagger-scripts", "sub", "x.ptsp"), Path("tagger-scripts", "notes.md"), + Path("plugins", "helper.py"), Path("tests", "test_tagger_scripts.py"), Path("tests", "x.ptsp"), Path("tools", "install.py"), @@ -1320,6 +1330,30 @@ def test_behaviour_docs_count_write(bare_repo, tmp_path): assert stop(tmp_path, prompt(), edit(bare_repo / SCRIPT), readme) is None +def test_behaviour_docs_name_every_file_in_order(bare_repo, tmp_path): + reason = stop(tmp_path, prompt(), edit(bare_repo / SCRIPT, bare_repo / PLUGIN)) + assert reason.startswith( + "This turn changed plugins/my-plugin/__init__.py, tagger-scripts/01-x.ptsp" + f" in {bare_repo} without" + ) + + +def test_behaviour_docs_resolve_the_path(bare_repo, tmp_path): + reason = stop(tmp_path, prompt(), edit(bare_repo / "tests" / ".." / SCRIPT)) + assert reason.startswith("This turn changed tagger-scripts/01-x.ptsp in") + + +def test_behaviour_docs_skip_failed_edits(bare_repo, tmp_path): + """A call whose result was an error (a failed, denied or refused edit) changed nothing.""" + script, readme = ( + edit(bare_repo / SCRIPT, ids=["s"]), + edit(bare_repo / "README.md", ids=["r"]), + ) + assert stop(tmp_path, prompt(), script, tool_result("s", error=True)) is None + assert stop(tmp_path, prompt(), script, readme, tool_result("r", error=True)) + assert stop(tmp_path, prompt(), script, readme, tool_result("r")) is None + + def test_behaviour_docs_count_only_edit_tools(bare_repo, tmp_path): read_script = edit(bare_repo / SCRIPT, tool="Read") read_readme = edit(bare_repo / "README.md", tool="Read") @@ -1360,6 +1394,30 @@ def test_behaviour_docs_read_only_this_turn(bare_repo, tmp_path): assert stop(tmp_path, readme, tool_result(), meta, script) is None +@pytest.mark.parametrize( + "entry", + [ + { + "type": "user", + "isCompactSummary": True, + "isVisibleInTranscriptOnly": True, + "message": {"content": "This session is being continued..."}, + }, + { + "type": "user", + "origin": {"kind": "task-notification"}, + "message": {"content": "..."}, + }, + ], +) +def test_behaviour_docs_carry_the_turn_past_added_messages(bare_repo, tmp_path, entry): + """A compaction summary or a background task's notification can arrive mid-task.""" + script = edit(bare_repo / SCRIPT) + assert stop(tmp_path, prompt(), script, entry) is not None + typed = dict(prompt(), origin={"kind": "human"}) + assert stop(tmp_path, script, entry, typed) is None + + def test_behaviour_docs_let_claude_stop_after_one_reminder(bare_repo, tmp_path): assert stop(tmp_path, prompt(), edit(bare_repo / SCRIPT), active=True) is None @@ -1387,6 +1445,9 @@ def test_behaviour_docs_skip_what_they_cannot_read(bare_repo, tmp_path): "message": {"content": [{"type": "tool_use", "name": "Edit"}]}, }, {"type": "user", "message": {"content": None}}, + {"type": "user", "message": "text"}, + {"type": "assistant", "message": [1]}, + tool_result(None, error=True), ["not", "an", "entry"], ] bad_path = { From f8215132cd7f3cfdf220909780a37b2ea1bbeb48 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Fri, 4 Dec 2026 17:21:40 +1300 Subject: [PATCH 06/10] fix(hooks): a task notification starts a turn again Each background task's notification is answered in a turn of its own, which ends in a Stop with stop_hook_active false, so carrying the earlier turn's edits past it re-raised a reminder Claude had already answered, once per notification. Mid-turn notifications are queued attachments, never user entries. Only compaction summaries stay excluded. Also pins an error result that matches no edit. --- .claude/hooks/behaviour_docs.py | 23 ++++++++-------- tests/test_claude_hooks.py | 48 +++++++++++++++++---------------- 2 files changed, 36 insertions(+), 35 deletions(-) diff --git a/.claude/hooks/behaviour_docs.py b/.claude/hooks/behaviour_docs.py index 940f2fc..05db6b4 100644 --- a/.claude/hooks/behaviour_docs.py +++ b/.claude/hooks/behaviour_docs.py @@ -3,17 +3,18 @@ CLAUDE.md asks for the README tables and, for a plugin, MANIFEST.toml's long_description to change in the same change as the behaviour. The hook reads this turn's Edit, Write and MultiEdit calls -from the transcript, since the last prompt the user typed, leaving out calls whose result was an -error. For each repo root they touched (a -folder holding tools/run_tests.py, so each worktree is judged on its own), a changed -tagger-scripts/*.ptsp needs README.md edited too, and a changed .py file under plugins// needs -README.md or plugins//MANIFEST.toml. Only the root README.md counts. If a root's docs weren't -edited, the hook blocks the stop once, naming the files; when Claude continues because of it +from the transcript (since the last prompt the user typed or a background task's notification), +leaving out calls whose result was an error. For each repo root they touched (a folder holding +tools/run_tests.py, so each worktree is judged on its own), a changed tagger-scripts/*.ptsp needs +README.md edited too, and a changed .py file under plugins// needs README.md or +plugins//MANIFEST.toml. Only the root README.md counts. If a root's docs weren't edited, the +hook blocks the stop once, naming the files; when Claude continues because of it (stop_hook_active), the next stop goes through, so Claude can answer that the behaviour didn't change. Docs edited in an earlier turn, or in a shell command, don't count. Edits made in a shell command, -or by a subagent (its calls are in its own transcript), aren't seen at all. An unreadable transcript, or a line it can't parse, is skipped. +or by a subagent (its calls are in its own transcript), aren't seen at all. An unreadable +transcript, or a line it can't parse, is skipped. """ import json @@ -45,14 +46,12 @@ def content_of(entry, kind): def is_prompt(entry): - """A message the user typed: not a tool result, a compaction summary or a background - task's notification, which can all arrive in the middle of a task.""" + """A message that starts a turn: a prompt the user typed or a background task's + notification. Not a tool result, a message Claude Code added, or a compaction summary, + which can land in the middle of a turn.""" content = content_of(entry, "user") if entry.get("isMeta") or entry.get("isCompactSummary"): return False - origin = entry.get("origin") - if isinstance(origin, dict) and origin.get("kind") != "human": - return False # older transcripts have no origin if isinstance(content, str): return True return isinstance(content, list) and not any( diff --git a/tests/test_claude_hooks.py b/tests/test_claude_hooks.py index 1066de0..5a8f8a2 100644 --- a/tests/test_claude_hooks.py +++ b/tests/test_claude_hooks.py @@ -1222,7 +1222,7 @@ def edit(*paths, tool="Edit", ids=()): {"type": "tool_use", "name": tool, "input": {"file_path": str(p)}} for p in paths ] - for call, tool_id in zip(calls, ids): + for call, tool_id in zip(calls, ids, strict=False): # ids may cover only some call["id"] = tool_id return {"type": "assistant", "message": {"role": "assistant", "content": calls}} @@ -1352,6 +1352,9 @@ def test_behaviour_docs_skip_failed_edits(bare_repo, tmp_path): assert stop(tmp_path, prompt(), script, tool_result("s", error=True)) is None assert stop(tmp_path, prompt(), script, readme, tool_result("r", error=True)) assert stop(tmp_path, prompt(), script, readme, tool_result("r")) is None + # Another tool's failure, or an earlier turn's, matches no edit of this turn. + assert stop(tmp_path, prompt(), script, tool_result("bash", error=True)) + assert stop(tmp_path, script, prompt(), tool_result("s", error=True)) is None def test_behaviour_docs_count_only_edit_tools(bare_repo, tmp_path): @@ -1394,28 +1397,25 @@ def test_behaviour_docs_read_only_this_turn(bare_repo, tmp_path): assert stop(tmp_path, readme, tool_result(), meta, script) is None -@pytest.mark.parametrize( - "entry", - [ - { - "type": "user", - "isCompactSummary": True, - "isVisibleInTranscriptOnly": True, - "message": {"content": "This session is being continued..."}, - }, - { - "type": "user", - "origin": {"kind": "task-notification"}, - "message": {"content": "..."}, - }, - ], -) -def test_behaviour_docs_carry_the_turn_past_added_messages(bare_repo, tmp_path, entry): - """A compaction summary or a background task's notification can arrive mid-task.""" - script = edit(bare_repo / SCRIPT) - assert stop(tmp_path, prompt(), script, entry) is not None - typed = dict(prompt(), origin={"kind": "human"}) - assert stop(tmp_path, script, entry, typed) is None +def test_behaviour_docs_carry_the_turn_past_a_compaction_summary(bare_repo, tmp_path): + summary = { + "type": "user", + "isCompactSummary": True, + "isVisibleInTranscriptOnly": True, + "message": {"content": "This session is being continued..."}, + } + assert stop(tmp_path, prompt(), edit(bare_repo / SCRIPT), summary) is not None + + +def test_behaviour_docs_start_a_turn_at_a_task_notification(bare_repo, tmp_path): + """Claude answers a notification in a turn of its own, so an earlier turn's edit, + already reminded about once, isn't raised again.""" + notification = { + "type": "user", + "origin": {"kind": "task-notification"}, + "message": {"content": "..."}, + } + assert stop(tmp_path, prompt(), edit(bare_repo / SCRIPT), notification) is None def test_behaviour_docs_let_claude_stop_after_one_reminder(bare_repo, tmp_path): @@ -1447,7 +1447,9 @@ def test_behaviour_docs_skip_what_they_cannot_read(bare_repo, tmp_path): {"type": "user", "message": {"content": None}}, {"type": "user", "message": "text"}, {"type": "assistant", "message": [1]}, + {"type": "user", "message": {"content": ["x", 5, None]}}, tool_result(None, error=True), + tool_result(["a"], error=True), ["not", "an", "entry"], ] bad_path = { From 5c9537cb6b8d7026ff87b65ed4bb499db1c58f83 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Fri, 4 Dec 2026 17:27:16 +1300 Subject: [PATCH 07/10] fix(hooks): another agent's message starts a turn too A subagent's hand-back is a user entry marked isMeta with origin kind peer, and Claude answers it in a turn of its own, so it re-raised the earlier turn's reminder just as task notifications did. The message resuming a turn a usage limit cut off (auto-continuation) still carries the turn, and that is pinned. Docstrings now say what starts a turn; a test assertion that couldn't fail is gone. --- .claude/hooks/behaviour_docs.py | 21 +++++++---- tests/test_claude_hooks.py | 64 ++++++++++++++++++++++----------- 2 files changed, 59 insertions(+), 26 deletions(-) diff --git a/.claude/hooks/behaviour_docs.py b/.claude/hooks/behaviour_docs.py index 05db6b4..64e4c83 100644 --- a/.claude/hooks/behaviour_docs.py +++ b/.claude/hooks/behaviour_docs.py @@ -3,8 +3,8 @@ CLAUDE.md asks for the README tables and, for a plugin, MANIFEST.toml's long_description to change in the same change as the behaviour. The hook reads this turn's Edit, Write and MultiEdit calls -from the transcript (since the last prompt the user typed or a background task's notification), -leaving out calls whose result was an error. For each repo root they touched (a folder holding +from the transcript (since the last prompt the user typed, or message from a background task or +another agent), leaving out calls whose result was an error. For each repo root they touched (a folder holding tools/run_tests.py, so each worktree is judged on its own), a changed tagger-scripts/*.ptsp needs README.md edited too, and a changed .py file under plugins// needs README.md or plugins//MANIFEST.toml. Only the root README.md counts. If a root's docs weren't edited, the @@ -46,10 +46,19 @@ def content_of(entry, kind): def is_prompt(entry): - """A message that starts a turn: a prompt the user typed or a background task's - notification. Not a tool result, a message Claude Code added, or a compaction summary, - which can land in the middle of a turn.""" + """A message that starts a turn: a prompt the user typed, a background task's notification + or another agent's message. Not a tool result, another isMeta message (such as the one that + resumes a turn cut off by a usage limit), or a compaction summary, excluded in case one + lands mid-turn.""" content = content_of(entry, "user") + origin = entry.get("origin") + # Another agent's message is marked isMeta, but Claude answers it in a turn of its own. + if ( + isinstance(origin, dict) + and origin.get("kind") == "peer" + and content is not None + ): + return True if entry.get("isMeta") or entry.get("isCompactSummary"): return False if isinstance(content, str): @@ -82,7 +91,7 @@ def failed_calls(entry): def turn_edits(transcript): - """The files the Edit tools changed since the user's last prompt.""" + """The files the Edit tools changed since the turn began (see is_prompt).""" edits = {} with open(transcript, encoding="utf-8", errors="replace") as lines: for line in lines: diff --git a/tests/test_claude_hooks.py b/tests/test_claude_hooks.py index 5a8f8a2..7cf21ab 100644 --- a/tests/test_claude_hooks.py +++ b/tests/test_claude_hooks.py @@ -1352,9 +1352,8 @@ def test_behaviour_docs_skip_failed_edits(bare_repo, tmp_path): assert stop(tmp_path, prompt(), script, tool_result("s", error=True)) is None assert stop(tmp_path, prompt(), script, readme, tool_result("r", error=True)) assert stop(tmp_path, prompt(), script, readme, tool_result("r")) is None - # Another tool's failure, or an earlier turn's, matches no edit of this turn. + # Another tool's failure matches no edit. assert stop(tmp_path, prompt(), script, tool_result("bash", error=True)) - assert stop(tmp_path, script, prompt(), tool_result("s", error=True)) is None def test_behaviour_docs_count_only_edit_tools(bare_repo, tmp_path): @@ -1397,25 +1396,50 @@ def test_behaviour_docs_read_only_this_turn(bare_repo, tmp_path): assert stop(tmp_path, readme, tool_result(), meta, script) is None -def test_behaviour_docs_carry_the_turn_past_a_compaction_summary(bare_repo, tmp_path): - summary = { - "type": "user", - "isCompactSummary": True, - "isVisibleInTranscriptOnly": True, - "message": {"content": "This session is being continued..."}, - } - assert stop(tmp_path, prompt(), edit(bare_repo / SCRIPT), summary) is not None +@pytest.mark.parametrize( + "entry", + [ + { + "type": "user", + "isCompactSummary": True, + "isVisibleInTranscriptOnly": True, + "message": {"content": "This session is being continued..."}, + }, + { + "type": "user", + "isMeta": True, + "origin": {"kind": "auto-continuation"}, + "message": {"content": "Your usage limit has reset. Continue the task."}, + }, + ], +) +def test_behaviour_docs_carry_the_turn_past_these(bare_repo, tmp_path, entry): + """A compaction summary, or the message resuming a turn a usage limit cut off.""" + assert stop(tmp_path, prompt(), edit(bare_repo / SCRIPT), entry) is not None -def test_behaviour_docs_start_a_turn_at_a_task_notification(bare_repo, tmp_path): - """Claude answers a notification in a turn of its own, so an earlier turn's edit, - already reminded about once, isn't raised again.""" - notification = { - "type": "user", - "origin": {"kind": "task-notification"}, - "message": {"content": "..."}, - } - assert stop(tmp_path, prompt(), edit(bare_repo / SCRIPT), notification) is None +@pytest.mark.parametrize( + "entry", + [ + { + "type": "user", + "origin": {"kind": "task-notification"}, + "message": {"content": "..."}, + }, + { + "type": "user", + "isMeta": True, + "origin": {"kind": "peer"}, + "message": {"content": "Another Claude session sent a message: ..."}, + }, + ], +) +def test_behaviour_docs_start_a_turn_at_these(bare_repo, tmp_path, entry): + """Claude answers a background task's notification or another agent's message in a turn + of its own, so an earlier turn's edit, already reminded about once, isn't raised again.""" + assert stop(tmp_path, prompt(), edit(bare_repo / SCRIPT), entry) is None + empty = dict(entry, message={}) # one with no content starts nothing + assert stop(tmp_path, prompt(), edit(bare_repo / SCRIPT), empty) def test_behaviour_docs_let_claude_stop_after_one_reminder(bare_repo, tmp_path): @@ -1447,7 +1471,7 @@ def test_behaviour_docs_skip_what_they_cannot_read(bare_repo, tmp_path): {"type": "user", "message": {"content": None}}, {"type": "user", "message": "text"}, {"type": "assistant", "message": [1]}, - {"type": "user", "message": {"content": ["x", 5, None]}}, + {"type": "user", "message": {"content": ["x", 5, None]}}, # a prompt, oddly tool_result(None, error=True), tool_result(["a"], error=True), ["not", "an", "entry"], From a199e3e5f472feb4f5964a8f3c64bcf08e643169 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Fri, 4 Dec 2026 17:43:48 +1300 Subject: [PATCH 08/10] fix(hooks): judge only edits since the last Stop's hooks ran Claude Code writes a stop_hook_summary entry after each Stop's hooks run, so resetting there too means a /loop wakeup (an isMeta prompt) or an auto-continuation after a graceful stop no longer re-raises edits an earlier Stop judged. Prompt resets stay as the fallback. A turn that ends with no Stop (interrupt, API error) still loses its edits; the docstring says so. Tests: the odd-entries case no longer resets its own garbage, and invalid UTF-8 and a non-string tool_use_id are pinned. --- .claude/hooks/behaviour_docs.py | 18 ++++++++++++------ tests/test_claude_hooks.py | 23 +++++++++++++++++++---- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/.claude/hooks/behaviour_docs.py b/.claude/hooks/behaviour_docs.py index 64e4c83..0dfb88f 100644 --- a/.claude/hooks/behaviour_docs.py +++ b/.claude/hooks/behaviour_docs.py @@ -3,8 +3,8 @@ CLAUDE.md asks for the README tables and, for a plugin, MANIFEST.toml's long_description to change in the same change as the behaviour. The hook reads this turn's Edit, Write and MultiEdit calls -from the transcript (since the last prompt the user typed, or message from a background task or -another agent), leaving out calls whose result was an error. For each repo root they touched (a folder holding +from the transcript since the last Stop's hooks ran or the turn began (a prompt the user typed, or +a message from a background task or another agent), leaving out calls whose result was an error. For each repo root they touched (a folder holding tools/run_tests.py, so each worktree is judged on its own), a changed tagger-scripts/*.ptsp needs README.md edited too, and a changed .py file under plugins// needs README.md or plugins//MANIFEST.toml. Only the root README.md counts. If a root's docs weren't edited, the @@ -13,8 +13,9 @@ change. Docs edited in an earlier turn, or in a shell command, don't count. Edits made in a shell command, -or by a subagent (its calls are in its own transcript), aren't seen at all. An unreadable -transcript, or a line it can't parse, is skipped. +or by a subagent (its calls are in its own transcript), aren't seen at all, and neither are those +of a turn that ended with no Stop (interrupted, or cut off by an API error) once the next one +begins. An unreadable transcript, or a line it can't parse, is skipped. """ import json @@ -90,8 +91,13 @@ def failed_calls(entry): yield item.get("tool_use_id") +def ran_stop_hooks(entry): + """The summary Claude Code writes once a Stop's hooks have run: what came before was judged.""" + return entry.get("type") == "system" and entry.get("subtype") == "stop_hook_summary" + + def turn_edits(transcript): - """The files the Edit tools changed since the turn began (see is_prompt).""" + """The files the Edit tools changed since the last Stop's hooks ran or the turn began.""" edits = {} with open(transcript, encoding="utf-8", errors="replace") as lines: for line in lines: @@ -101,7 +107,7 @@ def turn_edits(transcript): continue if not isinstance(entry, dict): continue - if is_prompt(entry): + if ran_stop_hooks(entry) or is_prompt(entry): edits = {} edits.update(edited_paths(entry)) for tool_id in failed_calls(entry): diff --git a/tests/test_claude_hooks.py b/tests/test_claude_hooks.py index 7cf21ab..2d5c5bb 100644 --- a/tests/test_claude_hooks.py +++ b/tests/test_claude_hooks.py @@ -1243,7 +1243,10 @@ def stop(tmp_path, *entries, active=False, lines=()): """Run behaviour_docs.py on a transcript of these entries. Returns its reason or None.""" transcript = tmp_path / "transcript.jsonl" text = [json.dumps(e) for e in entries] + list(lines) - transcript.write_text("\n".join(text) + "\n", encoding="utf-8") + # surrogateescape lets a line carry bytes that aren't UTF-8: "\udcff" is written as 0xff. + transcript.write_text( + "\n".join(text) + "\n", encoding="utf-8", errors="surrogateescape" + ) payload = { "hook_event_name": "Stop", "transcript_path": str(transcript), @@ -1352,8 +1355,9 @@ def test_behaviour_docs_skip_failed_edits(bare_repo, tmp_path): assert stop(tmp_path, prompt(), script, tool_result("s", error=True)) is None assert stop(tmp_path, prompt(), script, readme, tool_result("r", error=True)) assert stop(tmp_path, prompt(), script, readme, tool_result("r")) is None - # Another tool's failure matches no edit. + # Another tool's failure matches no edit, nor does one with an id that isn't a string. assert stop(tmp_path, prompt(), script, tool_result("bash", error=True)) + assert stop(tmp_path, prompt(), script, tool_result(["s"], error=True)) def test_behaviour_docs_count_only_edit_tools(bare_repo, tmp_path): @@ -1396,6 +1400,16 @@ def test_behaviour_docs_read_only_this_turn(bare_repo, tmp_path): assert stop(tmp_path, readme, tool_result(), meta, script) is None +def test_behaviour_docs_judge_only_edits_since_the_last_stop(bare_repo, tmp_path): + """Edits before a Stop whose hooks ran were judged there, even when the next turn starts + with a message that isn't a prompt, such as a /loop wakeup.""" + ran = {"type": "system", "subtype": "stop_hook_summary"} + wakeup = dict(prompt("/loop"), isMeta=True, turnOrigin="scheduled") + script = edit(bare_repo / SCRIPT) + assert stop(tmp_path, prompt(), script, ran, wakeup) is None + assert stop(tmp_path, prompt(), ran, wakeup, script) is not None + + @pytest.mark.parametrize( "entry", [ @@ -1452,6 +1466,8 @@ def test_behaviour_docs_ignore_files_outside_a_repo(tmp_path): def test_behaviour_docs_skip_what_they_cannot_read(bare_repo, tmp_path): odd = [ + # A prompt, oddly, so first: anything after it must survive to the verdict. + {"type": "user", "message": {"content": ["x", 5, None]}}, {"type": "assistant", "message": {"content": "text"}}, {"type": "assistant", "message": None}, {"type": "assistant", "message": {"content": ["x", {"type": "text"}]}}, @@ -1471,7 +1487,6 @@ def test_behaviour_docs_skip_what_they_cannot_read(bare_repo, tmp_path): {"type": "user", "message": {"content": None}}, {"type": "user", "message": "text"}, {"type": "assistant", "message": [1]}, - {"type": "user", "message": {"content": ["x", 5, None]}}, # a prompt, oddly tool_result(None, error=True), tool_result(["a"], error=True), ["not", "an", "entry"], @@ -1484,7 +1499,7 @@ def test_behaviour_docs_skip_what_they_cannot_read(bare_repo, tmp_path): ] }, } - lines = ["not json", "{"] + lines = ["not json", "{", '{"bad": "\udcff"}'] reason = stop( tmp_path, prompt(), *odd, bad_path, edit(bare_repo / SCRIPT), lines=lines ) From 6e134ea4f493a7997425d7a7062e278c9af2807b Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Fri, 4 Dec 2026 18:05:00 +1300 Subject: [PATCH 09/10] fix(hooks): make the Stop hook's odd-entries test reach the verdict; correct its docstring The edit now sits right after the prompt-like entry, so the garbage after it must leave it in place. The docstring says a resumed turn carries a cut-off turn's edits on, and is rewrapped. --- .claude/hooks/behaviour_docs.py | 19 ++++++++++--------- tests/test_claude_hooks.py | 7 +++---- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/.claude/hooks/behaviour_docs.py b/.claude/hooks/behaviour_docs.py index 0dfb88f..98cb202 100644 --- a/.claude/hooks/behaviour_docs.py +++ b/.claude/hooks/behaviour_docs.py @@ -4,18 +4,19 @@ CLAUDE.md asks for the README tables and, for a plugin, MANIFEST.toml's long_description to change in the same change as the behaviour. The hook reads this turn's Edit, Write and MultiEdit calls from the transcript since the last Stop's hooks ran or the turn began (a prompt the user typed, or -a message from a background task or another agent), leaving out calls whose result was an error. For each repo root they touched (a folder holding -tools/run_tests.py, so each worktree is judged on its own), a changed tagger-scripts/*.ptsp needs -README.md edited too, and a changed .py file under plugins// needs README.md or -plugins//MANIFEST.toml. Only the root README.md counts. If a root's docs weren't edited, the -hook blocks the stop once, naming the files; when Claude continues because of it -(stop_hook_active), the next stop goes through, so Claude can answer that the behaviour didn't -change. +a message from a background task or another agent), leaving out calls whose result was an error. +For each repo root they touched (a folder holding tools/run_tests.py, so each worktree is judged +on its own), a changed tagger-scripts/*.ptsp needs README.md edited too, and a changed .py file +under plugins// needs README.md or plugins//MANIFEST.toml. Only the root README.md counts. +If a root's docs weren't edited, the hook blocks the stop once, naming the files; when Claude +continues because of it (stop_hook_active), the next stop goes through, so Claude can answer that +the behaviour didn't change. Docs edited in an earlier turn, or in a shell command, don't count. Edits made in a shell command, or by a subagent (its calls are in its own transcript), aren't seen at all, and neither are those -of a turn that ended with no Stop (interrupted, or cut off by an API error) once the next one -begins. An unreadable transcript, or a line it can't parse, is skipped. +of a turn that ended with no Stop (interrupted, or cut off by an API error) once a prompt starts +the next one (a usage-limit or /loop resume carries them on). An unreadable transcript, or a line +it can't parse, is skipped. """ import json diff --git a/tests/test_claude_hooks.py b/tests/test_claude_hooks.py index 2d5c5bb..3a832a7 100644 --- a/tests/test_claude_hooks.py +++ b/tests/test_claude_hooks.py @@ -1466,8 +1466,9 @@ def test_behaviour_docs_ignore_files_outside_a_repo(tmp_path): def test_behaviour_docs_skip_what_they_cannot_read(bare_repo, tmp_path): odd = [ - # A prompt, oddly, so first: anything after it must survive to the verdict. + # A prompt, oddly, so first: the edit after it must survive to the verdict. {"type": "user", "message": {"content": ["x", 5, None]}}, + edit(bare_repo / SCRIPT), {"type": "assistant", "message": {"content": "text"}}, {"type": "assistant", "message": None}, {"type": "assistant", "message": {"content": ["x", {"type": "text"}]}}, @@ -1500,9 +1501,7 @@ def test_behaviour_docs_skip_what_they_cannot_read(bare_repo, tmp_path): }, } lines = ["not json", "{", '{"bad": "\udcff"}'] - reason = stop( - tmp_path, prompt(), *odd, bad_path, edit(bare_repo / SCRIPT), lines=lines - ) + reason = stop(tmp_path, prompt(), *odd, bad_path, lines=lines) assert reason.startswith("This turn changed tagger-scripts/01-x.ptsp") From ce7d9f2becf48a3a538fd85432305fe04ebd2bc5 Mon Sep 17 00:00:00 2001 From: Robert Richardson Date: Fri, 4 Dec 2026 18:08:04 +1300 Subject: [PATCH 10/10] docs(hooks): any message that starts a turn drops an unstopped turn's edits, not only a prompt --- .claude/hooks/behaviour_docs.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.claude/hooks/behaviour_docs.py b/.claude/hooks/behaviour_docs.py index 98cb202..5c80177 100644 --- a/.claude/hooks/behaviour_docs.py +++ b/.claude/hooks/behaviour_docs.py @@ -14,9 +14,9 @@ Docs edited in an earlier turn, or in a shell command, don't count. Edits made in a shell command, or by a subagent (its calls are in its own transcript), aren't seen at all, and neither are those -of a turn that ended with no Stop (interrupted, or cut off by an API error) once a prompt starts -the next one (a usage-limit or /loop resume carries them on). An unreadable transcript, or a line -it can't parse, is skipped. +of a turn that ended with no Stop (interrupted, or cut off by an API error) once a prompt or +message starts the next one (a usage-limit resume or /loop wakeup carries them on). An unreadable +transcript, or a line it can't parse, is skipped. """ import json