diff options
| author | Claude <noreply@anthropic.com> | 2026-10-13 21:01:00 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-13 21:01:00 +0000 |
| commit | 49a4d974b935e20dc2b9a49a26ab175d37a01aa7 (patch) | |
| tree | 00babcbb64095e73ee6df512415456219badf8cf /plugins | |
| parent | 8d392c8169665866be1d95f2bfeda5aaae7149dd (diff) | |
security-guidance: start fewer hook processes per Bash call
Claude Code runs every `if`-filtered hook entry when it cannot parse a
Bash command, so the seven commit/push entries started seven processes
on those calls. Use three entries (git commit, git push, gt) and let the
hook's own regex decide what is a commit or a push.
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/hooks.json | 50 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 53 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_repo_resolution.py | 26 |
3 files changed, 55 insertions, 74 deletions
diff --git a/plugins/security-guidance/hooks/hooks.json b/plugins/security-guidance/hooks/hooks.json index a4723026..eef54730 100644 --- a/plugins/security-guidance/hooks/hooks.json +++ b/plugins/security-guidance/hooks/hooks.json @@ -37,58 +37,26 @@ { "type": "command", "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(git commit:*)", + "if": "Bash(git*commit*)", "asyncRewake": true, - "rewakeMessage": "Background security review of commit — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Commit security review found issues" + "rewakeMessage": "Background security review of committed or pushed changes — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", + "rewakeSummary": "Security review found issues" }, { "type": "command", "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(git -C * commit *)", + "if": "Bash(git*push*)", "asyncRewake": true, - "rewakeMessage": "Background security review of commit — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Commit security review found issues" + "rewakeMessage": "Background security review of committed or pushed changes — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", + "rewakeSummary": "Security review found issues" }, { "type": "command", "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(git push:*)", + "if": "Bash(gt *)", "asyncRewake": true, - "rewakeMessage": "Background security review of pushed commits not yet reviewed — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Push security review found issues" - }, - { - "type": "command", - "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(git -C * push*)", - "asyncRewake": true, - "rewakeMessage": "Background security review of pushed commits not yet reviewed — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Push security review found issues" - }, - { - "type": "command", - "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(gt create:*)", - "asyncRewake": true, - "rewakeMessage": "Background security review of commit — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Commit security review found issues" - }, - { - "type": "command", - "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(gt modify:*)", - "asyncRewake": true, - "rewakeMessage": "Background security review of commit — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Commit security review found issues" - }, - { - "type": "command", - "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"", - "if": "Bash(gt submit:*)", - "asyncRewake": true, - "rewakeMessage": "Background security review of pushed commits not yet reviewed — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", - "rewakeSummary": "Push security review found issues" + "rewakeMessage": "Background security review of committed or pushed changes — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply:", + "rewakeSummary": "Security review found issues" } ], "matcher": "Bash" diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index f36cb475..b7eb0966 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -658,18 +658,13 @@ _COMMIT_DIFFSTAT_PATTERNS = [ # or trailing hook output isn't picked up and fed to `git show`. _COMMIT_SHA_RE = re.compile(r'^\[[^\]]*?\b([0-9a-f]{7,40})\]', re.MULTILINE) -# Regex matching `git commit` commands. Mirrors Claude Code's own commit -# detection — it does NOT tolerate `git -c k=v commit` global options, which -# keeps this hook aligned with CC's commit attribution on what counts as a -# commit. +# Regex matching `git commit` commands, global options included (see below). # # Also matches `gt create` and `gt modify` — Graphite's stacked-PR wrapper # around git. `gt create` produces a new commit (mapped to git commit # semantics); `gt modify` amends the current commit (mapped to git commit -# --amend, also flagged by _GIT_AMEND_RE below). The hooks.json matcher -# widening for `gt create:*` / `gt modify:*` / `gt submit:*` ships in the -# same change set — without that widening this regex change is dead code -# because the hook subprocess never spawns for gt invocations. See #2048. +# --amend, also flagged by _GIT_AMEND_RE below). hooks.json has a +# `Bash(gt *)` entry so the hook subprocess spawns for gt invocations. _GIT_COMMIT_RE = re.compile( # `git -C <path>` and `git -c key=val` global options are allowed between # `git` and `commit` (mirrors the long-standing tolerance in @@ -677,7 +672,8 @@ _GIT_COMMIT_RE = re.compile( # by the handler — see #2089's secondary finding. The gt branch has no # global-option layer to worry about. r'\bgit(?:\s+-[Cc]\s+(?:"[^"]*"|\'[^\']*\'|[^\s"\']\S*)|\s+--[^\s=]+=\S+' - r'|\s+--(?:git-dir|work-tree)\s+\S+)*\s+commit\b' + # `(?!-)`: not the plumbing commands `git commit-graph` / `git commit-tree`. + r'|\s+--(?:git-dir|work-tree)\s+\S+)*\s+commit\b(?!-)' r'|\bgt\s+(?:create|modify)\b' ) # Match either the `--amend` flag (with the leading whitespace boundary @@ -702,11 +698,9 @@ COMMIT_REVIEW_RATE_WINDOW_S = int( # ─── push-sweep ───────────────────────────────────────────────────────────── # # Mirrors Claude Code's own push-command matching — tolerates `git -C <p>` / -# `git -c k=v` global options. The hooks.json `Bash(git push:*)` matcher -# (subcommand prefix) doesn't, but those forms are rare in practice -# and the python only ever runs after CC's matcher fired, so this regex is a -# defensive re-gate, not a widening — `git -C path push` won't reach python -# unless chained with a plain `git push` in the same compound command. +# `git -c k=v` global options, as the hooks.json `Bash(git*push*)` matcher +# does. That matcher also lets through e.g. `git stash push`; this regex is +# what decides whether the command is a push. # # `gh pr create` is intentionally NOT a separate hooks.json matcher: gh runs # `git push` as a child process, which CC's matcher doesn't observe (it sees @@ -714,8 +708,8 @@ COMMIT_REVIEW_RATE_WINDOW_S = int( # entry would buy minimal extra coverage (sessions that push only via gh) at # the cost of an extra python spawn on every `... && gh pr create` compound # (the common case). Those sessions are caught on their next standalone `git push`. -# Matches `git push` (with optional `-c k=v` / `-C path` global options -# CC's hooks.json matcher doesn't tolerate) OR `gt submit` — Graphite's +# Matches `git push` (with optional `-c k=v` / `-C path` global options) +# OR `gt submit` — Graphite's # stacked-PR push command. gt submit forwards to `git push` internally, # but the bash hook fires on Claude's top-level command so we need to # recognize gt submit at the matcher level. See #2048. @@ -742,8 +736,9 @@ PUSH_SWEEP_REPORT_CAP = int(os.environ.get("SG_PUSH_SWEEP_REPORT_CAP", "3")) def _claim_bash_hook_once(input_data): """De-dupe across hooks.json `if` matchers firing for the same Bash call. - `git commit -m x && git push` matches both `Bash(git commit:*)` and - `Bash(git push:*)` `if` configs → CC spawns this script twice with the + `git commit -m x && git push` matches both `Bash(git*commit*)` and + `Bash(git*push*)` `if` configs, and a command CC cannot parse runs every + `if` config → CC spawns this script more than once with the SAME `tool_use_id`. The first spawn atomically creates a sentinel under `.git/`; subsequent spawns see it and exit early. Avoids redundant LLM calls (and the redundant asyncRewake) on compound commands. @@ -1147,9 +1142,10 @@ def handle_commit_review_posttooluse(input_data): command = tool_input.get("command", "") if not isinstance(command, str) or not _GIT_COMMIT_RE.search(command): - # Defensive only — hooks.json's `"if": "Bash(git commit:*)"` is the - # real gate so CC never spawns python3 for ls/grep/etc. This catches - # cases where CC's command matching fails open and spawns the hook anyway. + # hooks.json's `"if": "Bash(git*commit*)"` only keeps CC from + # spawning python3 for ls/grep/etc. It lets through other git commands + # with "commit" in them (`git merge --no-commit`), and CC runs the hook + # anyway when it cannot parse the command; this regex decides. sys.exit(0) debug_log(f"Commit review: detected git commit in command") @@ -1695,9 +1691,8 @@ def handle_push_sweep_posttooluse(input_data): ) interrupted = tool_response.get("interrupted", False) - # Re-gate: hooks.json `if` matched, but confirm with the broader regex - # (defensive — `git -C`/`-c` forms won't reach here via the hooks.json - # prefix matcher alone, but a compound with a plain `git push` would). + # Re-gate: hooks.json `if` matched (or CC could not parse the command + # and ran every entry), so confirm with the regex. if not _GIT_PUSH_RE.search(command): sys.exit(0) @@ -2440,11 +2435,15 @@ def main(): # Handle PostToolUse[Bash] — commit review or push sweep (asyncRewake). # - # hooks.json has two `if` configs under the Bash matcher (`git commit:*` - # and `git push:*`). CC evaluates each `if` independently and spawns this + # hooks.json has three `if` configs under the Bash matcher (`git*commit*`, + # `git*push*` and `gt *`), kept to one per kind because CC runs EVERY + # entry when it cannot parse the command (loops, some substitutions): one + # entry per spelling meant one python per entry on those calls. CC + # evaluates each `if` independently and spawns this # script ONCE PER MATCH — so `git commit -m x && git push` spawns python # twice with the same command string and the same tool_use_id. The python - # cannot tell which `if` fired it. + # cannot tell which `if` fired it, which is also why the three entries + # share one rewakeMessage. # # Routing therefore MUST check commit FIRST so that compound commit+push # commands continue to hit commit-review (the pre-existing behaviour) on diff --git a/plugins/security-guidance/tests/test_repo_resolution.py b/plugins/security-guidance/tests/test_repo_resolution.py index 8bcf24b9..60288029 100644 --- a/plugins/security-guidance/tests/test_repo_resolution.py +++ b/plugins/security-guidance/tests/test_repo_resolution.py @@ -204,10 +204,16 @@ class TestRegexes: def test_push_re(self, cmd): assert hook._GIT_PUSH_RE.search(cmd) - @pytest.mark.parametrize("cmd", ["git status", "git log --oneline", "echo commit"]) + @pytest.mark.parametrize("cmd", ["git status", "git log --oneline", "echo commit", + "git commit-graph write --reachable", "git commit-tree HEAD^{tree}", + "git log --grep commit", "git stash push"]) def test_commit_re_negative(self, cmd): assert not hook._GIT_COMMIT_RE.search(cmd) + @pytest.mark.parametrize("cmd", ["git stash push", "git log --grep push", "git commit-graph write"]) + def test_push_re_negative(self, cmd): + assert not hook._GIT_PUSH_RE.search(cmd) + @pytest.mark.parametrize("unit", ['-c "a"', "-c 'a'", "--no-a=b", "--a=b=c=d", "--git-dir x"]) @pytest.mark.parametrize("regex,verb", [("_GIT_COMMIT_RE", "commit"), ("_GIT_PUSH_RE", "push")]) def test_global_option_prefix_is_linear(self, regex, verb, unit): @@ -228,11 +234,19 @@ class TestHooksJson: assert stop["command"].endswith('security_reminder_hook.py"') assert stop["asyncRewake"] is True bash = [g for g in cfg["hooks"]["PostToolUse"] if g.get("matcher") == "Bash"][0] - ifs = {h.get("if") for h in bash["hooks"]} - assert {"Bash(git commit:*)", "Bash(git push:*)", "Bash(git -C * commit *)", - "Bash(git -C * push*)", "Bash(gt create:*)", "Bash(gt modify:*)", - "Bash(gt submit:*)"} <= ifs - + # One entry per kind, not per spelling: when Claude Code cannot parse + # a command it runs every entry, so each extra entry is one more process. + assert [h.get("if") for h in bash["hooks"]] == [ + "Bash(git*commit*)", "Bash(git*push*)", "Bash(gt *)"] + assert all(h["asyncRewake"] is True and h["rewakeMessage"] for h in bash["hooks"]) + + @pytest.mark.parametrize("cmd", ["git stash push", "git commit-graph write --reachable", + "git log --grep commit", "gt log"]) + def test_other_commands_the_if_patterns_let_through_do_nothing(self, workspace, hook_env, stub_api, cmd): + ws, repo = workspace + commit_file(repo, "app.py", VULN_PY) + rc, so, se = run_hook(bash_payload(repo, cmd, ""), hook_env) + assert rc == 0 and so.strip() == "" and not stub_api.calls def _read_state(env): |
