diff --git a/.claude/hooks/behaviour_docs.py b/.claude/hooks/behaviour_docs.py new file mode 100644 index 0000000..5c80177 --- /dev/null +++ b/.claude/hooks/behaviour_docs.py @@ -0,0 +1,176 @@ +"""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 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. + +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 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 +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 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 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): + 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): + """(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 + 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): + 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 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 last Stop's hooks ran or the turn began.""" + 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 ran_stop_hooks(entry) or is_prompt(entry): + 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, except on Windows from Python 3.14 + 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) + 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 8e10143..07a26df 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 57874f3..84b147e 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`, import sorting, a report-only `ruff check` (F401 and F841 are left to `mise run lint`; the hook's docstring says why) 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 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. Review a pull request that bumps `PICARD_REF` with `/picard-bump `. - For Picard's API, script functions and plugin rules, `.picard/src` at `PICARD_REF` overrides context7 and the online docs, which may describe another release. - 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". diff --git a/tests/test_claude_hooks.py b/tests/test_claude_hooks.py index f69a6c2..b605ad2 100644 --- a/tests/test_claude_hooks.py +++ b/tests/test_claude_hooks.py @@ -964,7 +964,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"] @@ -1008,6 +1008,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(): @@ -1292,3 +1293,311 @@ 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", 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, strict=False): # ids may cover only some + call["id"] = tool_id + return {"type": "assistant", "message": {"role": "assistant", "content": calls}} + + +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}} + + +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) + # 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), + "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("plugins", "helper.py"), + 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_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 + # 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): + 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) + 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_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", + [ + { + "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 + + +@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): + 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 = [ + # 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"}]}}, + {"type": "assistant", "message": {"content": [{"type": "tool_use"}]}}, + { + "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}}, + {"type": "user", "message": "text"}, + {"type": "assistant", "message": [1]}, + tool_result(None, error=True), + tool_result(["a"], error=True), + ["not", "an", "entry"], + ] + bad_path = { + "type": "assistant", + "message": { + "content": [ + {"type": "tool_use", "name": "Edit", "input": {"file_path": "\0"}} + ] + }, + } + lines = ["not json", "{", '{"bad": "\udcff"}'] + reason = stop(tmp_path, prompt(), *odd, bad_path, 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, "", "")