summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/hooks/security_reminder_hook.py
diff options
context:
space:
mode:
authorBryan Thompson <bthompson@anthropic.com>2026-06-22 20:03:36 -0500
committerBryan Thompson <bthompson@anthropic.com>2026-06-22 20:03:36 -0500
commit7bc909dc203c249bfed698dc5095c956483cc80e (patch)
tree9683cb5c05e4a9494e9c8054cd09036940389cd0 /plugins/security-guidance/hooks/security_reminder_hook.py
parent286eb1e2178e64571fe339576b06ea03b7754ece (diff)
parentb8c05307dbdfcc8bc4ba48e44dbae5a87e30512d (diff)
Merge main into add-hana-cli (refresh 991-commit-stale branch)add-hana-cli
Diffstat (limited to 'plugins/security-guidance/hooks/security_reminder_hook.py')
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py221
1 files changed, 177 insertions, 44 deletions
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index ffc9ba3c..d3f726e8 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -82,6 +82,7 @@ from _base import ( # noqa: E402,F401
PROVENANCE_TAG, PROVENANCE_BANNER,
_read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK,
_PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics,
+ state_dir as _resolve_state_dir,
)
import extensibility # noqa: E402
from patterns import ( # noqa: E402,F401
@@ -190,7 +191,13 @@ CONTINUATION_SUFFIX = (
"response."
)
-def emit_metrics(metrics, rewake_summary=None):
+def emit_metrics(
+ metrics,
+ rewake_summary=None,
+ additional_context=None,
+ system_message=None,
+ hook_event_name="PostToolUse",
+):
"""
Write a SyncHookJSONOutput line to stdout for Claude Code to pick up.
For asyncRewake (Stop) hooks, CC scans stdout for the first {-prefixed line
@@ -213,6 +220,45 @@ def emit_metrics(metrics, rewake_summary=None):
rewakeSummary in hooks.json, shown to the user in the terminal as the
task-notification one-liner. Must be in the same JSON line as the metrics
because CC stops scanning stdout after the first {-prefixed line.
+
+ `additional_context` (asyncRewake findings): model-visible guidance text.
+ Delivery channel depends on `hook_event_name` because CC's hook-output
+ contract is NOT symmetric across events:
+
+ - PostToolUse (commit-review, push-sweep): surfaced via the modern
+ hookSpecificOutput.additionalContext protocol. `PostToolUse` is a
+ member of CC's hookSpecificOutput discriminated union
+ (coreSchemas.ts), so the JSON validates and metrics/rewakeSummary
+ are consumed. See #1375 / #1783 for why this replaced the legacy
+ stderr + exit(2) shape for PostToolUse.
+
+ - Stop / SubagentStop: there is NO `Stop` member in that union, so
+ emitting hookSpecificOutput{hookEventName:"Stop"} makes the whole
+ line fail isSyncHookJSONOutput validation — which on the asyncRewake
+ path silently drops metrics AND rewakeSummary, and (because the
+ legacy stderr write was removed) leaks the raw JSON to the model as
+ the rewake body. CC's asyncRewake delivery actually reads
+ `stderr || stdout` for the model-visible body and only scans stdout
+ JSON for metrics+rewakeSummary — it never reads additionalContext
+ on this path. So for Stop we use the documented clean pattern:
+ guidance on stderr, valid JSON (metrics + rewakeSummary +
+ top-level decision/reason) on stdout. The top-level decision:"block"
+ + reason also covers the sync-fallback path (single-shot `claude -p`,
+ where asyncRewake degrades to a sync Stop hook that reads
+ decision/reason). See #2159.
+
+ Empty/None additional_context emits neither channel (back-compat for
+ metrics-only callers).
+
+ `system_message` (optional, asyncRewake only): user-visible TUI message,
+ distinct from rewakeSummary which is the task-notification one-liner.
+ Use sparingly — the rewakeMessage in hooks.json is the primary user
+ surface; systemMessage adds a per-fire override when the static
+ rewakeMessage isn't specific enough for the finding being shown.
+
+ `hook_event_name` (used only when additional_context is set): selects the
+ delivery channel above. Defaults to "PostToolUse" (commit-review and
+ push-sweep are the most common callers); handle_stop_hook passes "Stop".
"""
head = {}
if _PV and "pv" not in metrics:
@@ -223,6 +269,26 @@ def emit_metrics(metrics, rewake_summary=None):
out = {"metrics": metrics}
if rewake_summary:
out["rewakeSummary"] = rewake_summary
+ if additional_context:
+ if hook_event_name in ("Stop", "SubagentStop"):
+ # Stop is NOT in CC's hookSpecificOutput union — emitting it there
+ # fails schema validation and drops metrics+rewakeSummary (#2159).
+ # Clean pattern: guidance on stderr (the asyncRewake body channel,
+ # delivered via `stderr || stdout`), top-level decision/reason for
+ # the sync-fallback path. stdout JSON stays valid so metrics +
+ # rewakeSummary survive.
+ sys.stderr.write(additional_context)
+ sys.stderr.flush()
+ out["decision"] = "block"
+ out["reason"] = additional_context
+ else:
+ # PostToolUse et al. — valid union member; modern protocol.
+ out["hookSpecificOutput"] = {
+ "hookEventName": hook_event_name,
+ "additionalContext": additional_context,
+ }
+ if system_message:
+ out["systemMessage"] = system_message
print(json.dumps(out), flush=True)
# =====================================================================
@@ -510,7 +576,11 @@ def handle_user_prompt_submit(input_data):
elif sha:
debug_log(f"Captured git baseline: {sha[:12]}")
else:
- debug_log("Failed to capture git baseline (not a git repo?)")
+ # Show cwd so the next reporter can immediately see when this isn't
+ # actually "not a git repo" but a path-encoding / permissions / git
+ # invocation failure. See #2099.
+ debug_log(f"Failed to capture git baseline (cwd={cwd!r}) — not a git repo, "
+ f"or git invocation failed (check log entries above)")
sys.exit(0)
@@ -594,8 +664,29 @@ _COMMIT_SHA_RE = re.compile(r'^\[[^\]]*?\b([0-9a-f]{7,40})\]', re.MULTILINE)
# 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.
-_GIT_COMMIT_RE = re.compile(r'\bgit\s+commit(?:\s|$)')
-_GIT_AMEND_RE = re.compile(r'\s--amend\b')
+#
+# 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.
+_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+commit\b'
+ r'|\bgt\s+(?:create|modify)\b'
+)
+# Match either the `--amend` flag (with the leading whitespace boundary
+# preserved from the original) OR `gt modify` which is semantically an
+# amend. The handler treats matches as "find the pre-amend SHA via reflog
+# and diff against THAT, not against the post-amend HEAD's parent" — same
+# code path for both git --amend and gt modify.
+_GIT_AMEND_RE = re.compile(r'(?:\s--amend\b|\bgt\s+modify\b)')
# Rolling-window cap on LLM commit-review calls. See atomic_check_rate_limit
# docstring for the rationale that motivated the switch from a lifetime cap.
@@ -624,8 +715,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
+# 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+push\b'
+ r'(?:\bgit(?:\s+-[cC]\s+\S+|\s+--\S+=\S+)*\s+push\b|\bgt\s+submit\b)'
)
# `git push` stdout: "abc1234..def5678 branch -> branch" (or `+abc..def` on
@@ -791,23 +887,30 @@ def _detect_prev_upstream(repo_root, bash_output):
# @{u}@{1} — only meaningful if an upstream is configured.
for ref in ("@{u}@{1}", "@{push}@{1}"):
try:
+ # See #2099: stdout is a SHA but stderr can carry non-ASCII git
+ # warnings — keep bytes raw to avoid cp1252 reader-thread crash.
r = subprocess.run(
[*GIT_CMD, "rev-parse", "--verify", "-q", ref],
- cwd=repo_root, capture_output=True, text=True, timeout=5,
+ cwd=repo_root, capture_output=True, timeout=5,
)
- if r.returncode == 0 and r.stdout.strip():
- return r.stdout.strip()
+ sha = r.stdout.decode("utf-8", errors="replace").strip()
+ if r.returncode == 0 and sha:
+ return sha
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
pass
main = _detect_main_branch(repo_root)
if main:
try:
+ # See #2099: drop text=True; decode bytes manually so a
+ # cp1252-undefined byte in git's stderr doesn't crash the
+ # reader thread.
r = subprocess.run(
[*GIT_CMD, "merge-base", "HEAD", main],
- cwd=repo_root, capture_output=True, text=True, timeout=5,
+ cwd=repo_root, capture_output=True, timeout=5,
)
- if r.returncode == 0 and r.stdout.strip():
- return r.stdout.strip()
+ sha = r.stdout.decode("utf-8", errors="replace").strip()
+ if r.returncode == 0 and sha:
+ return sha
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
pass
return None
@@ -1118,11 +1221,16 @@ def handle_commit_review_posttooluse(input_data):
resolved = 0
for sha in shas:
try:
+ # core.quotePath=false: emit raw UTF-8 in `diff --git a/... b/...`
+ # headers so non-ASCII paths aren't C-quoted past the downstream
+ # parse_diff_into_files regex (sibling of #2056 / #2075). See #2082.
+ # core.quotePath=false comes from GIT_CMD globally (see gitutil.py).
if pre_amend_sha:
# 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", pre_amend_sha, sha, "--"],
+ [*GIT_CMD, "diff", "--no-color", "--no-ext-diff",
+ pre_amend_sha, sha, "--"],
cwd=repo_root, capture_output=True, timeout=15
)
else:
@@ -1254,12 +1362,13 @@ def handle_commit_review_posttooluse(input_data):
try:
full_shas = []
for s in shas:
+ # See #2099: drop text=True; decode manually for cp1252 safety.
r = subprocess.run(
[*GIT_CMD, "rev-parse", "--verify", "-q", s],
- cwd=repo_root, capture_output=True, text=True, timeout=5,
+ cwd=repo_root, capture_output=True, timeout=5,
)
if r.returncode == 0:
- full_shas.append(r.stdout.strip())
+ full_shas.append(r.stdout.decode("utf-8", errors="replace").strip())
_append_reviewed_shas(repo_root, full_shas, vulns_found=len(vulns or []))
except Exception:
pass
@@ -1361,18 +1470,26 @@ def handle_commit_review_posttooluse(input_data):
if s in sev:
sev[s] += 1
+ # Rebuild guidance from new_vulns only — concrete_guidance from the LLM
+ # still lists deduped entries. Pass via additional_context so CC surfaces
+ # the reason via hookSpecificOutput.additionalContext instead of empty
+ # stdout (#1783) / stderr-only "json output validation failed" (#1375).
+ _commit_guidance = (PROVENANCE_BANNER + "\n\n"
+ + _format_vulns_guidance(new_vulns)
+ + CONTINUATION_SUFFIX + "\n")
emit_metrics({
"vulns_found": len(new_vulns), **_base, **_agentic_m,
"critical_count": sev["critical"], "high_count": sev["high"],
"files_reviewed": len(diff_files), "review_ms": review_ms,
**({"deduped": n_deduped} if n_deduped else {}),
- }, rewake_summary=_format_vulns_summary(new_vulns, prefix="Commit security review found"))
-
- # Rebuild guidance from new_vulns only — concrete_guidance from the LLM
- # still lists deduped entries.
- sys.stderr.write(PROVENANCE_BANNER + "\n\n"
- + _format_vulns_guidance(new_vulns)
- + CONTINUATION_SUFFIX + "\n")
+ }, rewake_summary=_format_vulns_summary(new_vulns, prefix="Commit security review found"),
+ additional_context=_commit_guidance,
+ hook_event_name="PostToolUse")
+
+ # exit(2) is preserved per the asyncRewake protocol — it's what CC
+ # uses as the "force fix" signal that triggers the rewakeMessage flow.
+ # The stderr.write was removed; additional_context above now carries
+ # the same text via the modern JSON channel. See #1358/#1375/#1783.
sys.exit(2)
def handle_push_sweep_posttooluse(input_data):
@@ -1453,9 +1570,10 @@ def handle_push_sweep_posttooluse(input_data):
# both.
head = None
try:
+ # See #2099: drop text=True; decode manually for cp1252 safety.
r = subprocess.run([*GIT_CMD, "rev-parse", "HEAD"], cwd=repo_root,
- capture_output=True, text=True, timeout=5)
- head = r.stdout.strip() if r.returncode == 0 else None
+ capture_output=True, timeout=5)
+ head = r.stdout.decode("utf-8", errors="replace").strip() if r.returncode == 0 else None
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
pass
push_section = _push_section(bash_output or "")
@@ -1485,14 +1603,15 @@ def handle_push_sweep_posttooluse(input_data):
quiet_success = False
if not (bash_output or "").strip() and not interrupted:
try:
+ # See #2099: drop text=True; decode manually for cp1252 safety.
r_cur = subprocess.run(
[*GIT_CMD, "rev-parse", "--verify", "-q", "@{u}"],
- cwd=repo_root, capture_output=True, text=True, timeout=5)
+ cwd=repo_root, capture_output=True, timeout=5)
r_prev = subprocess.run(
[*GIT_CMD, "rev-parse", "--verify", "-q", "@{u}@{1}"],
- cwd=repo_root, capture_output=True, text=True, timeout=5)
- cur = r_cur.stdout.strip() if r_cur.returncode == 0 else ""
- prev_u = r_prev.stdout.strip() if r_prev.returncode == 0 else ""
+ cwd=repo_root, capture_output=True, timeout=5)
+ cur = r_cur.stdout.decode("utf-8", errors="replace").strip() if r_cur.returncode == 0 else ""
+ prev_u = r_prev.stdout.decode("utf-8", errors="replace").strip() if r_prev.returncode == 0 else ""
quiet_success = bool(cur and prev_u and cur == head and prev_u != cur)
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
pass
@@ -1506,11 +1625,12 @@ def handle_push_sweep_posttooluse(input_data):
# reviewed-shas state.
for local_ref in new_branch_matches:
try:
+ # See #2099: drop text=True; decode manually for cp1252 safety.
r = subprocess.run(
[*GIT_CMD, "rev-parse", "--verify", "-q", local_ref],
- cwd=repo_root, capture_output=True, text=True, timeout=5,
+ cwd=repo_root, capture_output=True, timeout=5,
)
- local_sha = r.stdout.strip() if r.returncode == 0 else ""
+ local_sha = r.stdout.decode("utf-8", errors="replace").strip() if r.returncode == 0 else ""
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
local_sha = ""
if local_sha and local_sha != head:
@@ -1629,17 +1749,23 @@ def handle_push_sweep_posttooluse(input_data):
# Metrics — keep within the 10-key cap; agentic sub-metrics are dropped
# here in favour of the push-sweep funnel keys (telemetry can join on session_id
# to the per-commit fires for agentic detail). rewake_summary must ride
- # this line (CC reads only the first {-prefixed stdout line); it's a
- # no-op when new_vulns is empty since we exit 0 below.
- emit_metrics({
+ # this line (CC reads only the first {-prefixed stdout line); the emit
+ # is deferred to the two exit points below so the with-vulns path can
+ # also pass additional_context in the same JSON line (#1375/#1783) —
+ # the by-design "CC keeps only the first JSON line" constraint means
+ # we can't emit twice. Builds the shared metrics dict here; vulns path
+ # adds additional_context, no-vulns path emits as-is.
+ _push_metrics = {
**_base, "pushed": len(push_range), "unreviewed": len(tail),
"prefix_advanced": prefix_advanced, "vulns_found": len(new_vulns),
"files_reviewed": len(diff_files), "review_ms": review_ms,
**({"deduped": n_deduped} if n_deduped else {}),
- }, rewake_summary=_format_vulns_summary(new_vulns, prefix="Push security review found"))
+ }
+ _push_rewake_summary = _format_vulns_summary(new_vulns, prefix="Push security review found")
if not new_vulns:
debug_log("Push sweep: no new findings")
+ emit_metrics(_push_metrics, rewake_summary=_push_rewake_summary)
sys.exit(0)
# First-push of a big branch can surface many findings at once across
@@ -1692,9 +1818,14 @@ def handle_push_sweep_posttooluse(input_data):
guidance = _format_vulns_guidance(reported) or ""
else:
guidance = concrete_guidance or _format_vulns_guidance(reported) or ""
- sys.stderr.write(
- PROVENANCE_BANNER + "\n\n" + guidance + CONTINUATION_SUFFIX + "\n"
- )
+ # Emit metrics + additional_context together — single JSON line is the
+ # contract CC's hook parser expects. exit(2) preserved as the asyncRewake
+ # "force fix" trigger (see comment near handle_commit_review_posttooluse).
+ # See #1358 / #1375 / #1783.
+ emit_metrics(_push_metrics, rewake_summary=_push_rewake_summary,
+ additional_context=(PROVENANCE_BANNER + "\n\n"
+ + guidance + CONTINUATION_SUFFIX + "\n"),
+ hook_event_name="PostToolUse")
sys.exit(2)
def handle_stop_hook(input_data):
@@ -1927,6 +2058,11 @@ def handle_stop_hook(input_data):
# untracked_baseline_n is the signal for whether the UPS-time
# untracked-snapshot capture actually ran.
sweep_trimmed = {k: v for k, v in sweep.items() if k != "warn_unresolved_mask"}
+ # Pass guidance via additional_context so CC surfaces the findings via
+ # hookSpecificOutput.additionalContext instead of stderr-only (which
+ # was the cause of "json output validation failed" / empty-reason UI in
+ # #1375 / #1783). exit(2) preserved as the asyncRewake "force fix"
+ # signal — that's the documented mechanism. See #1358 / #1375 / #1783.
emit_metrics({
"vulns_found": len(vulns),
"untracked_baseline_n": len(untracked_at_baseline),
@@ -1940,10 +2076,10 @@ def handle_stop_hook(input_data):
**({"diff_truncated": llm._last_review_truncated_bytes}
if llm._last_review_truncated_bytes else {}),
**sweep_trimmed,
- }, rewake_summary=_format_vulns_summary(vulns))
-
- # Exit code 2 with stderr forces Claude to continue and fix
- sys.stderr.write(PROVENANCE_BANNER + "\n\n" + concrete_guidance + CONTINUATION_SUFFIX + "\n")
+ }, rewake_summary=_format_vulns_summary(vulns),
+ additional_context=(PROVENANCE_BANNER + "\n\n"
+ + concrete_guidance + CONTINUATION_SUFFIX + "\n"),
+ hook_event_name="Stop")
sys.exit(2)
if llm._last_call_claude_http_error is not None:
@@ -1971,10 +2107,7 @@ def handle_stop_hook(input_data):
})
sys.exit(0)
-_SDK_BOOTSTRAP_THROTTLE = os.path.join(
- os.environ.get("SECURITY_WARNINGS_STATE_DIR")
- or os.path.expanduser("~/.claude/security"),
- ".sdk_bootstrap_spawned")
+_SDK_BOOTSTRAP_THROTTLE = os.path.join(_resolve_state_dir(), ".sdk_bootstrap_spawned")
def _maybe_bootstrap_agent_sdk_async():
"""Fire-and-forget SDK bootstrap, for remote-pod environments.