summaryrefslogtreecommitdiff
path: root/plugins/security-guidance
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
parent286eb1e2178e64571fe339576b06ea03b7754ece (diff)
parentb8c05307dbdfcc8bc4ba48e44dbae5a87e30512d (diff)
Merge main into add-hana-cli (refresh 991-commit-stale branch)add-hana-cli
Diffstat (limited to 'plugins/security-guidance')
-rw-r--r--plugins/security-guidance/.claude-plugin/plugin.json2
-rw-r--r--plugins/security-guidance/hooks/_base.py108
-rw-r--r--plugins/security-guidance/hooks/diffstate.py67
-rw-r--r--plugins/security-guidance/hooks/ensure_agent_sdk.py614
-rw-r--r--plugins/security-guidance/hooks/gitutil.py124
-rw-r--r--plugins/security-guidance/hooks/hooks.json24
-rw-r--r--plugins/security-guidance/hooks/llm.py48
-rw-r--r--plugins/security-guidance/hooks/patterns.py15
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py221
-rw-r--r--plugins/security-guidance/hooks/session_state.py8
-rwxr-xr-xplugins/security-guidance/hooks/sg-python.sh65
11 files changed, 1150 insertions, 146 deletions
diff --git a/plugins/security-guidance/.claude-plugin/plugin.json b/plugins/security-guidance/.claude-plugin/plugin.json
index c54d19b0..f4cc218e 100644
--- a/plugins/security-guidance/.claude-plugin/plugin.json
+++ b/plugins/security-guidance/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "security-guidance",
- "version": "2.0.0",
+ "version": "2.0.6",
"description": "Security review for Claude-generated code. Pattern-based warnings on edits, LLM-powered diff review on Stop, and an agentic commit reviewer that catches injection, XSS, SSRF, hardcoded secrets, and 25+ other vulnerability classes.",
"author": {
"name": "David Dworken",
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py
index 7e8eeed5..ce051753 100644
--- a/plugins/security-guidance/hooks/_base.py
+++ b/plugins/security-guidance/hooks/_base.py
@@ -10,15 +10,42 @@ import os
import threading
from datetime import datetime
+def state_dir():
+ """Return the absolute path of the plugin's state directory.
+
+ Resolution precedence (highest first):
+ 1. SECURITY_WARNINGS_STATE_DIR — plugin-specific override (existing)
+ 2. CLAUDE_CONFIG_DIR/security — CC's config-dir env var (#1868)
+ 3. ~/.claude/security — default fallback
+
+ Empty-string env vars are treated as not-set so a misconfigured shell
+ (`CLAUDE_CONFIG_DIR=` with no value) doesn't silently write to
+ /security at the filesystem root.
+
+ Returns a fully-expanded absolute path (no literal `~`) so subprocess
+ callers can pass it through to code that doesn't re-expand tildes.
+
+ Called per-invocation rather than cached at import time so test
+ monkeypatches of the env vars take effect — the plugin's hooks each
+ run as fresh subprocesses in production, so the per-call cost is
+ negligible compared to subprocess spawn.
+ """
+ explicit = os.environ.get("SECURITY_WARNINGS_STATE_DIR")
+ if explicit:
+ return os.path.expanduser(explicit)
+ cc_config = os.environ.get("CLAUDE_CONFIG_DIR")
+ if cc_config:
+ return os.path.expanduser(os.path.join(cc_config, "security"))
+ return os.path.expanduser("~/.claude/security")
+
+
# Debug log file. Lives under the plugin state dir (default ~/.claude/security/)
# rather than /tmp because /tmp is world-writable on multi-user hosts (TOCTOU /
# symlink-attack surface, cross-user log leakage). Overridable per-process via
-# SECURITY_GUIDANCE_DEBUG_LOG, or per-state-dir via SECURITY_WARNINGS_STATE_DIR.
-_DEFAULT_STATE_DIR = os.path.expanduser(
- os.environ.get("SECURITY_WARNINGS_STATE_DIR") or "~/.claude/security"
-)
+# SECURITY_GUIDANCE_DEBUG_LOG, or per-state-dir via SECURITY_WARNINGS_STATE_DIR
+# (plugin-specific override) or CLAUDE_CONFIG_DIR (CC-wide config dir, #1868).
DEBUG_LOG_FILE = os.environ.get("SECURITY_GUIDANCE_DEBUG_LOG") or os.path.join(
- _DEFAULT_STATE_DIR, "log.txt"
+ state_dir(), "log.txt"
)
# Cap the debug log so parallel-worker fleets don't fill disk. When the active
# file exceeds this it's atomically rotated to <file>.1 (overwriting any prior
@@ -89,7 +116,18 @@ _PV = _read_plugin_version_int()
# Emitted via _usage_metrics() into the existing emit_metrics() channel so
# hook metrics rows carry per-invocation token/cost totals
# alongside the existing skip_reason / vulns_found fields.
-_USAGE = {"in": 0, "out": 0, "cr": 0, "cw": 0, "cost": 0.0, "n": 0}
+_USAGE = {
+ "in": 0, "out": 0, "cr": 0, "cw": 0, "cost": 0.0, "n": 0,
+ # HTTP error visibility (#2098 visibility gap — see emit comment in
+ # _usage_metrics). Without this, API failures from `_call_claude` left
+ # zero fingerprint in telemetry: the call returns None, the caller's
+ # emit_metrics carries no api_calls field, and the failure is
+ # indistinguishable from "no review needed". The deprecation outage
+ # that broke every commit-review LLM call was invisible until users
+ # reported it manually.
+ "http_err_last": 0, # most recent HTTP error code this invocation
+ "http_err_count": 0, # total HTTP errors (4xx + 5xx + network)
+}
_USAGE_LOCK = threading.Lock()
# $/Mtok (input, output). Used only for the raw-HTTP path; the SDK path
@@ -139,19 +177,55 @@ def _record_usage(usage, model, cost_usd=None):
_USAGE["n"] += 1
+def _record_http_error(status):
+ """Record an HTTP error from an LLM API call. `status` is the HTTP
+ status code (integer 400–599) or -1 for network/timeout errors. Stored
+ in `_USAGE["http_err_last"]` (most recent) and counted in
+ `_USAGE["http_err_count"]`. Snapshot via `_usage_metrics()` so every
+ subsequent `emit_metrics` includes the failure fingerprint.
+
+ Background: without this, the most recent example was the #2098
+ deprecation 400. Every hook fire's LLM call returned HTTP 400; the
+ plugin caught it and returned None; the emit_metrics carried no
+ api_calls field; aggregate dashboards looked normal. The failure
+ only became visible when a user manually reported errors out of
+ their debug log. With this field, a category-of-failure spike (4xx,
+ 5xx, or -1 network) is queryable from BQ in real time.
+ """
+ try:
+ s = int(status)
+ except (TypeError, ValueError):
+ return
+ with _USAGE_LOCK:
+ _USAGE["http_err_last"] = s
+ _USAGE["http_err_count"] += 1
+
+
def _usage_metrics():
"""Snapshot the accumulator as metric keys. Returns {} when no API calls
- were made so skip-path emits don't burn key budget. cost_usd rounded to
- 1e-6 to keep the float finite/short for the zod schema."""
+ AND no HTTP errors were made so skip-path emits don't burn key budget.
+ cost_usd rounded to 1e-6 to keep the float finite/short for the zod
+ schema.
+
+ HTTP errors (`http_err_last`, `http_err_count`) emitted ONLY when
+ `http_err_count > 0` so successful calls don't pad every metrics row
+ with two zero fields.
+ """
with _USAGE_LOCK:
- if _USAGE["n"] == 0:
+ if _USAGE["n"] == 0 and _USAGE["http_err_count"] == 0:
return {}
- return {
- "tok_in": _USAGE["in"],
- "tok_out": _USAGE["out"],
- "tok_cache_r": _USAGE["cr"],
- "tok_cache_w": _USAGE["cw"],
- "cost_usd": round(_USAGE["cost"], 6),
- "api_calls": _USAGE["n"],
- }
+ out = {}
+ if _USAGE["n"] > 0:
+ out.update({
+ "tok_in": _USAGE["in"],
+ "tok_out": _USAGE["out"],
+ "tok_cache_r": _USAGE["cr"],
+ "tok_cache_w": _USAGE["cw"],
+ "cost_usd": round(_USAGE["cost"], 6),
+ "api_calls": _USAGE["n"],
+ })
+ if _USAGE["http_err_count"] > 0:
+ out["http_err_last"] = _USAGE["http_err_last"]
+ out["http_err_count"] = _USAGE["http_err_count"]
+ return out
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index 7dbe542a..3ce9da1b 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -138,7 +138,17 @@ def restore_unreviewed_stop_state(session_id, paths, baseline_sha):
def get_baseline_file_content(session_id, file_path, cwd):
- """Get the content of a file at the baseline SHA. Returns None if unavailable."""
+ """Get the content of a file at the baseline SHA. Returns None if unavailable.
+
+ Decode the file content as UTF-8 with errors="replace" rather than using
+ text=True: source files in user repos can be latin-1 / cp1252 / shift-jis
+ / etc., and on Windows text=True would decode via locale.getpreferredencoding()
+ in strict mode and raise UnicodeDecodeError in the subprocess reader
+ thread — leaving result.stdout=None and propagating AttributeError when
+ the caller tries to use it. Same class as the existing migrations at
+ security_reminder_hook.py:540 (reflog subjects) and :1115 (commit
+ diffs); this helper was missed in that pass. See
+ anthropics/claude-plugins-official#2056."""
baseline_sha = load_baseline_sha(session_id)
if not baseline_sha:
return None
@@ -151,12 +161,12 @@ def get_baseline_file_content(session_id, file_path, cwd):
return None
result = subprocess.run(
[*GIT_CMD, "show", f"{baseline_sha}:{rel_path}"],
- cwd=cwd, capture_output=True, text=True, timeout=5
+ cwd=cwd, capture_output=True, timeout=5
)
if result.returncode == 0:
- return result.stdout
+ return (result.stdout or b"").decode("utf-8", errors="replace")
return None
- except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError):
return None
@@ -173,11 +183,16 @@ def capture_git_baseline(cwd):
and `compute_v2_review_set` subtracts that set so pre-existing untracked
files are not reviewed as Claude-authored.
"""
+ # 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
+ # with `Ávila_report.txt` triggers a quotePath/locale warning) would
+ # trip the stderr reader thread on Windows cp1252. Decode both streams
+ # leniently for symmetry with _list_untracked. See #2056.
try:
# Check if HEAD exists (i.e., repo has at least one commit)
head_check = subprocess.run(
[*GIT_CMD, "rev-parse", "HEAD"],
- cwd=cwd, capture_output=True, text=True, timeout=5
+ cwd=cwd, capture_output=True, timeout=5
)
if head_check.returncode != 0:
# No commits yet — skip review rather than creating commits in the user's repo
@@ -186,20 +201,20 @@ def capture_git_baseline(cwd):
result = subprocess.run(
[*GIT_CMD, "stash", "create"],
- cwd=cwd, capture_output=True, text=True, timeout=15
+ cwd=cwd, capture_output=True, timeout=15
)
- sha = result.stdout.strip()
+ sha = (result.stdout or b"").decode("utf-8", errors="replace").strip()
if sha:
return sha
# Working tree is clean — stash create returns empty. Use HEAD.
result = subprocess.run(
[*GIT_CMD, "rev-parse", "HEAD"],
- cwd=cwd, capture_output=True, text=True, timeout=5
+ cwd=cwd, capture_output=True, timeout=5
)
- sha = result.stdout.strip()
+ sha = (result.stdout or b"").decode("utf-8", errors="replace").strip()
return sha if sha else None
- except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
debug_log(f"Failed to capture git baseline: {e}")
return None
@@ -323,19 +338,35 @@ def _list_untracked(cwd):
mtime is captured so an in-place edit during the turn is still reviewed.
Uses ls-files (not status) for the UPS path: the index diff isn't needed,
- and ls-files --others only walks the worktree against .gitignore."""
+ and ls-files --others only walks the worktree against .gitignore.
+
+ Decodes stdout/stderr as UTF-8 with errors="replace" instead of using
+ text=True. With core.quotePath=false git emits raw UTF-8 bytes for
+ non-ASCII filenames; text=True decodes via locale.getpreferredencoding()
+ in strict mode — on Windows that's cp1252 with several undefined bytes
+ (0x81/0x8D/0x8F/0x90/0x9D), all of which appear in UTF-8 encodings of
+ common accented capitals (Á Í Ï Ð Ý) and most CJK/emoji codepoints.
+ A non-ASCII filename in the worktree crashed the subprocess reader
+ thread, left r.stdout=None, and propagated AttributeError out of the
+ helper — silently losing the baseline snapshot every UserPromptSubmit.
+ See anthropics/claude-plugins-official#2056. The sibling helpers in
+ gitutil.py already follow the lenient pattern; this function and
+ capture_git_baseline / _git_name_only / _git_status_porcelain were
+ the holdouts."""
try:
repo = _git_toplevel(cwd) or cwd
+ # core.quotePath=false comes from GIT_CMD globally (see gitutil.py).
r = subprocess.run(
- [*GIT_CMD, "-c", "core.quotePath=false", "ls-files",
- "--others", "--exclude-standard", "-z"],
- cwd=repo, capture_output=True, text=True, timeout=15,
+ [*GIT_CMD, "ls-files", "--others", "--exclude-standard", "-z"],
+ cwd=repo, capture_output=True, timeout=15,
)
if r.returncode != 0:
- debug_log(f"_list_untracked rc={r.returncode}: {r.stderr[:200]}")
+ stderr_str = (r.stderr or b"").decode("utf-8", errors="replace")
+ debug_log(f"_list_untracked rc={r.returncode}: {stderr_str[:200]}")
return {}
+ stdout = (r.stdout or b"").decode("utf-8", errors="replace")
out = {}
- for p in r.stdout.split("\0"):
+ for p in stdout.split("\0"):
if not p:
continue
try:
@@ -346,7 +377,9 @@ def _list_untracked(cwd):
debug_log(f"_list_untracked: capped at {UNTRACKED_BASELINE_CAP}")
break
return out
- except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
+ # ValueError guards against any future strict-decode regression
+ # so the helper degrades to {} instead of crashing the hook.
debug_log(f"_list_untracked error: {e}")
return {}
diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py
index 220188e5..23312baa 100644
--- a/plugins/security-guidance/hooks/ensure_agent_sdk.py
+++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py
@@ -23,6 +23,12 @@ import sys
import time
from pathlib import Path
+# Shared state-dir resolver: SECURITY_WARNINGS_STATE_DIR → CLAUDE_CONFIG_DIR/security
+# → ~/.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
+
# Outcome codes for the sdk_bootstrap metric. Values are stable for telemetry.
NOOP_SYSTEM = 0 # claude_agent_sdk already importable in system python
NOOP_VENV = 1 # venv already built and SDK imports from it
@@ -32,6 +38,379 @@ BUILD_FAILED = 3 # venv create or pip install raised/timed out
# llm.py also matches Windows venv layout (Lib/site-packages). Don't reuse the
# value — telemetry rows from older plugin builds still emit 4.
SKIP_SENTINEL = 5 # another SessionStart is currently building
+HOOK_PY_INCOMPATIBLE = 6 # hook interpreter is <3.10 — SDK syntax can't load
+ # here no matter how the venv was built. See #2071.
+# --target fallback: when `python -m venv` can't bootstrap pip (ensurepip
+# missing — Debian python3-venv not installed, or a python.org/pyenv build
+# without ensurepip), fall back to `pip install --target <dir>` which needs
+# only the system pip, not venv/ensurepip. Telemetry (v2.0.4 sdk_has_pip
+# probe) confirmed ~95% of venv_ensurepip_fail users HAVE pip, so this
+# recovers the agentic reviewer for them instead of degrading to pattern +
+# single-shot review. See #2154 follow-up.
+BUILT_TARGET = 7 # venv ensurepip failed → SDK pip-installed via --target
+NOOP_TARGET = 8 # --target libs already present and importable
+SKIP_COOLDOWN = 9 # a recent build was signal-killed (memory pressure) — not
+ # retrying this session to avoid burning the user's
+ # memory/CPU on a build that keeps getting killed. CCR
+ # repro confirmed the dominant Linux BUILD_FAILED is a
+ # SIGKILL/SIGSEGV of the memory-heavy venv+pip subprocess
+ # (rc<0, empty streams). See #2154 follow-up.
+
+# How long to skip rebuilds after a signal kill. Retries at most once per
+# window so a machine whose memory frees up still recovers (just not every
+# session). Keyed by marker mtime.
+SIGNAL_KILL_COOLDOWN_SEC = 24 * 3600
+
+
+# Phase + err-kind integer encoding for sdk_bootstrap_phase / sdk_bootstrap_err.
+#
+# Earlier versions emitted these as STRINGS (e.g. "pip", "dns_fail"). CC's
+# plugin-metrics pipeline silently drops plugin-emitted string values —
+# only `bool|finite-number` plugin metrics reach BigQuery. (CC-core
+# metrics like `subscription_type` are exempt because they're injected
+# downstream of plugin validation.) Confirmed empirically: 185K
+# BUILD_FAILED rows in BQ had `sdk_bootstrap_phase`/`sdk_bootstrap_err`
+# = NULL despite the Python code emitting them. This left ~28K
+# BUILD_FAILED sessions/day with no diagnostic split — flying blind on
+# the real failure modes (pip-no-match vs dns-fail vs ssl-verify etc.).
+#
+# Fix: encode as small integers per the maps below. Values are
+# APPEND-ONLY for telemetry stability. Reserve 99 as the "unknown /
+# uncategorized" bucket so an unmapped err_kind (e.g., a new exception
+# type) still emits a non-zero signal.
+SDK_BOOTSTRAP_PHASE_CODES = {
+ "pre": 1, # pre-venv (state_dir.mkdir, sentinel open)
+ "venv": 2, # python -m venv --clear
+ "pip": 3, # pip install
+ "main": 4, # uncaught exception above main()
+ "pip_target": 5, # `pip install --target` fallback (venv ensurepip failed)
+}
+SDK_BOOTSTRAP_ERR_CODES = {
+ "pip_no_match": 1,
+ "dns_fail": 2,
+ "conn_refused": 3,
+ "ssl_verify": 4,
+ "perm_denied": 5,
+ "no_pip": 6,
+ "disk_full": 7,
+ "proxy_auth": 8,
+ "stderr_timeout": 9, # pip stderr containing "timeout"/"timed out"
+ "subprocess_timeout": 10, # subprocess.TimeoutExpired (>120s)
+ "signal_killed": 16, # venv/pip subprocess killed by a signal
+ # (rc<0 or 128+sig) — OOM-killer SIGKILL /
+ # RLIMIT_AS SIGSEGV, empty streams. The
+ # actual rc rides in sdk_bootstrap_rc. This
+ # is the dominant Linux failure (CCR repro).
+ # Venv-stage specific categories added after PR #2112 telemetry surfaced
+ # 2,406 phase=2/err=99 sessions in the first 3h of v2.0.1 — venv phase
+ # failing in ways the original pip-flavored patterns didn't catch. These
+ # all split out of what was previously collapsing to _uncategorized.
+ "venv_ensurepip_fail": 11, # Debian/Ubuntu missing python3-venv;
+ # stderr mentions ensurepip non-zero exit
+ # or "ensurepip is not available"
+ "venv_path_too_long": 12, # Windows MAX_PATH (260) or POSIX
+ # ENAMETOOLONG — venv writes deep paths
+ # under state_dir/agent-sdk-venv/Lib/...
+ "venv_no_module": 13, # `python3 -m venv` itself missing — "No
+ # module named 'venv'" / "No module named venv"
+ "venv_already_exists": 14, # Errno 17 / "file exists" — sentinel race
+ # past O_EXCL or stale dir survived --clear
+ "venv_setup_failed": 15, # Generic "virtual environment was not
+ # created successfully" — catches the long
+ # tail of venv setup failures that don't
+ # match a more specific category above
+ # 16–98 reserved for future categories; APPEND-ONLY.
+ # 99 catches everything else (including "exc:<TypeName>" and "other:<tail>"
+ # — the original string is debug-loggable but the integer is what makes
+ # it to telemetry). For the "other:" tail, `sdk_bootstrap_stderr_sig`
+ # carries a bounded integer hash so we can still distinguish patterns
+ # in BQ aggregation.
+ "_uncategorized": 99,
+}
+
+# Exception-type encoding for the "exc:<TypeName>" err_kinds (the generic
+# `except Exception` path — venv/pip raised a Python exception rather than
+# a CalledProcessError with categorizable stderr).
+#
+# #2154 telemetry surfaced that the dominant remaining venv BUILD_FAILED
+# bucket (phase=venv, err=99) is ~99% `exc:` with stderr_sig=NULL — i.e.
+# exceptions, not stderr-bearing subprocess failures — so the stderr_sig
+# hash couldn't distinguish them. This maps the exception TYPE to a stable
+# code so BQ can tell FileNotFoundError (python/venv binary missing) from
+# PermissionError (read-only home) from a bare OSError, etc.
+#
+# All the FileNotFoundError/PermissionError/etc. entries are OSError
+# subclasses, so they ALSO carry an errno (see _encode_errno) — the type
+# code gives the Python class, errno gives the OS-level cause. APPEND-ONLY.
+SDK_BOOTSTRAP_EXC_CODES = {
+ "FileNotFoundError": 1, # interpreter/venv path component missing
+ "PermissionError": 2, # read-only home, sandboxed FS
+ "NotADirectoryError": 3,
+ "IsADirectoryError": 4,
+ "FileExistsError": 5, # (sentinel race is handled separately; this
+ # is FileExistsError from elsewhere in venv)
+ "OSError": 6, # bare OSError — errno carries the real cause
+ "BlockingIOError": 7,
+ "BrokenPipeError": 8,
+ "ConnectionError": 9,
+ "TimeoutError": 10, # distinct from subprocess.TimeoutExpired
+ "InterruptedError": 11,
+ "MemoryError": 12,
+ "UnicodeDecodeError": 13,
+ "ValueError": 14,
+ "RuntimeError": 15,
+ # 16–98 reserved; APPEND-ONLY.
+ "_other_exc": 99, # an exception type not in this map
+}
+
+
+def _encode_phase(s):
+ """Map err_phase string to its telemetry integer code, or 0 if unset.
+ Empty/None → 0 lets `if encoded:` cleanly skip emission. Per
+ SDK_BOOTSTRAP_PHASE_CODES, valid codes are 1-4."""
+ return SDK_BOOTSTRAP_PHASE_CODES.get((s or "").strip(), 0)
+
+
+def _encode_err_kind(s):
+ """Map err_kind string to its telemetry integer code, or 0 if unset.
+ Direct hits use the static map; "exc:<X>" and "other:<tail>" both
+ collapse to _uncategorized (99) — the raw string survives in debug
+ logs, only the integer reaches BQ."""
+ s = (s or "").strip()
+ if not s:
+ return 0
+ if s in SDK_BOOTSTRAP_ERR_CODES:
+ return SDK_BOOTSTRAP_ERR_CODES[s]
+ # "signal_killed:<rc>" carries the returncode in sdk_bootstrap_rc; the
+ # category maps to the signal_killed code.
+ if s.startswith("signal_killed"):
+ return SDK_BOOTSTRAP_ERR_CODES["signal_killed"]
+ # Prefix matches for the catch-all categories
+ if s.startswith("exc:") or s.startswith("other:") or s == "other":
+ return SDK_BOOTSTRAP_ERR_CODES["_uncategorized"]
+ # Unknown string — still emit as uncategorized rather than dropping
+ return SDK_BOOTSTRAP_ERR_CODES["_uncategorized"]
+
+
+def _encode_rc(err_kind):
+ """Extract the subprocess returncode embedded in a 'signal_killed:<rc>'
+ err_kind (e.g. -11 SIGSEGV / -9 SIGKILL / 139 shell-wrapped). Emitted as
+ sdk_bootstrap_rc so BQ can tell OOM-killer (-9) from RLIMIT_AS (-11).
+ Returns 0 when absent/non-numeric."""
+ if not err_kind or not err_kind.startswith("signal_killed:"):
+ return 0
+ try:
+ return int(err_kind.split(":", 1)[1])
+ except (ValueError, IndexError):
+ return 0
+
+
+def _is_signal_kill(returncode) -> bool:
+ """A subprocess killed by a signal rather than a clean non-zero exit.
+ subprocess.run (no shell, as used here) reports negative rc = -signum
+ (SIGKILL→-9 OOM-killer, SIGSEGV→-11 RLIMIT_AS, SIGABRT→-6). The 128+sig
+ forms (134/137/139) are defensive for any shell-wrapped path. Paired with
+ empty stdout+stderr this is the memory-kill signature (CCR repro)."""
+ if returncode is None:
+ return False
+ return returncode < 0 or returncode in (134, 137, 139)
+
+
+def _cooldown_remaining(state_dir) -> float:
+ """Seconds left in the signal-kill cooldown (0 if none/expired). Reads the
+ marker's mtime; a missing/unreadable marker means not in cooldown."""
+ marker = Path(state_dir) / "agent-sdk-venv.cooldown"
+ try:
+ age = time.time() - marker.stat().st_mtime
+ except OSError:
+ return 0.0
+ return max(0.0, SIGNAL_KILL_COOLDOWN_SEC - age)
+
+
+def _write_cooldown(state_dir) -> None:
+ """Start/refresh the signal-kill cooldown so we stop re-attempting a build
+ that keeps getting killed every session. Best-effort."""
+ try:
+ Path(state_dir).mkdir(parents=True, exist_ok=True)
+ (Path(state_dir) / "agent-sdk-venv.cooldown").write_text(
+ time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
+ except OSError:
+ pass
+
+
+def _encode_stderr_sig(err_kind):
+ """Bounded integer hash of the stderr tail captured in "other:<tail>"
+ err_kinds. Lets us distinguish patterns INSIDE the _uncategorized
+ (code 99) bucket without unbounded cardinality.
+
+ Returns 0 for non-"other:" err_kinds (so the field auto-omits from
+ emit_metrics on categorized failures — see the emit block in main()).
+
+ Strategy: take the tail's first ~30 chars (post-lowercase, post-trim),
+ SHA-1, fold the first 2 bytes to 0–999. Different stderr messages
+ cluster into different buckets; same stderr always maps to the same
+ bucket. Cardinality is bounded at 1000, well below any "high
+ cardinality" alarm — and a real failure mode typically produces
+ near-identical stderr across thousands of machines, so 1000 buckets
+ is comfortably wide.
+
+ Why first ~30 chars: stderr like "ERROR: Command failed: <full
+ path>" varies the tail wildly (paths) but the categorization signal
+ is in the leading words. Dropping the suffix focuses the hash on
+ the discriminative part.
+ """
+ if not err_kind or not err_kind.startswith("other:"):
+ return 0
+ import hashlib
+ tail = err_kind[len("other:"):].strip().lower()[:30]
+ if not tail:
+ return 0
+ h = hashlib.sha1(tail.encode("utf-8", errors="replace")).digest()
+ return int.from_bytes(h[:2], "big") % 1000
+
+
+def _encode_exc_kind(err_kind):
+ """Map an "exc:<TypeName>[:errno]" err_kind to its exception-type code
+ (SDK_BOOTSTRAP_EXC_CODES). Returns 0 for non-exc err_kinds (so the
+ sdk_bootstrap_exc field auto-omits on stderr/categorized failures).
+ Unmapped exception types → 99 (_other_exc)."""
+ if not err_kind or not err_kind.startswith("exc:"):
+ return 0
+ # "exc:OSError:28" → "OSError"; "exc:RuntimeError" → "RuntimeError"
+ name = err_kind[len("exc:"):].split(":", 1)[0].strip()
+ if not name:
+ return 0
+ return SDK_BOOTSTRAP_EXC_CODES.get(name, SDK_BOOTSTRAP_EXC_CODES["_other_exc"])
+
+
+def _encode_errno(err_kind):
+ """Extract the OS errno from an "exc:<TypeName>:<errno>" err_kind.
+ OSError-family exceptions embed their errno (ENOENT=2, EACCES=13,
+ ENOSPC=28, …) — the OS-level cause is far more actionable than the
+ Python class alone. Returns 0 when absent/non-numeric (field omitted)."""
+ if not err_kind or not err_kind.startswith("exc:"):
+ return 0
+ parts = err_kind.split(":")
+ if len(parts) < 3:
+ return 0
+ try:
+ return int(parts[2])
+ except (ValueError, IndexError):
+ return 0
+
+
+def _probe_has_pip() -> bool:
+ """True iff the current interpreter can run pip (`-m pip --version`).
+
+ Probed only on the venv_ensurepip_fail path (see __main__), NOT on the
+ happy path — it's an extra subprocess we only want when diagnosing a
+ failure. The result decides whether a `pip install --target` fallback
+ (Option A) is even viable for this machine: ensurepip/venv missing but
+ pip present → --target would work; pip also missing → it wouldn't, and
+ the user needs a system package (python3-venv / a complete Python)."""
+ try:
+ r = subprocess.run(
+ [sys.executable, "-m", "pip", "--version"],
+ capture_output=True, timeout=10,
+ )
+ return r.returncode == 0
+ except Exception:
+ return False
+
+
+def _pip_err_from_stderr(stderr_b):
+ """Categorize a pip-install stderr into a known err_kind (the pip subset
+ of SDK_BOOTSTRAP_ERR_CODES). Used by the --target fallback; mirrors the
+ pip branches of main()'s inline categorizer. Kept as a sibling rather
+ than extracting main()'s chain (which also has venv-phase branches) to
+ avoid disturbing the working venv categorization."""
+ if isinstance(stderr_b, bytes):
+ s = stderr_b.decode("utf-8", errors="replace")
+ else:
+ s = str(stderr_b or "")
+ low = s.lower()
+ if "no matching distribution" in low or "could not find a version" in low:
+ return "pip_no_match"
+ if ("name or service not known" in low or "name resolution" in low
+ or "nodename nor servname" in low or "temporary failure in name" in low):
+ return "dns_fail"
+ if "connection refused" in low or "connection reset" in low:
+ return "conn_refused"
+ if "ssl" in low and ("verify" in low or "certificate" in low):
+ return "ssl_verify"
+ if "permission denied" in low or "read-only file system" in low:
+ return "perm_denied"
+ if "no module named pip" in low or "no module named ensurepip" in low:
+ return "no_pip"
+ if "no space left" in low or "disk quota" in low:
+ return "disk_full"
+ if "proxy" in low and ("authent" in low or "tunnel" in low or "407" in low):
+ return "proxy_auth"
+ if "timeout" in low or "timed out" in low:
+ return "stderr_timeout"
+ tail = next((ln.strip() for ln in reversed(s.splitlines()) if ln.strip()), "")[:60]
+ return f"other:{tail}" if tail else "other"
+
+
+def _target_dir(state_dir) -> Path:
+ return Path(state_dir) / "agent-sdk-libs"
+
+
+def _target_sdk_importable(state_dir) -> bool:
+ """True iff the --target libs dir has an importable claude_agent_sdk,
+ probed with THIS interpreter (the one llm.py will import it from) and the
+ target dir prepended to sys.path. Cheap dir-check first to avoid a
+ subprocess on the common no-target path."""
+ target = _target_dir(state_dir)
+ if not (target / "claude_agent_sdk").is_dir():
+ return False
+ try:
+ r = subprocess.run(
+ [sys.executable, "-c",
+ "import sys; sys.path.insert(0, sys.argv[1]); import claude_agent_sdk",
+ str(target)],
+ capture_output=True, timeout=10,
+ )
+ return r.returncode == 0
+ except Exception:
+ return False
+
+
+def _build_via_target(state_dir) -> tuple[int, str, str]:
+ """Fallback install when `python -m venv` can't bootstrap pip (ensurepip
+ missing — Debian python3-venv absent, or a python.org/pyenv build without
+ ensurepip). `pip install --target <dir>` needs only the system pip, not
+ venv/ensurepip. v2.0.4 telemetry (sdk_has_pip) confirmed ~95% of
+ venv_ensurepip_fail users have pip. The consumer (llm.py) adds this flat
+ dir to sys.path. Returns (outcome, err_phase, err_kind).
+
+ --upgrade so a stale/partial target dir from a prior failed attempt
+ doesn't make pip refuse; --prefer-binary mirrors the venv path's wheel
+ preference (ARM64 Windows cryptography)."""
+ target = _target_dir(state_dir)
+ try:
+ subprocess.run(
+ [sys.executable, "-m", "pip", "install",
+ "--target", str(target), "--upgrade",
+ "--disable-pip-version-check", "--prefer-binary", "--no-cache-dir",
+ "claude-agent-sdk"],
+ capture_output=True, timeout=120, check=True,
+ )
+ return BUILT_TARGET, "", ""
+ except subprocess.CalledProcessError as e:
+ # A --target pip install is also memory-heavy, so it too can be
+ # signal-killed under memory pressure — cool down, same as the venv path.
+ if _is_signal_kill(e.returncode):
+ _write_cooldown(state_dir)
+ return BUILD_FAILED, "pip_target", f"signal_killed:{e.returncode}"
+ return BUILD_FAILED, "pip_target", _pip_err_from_stderr(e.stderr)
+ except subprocess.TimeoutExpired:
+ return BUILD_FAILED, "pip_target", "subprocess_timeout"
+ except Exception as e:
+ errno = getattr(e, "errno", None)
+ if isinstance(errno, int):
+ return BUILD_FAILED, "pip_target", f"exc:{type(e).__name__}:{errno}"
+ return BUILD_FAILED, "pip_target", f"exc:{type(e).__name__}"
def _sdk_on_syspath() -> bool:
@@ -62,13 +441,33 @@ def main() -> tuple[int, str, str]:
err_phase / err_kind are non-empty only on BUILD_FAILED — they let
telemetry split bootstrap failures by root cause.
"""
+ # Honesty check (fixes the misleading NOOP_VENV in #2071): the SDK
+ # requires Python >=3.10 and uses 3.10+ syntax (match statements,
+ # PEP 604 unions). On a 3.9 hook interpreter we CANNOT import it no
+ # matter how the venv was built — llm.py runs in this same interpreter
+ # and the syntax-level import will SyntaxError. macOS ships 3.9.6 as
+ # the default `python3` and `/usr/bin` precedes Homebrew in PATH, so
+ # this case is the default state for a large share of macOS users.
+ #
+ # sg-python.sh now prefers python3.10+ binaries so most users won't
+ # reach this branch; the fallback to 3.9 is preserved for the
+ # pattern-warning hooks that don't need the SDK. Reporting
+ # HOOK_PY_INCOMPATIBLE here:
+ # (a) avoids 30-60s of wasted pip install,
+ # (b) avoids the lie where the venv_py probe says NOOP_VENV but the
+ # consumer import fails, and
+ # (c) gives telemetry a clean bucket to size the affected fleet.
+ if sys.version_info < (3, 10):
+ return (
+ HOOK_PY_INCOMPATIBLE,
+ "hook_py",
+ f"py_{sys.version_info[0]}.{sys.version_info[1]}",
+ )
+
if _sdk_on_syspath():
return NOOP_SYSTEM, "", ""
- state_dir = Path(
- os.environ.get("SECURITY_WARNINGS_STATE_DIR")
- or os.path.expanduser("~/.claude/security")
- )
+ state_dir = Path(_resolve_state_dir())
venv = state_dir / "agent-sdk-venv"
# Windows venvs put the interpreter at Scripts\python.exe; POSIX uses bin/python.
if sys.platform == "win32":
@@ -102,6 +501,20 @@ def main() -> tuple[int, str, str]:
except Exception:
pass # broken venv; rebuild below
+ # If a prior run installed the SDK via the --target fallback (ensurepip
+ # path), reuse it. Only reached when there's no working venv, so healthy
+ # NOOP_VENV users never pay for this probe.
+ if _target_sdk_importable(state_dir):
+ return NOOP_TARGET, "", ""
+
+ # If a recent build was signal-killed (memory pressure), don't re-attempt
+ # this session — the memory-heavy venv+pip just gets killed again, burning
+ # the user's resources. Retry at most once per cooldown window. Reached
+ # only after all no-op probes, so a machine that later gets the SDK via
+ # system/venv/target still short-circuits above.
+ if _cooldown_remaining(state_dir) > 0:
+ return SKIP_COOLDOWN, "", ""
+
err_phase = ""
err_kind = ""
we_own_sentinel = False
@@ -134,14 +547,25 @@ def main() -> tuple[int, str, str]:
# --prefer-binary tells pip to pick it. Cross-platform safe: no-op
# on platforms where the latest version already has a wheel.
err_phase = "pip"
+ # --no-cache-dir trims pip's peak memory (no cache read/write/unpack
+ # buffering) — helps marginal low-memory machines get under the OOM
+ # threshold that kills the dominant Linux builds (CCR repro).
subprocess.run(
[str(venv_py), "-m", "pip", "install", "--quiet",
- "--disable-pip-version-check", "--prefer-binary",
+ "--disable-pip-version-check", "--prefer-binary", "--no-cache-dir",
"claude-agent-sdk"],
capture_output=True, timeout=120, check=True,
)
return BUILT, "", ""
except subprocess.CalledProcessError as e:
+ # Signal kill (OOM-killer SIGKILL / RLIMIT_AS SIGSEGV) — rc<0, empty
+ # streams. The dominant Linux failure. Record the rc, start a cooldown
+ # so we stop retry-storming a build that keeps getting killed, and
+ # skip the stderr categorization (there's nothing in stderr). err_phase
+ # says whether it died creating the venv or installing via pip.
+ if _is_signal_kill(e.returncode):
+ _write_cooldown(state_dir)
+ return BUILD_FAILED, err_phase, f"signal_killed:{e.returncode}"
# Capture a stderr fingerprint so telemetry can split BUILD_FAILED by
# root cause (no-network, package-not-found, dns-fail, etc.).
# Categorize first, then keep a short raw tail for the long tail of
@@ -152,7 +576,34 @@ def main() -> tuple[int, str, str]:
else:
stderr_str = str(stderr_b)
s = stderr_str.lower()
- if "no matching distribution" in s or "could not find a version" in s:
+ # Venv-specific patterns checked FIRST — they overlap with some pip
+ # patterns (e.g. "no module named ensurepip" could match no_pip OR
+ # venv_ensurepip_fail; the venv-stage interpretation is the right
+ # one when err_phase=="venv"). Order is venv-most-specific →
+ # pip-historical → generic.
+ if err_phase == "venv" and (
+ "ensurepip is not available" in s
+ or ("ensurepip" in s and "returned non-zero" in s)
+ or "the virtual environment was not created" in s and "ensurepip" in s
+ ):
+ err_kind = "venv_ensurepip_fail"
+ elif err_phase == "venv" and (
+ "[errno 36]" in s
+ or "file name too long" in s
+ or "path too long" in s
+ ):
+ err_kind = "venv_path_too_long"
+ elif err_phase == "venv" and (
+ "no module named venv" in s
+ or "no module named 'venv'" in s
+ ):
+ err_kind = "venv_no_module"
+ elif err_phase == "venv" and (
+ "[errno 17]" in s
+ or ("file exists" in s and "venv" in s)
+ ):
+ err_kind = "venv_already_exists"
+ elif "no matching distribution" in s or "could not find a version" in s:
err_kind = "pip_no_match"
elif "name or service not known" in s or "name resolution" in s \
or "nodename nor servname" in s or "temporary failure in name" in s:
@@ -171,6 +622,15 @@ def main() -> tuple[int, str, str]:
err_kind = "proxy_auth"
elif "timeout" in s or "timed out" in s:
err_kind = "stderr_timeout"
+ elif err_phase == "venv" and (
+ "virtual environment was not created" in s
+ or "error: command" in s and "venv" in s
+ ):
+ # Generic venv-setup catch-all — matched AFTER the more specific
+ # venv patterns above so we don't shadow them, but BEFORE the
+ # other: fallback so generic venv setup failures get their own
+ # bucket instead of polluting the long-tail signature space.
+ err_kind = "venv_setup_failed"
else:
# First 60 chars of the last non-empty stderr line — bounded to
# stay inside CC's metric value-length budget. Real failure modes
@@ -180,10 +640,27 @@ def main() -> tuple[int, str, str]:
"",
)[:60]
err_kind = f"other:{tail}" if tail else "other"
+ # venv couldn't bootstrap pip (ensurepip missing) but pip itself may
+ # work — fall back to a flat `pip install --target`. Only this one
+ # category falls through; every other venv/pip failure is terminal.
+ # The finally block unlinks our sentinel first (so the target build
+ # isn't blocked by it); _build_via_target does the target install.
+ if err_kind == "venv_ensurepip_fail":
+ if we_own_sentinel:
+ sentinel.unlink(missing_ok=True)
+ we_own_sentinel = False
+ return _build_via_target(state_dir)
return BUILD_FAILED, err_phase, err_kind
except subprocess.TimeoutExpired:
return BUILD_FAILED, err_phase, "subprocess_timeout"
except Exception as e:
+ # Embed errno for OSError-family exceptions ("exc:OSError:28") so
+ # telemetry can decode the OS-level cause (ENOENT/EACCES/ENOSPC/…),
+ # not just the Python class. #2154 follow-up: this is the dominant
+ # remaining venv BUILD_FAILED bucket. See _encode_exc_kind/_encode_errno.
+ errno = getattr(e, "errno", None)
+ if isinstance(errno, int):
+ return BUILD_FAILED, err_phase, f"exc:{type(e).__name__}:{errno}"
return BUILD_FAILED, err_phase, f"exc:{type(e).__name__}"
finally:
# Only remove the sentinel if THIS process created it. The
@@ -195,6 +672,53 @@ def main() -> tuple[int, str, str]:
sentinel.unlink(missing_ok=True)
+def _maybe_emit_user_notice(outcome: int, pv: int) -> str | None:
+ """Return a one-time user-visible notice when the agentic reviewer is
+ in a persistent broken state on this machine, or None if we've already
+ shown the notice for this plugin version (or shouldn't show one).
+
+ The marker file is plugin-version-keyed: a future plugin update can
+ re-notify if behavior changes (e.g. we ship out-of-process SDK in v3
+ and want to tell affected users it's fixed). Failures to write the
+ marker degrade to "skip the notice this session" so we don't spam
+ every SessionStart on a read-only home dir.
+
+ Currently only HOOK_PY_INCOMPATIBLE qualifies. BUILD_FAILED is
+ intentionally excluded — it covers transient causes (network failure,
+ pip registry hiccup, in-flight rebuild) where the next session may
+ succeed and a permanent notice would mislead.
+ """
+ if outcome != HOOK_PY_INCOMPATIBLE:
+ return None
+ try:
+ state_dir = Path(_resolve_state_dir())
+ marker = state_dir / f".agentic_unavailable_notice_v{pv or 0}"
+ if marker.exists():
+ return None
+ state_dir.mkdir(parents=True, exist_ok=True)
+ # Write timestamp + Python version so the marker is self-documenting
+ # if a user goes looking. O_EXCL would be racier with no real win
+ # (two concurrent SessionStarts both showing the notice once is fine).
+ marker.write_text(
+ f"{time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())} "
+ f"py={sys.version_info[0]}.{sys.version_info[1]}\n"
+ )
+ except OSError:
+ return None
+ return (
+ f"⚠ security-guidance plugin: the cross-file commit reviewer "
+ f"(layer 3 of 3 — catches IDOR, auth-bypass, cross-file SSRF) "
+ f"is unavailable in this environment. It requires Python ≥3.10, "
+ f"but the hook is running on "
+ f"{sys.version_info[0]}.{sys.version_info[1]}.\n\n"
+ f"Pattern checks and the single-shot LLM diff review are still "
+ f"active. To enable the deeper reviewer, install Python 3.10+ "
+ f"(e.g. `brew install python` on macOS) and restart Claude Code.\n\n"
+ f"This notice is shown once per plugin version. "
+ f"See: github.com/anthropics/claude-plugins-official/issues/2071"
+ )
+
+
if __name__ == "__main__":
# Tell the harness this is async — venv create + pip install can take
# 30-60s on a cold cache, well past the default sync hook timeout.
@@ -213,22 +737,78 @@ if __name__ == "__main__":
# and takes the FIRST non-{"async":...} JSON line as the hook response;
# its `metrics` key is forwarded to the hook metrics event on the
# next attachments pass. Must be a single line — the registry splits on
- # \n and json-parses each independently. Values must be bool|number OR
- # short strings (CC accepts string metric values if they're not
- # null). Stay inside the 10-key emit cap.
+ # \n and json-parses each independently.
+ #
+ # IMPORTANT — values must be bool|finite-number. The validation comment
+ # has historically said "or short strings" but that was wrong: CC's
+ # plugin-metrics pipeline silently drops plugin-emitted string values.
+ # Stay inside the 10-key emit cap.
metrics: dict[str, object] = {
"sdk_bootstrap": outcome,
"sdk_bootstrap_ms": round((time.perf_counter() - t0) * 1000),
}
if err_kind:
- # Truncate defensively; categorized values are <40 chars but the
- # `other:<tail>` mode could be longer. err_phase may be empty for
- # pre-venv failures (state_dir.mkdir perm-denied, sentinel O_EXCL
- # raising a non-FileExistsError OSError) — emit as "pre" so the
- # err_kind isn't silently dropped.
- metrics["sdk_bootstrap_phase"] = (err_phase or "pre")[:16]
- metrics["sdk_bootstrap_err"] = err_kind[:96]
+ # Encode phase + err_kind as integer codes (see
+ # SDK_BOOTSTRAP_PHASE_CODES / SDK_BOOTSTRAP_ERR_CODES). Earlier
+ # versions emitted these as strings and CC dropped them — restoring
+ # the diagnostic split that 28K BUILD_FAILED/day need to triage by
+ # root cause. err_phase defaults to "pre" when empty (pre-venv
+ # failure path, e.g. state_dir.mkdir perm-denied).
+ metrics["sdk_bootstrap_phase"] = _encode_phase(err_phase or "pre")
+ metrics["sdk_bootstrap_err"] = _encode_err_kind(err_kind)
+ # For "other:<tail>" (encoded err==99), emit a bounded integer
+ # hash of the stderr tail so BQ can distinguish patterns inside
+ # the _uncategorized bucket without unbounded cardinality. Zero
+ # when err_kind is categorized — the schema reader treats 0 as
+ # "no signal", matching the absence convention.
+ sig = _encode_stderr_sig(err_kind)
+ if sig:
+ metrics["sdk_bootstrap_stderr_sig"] = sig
+ # Exception-type + errno for the "exc:" bucket (the dominant
+ # remaining venv BUILD_FAILED mode per #2154 telemetry). Both
+ # auto-omit (0) on stderr/categorized failures.
+ exc = _encode_exc_kind(err_kind)
+ if exc:
+ metrics["sdk_bootstrap_exc"] = exc
+ exc_errno = _encode_errno(err_kind)
+ if exc_errno:
+ metrics["sdk_bootstrap_errno"] = exc_errno
+ # Subprocess returncode for signal kills (-9 OOM-killer / -11
+ # RLIMIT_AS / -6 abort). Confirms in prod which signal dominates the
+ # Linux memory-kill bucket. 0 (omitted) for non-signal failures.
+ rc = _encode_rc(err_kind)
+ if rc:
+ metrics["sdk_bootstrap_rc"] = rc
+ # venv_ensurepip_fail (code 11) is the top categorizable venv
+ # failure, and telemetry shows it's NOT just Debian — macOS has the
+ # most distinct affected users. Probe whether this interpreter has
+ # pip so we know if a `pip install --target` fallback (Option A)
+ # would actually help, vs the user needing a system package. Probed
+ # only here (not on the happy path) to avoid an extra subprocess
+ # per healthy session.
+ if _encode_err_kind(err_kind) == 11:
+ metrics["sdk_has_pip"] = _probe_has_pip()
+ # Interpreter version (major*100 + minor, e.g. 309 / 312), emitted on
+ # every bootstrap. Disambiguates the macOS cohort (Apple 3.9 vs a 3.10+
+ # with broken ensurepip) for both venv_ensurepip_fail AND
+ # HOOK_PY_INCOMPATIBLE (whose "py_3.9" err_kind otherwise collapses to
+ # err=99, losing the version). Cheap — no subprocess, just sys.version_info.
+ metrics["sdk_hook_py"] = sys.version_info[0] * 100 + sys.version_info[1]
pv = _plugin_version_int()
if pv:
metrics["pv"] = pv
- print(json.dumps({"metrics": metrics}), flush=True)
+ response: dict[str, object] = {"metrics": metrics}
+ # One-time user-visible notice when the agentic reviewer is dead on
+ # arrival. Uses hookSpecificOutput.additionalContext (SessionStart's
+ # supported channel for surfacing text to both the model and the user)
+ # plus systemMessage as a belt-and-suspenders. Marker-file-gated so
+ # this fires exactly once per plugin version per install — see
+ # _maybe_emit_user_notice.
+ notice = _maybe_emit_user_notice(outcome, pv)
+ if notice:
+ response["hookSpecificOutput"] = {
+ "hookEventName": "SessionStart",
+ "additionalContext": notice,
+ }
+ response["systemMessage"] = notice
+ print(json.dumps(response), flush=True)
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index 1a549d76..4d771b42 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -26,18 +26,34 @@ GIT_CMD = [
"git",
"-c", "core.fsmonitor=false",
"-c", "core.hooksPath=/dev/null",
+ # core.quotePath=false: emit raw UTF-8 in path-emitting commands instead
+ # of C-quoting non-ASCII bytes (default `"\\303\\201vila/..."` vs
+ # `Ávila/...`). Downstream parsers — both ours (parse_diff_into_files,
+ # extract_file_paths_from_diff) and Python stdlib (os.path.isabs,
+ # os.path.join) — expect raw paths and silently drop / mishandle the
+ # quoted form. Adding the flag globally to GIT_CMD covers every
+ # subprocess.run site that uses the splat — diff feeders, rev-parse
+ # path queries (--show-toplevel, --git-dir, --git-common-dir),
+ # reflog %gs subjects, ls-files, status, etc. — without per-site
+ # flag duplication. See #2082, #2099.
+ "-c", "core.quotePath=false",
]
def _git_rev_parse_head(cwd):
"""Return the current HEAD SHA, or None if not a git repo / no commits."""
try:
+ # See #2099: text=True on Windows cp1252 crashes the reader thread on
+ # any UTF-8 byte undefined in cp1252 (e.g. via a git error message
+ # referencing a non-ASCII filename in stderr). stdout is a SHA so it
+ # IS safe; stderr is not. capture_output=True with bytes-by-default
+ # never decodes, so the reader thread can't crash.
result = subprocess.run(
[*GIT_CMD, "rev-parse", "HEAD"],
- cwd=cwd, capture_output=True, text=True, timeout=5
+ cwd=cwd, capture_output=True, timeout=5
)
if result.returncode == 0 and result.stdout.strip():
- return result.stdout.strip()
+ return result.stdout.decode("utf-8", errors="replace").strip()
return None
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
return None
@@ -52,13 +68,17 @@ def _find_git_index(cwd):
Returns the absolute path to the index file, or None.
"""
try:
+ # See #2099: stdout here is a PATH which can contain non-ASCII bytes
+ # (e.g. C:\אבטחה\repo\.git). text=True decodes via cp1252 strict on
+ # Windows → crashes the reader thread → returns stdout=None →
+ # caller does .strip() on None → AttributeError. Decode manually.
result = subprocess.run(
[*GIT_CMD, "rev-parse", "--git-dir"],
- cwd=cwd, capture_output=True, text=True, timeout=5
+ cwd=cwd, capture_output=True, timeout=5
)
if result.returncode != 0:
return None
- git_dir = result.stdout.strip()
+ git_dir = result.stdout.decode("utf-8", errors="replace").strip()
if not os.path.isabs(git_dir):
git_dir = os.path.join(cwd, git_dir)
index_path = os.path.join(git_dir, "index")
@@ -128,9 +148,13 @@ def _temp_index(cwd, untracked_paths=None):
else:
add_args = None
if add_args:
+ # No stdout used here (only returncode matters), but text=True
+ # still spawns reader threads that decode stderr — git error
+ # messages can reference non-ASCII filenames and crash on
+ # cp1252. See #2099. Drop text=True so bytes stay raw.
subprocess.run(
[*GIT_CMD, "add", "--intent-to-add"] + add_args,
- cwd=cwd, capture_output=True, text=True, timeout=10,
+ cwd=cwd, capture_output=True, timeout=10,
env=env,
)
yield env
@@ -144,11 +168,17 @@ def _temp_index(cwd, untracked_paths=None):
def _git_toplevel(cwd):
"""Absolute repo root for `cwd`, or None if not in a work tree."""
try:
+ # See #2099: stdout is a PATH — `C:\אבטחה\repo` returned as UTF-8
+ # bytes by git. text=True would decode via cp1252 strict on Windows
+ # → reader-thread crash. Decode manually with errors="replace".
r = subprocess.run(
[*GIT_CMD, "rev-parse", "--show-toplevel"],
- cwd=cwd, capture_output=True, text=True, timeout=5,
+ cwd=cwd, capture_output=True, timeout=5,
)
- return r.stdout.strip() if r.returncode == 0 and r.stdout.strip() else None
+ if r.returncode != 0:
+ return None
+ path = r.stdout.decode("utf-8", errors="replace").strip()
+ return path if path else None
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
return None
@@ -164,13 +194,15 @@ def _git_dir(repo_root):
callers can degrade (push-sweep state is best-effort).
"""
try:
+ # See #2099: stdout is a PATH (shared gitdir), may be non-ASCII.
+ # Decode bytes manually to avoid cp1252 reader-thread crash.
r = subprocess.run(
[*GIT_CMD, "rev-parse", "--git-common-dir"],
- cwd=repo_root, capture_output=True, text=True, timeout=5,
+ cwd=repo_root, capture_output=True, timeout=5,
)
if r.returncode != 0:
return None
- d = r.stdout.strip()
+ d = r.stdout.decode("utf-8", errors="replace").strip()
return d if os.path.isabs(d) else os.path.join(repo_root, d)
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
return None
@@ -179,13 +211,15 @@ def _git_dir(repo_root):
def _git_rev_list_range(repo_root, base, head="HEAD"):
"""Shas in `base..head`, oldest→newest. Empty list on error."""
try:
+ # See #2099: stdout is ASCII SHAs, but stderr can carry git error
+ # messages referencing non-ASCII filenames — keep bytes raw.
r = subprocess.run(
[*GIT_CMD, "rev-list", "--reverse", f"{base}..{head}"],
- cwd=repo_root, capture_output=True, text=True, timeout=10,
+ cwd=repo_root, capture_output=True, timeout=10,
)
if r.returncode != 0:
return []
- return [s for s in r.stdout.strip().split("\n") if s]
+ return [s for s in r.stdout.decode("utf-8", errors="replace").strip().split("\n") if s]
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
return []
@@ -199,6 +233,10 @@ def _git_diff_range(repo_root, base, head="HEAD"):
them reviewed — otherwise unreviewed commits get permanently silenced.
"""
try:
+ # GIT_CMD globally passes core.quotePath=false (see definition) so
+ # non-ASCII paths in `diff --git a/... b/...` headers come through as
+ # 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],
cwd=repo_root, capture_output=True, timeout=30,
@@ -213,9 +251,11 @@ def _git_diff_range(repo_root, base, head="HEAD"):
def _detect_main_branch(repo_root):
for ref in ("origin/HEAD", "origin/main", "origin/master", "main", "master"):
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 ref
@@ -259,19 +299,29 @@ def _git_reflog_recent_commits(repo_root, max_age_s=120, max_n=5):
# %gs (the reflog subject) is `commit: <commit-msg first line>` and can
# contain `|`; put it LAST so split("|", 2) leaves it intact. %H is
# hex and %ct is integer, so the first two fields are delimiter-safe.
+ #
+ # Bytes + decode utf-8/replace: %gs embeds commit-message subjects
+ # which git stores as raw bytes — commits can be authored in
+ # latin-1 / cp1252 / shift-jis etc., and text=True would raise
+ # UnicodeDecodeError in the subprocess reader thread on Windows
+ # cp1252 (subprocess.run returns r.stdout=None, then
+ # r.stdout.splitlines() AttributeErrors). Mirrors the existing
+ # migration at security_reminder_hook.py:540 — same pattern was
+ # missed here. See anthropics/claude-plugins-official#2056.
r = subprocess.run(
[*GIT_CMD, "log", "-g", "-n", str(max_n),
"--format=%H|%ct|%gs", "HEAD"],
- cwd=repo_root, capture_output=True, text=True, timeout=5,
+ cwd=repo_root, capture_output=True, timeout=5,
)
- except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError):
return [], 0
if r.returncode != 0:
return [], 0
+ stdout = (r.stdout or b"").decode("utf-8", errors="replace")
import time as _time
now = int(_time.time())
fresh, stale = [], 0
- for idx, line in enumerate(r.stdout.splitlines()):
+ for idx, line in enumerate(stdout.splitlines()):
parts = line.split("|", 2)
if len(parts) != 3:
continue
@@ -306,23 +356,32 @@ def _git_name_only(cwd, base, include_untracked=False):
must distinguish None (error → don't trust as a filter) from set()
(genuinely nothing changed). `-c core.quotePath=false -z` keeps non-ASCII
and space-containing paths intact."""
+ # Decode stdout/stderr as UTF-8 with errors="replace" instead of using
+ # text=True. core.quotePath=false makes git emit raw UTF-8 for non-ASCII
+ # paths, and text=True on Windows decodes via cp1252 strict — a non-ASCII
+ # changed path would crash the subprocess reader thread, leave
+ # result.stdout=None, and propagate AttributeError out of the helper.
+ # Same fix shape as diffstate._list_untracked. See #2056.
def _run(env):
+ # core.quotePath=false comes from GIT_CMD globally (see definition).
result = subprocess.run(
- [*GIT_CMD, "-c", "core.quotePath=false", "diff", "--name-only", "-z", base],
- cwd=cwd, capture_output=True, text=True, timeout=30,
+ [*GIT_CMD, "diff", "--name-only", "-z", base],
+ cwd=cwd, capture_output=True, timeout=30,
env=env,
)
if result.returncode != 0:
- debug_log(f"_git_name_only({base!r}) rc={result.returncode}: {result.stderr[:200]}")
+ stderr_str = (result.stderr or b"").decode("utf-8", errors="replace")
+ debug_log(f"_git_name_only({base!r}) rc={result.returncode}: {stderr_str[:200]}")
return None
- return {p for p in result.stdout.split("\0") if p}
+ stdout = (result.stdout or b"").decode("utf-8", errors="replace")
+ return {p for p in stdout.split("\0") if p}
try:
if not include_untracked:
return _run(None)
with _temp_index(cwd) as env:
return _run(env)
- except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
debug_log(f"_git_name_only({base!r}) error: {e}")
return None
@@ -339,17 +398,22 @@ def _git_status_porcelain(cwd):
collapses to `dir/`). Required so the untracked set subtracts cleanly
against the UPS-time `_list_untracked` snapshot, which uses ls-files and
therefore always lists individual files."""
+ # Lenient decode: same UTF-8 + errors="replace" pattern as the
+ # sibling helpers — a non-ASCII path in the worktree would otherwise
+ # crash the cp1252 reader thread on Windows. See #2056.
try:
+ # core.quotePath=false comes from GIT_CMD globally (see definition).
r = subprocess.run(
- [*GIT_CMD, "-c", "core.quotePath=false", "status",
- "--porcelain=v1", "-uall", "-z"],
- cwd=cwd, capture_output=True, text=True, timeout=30,
+ [*GIT_CMD, "status", "--porcelain=v1", "-uall", "-z"],
+ cwd=cwd, capture_output=True, timeout=30,
)
if r.returncode != 0:
- debug_log(f"_git_status_porcelain rc={r.returncode}: {r.stderr[:200]}")
+ stderr_str = (r.stderr or b"").decode("utf-8", errors="replace")
+ debug_log(f"_git_status_porcelain rc={r.returncode}: {stderr_str[:200]}")
return None, None
tracked, untracked = set(), set()
- entries = r.stdout.split("\0")
+ stdout = (r.stdout or b"").decode("utf-8", errors="replace")
+ entries = stdout.split("\0")
i = 0
while i < len(entries):
e = entries[i]
@@ -368,7 +432,9 @@ def _git_status_porcelain(cwd):
i += 1
i += 1
return tracked, untracked
- except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
+ # ValueError guards against any future strict-decode regression
+ # so the helper degrades to (None, None) instead of crashing.
debug_log(f"_git_status_porcelain error: {e}")
return None, None
@@ -378,9 +444,12 @@ def _is_ancestor(cwd, maybe_ancestor, descendant):
"""True if `maybe_ancestor` is reachable from `descendant` (i.e. HEAD
moved forward via commit/merge, not sideways via checkout)."""
try:
+ # See #2099: only returncode matters, but text=True spawns reader
+ # threads that decode stderr — git error messages can carry non-ASCII
+ # filenames. Drop text=True to keep bytes raw, avoid cp1252 crash.
result = subprocess.run(
[*GIT_CMD, "merge-base", "--is-ancestor", maybe_ancestor, descendant],
- cwd=cwd, capture_output=True, text=True, timeout=5,
+ cwd=cwd, capture_output=True, timeout=5,
)
return result.returncode == 0
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
@@ -411,6 +480,7 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa
# change exists to fix.
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
try:
with _temp_index(cwd, untracked_paths) as env:
diff --git a/plugins/security-guidance/hooks/hooks.json b/plugins/security-guidance/hooks/hooks.json
index 0d29c5ac..39dbac57 100644
--- a/plugins/security-guidance/hooks/hooks.json
+++ b/plugins/security-guidance/hooks/hooks.json
@@ -49,6 +49,30 @@
"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"
}
],
"matcher": "Bash"
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index bd47aa43..8b7feef8 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -27,7 +27,7 @@ from typing import Optional, Tuple, Dict, Any, List
import extensibility
import review_api
-from _base import debug_log, _record_usage, _PV, PROVENANCE_TAG # noqa: F401
+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
@@ -55,6 +55,12 @@ def _inject_agent_sdk_venv_into_syspath(state_dir):
candidates = (
glob.glob(os.path.join(venv_root, "lib", "python*", "site-packages"))
+ glob.glob(os.path.join(venv_root, "Lib", "site-packages"))
+ # `pip install --target` fallback (ensure_agent_sdk BUILT_TARGET, used
+ # when venv can't bootstrap pip): a FLAT layout — packages sit directly
+ # in agent-sdk-libs/, not under a site-packages subdir. See #2154
+ # follow-up. The pywin32 .pth bootstrap below applies here too (target
+ # installs don't process .pth at runtime, same as a manual venv insert).
+ + [os.path.join(state_dir, "agent-sdk-libs")]
)
added = False
for sp in candidates:
@@ -355,10 +361,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None)
# Try the venv ensure_agent_sdk.py builds. Same fallback logic as
# agentic_review() — duplicated here so the 3P path doesn't require
# the agentic path to have run first.
- _state_dir = os.environ.get(
- "SECURITY_WARNINGS_STATE_DIR",
- os.path.expanduser("~/.claude/security"),
- )
+ _state_dir = _resolve_state_dir()
_inject_agent_sdk_venv_into_syspath(_state_dir)
try:
import asyncio as _asyncio # noqa: F811
@@ -371,6 +374,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None)
except Exception as e:
debug_log(f"3P sdk-single-turn: SDK unavailable ({e})")
_last_call_claude_http_error = -1
+ _record_http_error(-1)
return None
cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") or None
@@ -428,6 +432,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None)
except _asyncio.TimeoutError:
debug_log("3P sdk-single-turn: timeout after 60s")
_last_call_claude_http_error = -1
+ _record_http_error(-1)
return None
except Exception as e:
debug_log(f"3P sdk-single-turn: query failed ({e})")
@@ -436,6 +441,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None)
for _l in _captured_stderr[:20]:
debug_log(f" | {_l.rstrip()}")
_last_call_claude_http_error = -1
+ _record_http_error(-1)
return None
@@ -482,10 +488,21 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000,
"max_tokens": max_tokens,
"system": CLAUDE_CODE_SYSTEM_PROMPT,
"messages": [{"role": "user", "content": prompt}],
- "output_format": {
- "type": "json_schema",
- "schema": output_schema
- }
+ # API moved the structured-output schema from top-level `output_format`
+ # to `output_config.format` per
+ # https://platform.claude.com/docs/en/build-with-claude/structured-outputs.
+ # The old form "continues to work for a transition period" for some
+ # auth modes (API key + non-streaming), but is rejected with
+ # `invalid_request_error: output_format: This field is deprecated.
+ # Use 'output_config.format' instead.` for others (OAuth Bearer +
+ # newer CLI versions hit it consistently — reporter saw 462 errors
+ # in one day). See #2098.
+ "output_config": {
+ "format": {
+ "type": "json_schema",
+ "schema": output_schema,
+ },
+ },
}
if thinking_budget > 0:
# Models trained on adaptive thinking (4.6+) reject the budget_tokens
@@ -493,7 +510,10 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000,
# models (4.5 and earlier, all 3.x) reject adaptive. Pick by model.
if _model_supports_adaptive_thinking(payload["model"]):
payload["thinking"] = {"type": "adaptive"}
- payload["output_config"] = {"effort": "high"}
+ # Merge `effort` into the existing output_config dict (which
+ # now carries the `format` schema) rather than reassigning —
+ # otherwise the schema is silently overwritten. See #2098.
+ payload["output_config"]["effort"] = "high"
else:
payload["thinking"] = {
"type": "enabled",
@@ -531,6 +551,7 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000,
error_body = e.read().decode("utf-8") if e.fp else ""
debug_log(f"API error: {e.code} - {error_body[:200]}")
_last_call_claude_http_error = e.code
+ _record_http_error(e.code)
return None
except (urllib.error.URLError, TimeoutError) as e:
if attempt < 2:
@@ -540,6 +561,7 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000,
else:
debug_log(f"Request failed after retries: {e}")
_last_call_claude_http_error = -1
+ _record_http_error(-1)
return None
if not response_data:
@@ -548,6 +570,7 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000,
# call uses the token; record the 401 so callers don't see error=None.
if _last_call_claude_http_error is None:
_last_call_claude_http_error = 401
+ _record_http_error(401)
return None
# Find the text block (skip thinking blocks)
@@ -1145,10 +1168,7 @@ def agentic_review(
# ~/.claude/security/ with the SDK installed; try that as a fallback
# before giving up. The system import is attempted first so users
# who DO have it never touch the venv.
- _state_dir = os.environ.get(
- "SECURITY_WARNINGS_STATE_DIR",
- os.path.expanduser("~/.claude/security"),
- )
+ _state_dir = _resolve_state_dir()
_venv_tried = _inject_agent_sdk_venv_into_syspath(_state_dir)
try:
import asyncio as _asyncio # noqa: F811
diff --git a/plugins/security-guidance/hooks/patterns.py b/plugins/security-guidance/hooks/patterns.py
index b7f6f10a..8e749cad 100644
--- a/plugins/security-guidance/hooks/patterns.py
+++ b/plugins/security-guidance/hooks/patterns.py
@@ -94,6 +94,9 @@ Only use exec() if you absolutely need shell features and the input is guarantee
},
{
"ruleName": "new_function_injection",
+ # JS-only construct: gate to JS/TS files so docs/.md and other prose
+ # mentioning "new Function" don't trip the warning.
+ "path_filter": lambda p: p.endswith(_JS_EXTS),
"substrings": ["new Function"],
"reminder": "\u26a0\ufe0f Security Warning: Using new Function() with string interpolation is a CODE INJECTION vulnerability. If any variable is concatenated or interpolated into the function body string, an attacker controlling that variable can execute arbitrary code. Use safe alternatives: for property access use obj[key] or array.reduce((o, k) => o[k], root); for computation use a safe expression parser. NEVER interpolate untrusted strings into new Function() bodies.",
},
@@ -107,16 +110,24 @@ Only use exec() if you absolutely need shell features and the input is guarantee
},
{
"ruleName": "react_dangerously_set_html",
+ # JS/TS-only (React); gate so .md docs / .py / .go files don't trip.
+ "path_filter": lambda p: p.endswith(_JS_EXTS),
"substrings": ["dangerouslySetInnerHTML"],
"reminder": "⚠️ Security Warning: dangerouslySetInnerHTML can lead to XSS vulnerabilities if used with untrusted content. Ensure all content is properly sanitized using an HTML sanitizer library like DOMPurify, or use safe alternatives.",
},
{
"ruleName": "document_write_xss",
+ # Browser DOM API: only meaningful in JS/TS source.
+ "path_filter": lambda p: p.endswith(_JS_EXTS),
"substrings": ["document.write"],
"reminder": "⚠️ Security Warning: document.write() can be exploited for XSS attacks and has performance issues. Use DOM manipulation methods like createElement() and appendChild() instead.",
},
{
"ruleName": "innerHTML_xss",
+ # Browser DOM API: only meaningful in JS/TS source. Closes FPs like
+ # docs/example HTML, playground/self-contained skills that hardcode
+ # innerHTML strings with zero user input (#410).
+ "path_filter": lambda p: p.endswith(_JS_EXTS),
"substrings": [".innerHTML =", ".innerHTML="],
"reminder": "⚠️ Security Warning: Setting innerHTML with untrusted content can lead to XSS vulnerabilities. Use textContent for plain text or safe DOM methods for HTML content. If you need HTML support, consider using an HTML sanitizer library such as DOMPurify.",
},
@@ -217,11 +228,15 @@ Additionally, validate user inputs:
},
{
"ruleName": "outerHTML_xss",
+ # Browser DOM API: only meaningful in JS/TS source.
+ "path_filter": lambda p: p.endswith(_JS_EXTS),
"substrings": [".outerHTML =", ".outerHTML="],
"reminder": "⚠️ Security Warning: Use textContent or sanitize with DOMPurify. outerHTML assignment is an XSS sink equivalent to innerHTML.",
},
{
"ruleName": "insertAdjacentHTML_xss",
+ # Browser DOM API: only meaningful in JS/TS source.
+ "path_filter": lambda p: p.endswith(_JS_EXTS),
"substrings": [".insertAdjacentHTML("],
"reminder": "⚠️ Security Warning: Use insertAdjacentText() or sanitize with DOMPurify. insertAdjacentHTML is an XSS sink.",
},
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.
diff --git a/plugins/security-guidance/hooks/session_state.py b/plugins/security-guidance/hooks/session_state.py
index 4ccd15e8..8dbadfd2 100644
--- a/plugins/security-guidance/hooks/session_state.py
+++ b/plugins/security-guidance/hooks/session_state.py
@@ -19,7 +19,7 @@ import os
import re
from datetime import datetime
-from _base import debug_log
+from _base import debug_log, state_dir as _state_dir
def _state_key(session_id):
@@ -36,20 +36,20 @@ def _state_key(session_id):
def get_state_file(session_id):
"""Get session-specific state file path."""
- state_dir = os.environ.get("SECURITY_WARNINGS_STATE_DIR", os.path.expanduser("~/.claude/security"))
+ state_dir = _state_dir()
return os.path.join(state_dir, f"security_warnings_state_{_state_key(session_id)}.json")
def get_lock_file(session_id):
"""Get session-specific lock file path."""
- state_dir = os.environ.get("SECURITY_WARNINGS_STATE_DIR", os.path.expanduser("~/.claude/security"))
+ state_dir = _state_dir()
return os.path.join(state_dir, f"security_warnings_state_{_state_key(session_id)}.lock")
def cleanup_old_state_files():
"""Remove state files and lock files older than 30 days."""
try:
- state_dir = os.environ.get("SECURITY_WARNINGS_STATE_DIR", os.path.expanduser("~/.claude/security"))
+ state_dir = _state_dir()
if not os.path.exists(state_dir):
return
diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh
index e6ac7a80..9cf8cc07 100755
--- a/plugins/security-guidance/hooks/sg-python.sh
+++ b/plugins/security-guidance/hooks/sg-python.sh
@@ -22,6 +22,17 @@
# "${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py"
set -e
+# Force UTF-8 for ALL Python filesystem + IO operations (PEP 540).
+# Without this, Windows Python defaults `locale.getpreferredencoding()` to
+# cp1252 — which makes `text=True` in subprocess.run / open() / json.load
+# crash the internal reader thread on any byte that's undefined in cp1252
+# (e.g. the 0x81 byte from ف, present in any path/filename with
+# Arabic/Hebrew/CJK characters). See #2056, #2099.
+#
+# No-op on macOS/Linux (already UTF-8). Must be set BEFORE Python starts —
+# changing it from inside the interpreter has no effect.
+export PYTHONUTF8=1
+
# Git Bash / MSYS on Windows hands script paths to this shim in POSIX form
# (`/c/Users/...`). When we exec a Windows `python.exe` (which we do on
# Windows since `python3` is the Microsoft Store stub), python interprets the
@@ -47,21 +58,65 @@ fi
probe() {
# $1..N: the interpreter command (may be multi-word like `py -3`)
- # Probe writes the major version to stdout and exits 0 iff it's >=3.
- "$@" -c 'import sys; print(sys.version_info[0])' 2>/dev/null
+ # Writes "<major>.<minor>" to stdout and exits 0 iff at least Python 3.
+ "$@" -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")' 2>/dev/null
+}
+
+# True iff arg is a "M.m" version string >= 3.10. claude_agent_sdk requires
+# Python >= 3.10; below that, pip install fails ("No matching distribution")
+# and the LLM-powered review (Stop / commit / push) silently no-ops while
+# pattern checks (PostToolUse regex) keep working. macOS ships 3.9.6 as the
+# default `python3` on current versions, so this guard matters in practice.
+# See anthropics/claude-plugins-official#2071.
+is_sdk_compatible() {
+ case "$1" in
+ 3.1[0-9]|3.[2-9][0-9]|[4-9].*|[1-9][0-9].*) return 0 ;;
+ *) return 1 ;;
+ esac
}
+# Pass 1 — try minor-versioned binaries in descending order. These are only
+# present if the user explicitly installed them (Homebrew / python.org / pyenv),
+# so picking one here always upgrades over the system `python3`. Highest
+# available wins; the user doesn't have to PATH-prefer it.
+for cmd in "python3.13" "python3.12" "python3.11" "python3.10"; do
+ v=$(probe "$cmd") || continue
+ if is_sdk_compatible "$v"; then
+ exec "$cmd" "$@"
+ fi
+done
+
+# Pass 2 — bare interpreters, but only if SDK-compatible. Covers Linux distros
+# that ship 3.10+ as the default `python3`, and Windows where `python` /
+# `py -3` resolves to the user's python.org install.
for cmd in "python3" "python" "py -3"; do
- # Word-split intentionally so `py -3` works
# shellcheck disable=SC2086
v=$(probe $cmd) || continue
- if [ "$v" = "3" ]; then
+ if is_sdk_compatible "$v"; then
# shellcheck disable=SC2086
exec $cmd "$@"
fi
done
+# Pass 3 — fallback to any Python 3, even <3.10. Pattern-based checks
+# (PostToolUse regex on Edit/Write) only need 3.6+ and are useful on their
+# own; the SDK-dependent paths will detect the version mismatch and degrade
+# inside the Python code. Without this fallback, the entire plugin would
+# stop working on default macOS, which is a regression vs today.
+for cmd in "python3" "python" "py -3"; do
+ # shellcheck disable=SC2086
+ v=$(probe $cmd) || continue
+ # Accept anything that successfully reported a "M.m" string.
+ case "$v" in
+ [0-9]*.[0-9]*)
+ # shellcheck disable=SC2086
+ exec $cmd "$@"
+ ;;
+ esac
+done
+
echo "security-guidance: no working Python 3 interpreter found." >&2
-echo " tried: python3, python, py -3" >&2
+echo " tried: python3.13, python3.12, python3.11, python3.10, python3, python, py -3" >&2
echo " on Windows, install Python from https://python.org (NOT the Microsoft Store)" >&2
+echo " on macOS, install Python 3.10+ via Homebrew (\`brew install python\`)" >&2
exit 1