|
| 1 | +"""Shared plumbing for the PreToolUse Bash reminder hooks. |
| 2 | +
|
| 3 | +Each sibling module is one check: a pure `reminder(command, cwd) -> str | None`. `__main__.py` is |
| 4 | +the single entrypoint `.claude/settings.json` invokes; it reads the hook payload once and runs every |
| 5 | +check. This module owns the I/O contract with Claude Code so the checks stay pure and self-evident: |
| 6 | +read the Bash command (and the tool's working directory) from the payload on stdin, and, when a check |
| 7 | +returns text, emit it as non-blocking `additionalContext` that the harness injects into the model's |
| 8 | +context. Nothing here blocks the tool. |
| 9 | +""" |
| 10 | +import json |
| 11 | +import re |
| 12 | +import sys |
| 13 | + |
| 14 | + |
| 15 | +def payload_from_stdin(): |
| 16 | + """The parsed hook payload on stdin, or {} if unavailable.""" |
| 17 | + try: |
| 18 | + return json.load(sys.stdin) |
| 19 | + except Exception: |
| 20 | + return {} |
| 21 | + |
| 22 | + |
| 23 | +def command_of(payload): |
| 24 | + """The Bash command string from a hook payload, or ''.""" |
| 25 | + return (payload.get("tool_input") or {}).get("command") or "" |
| 26 | + |
| 27 | + |
| 28 | +def cwd_of(payload): |
| 29 | + """The working directory Claude Code reports for the tool call, or None.""" |
| 30 | + return payload.get("cwd") or None |
| 31 | + |
| 32 | + |
| 33 | +def matches(command, *words): |
| 34 | + """True if `command` runs `words` as a whitespace-separated token sequence. |
| 35 | +
|
| 36 | + The hook payload only carries the raw command string (there is no structured "which binary |
| 37 | + ran" signal), and fully parsing the shell (pipes, quoting, `$()`, aliases) is impractical and |
| 38 | + still defeatable. A word-boundary regex is the right cost/benefit for an advisory, non-blocking |
| 39 | + nudge: it tolerates extra whitespace and, unlike a plain substring test, does not fire on |
| 40 | + hyphenated look-alikes like `gh-pr-create-helper`. A false positive only adds a harmless |
| 41 | + reminder, so we do not chase quoted-string or comment edge cases. |
| 42 | + """ |
| 43 | + pattern = r"\b" + r"\s+".join(map(re.escape, words)) + r"\b" |
| 44 | + return re.search(pattern, command) is not None |
| 45 | + |
| 46 | + |
| 47 | +def emit(message): |
| 48 | + """Inject `message` into the model's context (non-blocking).""" |
| 49 | + json.dump( |
| 50 | + {"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": message}}, |
| 51 | + sys.stdout, |
| 52 | + ) |
| 53 | + |
| 54 | + |
| 55 | +def run(reminder): |
| 56 | + """Wire a single check's `reminder` to the I/O contract for direct invocation. Returns 0.""" |
| 57 | + payload = payload_from_stdin() |
| 58 | + message = reminder(command_of(payload), cwd_of(payload)) |
| 59 | + if message: |
| 60 | + emit(message) |
| 61 | + return 0 |
0 commit comments