diff options
| author | Claude <noreply@anthropic.com> | 2026-10-15 22:30:36 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-15 22:30:36 +0000 |
| commit | ba27dfbea7ee01b2cbaf4fbfd6ed23c074b3ca88 (patch) | |
| tree | f4dc2ef8188ed691fdc968d299be198548403642 /plugins/security-guidance/hooks | |
| parent | 7b5d1742310abe7d90f10aa574adfa0613226ec6 (diff) | |
| parent | 7b2259ba542c313099b1f00be8b670f7aa0c63bb (diff) | |
Merge remote-tracking branch 'origin/main' into mhegazy/sg-no-credentials-notice
# Conflicts:
# plugins/security-guidance/hooks/security_reminder_hook.py
Diffstat (limited to 'plugins/security-guidance/hooks')
| -rw-r--r-- | plugins/security-guidance/hooks/_base.py | 41 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 10 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/ensure_agent_sdk.py | 10 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/extensibility.py | 27 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/hooks.json | 50 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 154 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/session_state.py | 72 |
7 files changed, 252 insertions, 112 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py index 44b205f0..f05a0094 100644 --- a/plugins/security-guidance/hooks/_base.py +++ b/plugins/security-guidance/hooks/_base.py @@ -94,6 +94,47 @@ PROVENANCE_BANNER = ( ) +# Output that only Claude Code reads: the `metrics` and `rewakeSummary` fields, +# and the separate `{"async": ...}` line an async hook prints first. Other hosts +# that run this plugin's hooks can validate hook output against a closed schema +# and reject the whole output over a field or a second line they do not know, +# which shows up as a hook error. +_CLAUDE_CODE_OUTPUT_FIELDS = ("metrics", "rewakeSummary") + + +def _detect_portable_output(): + forced = os.environ.get("SECURITY_GUIDANCE_PORTABLE_OUTPUT", "").strip().lower() + if forced in ("1", "true", "yes", "on"): + return True + if forced in ("0", "false", "no", "off"): + return False + if os.environ.get("CLAUDECODE") or os.environ.get("CLAUDE_CODE_ENTRYPOINT"): + return False + return bool(os.environ.get("PLUGIN_ROOT")) + + +# Decided once, from the environment the host started the hook with: code the +# hook runs in-process later can set these variables itself. +_PORTABLE_OUTPUT = _detect_portable_output() + + +def portable_output(): + """True when stdout should carry only the standard hook output fields. + + SECURITY_GUIDANCE_PORTABLE_OUTPUT=1 or =0 forces it on or off. Otherwise it + is on only when the host passes PLUGIN_ROOT and does not identify itself as + Claude Code, so Claude Code and direct invocations are unchanged.""" + return _PORTABLE_OUTPUT + + +def write_hook_output(out): + """Print one hook output line. In portable mode the Claude Code only + fields are left out; what remains (possibly `{}`) is still valid output.""" + if portable_output(): + out = {k: v for k, v in out.items() if k not in _CLAUDE_CODE_OUTPUT_FIELDS} + print(json.dumps(out), flush=True) + + def _read_plugin_version_int(): """Encode plugin.json version "M.m.p" as M*10000 + m*100 + p so it fits the bool|number metrics constraint. Returns 0 if unreadable.""" diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index 74870c15..7725cdd9 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -104,17 +104,22 @@ def consume_stop_state(session_id, clear=True): "fire_count_expired": expired and state.get("stop_hook_fire_count", 0) > 0, "previous_findings": [] if findings_expired else list(state.get("previous_findings", [])), "reviewed_diff_hash": state.get("reviewed_diff_hash"), + # State lost or overwritten since the last Stop (session_state). + "state_resets": state.get("state_resets", 0), + "state_overwrites": state.get("state_overwrites", 0), } if clear: state["touched_paths"] = [] state.pop("reviewed_diff_hash", None) + state.pop("state_resets", None) + state.pop("state_overwrites", None) return snap return with_locked_state(session_id, _snap) or { "touched_paths": [], "baseline_sha": None, "head_at_capture": None, "untracked_at_baseline": {}, "fire_count": 0, "fire_count_expired": False, "previous_findings": [], - "reviewed_diff_hash": None, + "reviewed_diff_hash": None, "state_resets": 0, "state_overwrites": 0, } @@ -199,7 +204,8 @@ def capture_git_baseline(cwd): NOTE: `git stash create` does NOT capture untracked files. UPS pairs this SHA with a `_list_untracked()` snapshot stored as `untracked_at_baseline`, and `compute_v2_review_set` subtracts that set so pre-existing untracked - files are not reviewed as Claude-authored. + files are not reviewed as Claude-authored. UPS takes no snapshot while the + Stop review, its only reader, is switched off. """ # stdout is a SHA so text=True is safe on stdout, but a non-ASCII # filename in `git stash create`'s STDERR warning (e.g. a worktree diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py index f5d016db..f49e857d 100644 --- a/plugins/security-guidance/hooks/ensure_agent_sdk.py +++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py @@ -27,7 +27,7 @@ from pathlib import Path # → ~/.claude/security. See _base.state_dir for resolution precedence. Re-aliased # here to match the existing local name (state_dir was already a local var in # main() and _maybe_emit_user_notice). -from _base import state_dir as _resolve_state_dir +from _base import portable_output, state_dir as _resolve_state_dir, write_hook_output # Outcome codes for the sdk_bootstrap metric. Values are stable for telemetry. NOOP_SYSTEM = 0 # claude_agent_sdk already importable in system python @@ -765,7 +765,11 @@ if __name__ == "__main__": # SessionStart runs before the user's first prompt; doing this in the # background means the first commit-review of the session usually finds # the venv ready. - print(json.dumps({"async": True, "asyncTimeout": 180000}), flush=True) + # + # Not printed in portable mode: a host that reads stdout as one JSON + # document rejects a second line, and runs this hook to completion anyway. + if not portable_output(): + print(json.dumps({"async": True, "asyncTimeout": 180000}), flush=True) t0 = time.perf_counter() try: outcome, err_phase, err_kind = main() @@ -859,4 +863,4 @@ if __name__ == "__main__": "additionalContext": notice, } response["systemMessage"] = notice - print(json.dumps(response), flush=True) + write_hook_output(response) diff --git a/plugins/security-guidance/hooks/extensibility.py b/plugins/security-guidance/hooks/extensibility.py index a9c7f8fe..cb3e0a8d 100644 --- a/plugins/security-guidance/hooks/extensibility.py +++ b/plugins/security-guidance/hooks/extensibility.py @@ -12,11 +12,13 @@ Two extensibility points, both additive only: Discovery, in precedence order (matching CLAUDE.md / settings.json): - ``~/.claude/<name>`` (user) + - ``$CLAUDE_CONFIG_DIR/<name>`` (user, when set to another directory) - ``<cwd>/.claude/<name>`` (project, committed) - ``<cwd>/.claude/<name>.local.<ext>`` (project local, gitignored) Managed delivery via ``managed-settings.json`` is not yet supported. -Org admins can still push files to ``~/.claude/`` via MDM/GPO. +Org admins can still push files to ``~/.claude/`` (or the directory +``CLAUDE_CONFIG_DIR`` names) via MDM/GPO. Trust model: - The ``.md`` is repo-controlled and goes into the USER prompt (not system), @@ -89,11 +91,32 @@ def user_patterns() -> List[Dict[str, Any]]: # ── claude-security-guidance.md ─────────────────────────────────────────────────────── +def _user_config_dirs() -> List[str]: + """User-level config directories. ``~/.claude`` always, so a file placed + there keeps loading; then ``CLAUDE_CONFIG_DIR`` when it names another + directory. Empty is treated as not set, as in ``_base.state_dir``.""" + dirs = [os.path.expanduser(os.path.join("~", ".claude"))] + configured = (os.environ.get("CLAUDE_CONFIG_DIR") or "").strip() + if configured: + configured = os.path.expanduser(configured) + if _same_dir(configured, dirs[0]): + return dirs + dirs.append(configured) + return dirs + + +def _same_dir(a: str, b: str) -> bool: + try: + return os.path.samefile(a, b) + except OSError: + return os.path.normcase(os.path.abspath(a)) == os.path.normcase(os.path.abspath(b)) + + def _config_paths(cwd: Optional[str], basename: str) -> List[Tuple[str, str]]: """Existing config file paths, lowest precedence first (so concat reads in precedence order user → project → project-local). Truncation is done on the concatenated string, so lowest-precedence content is dropped last.""" - paths = [("User", os.path.expanduser(os.path.join("~", ".claude", basename)))] + paths = [("User", os.path.join(d, basename)) for d in _user_config_dirs()] if cwd: paths.append(("Project", os.path.join(cwd, ".claude", basename))) # claude-security-guidance.local.md / security-patterns.local.yaml 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 116059a7..639e9c64 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -86,6 +86,7 @@ from _base import ( # noqa: E402,F401 _read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK, _PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics, state_dir as _resolve_state_dir, + write_hook_output as _write_hook_output, ) import extensibility # noqa: E402 from patterns import ( # noqa: E402,F401 @@ -296,7 +297,7 @@ def emit_metrics( out["reason"] = additional_context if system_message: out["systemMessage"] = system_message - print(json.dumps(out), flush=True) + _write_hook_output(out) def _llm_review_off(): @@ -600,29 +601,38 @@ def handle_user_prompt_submit(input_data): sys.exit(0) session_id = input_data.get("session_id", "default") - # stash-create and ls-files both walk the worktree (~2-5s each in a very - # large repo). Run them concurrently so UPS latency stays ≈ max(both). - import concurrent.futures as _cf - with _cf.ThreadPoolExecutor(max_workers=2) as _ex: - _f_sha = _ex.submit(capture_git_baseline, cwd) - _f_ut = _ex.submit(_list_untracked, cwd) - sha = _f_sha.result() - # Always capture the untracked snapshot. `git stash create` returns - # empty when there are no TRACKED changes, but pre-existing untracked - # files still need to be excluded from the next Stop's review_set — - # otherwise an untracked-only working tree gets every untracked file - # reviewed on every turn until something tracked is dirtied. - untracked_now = _f_ut.result() or {} + # The untracked snapshot has one reader: the Stop-hook diff review, which + # skips before reading it when either of these switches is off (see + # handle_stop_hook). Listing the worktree on every prompt then buys + # nothing, so only the stash baseline (still read by the Write pattern + # filter) is captured. + snapshot_untracked = ENABLE_STOP_REVIEW and ENABLE_CODE_SECURITY_REVIEW + + def _capture(repo_cwd): + if not snapshot_untracked: + return capture_git_baseline(repo_cwd), None + # stash-create and ls-files both walk the worktree (~2-5s each in a + # very large repo). Run them concurrently so UPS latency stays + # ≈ max(both). + import concurrent.futures as _cf + with _cf.ThreadPoolExecutor(max_workers=2) as _ex: + _f_sha = _ex.submit(capture_git_baseline, repo_cwd) + _f_ut = _ex.submit(_list_untracked, repo_cwd) + # Taken whether or not the stash produced a SHA. `git stash + # create` returns empty when there are no TRACKED changes, but + # pre-existing untracked files still need to be excluded from the + # next Stop's review_set — otherwise an untracked-only working + # tree gets every untracked file reviewed on every turn until + # something tracked is dirtied. + return _f_sha.result(), _f_ut.result() or {} + + sha, untracked_now = _capture(cwd) if not sha and not _git_toplevel(cwd): hint = load_repo_hint(session_id) if hint: debug_log(f"UPS: cwd is not a git repo; using repo hint {hint!r}") cwd = hint - with _cf.ThreadPoolExecutor(max_workers=2) as _ex: - _f_sha = _ex.submit(capture_git_baseline, cwd) - _f_ut = _ex.submit(_list_untracked, cwd) - sha = _f_sha.result() - untracked_now = _f_ut.result() or {} + sha, untracked_now = _capture(cwd) head = _git_rev_parse_head(cwd) # If the previous turn's Stop hook never ran (user interrupt, follow-up @@ -641,14 +651,24 @@ def handle_user_prompt_submit(input_data): # we still need to capture a baseline. if state.get("touched_paths") and state.get("baseline_sha"): preserved["value"] = True + # A baseline captured while the Stop review was off has no + # snapshot beside it. Without one the next Stop would take every + # untracked file in the tree as written this turn. + if untracked_now is not None and "untracked_at_baseline" not in state: + state["untracked_at_baseline"] = untracked_now return if sha: state["baseline_sha"] = sha state["head_at_capture"] = head # untracked_at_baseline is independent of whether the stash produced - # a SHA — write it unconditionally so compute_v2_review_set's - # preexisting-untracked exclusion works in untracked-only trees. - state["untracked_at_baseline"] = untracked_now + # a SHA, so compute_v2_review_set's preexisting-untracked exclusion + # works in untracked-only trees. None means no snapshot was taken + # (Stop review off): drop the previous one, which belongs to an older + # baseline. + if untracked_now is None: + state.pop("untracked_at_baseline", None) + else: + state["untracked_at_baseline"] = untracked_now with_locked_state(session_id, _save) if preserved["value"]: @@ -743,26 +763,33 @@ _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. +# +# Global options allowed between `git` and the subcommand, shared by +# _GIT_COMMIT_RE and _GIT_PUSH_RE: `-C <path>`, `-c key=val`, `--opt=val`, +# the long options that take a separate value, and flags that take none +# (`--no-pager`, `-p`). A value may be quoted in part (`-c user.name="A B"`). +_GIT_OPT_VALUE = r'''(?:[^\s"']|"[^"]*"|'[^']*')+''' +_GIT_VALUE_OPTS = r'git-dir|work-tree|namespace|config-env|attr-source' +_GIT_GLOBAL_OPTS = ( + r'(?:\s+-[Cc]\s+' + _GIT_OPT_VALUE + + r'|\s+--[^\s=]+=' + _GIT_OPT_VALUE + + r'|\s+--(?:' + _GIT_VALUE_OPTS + r')\s+' + _GIT_OPT_VALUE + # `--help` / `--version` run no subcommand. + + r'|\s+(?:--(?!(?:' + _GIT_VALUE_OPTS + r'|help|version)\s)[^\s=]+|-[pP])(?=\s))*' +) _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 - # _GIT_PUSH_RE). Without this, `git -C /repo commit` is silently dropped - # 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' + # Without the global-option tolerance, `git -C /repo commit` is silently + # dropped by the handler — see #2089's secondary finding. The gt branch + # has no global-option layer to worry about. + # `(?!-)`: not the plumbing commands `git commit-graph` / `git commit-tree`. + r'\bgit' + _GIT_GLOBAL_OPTS + r'\s+commit\b(?!-)' r'|\bgt\s+(?:create|modify)\b' ) # Match either the `--amend` flag (with the leading whitespace boundary @@ -787,11 +814,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 @@ -799,14 +824,13 @@ 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. _GIT_PUSH_RE = re.compile( - r'(?:\bgit(?:\s+-[cC]\s+(?:"[^"]*"|\'[^\']*\'|[^\s"\']\S*)|\s+--[^\s=]+=\S+' - r'|\s+--(?:git-dir|work-tree)\s+\S+)*\s+push\b|\bgt\s+submit\b)' + r'(?:\bgit' + _GIT_GLOBAL_OPTS + r'\s+push\b|\bgt\s+submit\b)' ) # `git push` stdout: "abc1234..def5678 branch -> branch" (or `+abc..def` on @@ -827,8 +851,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. @@ -1232,9 +1257,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") @@ -1786,9 +1812,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) @@ -2160,6 +2185,13 @@ def handle_stop_hook(input_data): head_at_capture = snap["head_at_capture"] untracked_at_baseline = snap.get("untracked_at_baseline") or {} previous_findings = snap["previous_findings"] + # Only when it happened: state lost to an unreadable file, and saves that + # overwrote another hook's (possible only without locking). SubagentStop + # does not clear them, so it does not report them either. + if not is_subagent: + for _k in ("state_resets", "state_overwrites"): + if isinstance(snap.get(_k), int) and snap[_k] > 0: + _TAIL_METRICS[_k] = snap[_k] # Sweep pattern-warning outcomes (pure local work; stop_hook_active is # already guaranteed False here so no double-count guard needed). @@ -2547,11 +2579,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 @@ -2574,7 +2610,7 @@ def main(): # Another spawn for this same tool_use_id already claimed the # work (compound matched multiple `if` configs). Emit a single # metric so telemetry can count how often the de-dupe kicks in. - print(json.dumps({"metrics": {"bash_hook_dedup": True}}), flush=True) + _write_hook_output({"metrics": {"bash_hook_dedup": True}}) sys.exit(0) if _GIT_COMMIT_RE.search(cmd): handle_commit_review_posttooluse(input_data) @@ -2659,7 +2695,7 @@ def main(): if notice: output["systemMessage"] = notice if output: - print(json.dumps(output)) + _write_hook_output(output) sys.exit(0) diff --git a/plugins/security-guidance/hooks/session_state.py b/plugins/security-guidance/hooks/session_state.py index 8dbadfd2..c8045532 100644 --- a/plugins/security-guidance/hooks/session_state.py +++ b/plugins/security-guidance/hooks/session_state.py @@ -17,6 +17,7 @@ except ImportError: import json import os import re +import tempfile from datetime import datetime from _base import debug_log, state_dir as _state_dir @@ -47,7 +48,7 @@ def get_lock_file(session_id): def cleanup_old_state_files(): - """Remove state files and lock files older than 30 days.""" + """Remove state files, lock files and leftover temporary files older than 30 days.""" try: state_dir = _state_dir() if not os.path.exists(state_dir): @@ -58,7 +59,7 @@ def cleanup_old_state_files(): for filename in os.listdir(state_dir): if filename.startswith("security_warnings_state_") and ( - filename.endswith(".json") or filename.endswith(".lock") + filename.endswith((".json", ".lock", ".tmp")) ): file_path = os.path.join(state_dir, filename) try: @@ -96,25 +97,79 @@ def load_state(session_id): if isinstance(data, dict): data.setdefault("shown_warnings", []) return data - except (json.JSONDecodeError, IOError, KeyError, TypeError): + except FileNotFoundError: + return {"shown_warnings": []} + except (ValueError, IOError, KeyError, TypeError): + # ValueError: not JSON, or bytes that do not decode. pass - return {"shown_warnings": []} + # The file is there but cannot be used, so everything the session had + # recorded is gone. Leave a mark for the Stop hook to report: a flag, not + # a count, since an earlier mark is lost with the rest. + debug_log(f"State file {state_file} is unreadable, starting from an empty state") + return {"shown_warnings": [], "state_resets": 1} + + +# Windows still writes the state file in place: a rename there is refused +# while another process has the file open and can make a concurrent open fail, +# and hooks run without a state lock on Windows (see with_locked_state). +_RENAME_INTO_PLACE = os.name != "nt" + + +def _write_then_rename(state_file, state): + """Write `state` to a temporary file and rename it over `state_file`. + Returns False, with nothing changed, when this directory does not allow + it; any other failure raises OSError and leaves the state file as it was.""" + tmp = None + try: + fd, tmp = tempfile.mkstemp( + dir=os.path.dirname(state_file), + prefix=os.path.basename(state_file) + ".", suffix=".tmp") + with os.fdopen(fd, "w") as f: + json.dump(state, f) + os.replace(tmp, state_file) + return True + except BaseException as e: + if tmp: + try: + os.unlink(tmp) + except OSError: + pass + if isinstance(e, PermissionError): + return False + raise def save_state(session_id, state): - """Save the full state dict to file.""" + """Save the full state dict to file. + + The new contents go to a temporary file that is then renamed over the + state file, so a hook killed part-way through a save (a timeout, an + interrupt) leaves the previous state. Written in place it left a truncated + file, which load_state reads as an empty state: the turn baseline, touched + paths and shown warnings were lost. + """ state_file = get_state_file(session_id) try: state_dir = os.path.dirname(state_file) if state_dir: os.makedirs(state_dir, exist_ok=True) + if _RENAME_INTO_PLACE and _write_then_rename(state_file, state): + return with open(state_file, "w") as f: json.dump(state, f) except (IOError, OSError) as e: debug_log(f"Failed to save state file {state_file}: {e}") +def _raw_state(state_file): + try: + with open(state_file, "rb") as f: + return f.read() + except OSError: + return None + + def with_locked_state(session_id, callback): """ Execute callback with exclusive access to the state file. @@ -132,8 +187,15 @@ def with_locked_state(session_id, callback): if fcntl is None: # No file locking available (Windows) — run without locking + state_file = get_state_file(session_id) + before = _raw_state(state_file) state = load_state(session_id) result = callback(state) + if _raw_state(state_file) != before: + # Another hook changed the state after it was read here, and this + # save is about to drop that change. Count how often it happens; + # the Stop hook reports the count. + state["state_overwrites"] = state.get("state_overwrites", 0) + 1 save_state(session_id, state) return result |
