summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/hooks
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-09-10 20:49:44 +0000
committerClaude <noreply@anthropic.com>2026-09-10 20:49:44 +0000
commit8459dfc26ec93b3d7f53353a902fa2d530bcb154 (patch)
tree9b87c6ca0f487f396d792c793a2f0ff56cf693bb /plugins/security-guidance/hooks
parent4d2a599463bf3966c368dd8bfb30cfa1682cf126 (diff)
parent3b600518a637492d37c9877aeb49c2a55d939c04 (diff)
Merge remote-tracking branch 'origin/main' into tobin/add-dynatrace
# Conflicts: # .claude-plugin/marketplace.json
Diffstat (limited to 'plugins/security-guidance/hooks')
-rw-r--r--plugins/security-guidance/hooks/diffstate.py14
-rw-r--r--plugins/security-guidance/hooks/gitutil.py27
-rw-r--r--plugins/security-guidance/hooks/hooks.json29
-rw-r--r--plugins/security-guidance/hooks/llm.py2
-rw-r--r--plugins/security-guidance/hooks/reporesolve.py306
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py137
6 files changed, 493 insertions, 22 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index 3ce9da1b..8d0665dd 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -71,7 +71,7 @@ def record_touched_path(session_id, file_path):
with_locked_state(session_id, _record)
-def consume_stop_state(session_id):
+def consume_stop_state(session_id, clear=True):
"""Atomically snapshot all state the Stop hook needs and clear touched_paths.
The Stop hook is asyncRewake — it runs in the background after Claude's
@@ -102,17 +102,27 @@ def consume_stop_state(session_id):
"fire_count": 0 if expired else state.get("stop_hook_fire_count", 0),
"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["touched_paths"] = []
+ if clear:
+ state["touched_paths"] = []
+ state.pop("reviewed_diff_hash", 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,
}
+def record_reviewed_diff(session_id, diff_hash):
+ def _save(state):
+ state["reviewed_diff_hash"] = diff_hash
+ with_locked_state(session_id, _save)
+
+
def restore_unreviewed_stop_state(session_id, paths, baseline_sha):
"""Put consumed touched_paths back so the next Stop reviews them.
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index 4d771b42..b6e8cd54 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -39,6 +39,29 @@ GIT_CMD = [
"-c", "core.quotePath=false",
]
+SAFE_GIT_CONFIG = (
+ ("core.fsmonitor", "false"),
+ ("core.hooksPath", "/dev/null"),
+)
+
+
+def git_config_env(pairs, base=None):
+ base = os.environ if base is None else base
+ try:
+ n = max(0, int(base.get("GIT_CONFIG_COUNT") or 0))
+ except (TypeError, ValueError):
+ n = 0
+ env = {}
+ for i, (k, v) in enumerate(pairs, start=n):
+ env[f"GIT_CONFIG_KEY_{i}"] = k
+ env[f"GIT_CONFIG_VALUE_{i}"] = v
+ env["GIT_CONFIG_COUNT"] = str(n + len(pairs))
+ return env
+
+
+def apply_safe_git_env():
+ os.environ.update(git_config_env(SAFE_GIT_CONFIG))
+
def _git_rev_parse_head(cwd):
"""Return the current HEAD SHA, or None if not a git repo / no commits."""
@@ -238,7 +261,7 @@ def _git_diff_range(repo_root, base, head="HEAD"):
# raw UTF-8, not C-quoted. Required by the downstream
# parse_diff_into_files / extract_file_paths_from_diff regex.
r = subprocess.run(
- [*GIT_CMD, "diff", "-p", "--no-color", "--no-ext-diff", base, head],
+ [*GIT_CMD, "diff", "-p", "--no-color", "--no-ext-diff", "--no-textconv", base, head],
cwd=repo_root, capture_output=True, timeout=30,
)
if r.returncode != 0:
@@ -481,7 +504,7 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa
return ""
# core.quotePath=false comes from GIT_CMD globally (see definition).
- cmd = [*GIT_CMD, "diff", "--no-color", "--no-ext-diff", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec
+ cmd = [*GIT_CMD, "diff", "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec
try:
with _temp_index(cwd, untracked_paths) as env:
# env is None when no index could be found (bare repo / not a
diff --git a/plugins/security-guidance/hooks/hooks.json b/plugins/security-guidance/hooks/hooks.json
index 39dbac57..22734270 100644
--- a/plugins/security-guidance/hooks/hooks.json
+++ b/plugins/security-guidance/hooks/hooks.json
@@ -45,6 +45,14 @@
{
"type": "command",
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"",
+ "if": "Bash(git -C * 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"
+ },
+ {
+ "type": "command",
+ "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"",
"if": "Bash(git 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:",
@@ -53,6 +61,14 @@
{
"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:",
@@ -90,6 +106,19 @@
}
]
}
+ ],
+ "SubagentStop": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"",
+ "asyncRewake": true,
+ "rewakeMessage": "Background security review feedback — address or acknowledge the findings below, then continue with the user's original request or continue waiting for their reply. This is supplementary, not a replacement for your previous response:",
+ "rewakeSummary": "Background security review found issues"
+ }
+ ]
+ }
]
}
}
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index 8b7feef8..1430dd4e 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -29,6 +29,7 @@ import extensibility
import review_api
from _base import debug_log, _record_usage, _record_http_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir # noqa: F401
from session_state import with_locked_state
+from gitutil import git_config_env, SAFE_GIT_CONFIG
def _inject_agent_sdk_venv_into_syspath(state_dir):
@@ -1123,6 +1124,7 @@ def _agentic_spawn_env() -> Dict[str, str]:
"GIT_SSH_COMMAND": "/bin/false",
"GIT_TERMINAL_PROMPT": "0",
"GIT_OPTIONAL_LOCKS": "0",
+ **git_config_env(SAFE_GIT_CONFIG),
}
if os.environ.get("ANTHROPIC_API_KEY"):
# API key present → blank the OAuth token so API-key auth wins.
diff --git a/plugins/security-guidance/hooks/reporesolve.py b/plugins/security-guidance/hooks/reporesolve.py
new file mode 100644
index 00000000..7611cfaf
--- /dev/null
+++ b/plugins/security-guidance/hooks/reporesolve.py
@@ -0,0 +1,306 @@
+import os
+import re
+import shlex
+import subprocess
+import time
+
+from gitutil import GIT_CMD, _git_toplevel
+from session_state import with_locked_state
+
+
+RES_NONE = 0
+RES_CWD = 1
+RES_COMMAND = 2
+RES_SHA_SCAN = 3
+RES_TOUCHED_PATHS = 4
+RES_HINT = 5
+
+COMMIT_SUBCOMMANDS = {("git", "commit"), ("gt", "create"), ("gt", "modify")}
+PUSH_SUBCOMMANDS = {("git", "push"), ("gt", "submit")}
+
+SCAN_SKIP_DIRS = {
+ "node_modules", ".venv", "venv", "__pycache__", ".tox", "dist",
+ "build", "target", ".cache", ".git", "vendor", "site-packages",
+}
+SCAN_MAX_DEPTH = int(os.environ.get("SG_REPO_SCAN_MAX_DEPTH", "3"))
+SCAN_MAX_REPOS = int(os.environ.get("SG_REPO_SCAN_MAX_REPOS", "64"))
+SCAN_BUDGET_S = float(os.environ.get("SG_REPO_SCAN_BUDGET_S", "4"))
+
+_SEPARATORS = frozenset(";&|()\n")
+_SHA_RE = re.compile(r"^[0-9a-f]{7,40}$")
+_ENV_ASSIGN_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
+_PREFIX_WORDS = frozenset(("env", "time", "exec", "command", "nohup"))
+
+
+def _abs(base, p):
+ try:
+ p = os.path.expanduser(p)
+ if not os.path.isabs(p):
+ p = os.path.join(base or os.getcwd(), p)
+ return os.path.normpath(p)
+ except (TypeError, ValueError, OSError):
+ return None
+
+
+def _is_sep(tok):
+ return bool(tok) and set(tok) <= _SEPARATORS
+
+
+def _tokenize(command):
+ if os.sep == "\\":
+ command = command.replace("\\", "\\\\")
+ try:
+ lex = shlex.shlex(command, posix=True, punctuation_chars=";&|()")
+ lex.whitespace_split = True
+ return list(lex)
+ except ValueError:
+ try:
+ return command.replace("&&", " && ").replace(";", " ; ").split()
+ except Exception:
+ return []
+
+
+def dirs_from_command(command, cwd, subcommands=None):
+ if not isinstance(command, str) or not command.strip():
+ return []
+ tokens = _tokenize(command)
+ out = []
+ cur = cwd or ""
+ i = 0
+ n = len(tokens)
+ at_start = True
+ while i < n:
+ t = tokens[i]
+ if _is_sep(t):
+ at_start = True
+ i += 1
+ continue
+ if at_start and (_ENV_ASSIGN_RE.match(t) or t in _PREFIX_WORDS):
+ i += 1
+ continue
+ if at_start and t in ("cd", "pushd"):
+ if i + 1 < n and not _is_sep(tokens[i + 1]) and tokens[i + 1] not in ("-",) \
+ and not tokens[i + 1].startswith("-"):
+ nxt = _abs(cur, tokens[i + 1])
+ if nxt:
+ cur = nxt
+ i += 2
+ else:
+ i += 1
+ at_start = False
+ continue
+ prog = os.path.basename(t) if t else t
+ if at_start and prog in ("git", "gt"):
+ j = i + 1
+ cdir = cur
+ gdir = None
+ wtree = None
+ if prog == "git":
+ while j < n and not _is_sep(tokens[j]):
+ a = tokens[j]
+ if a == "-C" and j + 1 < n:
+ cdir = _abs(cdir, tokens[j + 1]) or cdir
+ j += 2
+ continue
+ if a == "-c" and j + 1 < n:
+ j += 2
+ continue
+ if a.startswith("--git-dir="):
+ gdir = _abs(cdir, a.split("=", 1)[1])
+ j += 1
+ continue
+ if a == "--git-dir" and j + 1 < n:
+ gdir = _abs(cdir, tokens[j + 1])
+ j += 2
+ continue
+ if a.startswith("--work-tree="):
+ wtree = _abs(cdir, a.split("=", 1)[1])
+ j += 1
+ continue
+ if a == "--work-tree" and j + 1 < n:
+ wtree = _abs(cdir, tokens[j + 1])
+ j += 2
+ continue
+ if a.startswith("-"):
+ j += 1
+ continue
+ break
+ sub = tokens[j] if j < n and not _is_sep(tokens[j]) else None
+ if subcommands is None or (prog, sub) in subcommands:
+ cand = wtree
+ if not cand and gdir:
+ cand = os.path.dirname(gdir) if os.path.basename(gdir) == ".git" else gdir
+ if not cand:
+ cand = cdir
+ if cand:
+ out.append(cand)
+ i = j + 1 if j < n else j
+ at_start = False
+ continue
+ at_start = False
+ i += 1
+ return list(dict.fromkeys(d for d in out if d))
+
+
+def toplevel_from_command(command, cwd, subcommands=None, cwd_root=None):
+ cwd_abs = _abs(None, cwd) if cwd else None
+ for d in dirs_from_command(command, cwd, subcommands):
+ if cwd_root and d == cwd_abs:
+ return cwd_root
+ try:
+ if os.path.isdir(d):
+ top = _git_toplevel(d)
+ if top:
+ return top
+ except OSError:
+ continue
+ return None
+
+
+def scan_roots(cwd):
+ roots = []
+ for r in (cwd, os.environ.get("CLAUDE_PROJECT_DIR")):
+ if r and os.path.isdir(r):
+ a = os.path.abspath(r)
+ if a not in roots:
+ roots.append(a)
+ return roots
+
+
+def iter_git_repos(roots, max_depth=None, max_repos=None, deadline=None):
+ max_depth = SCAN_MAX_DEPTH if max_depth is None else max_depth
+ max_repos = SCAN_MAX_REPOS if max_repos is None else max_repos
+ seen = set()
+ for root in roots or []:
+ try:
+ if not root or not os.path.isdir(root):
+ continue
+ root = os.path.abspath(root)
+ except OSError:
+ continue
+ base_depth = root.rstrip(os.sep).count(os.sep)
+ for dirpath, dirnames, filenames in os.walk(root):
+ if deadline is not None and time.monotonic() > deadline:
+ return
+ if ".git" in dirnames or ".git" in filenames:
+ try:
+ key = os.path.realpath(dirpath)
+ except OSError:
+ key = dirpath
+ if key not in seen:
+ seen.add(key)
+ yield dirpath
+ if len(seen) >= max_repos:
+ return
+ depth = dirpath.rstrip(os.sep).count(os.sep) - base_depth
+ if depth >= max_depth:
+ dirnames[:] = []
+ else:
+ dirnames[:] = [
+ d for d in dirnames
+ if d not in SCAN_SKIP_DIRS and not d.startswith(".")
+ ]
+
+
+def repo_containing_commit(sha, roots, budget_s=None):
+ if not isinstance(sha, str) or not _SHA_RE.match(sha):
+ return None
+ budget_s = SCAN_BUDGET_S if budget_s is None else budget_s
+ deadline = time.monotonic() + budget_s
+ for repo in iter_git_repos(roots, deadline=deadline):
+ try:
+ r = subprocess.run(
+ [*GIT_CMD, "cat-file", "-e", f"{sha}^{{commit}}"],
+ cwd=repo, capture_output=True, timeout=3,
+ )
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
+ continue
+ if r.returncode == 0:
+ return _git_toplevel(repo) or repo
+ return None
+
+
+def repos_from_paths(paths, cwd=None, limit=200):
+ counts = {}
+ order = []
+ cache = {}
+ for p in list(paths or [])[:limit]:
+ if not isinstance(p, str) or not p:
+ continue
+ ap = p if os.path.isabs(p) else _abs(cwd, p)
+ if not ap:
+ continue
+ d = os.path.dirname(ap)
+ while d and not os.path.isdir(d):
+ parent = os.path.dirname(d)
+ if parent == d:
+ break
+ d = parent
+ if not d:
+ continue
+ if d in cache:
+ top = cache[d]
+ else:
+ try:
+ top = _git_toplevel(d) if os.path.isdir(d) else None
+ except OSError:
+ top = None
+ cache[d] = top
+ if top:
+ if top not in counts:
+ order.append(top)
+ counts[top] = counts.get(top, 0) + 1
+ return sorted(order, key=lambda t: (-counts[t], order.index(t)))
+
+
+def save_repo_hint(session_id, repo_root):
+ if not session_id or not repo_root:
+ return
+
+ def _save(state):
+ state["repo_root_hint"] = repo_root
+ try:
+ with_locked_state(session_id, _save)
+ except Exception:
+ pass
+
+
+def load_repo_hint(session_id):
+ if not session_id:
+ return None
+ try:
+ hint = with_locked_state(session_id, lambda s: s.get("repo_root_hint"))
+ except Exception:
+ return None
+ if isinstance(hint, str) and hint and os.path.isdir(hint):
+ top = _git_toplevel(hint)
+ if top:
+ return top
+ return None
+
+
+_UNSET = object()
+
+
+def resolve_repo_root(cwd, command=None, subcommands=None, sha=None,
+ touched_paths=None, session_id=None, cwd_root=_UNSET):
+ if cwd_root is _UNSET:
+ cwd_root = _git_toplevel(cwd) if cwd else None
+ if command:
+ top = toplevel_from_command(command, cwd, subcommands, cwd_root)
+ if top and top != cwd_root:
+ return top, RES_COMMAND
+ if cwd_root:
+ return cwd_root, RES_CWD
+ if touched_paths:
+ tops = repos_from_paths(touched_paths, cwd)
+ if tops:
+ return tops[0], RES_TOUCHED_PATHS
+ if sha:
+ top = repo_containing_commit(sha, scan_roots(cwd))
+ if top:
+ return top, RES_SHA_SCAN
+ hint = load_repo_hint(session_id)
+ if hint:
+ return hint, RES_HINT
+ return None, RES_NONE
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index d3f726e8..48a7eb49 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -58,6 +58,7 @@ except ImportError:
fcntl = None
import contextlib
import glob
+import hashlib
import json
import os
import random
@@ -96,7 +97,7 @@ from session_state import ( # noqa: E402,F401
load_state, save_state, with_locked_state,
)
from gitutil import ( # noqa: E402,F401
- GIT_CMD,
+ GIT_CMD, apply_safe_git_env,
_git_rev_parse_head, _find_git_index, _diff_pathspec, _temp_index,
_git_toplevel, _git_dir, _git_rev_list_range, _git_diff_range,
_detect_main_branch, _git_reflog_recent_commits, _git_name_only,
@@ -112,12 +113,18 @@ from gitutil import ( # noqa: E402,F401
from diffstate import ( # noqa: E402,F401
STOP_LOOP_STATE_TTL_SEC, PREVIOUS_FINDINGS_TTL_SEC,
save_baseline_sha, load_baseline_sha, record_touched_path,
- consume_stop_state, restore_unreviewed_stop_state,
+ consume_stop_state, restore_unreviewed_stop_state, record_reviewed_diff,
get_baseline_file_content, capture_git_baseline,
_REVIEWED_SHAS_BASENAME, _REVIEWED_SHAS_CAP,
_reviewed_shas_path, _load_reviewed_shas, _append_reviewed_shas,
UNTRACKED_BASELINE_CAP, _list_untracked, compute_v2_review_set,
)
+from reporesolve import ( # noqa: E402,F401
+ RES_NONE, RES_CWD, RES_COMMAND, RES_SHA_SCAN, RES_TOUCHED_PATHS, RES_HINT,
+ COMMIT_SUBCOMMANDS, PUSH_SUBCOMMANDS,
+ toplevel_from_command, repo_containing_commit, scan_roots,
+ resolve_repo_root, save_repo_hint, load_repo_hint,
+)
import llm # noqa: E402 module ref for reassignable globals (_last_call_claude_http_error etc.)
from llm import ( # noqa: E402,F401
ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, HAS_API_CREDENTIALS,
@@ -540,6 +547,16 @@ def handle_user_prompt_submit(input_data):
# 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 {}
+ 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 {}
head = _git_rev_parse_head(cwd)
# If the previous turn's Stop hook never ran (user interrupt, follow-up
@@ -678,7 +695,8 @@ _GIT_COMMIT_RE = re.compile(
# _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+commit\b'
+ r'\bgit(?:\s+-[Cc]\s+(?:"[^"]*"|\'[^\']*\'|[^\s"\']\S*)|\s+--[^\s=]+=\S+'
+ 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
@@ -721,7 +739,8 @@ COMMIT_REVIEW_RATE_WINDOW_S = int(
# 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+push\b|\bgt\s+submit\b)'
+ 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)'
)
# `git push` stdout: "abc1234..def5678 branch -> branch" (or `+abc..def` on
@@ -759,7 +778,12 @@ def _claim_bash_hook_once(input_data):
cwd = input_data.get("cwd")
if not tuid or not cwd:
return True
- gd = _git_dir(_git_toplevel(cwd) or cwd)
+ command = (input_data.get("tool_input") or {}).get("command", "") or ""
+ gd = _git_dir(
+ _git_toplevel(cwd)
+ or toplevel_from_command(command, cwd, COMMIT_SUBCOMMANDS | PUSH_SUBCOMMANDS)
+ or cwd
+ )
if not gd:
return True
# GC: best-effort sweep of stale sentinels so they don't accumulate.
@@ -1041,9 +1065,10 @@ def handle_commit_review_posttooluse(input_data):
# emitting labels like `[pre-commit abc1234]`, and on (b) chained
# `git commit || git log --stat` where `N files changed` appears in output
# even though the commit itself failed.
+ all_shas = _COMMIT_SHA_RE.findall(bash_output)
commit_succeeded = (
not interrupted
- and _COMMIT_SHA_RE.search(bash_output) is not None
+ and bool(all_shas)
and any(p.search(bash_output) for p in _COMMIT_DIFFSTAT_PATTERNS)
)
@@ -1051,6 +1076,18 @@ def handle_commit_review_posttooluse(input_data):
# commit_review and group by commit_review_on.
_base = {"commit_review": True, "commit_review_on": COMMIT_REVIEW_ENABLED}
+ cwd_root = _git_toplevel(cwd) if cwd else None
+ repo_root = cwd_root
+ repo_res = RES_CWD if cwd_root else RES_NONE
+ if cwd:
+ _cmd_root = toplevel_from_command(command, cwd, COMMIT_SUBCOMMANDS, cwd_root)
+ if _cmd_root and _cmd_root != cwd_root:
+ repo_root, repo_res = _cmd_root, RES_COMMAND
+ if not cwd_root:
+ _base["cwd_is_repo"] = False
+ if repo_res != RES_CWD:
+ _base["repo_resolution"] = repo_res
+
# Reflog fallback for hidden stdout. Analysis of skip_reason=21 emissions
# showed a large share were commits that DID succeed
# but whose `[branch sha]` line was hidden by piping/redirection/-q
@@ -1068,7 +1105,12 @@ def handle_commit_review_posttooluse(input_data):
_reflog_shas: List[str] = []
_skip_21_sub = 0
if not commit_succeeded and not interrupted and cwd:
- _root = _git_toplevel(cwd)
+ if not repo_root:
+ repo_root = load_repo_hint(session_id)
+ if repo_root:
+ repo_res = RES_HINT
+ _base["repo_resolution"] = repo_res
+ _root = repo_root
_fresh, _stale = _git_reflog_recent_commits(_root)
if _fresh:
_already = _load_reviewed_shas(_root)
@@ -1119,11 +1161,24 @@ def handle_commit_review_posttooluse(input_data):
emit_metrics({"skipped": True, "skip_reason": 25, **_base})
sys.exit(0)
- repo_root = _git_toplevel(cwd)
+ if not repo_root and all_shas and not _reflog_shas:
+ repo_root = repo_containing_commit(all_shas[-1], scan_roots(cwd))
+ if repo_root:
+ repo_res = RES_SHA_SCAN
+ if not repo_root:
+ repo_root = load_repo_hint(session_id)
+ if repo_root:
+ repo_res = RES_HINT
+ if repo_res != RES_CWD:
+ _base["repo_resolution"] = repo_res
if not repo_root:
debug_log("Commit review: not in a git repo")
emit_metrics({"skipped": True, "skip_reason": 26, **_base})
sys.exit(0)
+ if repo_res != RES_CWD:
+ debug_log(f"Commit review: repo resolved via {repo_res} -> {repo_root!r}")
+ if repo_res in (RES_COMMAND, RES_TOUCHED_PATHS):
+ save_repo_hint(session_id, repo_root)
# Pin the review to the exact SHA the Bash command produced, parsed from
# its stdout. Reviewing HEAD instead is wrong when the commit was made in
@@ -1150,7 +1205,6 @@ def handle_commit_review_posttooluse(input_data):
# all are reviewed.
shas = _reflog_shas
else:
- all_shas = _COMMIT_SHA_RE.findall(bash_output)
shas = [all_shas[-1]] if all_shas else []
if not shas:
debug_log("Commit review: no SHA in commit output")
@@ -1229,13 +1283,13 @@ def handle_commit_review_posttooluse(input_data):
# Delta review: pre-amend → post-amend. `git diff` (not show)
# so the output is a pure unified diff with no commit header.
result = subprocess.run(
- [*GIT_CMD, "diff", "--no-color", "--no-ext-diff",
+ [*GIT_CMD, "diff", "--no-color", "--no-ext-diff", "--no-textconv",
pre_amend_sha, sha, "--"],
cwd=repo_root, capture_output=True, timeout=15
)
else:
result = subprocess.run(
- [*GIT_CMD, "show", "-p", "--no-color", "--no-ext-diff", sha, "--"],
+ [*GIT_CMD, "show", "-p", "--no-color", "--no-ext-diff", "--no-textconv", sha, "--"],
cwd=repo_root, capture_output=True, timeout=15
)
except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
@@ -1543,10 +1597,24 @@ def handle_push_sweep_posttooluse(input_data):
if not cwd:
emit_metrics({"skipped": True, "skip_reason": 25, **_base})
sys.exit(0)
- repo_root = _git_toplevel(cwd)
+ _tip_m = _PUSH_RANGE_RE.search(_push_section(bash_output))
+ cwd_root = _git_toplevel(cwd)
+ repo_root, repo_res = resolve_repo_root(
+ cwd, command, PUSH_SUBCOMMANDS,
+ sha=_tip_m.group(2) if _tip_m else None,
+ session_id=session_id, cwd_root=cwd_root,
+ )
+ if not cwd_root:
+ _base["cwd_is_repo"] = False
+ if repo_res != RES_CWD:
+ _base["repo_resolution"] = repo_res
if not repo_root:
emit_metrics({"skipped": True, "skip_reason": 26, **_base})
sys.exit(0)
+ if repo_res != RES_CWD:
+ debug_log(f"Push sweep: repo resolved via {repo_res} -> {repo_root!r}")
+ if repo_res in (RES_COMMAND, RES_TOUCHED_PATHS):
+ save_repo_hint(session_id, repo_root)
# Guard: the sweep diffs `base..HEAD` and the agent Reads the working
# tree, so the pushed ref MUST be HEAD or the review is of the wrong
@@ -1842,6 +1910,8 @@ def handle_stop_hook(input_data):
session_id = input_data.get("session_id", "default")
stop_hook_active = input_data.get("stop_hook_active", False)
cwd = input_data.get("cwd", "")
+ hook_event_name = input_data.get("hook_event_name") or "Stop"
+ is_subagent = hook_event_name == "SubagentStop"
# Recursion guard FIRST — consume_stop_state clears touched_paths, and CC
# sets stop_hook_active session-wide while any asyncRewake Stop is in
@@ -1856,7 +1926,8 @@ def handle_stop_hook(input_data):
# git, network). asyncRewake Stop runs in the background; the next turn's
# UPS/PostToolUse can fire while we're still here. The snapshot is immune
# to those writes — they affect the NEXT Stop fire's snapshot.
- snap = consume_stop_state(session_id)
+ snap = (consume_stop_state(session_id, clear=False) if is_subagent
+ else consume_stop_state(session_id))
fire_count = snap["fire_count"]
touched_paths = snap["touched_paths"]
baseline_sha = snap["baseline_sha"]
@@ -1920,9 +1991,27 @@ def handle_stop_hook(input_data):
debug_log("Stop hook: no cwd")
_skip(4)
+ repo_cwd, repo_res = resolve_repo_root(
+ cwd, touched_paths=touched_paths, session_id=session_id)
+ res_metrics = ({} if repo_res == RES_CWD
+ else {"cwd_is_repo": False, "repo_resolution": repo_res})
+ if is_subagent and repo_cwd:
+ _pd = os.environ.get("CLAUDE_PROJECT_DIR")
+ _pd_root = _git_toplevel(_pd) if _pd and os.path.isdir(_pd) else None
+ if _pd_root and _pd_root != repo_cwd:
+ debug_log(f"Stop hook: SubagentStop in {repo_cwd!r}, session repo is {_pd_root!r}")
+ v2_metrics = dict(res_metrics)
+ _skip(11)
+ if repo_res != RES_CWD and repo_cwd:
+ debug_log(f"Stop hook: repo resolved via {repo_res} -> {repo_cwd!r}")
+ if not is_subagent and repo_res in (RES_COMMAND, RES_TOUCHED_PATHS):
+ save_repo_hint(session_id, repo_cwd)
+ cwd = repo_cwd
+
review_paths, diff_base, repo_root, untracked, v2_metrics = compute_v2_review_set(
cwd, baseline_sha, head_at_capture, untracked_at_baseline
)
+ v2_metrics = {**res_metrics, **v2_metrics}
if not review_paths:
debug_log("Stop hook: empty review set")
_skip(9, touched_paths_count=len(touched_paths))
@@ -1951,6 +2040,11 @@ def handle_stop_hook(input_data):
debug_log("Stop hook: no changes since baseline")
_skip(6)
+ diff_hash = hashlib.sha256(diff_output.encode("utf-8", "replace")).hexdigest()
+ if snap.get("reviewed_diff_hash") == diff_hash:
+ debug_log("Stop hook: diff already reviewed by SubagentStop")
+ _skip(12)
+
# Parse diff into per-file content
diff_files = parse_diff_into_files(diff_output)
if not diff_files:
@@ -2021,12 +2115,15 @@ def handle_stop_hook(input_data):
for v in vulns
]
# Update baseline so next stop hook iteration only sees new changes
- new_sha = capture_git_baseline(cwd)
+ new_sha = None if is_subagent else capture_git_baseline(cwd)
new_untracked_baseline = _list_untracked(cwd) if new_sha else None
def _record_fire(state):
- state["stop_hook_fire_count"] = fire_index
- state["stop_hook_fire_count_ts"] = _time.time()
+ if is_subagent:
+ state["reviewed_diff_hash"] = diff_hash
+ else:
+ state["stop_hook_fire_count"] = fire_index
+ state["stop_hook_fire_count_ts"] = _time.time()
# Re-read under lock — the commit-review PostToolUse hook may have
# appended findings since consume_stop_state snapshotted.
# Dedupe on (filePath, category) — vulnerableCode includes diff
@@ -2075,11 +2172,12 @@ def handle_stop_hook(input_data):
"fire_index": fire_index,
**({"diff_truncated": llm._last_review_truncated_bytes}
if llm._last_review_truncated_bytes else {}),
+ **({"repo_resolution": repo_res} if res_metrics else {}),
**sweep_trimmed,
}, rewake_summary=_format_vulns_summary(vulns),
additional_context=(PROVENANCE_BANNER + "\n\n"
+ concrete_guidance + CONTINUATION_SUFFIX + "\n"),
- hook_event_name="Stop")
+ hook_event_name=hook_event_name)
sys.exit(2)
if llm._last_call_claude_http_error is not None:
@@ -2087,6 +2185,8 @@ def handle_stop_hook(input_data):
restore_unreviewed_stop_state(session_id, touched_paths, snap_baseline)
else:
debug_log("Stop hook: no security issues found")
+ if is_subagent:
+ record_reviewed_diff(session_id, diff_hash)
# CC truncates metrics to 10 keys by
# insertion order. The previous **sweep,**v2_metrics tail meant the 3
# v2_metrics keys were always sliced off this most-common path, so the
@@ -2152,6 +2252,7 @@ def _maybe_bootstrap_agent_sdk_async():
def main():
"""Main hook function."""
debug_log(f"Hook called with args: {sys.argv}")
+ apply_safe_git_env()
# Master kill switch — honors ENABLE_SECURITY_REMINDER=0 (legacy) and
# SECURITY_GUIDANCE_DISABLE=1 (clearer name, no double negative). Emit
@@ -2200,7 +2301,7 @@ def main():
return
# Handle Stop hook — final security check
- if hook_event_name == "Stop":
+ if hook_event_name in ("Stop", "SubagentStop"):
handle_stop_hook(input_data)
return