Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 176 additions & 0 deletions .claude/hooks/behaviour_docs.py
Original file line number Diff line number Diff line change
@@ -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/<id>/ needs README.md or plugins/<id>/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())
11 changes: 11 additions & 0 deletions .claude/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
]
}
]
}
}
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <PR>`.
- 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".
Expand Down
Loading