summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-10-21 00:03:52 +0000
committerClaude <noreply@anthropic.com>2026-10-21 00:03:52 +0000
commit06d5a3f8e838c81680838aec3266b0ec4c50f992 (patch)
treec6ba4f2bd3cb4b1546c8edc083e3e7dd778a67e2 /plugins
parenta00d13d77ba7bf13a9d2ae0db5f7e24aeb4b12b2 (diff)
parent5d6e714341450ba38d85c8202e6a2a15d6af5a04 (diff)
Merge branch 'main' into mhegazy/sg-index-copy-gitlinks
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/_base.py20
-rw-r--r--plugins/security-guidance/hooks/ensure_agent_sdk.py6
-rw-r--r--plugins/security-guidance/hooks/extensibility.py61
-rw-r--r--plugins/security-guidance/hooks/gitutil.py165
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py63
-rwxr-xr-xplugins/security-guidance/hooks/sg-python.sh51
-rw-r--r--plugins/security-guidance/tests/test_launcher_probe_timing.py196
-rw-r--r--plugins/security-guidance/tests/test_pattern_fired_metrics.py90
-rw-r--r--plugins/security-guidance/tests/test_patterns_file_shape.py116
-rw-r--r--plugins/security-guidance/tests/test_stop_review_paths.py319
10 files changed, 1045 insertions, 42 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py
index 59e8e569..e5959e68 100644
--- a/plugins/security-guidance/hooks/_base.py
+++ b/plugins/security-guidance/hooks/_base.py
@@ -330,6 +330,26 @@ def _log_usage(usage):
)
+def launcher_probe_metrics():
+ """How long sg-python.sh waited for interpreters to answer its probe.
+
+ Only when this launch's probes took a second or more together, so ordinary
+ rows carry no extra keys: `launcher_probe_ms` is all of them,
+ `launcher_probe_max_ms` the slowest one. Both are capped at an hour (the
+ launcher reads the wall clock, which can jump). Read once: the variables
+ are removed so child processes do not report this launch as their own.
+ """
+ try:
+ slowest = int(os.environ.pop("SG_LAUNCHER_PROBE_MAX_MS", ""))
+ total = int(os.environ.pop("SG_LAUNCHER_PROBE_MS", ""))
+ except ValueError:
+ return {}
+ if total < 1000 or slowest > total:
+ return {}
+ cap = 3_600_000
+ return {"launcher_probe_ms": min(total, cap), "launcher_probe_max_ms": min(slowest, cap)}
+
+
def _usage_metrics():
"""Snapshot the accumulator as metric keys. Returns {} when no API calls
AND no HTTP errors were made so skip-path emits don't burn key budget.
diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py
index fadeae00..d3aaf96b 100644
--- a/plugins/security-guidance/hooks/ensure_agent_sdk.py
+++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py
@@ -27,7 +27,10 @@ from pathlib import Path
# → ~/.claude/security. See _base.state_dir for resolution precedence. Re-aliased
# here to match the existing local name (state_dir was already a local var in
# main() and _maybe_emit_user_notice).
-from _base import portable_output, state_dir as _resolve_state_dir, write_hook_output
+from _base import (
+ launcher_probe_metrics, portable_output, state_dir as _resolve_state_dir,
+ write_hook_output,
+)
from _base import llm_reviews_switched_off
@@ -973,6 +976,7 @@ if __name__ == "__main__":
# not read the plugin files.
if os.environ.get("SG_LAUNCHER_FALLBACK") == "1":
metrics["launcher_fallback"] = 1
+ metrics.update(launcher_probe_metrics())
response: dict[str, object] = {"metrics": metrics}
# One-time user-visible notice when the agentic reviewer is dead on
# arrival. Uses hookSpecificOutput.additionalContext (SessionStart's
diff --git a/plugins/security-guidance/hooks/extensibility.py b/plugins/security-guidance/hooks/extensibility.py
index cb3e0a8d..ed332c99 100644
--- a/plugins/security-guidance/hooks/extensibility.py
+++ b/plugins/security-guidance/hooks/extensibility.py
@@ -175,13 +175,16 @@ def _load_user_patterns(cwd: Optional[str]) -> List[Dict[str, Any]]:
# try each supported extension.
for ext in (".yaml", ".yml", ".json"):
candidate = path + ext
- data = _read_config(candidate)
- if data is None:
+ # One unusable file is skipped on its own, so the rules from the
+ # other locations still load.
+ try:
+ found = _rules_from_file(candidate, label)
+ except Exception as e:
+ debug_log(f"extensibility: skipping {candidate}: {type(e).__name__}: {e}")
continue
- for entry in (data or {}).get("patterns", []):
- rule = _validate_pattern(entry, source=label)
- if rule:
- rules.append(rule)
+ if found is None:
+ continue
+ rules.extend(found)
break # found one extension; don't double-load .yaml AND .json
if len(rules) >= PATTERN_MAX_RULES:
break
@@ -191,8 +194,32 @@ def _load_user_patterns(cwd: Optional[str]) -> List[Dict[str, Any]]:
return rules
+def _rules_from_file(path: str, label: str) -> Optional[List[Dict[str, Any]]]:
+ """The valid rules in one config file, or None when the file is missing
+ or does not hold a mapping with a ``patterns`` list."""
+ data = _read_config(path)
+ if data is None:
+ return None
+ entries = data.get("patterns", [])
+ if entries is None:
+ entries = []
+ if not isinstance(entries, list):
+ debug_log(
+ f"extensibility: skipping {path}: 'patterns' must be a list, "
+ f"got {type(entries).__name__}"
+ )
+ return None
+ rules = []
+ for entry in entries:
+ rule = _validate_pattern(entry, source=label)
+ if rule:
+ rules.append(rule)
+ return rules
+
+
def _read_config(path: str) -> Optional[Dict[str, Any]]:
- """Read a YAML or JSON config file. Returns None on missing/malformed."""
+ """Read a YAML or JSON config file. Returns None on missing/malformed,
+ and when the file parses to something other than a mapping."""
try:
with open(path, encoding="utf-8") as f:
raw = f.read()
@@ -202,7 +229,7 @@ def _read_config(path: str) -> Optional[Dict[str, Any]]:
return None
if path.endswith(".json"):
try:
- return json.loads(raw)
+ return _mapping_or_none(path, json.loads(raw))
except ValueError as e:
debug_log(f"extensibility: skipping {path}: invalid JSON: {e}")
return None
@@ -213,12 +240,26 @@ def _read_config(path: str) -> Optional[Dict[str, Any]]:
debug_log(f"extensibility: skipping {path}: PyYAML not installed (use .json)")
return None
try:
- return yaml.safe_load(raw)
+ return _mapping_or_none(path, yaml.safe_load(raw))
except yaml.YAMLError as e: # type: ignore
debug_log(f"extensibility: skipping {path}: invalid YAML: {e}")
return None
+def _mapping_or_none(path: str, data: Any) -> Optional[Dict[str, Any]]:
+ """A config file must hold a mapping. A scalar or a list is valid YAML or
+ JSON too (e.g. the pattern list written without its ``patterns:`` key);
+ skip that one file so the other locations still load."""
+ if isinstance(data, dict):
+ return data
+ if data is not None:
+ debug_log(
+ f"extensibility: skipping {path}: expected a mapping, "
+ f"got {type(data).__name__}"
+ )
+ return None
+
+
def _validate_pattern(entry: Any, source: str) -> Optional[Dict[str, Any]]:
"""Validate one user pattern entry. Returns a rule dict in the same shape
as the built-in SECURITY_PATTERNS, or None if invalid (logged)."""
@@ -250,7 +291,7 @@ def _validate_pattern(entry: Any, source: str) -> Optional[Dict[str, Any]]:
try:
rule["regex"] = regex
re.compile(regex)
- except re.error as e:
+ except (re.error, OverflowError, RecursionError) as e:
debug_log(f"extensibility: skipping {name}: invalid regex: {e}")
return None
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index 37866511..73d7c611 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -15,9 +15,11 @@ Functions that DO compose patched leaves (``compute_v2_review_set``,
``security_reminder_hook.py`` for that reason.
"""
import contextlib
+import errno
import os
import re
import subprocess
+import sys
import tempfile
import threading
import time
@@ -198,6 +200,119 @@ def _diff_pathspec(cwd, paths):
return ["--"] + rel if rel else []
+# Bytes of file paths per git call once a path list has proved too long for
+# one command. Windows caps a whole command line at 32,767 characters;
+# elsewhere the limit is about 1 MB (macOS) or 2 MB (Linux), environment
+# included.
+_MAX_PATH_ARGS_BYTES = (
+ 20000 if sys.platform in ("win32", "cygwin", "msys") else 500000)
+# More commands than this and the path list is not worth diffing: each one
+# matches its paths against the whole index, and a set that large is thrown
+# away as pathological after the diff anyway.
+_MAX_PATH_BATCHES = 4
+
+
+def _arg_cost(path):
+ # The exec limit also counts a terminator and a pointer per argument.
+ return len(os.fsencode(path)) + 9
+
+
+def _path_args_budget(env=None):
+ """_MAX_PATH_ARGS_BYTES, or less where this system's own limit is lower
+ (a small stack limit, a BSD, a very large environment). Half of what the
+ system leaves after the environment, so the rest of the command fits."""
+ try:
+ arg_max = os.sysconf("SC_ARG_MAX")
+ except (AttributeError, ValueError, OSError):
+ return _MAX_PATH_ARGS_BYTES
+ env_bytes = sum(len(k) + len(v) + 2 for k, v in (env or os.environ).items())
+ return min(_MAX_PATH_ARGS_BYTES, max(4096, (arg_max - env_bytes) // 2))
+
+
+def _path_batches(paths, budget=None):
+ if budget is None:
+ budget = _MAX_PATH_ARGS_BYTES
+ batch, size = [], 0
+ for p in paths:
+ n = _arg_cost(p)
+ if batch and size + n > budget:
+ yield batch
+ batch, size = [], 0
+ batch.append(p)
+ size += n
+ if batch:
+ yield batch
+
+
+# Why a path list too long for one command left the last get_git_diff call
+# without a diff, for the Stop review's skip reason: "gave_up" (still too
+# long once cut down) or "none_reviewable".
+_path_list_too_long = set()
+
+
+def _too_many_args(e):
+ """The OS refused to start the command because its arguments are too
+ long. Windows reports ERROR_FILENAME_EXCED_RANGE, which Python turns into
+ a FileNotFoundError."""
+ return e.errno == errno.E2BIG or getattr(e, "winerror", None) == 206
+
+
+def _run_captured(cmd, timeout, **kwargs):
+ return subprocess.run(cmd, capture_output=True, timeout=timeout, **kwargs)
+
+
+def _run_git_on_review_paths(args, paths, timeout, run=_run_captured, **kwargs):
+ """Run `git <args> -- <paths>` for the Stop review; return the results.
+ `run(cmd, timeout, **kwargs)` starts each command (_run_diff_bounded for
+ the diff, so its output is never held whole).
+
+ One command with every path whenever the OS takes it. When the OS refuses
+ the argument list as too long, only reviewable source paths are kept (the
+ review drops the rest from the diff anyway) and they go out in as few
+ commands as they need, all within `timeout` seconds together. If even
+ those need more than _MAX_PATH_BATCHES commands, the refusal is raised
+ again.
+
+ Secret-shaped paths that are gone from the work tree go into every one
+ of those commands: `git diff` must still pair a rename away from such a
+ name, or the secret's content would show as a new source file. A new file
+ that only resembles the secret may be paired with it too and left out of
+ the review. Any other rename is paired only when both of its paths are
+ reviewable source and in the same command; otherwise it shows as a delete
+ or an add.
+ """
+ cmd = [*GIT_CMD, *args, "--"]
+ paths = list(paths)
+ deadline = time.monotonic() + timeout
+ try:
+ return [run(cmd + paths, timeout, **kwargs)]
+ except OSError as e:
+ if not _too_many_args(e):
+ raise
+ too_long = e
+ budget = _path_args_budget(kwargs.get("env"))
+ batches = list(_path_batches(
+ [p for p in paths if _is_reviewable_source(p)], budget))
+ root = kwargs.get("cwd") or os.getcwd()
+ secret = [p for p in paths if _is_secret_shaped(p)
+ and not os.path.lexists(os.path.join(root, p))]
+ debug_log(f"git {args[0]}: {len(paths)} paths do not fit one command; "
+ f"{len(batches)} command(s) for the reviewable ones")
+ # The secret-shaped paths ride along with every batch, so they get a
+ # small share of a command of their own.
+ if (len(batches) > _MAX_PATH_BATCHES
+ or sum(map(_arg_cost, secret)) > budget // 4):
+ raise too_long
+ cmd += secret
+ results = []
+ for batch in batches:
+ left = deadline - time.monotonic()
+ if left <= 0:
+ raise subprocess.TimeoutExpired(cmd, timeout)
+ results.append(run(cmd + batch, left, **kwargs))
+ return results
+
+
_TEMP_INDEX_PREFIX = "security_hook_idx_"
# A copy is named <prefix>pid<hook pid>_<8 random chars>, so a later run can
# tell that the hook which made it is gone. Names from earlier releases have
@@ -509,7 +624,7 @@ def _copied_index(cwd, top, real_index, tmpdir, untracked_paths):
surviving = [p for p in untracked_paths
if not p.endswith("/")
and os.path.lexists(os.path.join(cwd, p))]
- add_args = ["--"] + surviving if surviving else None
+ add_args = surviving or None
else:
add_args = None
if add_args:
@@ -517,14 +632,12 @@ def _copied_index(cwd, top, real_index, tmpdir, untracked_paths):
# 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, timeout=10,
+ _run_git_on_review_paths(
+ ["add", "--intent-to-add"], add_args, timeout=10, cwd=cwd,
# The paths are file names, not patterns, for this git add
# only: an untracked file named `:(glob)**` must add only
# itself.
- env={**env, "GIT_LITERAL_PATHSPECS": "1"},
- )
+ env={**env, "GIT_LITERAL_PATHSPECS": "1"})
# A whole-tree add puts a nested repository back.
if untracked_paths is None and not _drop_gitlinks(top, env, tmp_index):
yield None
@@ -1266,12 +1379,15 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa
If `paths` is given, the diff is restricted to those paths (relative to
cwd; absolute paths are converted, paths outside cwd are dropped).
+ A path list too long for one command is cut down to reviewable source
+ files: see _run_git_on_review_paths.
`untracked_paths` (repo-root-relative) is forwarded to _temp_index so it
can add only those files instead of scanning the whole worktree.
The output is read through _DiffKeeper: files the review would drop come
back as their header line only, and a file's diff past
MAX_FILE_DIFF_BYTES is cut down to its added lines.
"""
+ _path_list_too_long.clear()
pathspec = _diff_pathspec(cwd, paths)
if paths and not pathspec:
# Caller restricted to specific paths but none are inside this repo
@@ -1281,25 +1397,36 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa
return ""
# core.quotePath=false comes from GIT_CMD globally (see definition).
- cmd = [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec
+ args = ["diff", IGNORE_SUBMODULES, "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else [])
_diff_read.update(bytes=0, cut_files=0, cut_bytes=0)
+
+ def _run(env):
+ if pathspec:
+ results = _run_git_on_review_paths(args, pathspec[1:], timeout=30, run=_run_diff_bounded, cwd=cwd, env=env)
+ else:
+ results = [_run_diff_bounded([*GIT_CMD, *args], 30, cwd=cwd, env=env)]
+ if not results:
+ _path_list_too_long.add("none_reviewable")
+ for result in results:
+ if result.returncode != 0:
+ debug_log(f"git diff failed: {result.stderr[:200].decode('utf-8', errors='replace')}")
+ return None
+ # Decode with errors='replace' so binary diffs don't crash
+ return b"".join(r.stdout for r in results).decode("utf-8", errors="replace")
+
try:
if untracked_paths is not None and not untracked_paths:
# Nothing to `add -N`, and the diff only reads the index.
- result = _run_diff_bounded(cmd, 30, cwd=cwd)
- else:
- with _temp_index(cwd, untracked_paths) as env:
- # env is None when there is no index (bare repo / not a repo)
- # or no copy slot — diff still runs, just without
- # untracked-file support.
- result = _run_diff_bounded(cmd, 30, cwd=cwd, env=env)
- if result.returncode != 0:
- debug_log(f"git diff failed: {result.stderr[:200].decode('utf-8', errors='replace')}")
- return None
- # Decode with errors='replace' so binary diffs don't crash
- return result.stdout.decode("utf-8", errors="replace")
+ return _run(None)
+ with _temp_index(cwd, untracked_paths) as env:
+ # env is None when there is no index (bare repo / not a repo)
+ # or no copy slot — diff still runs, just without
+ # untracked-file support.
+ return _run(env)
except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
debug_log(f"git diff error: {e}")
+ if isinstance(e, OSError) and _too_many_args(e):
+ _path_list_too_long.add("gave_up")
return None
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 99b00ce0..ecb2bb31 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -86,7 +86,7 @@ from _base import ( # noqa: E402,F401
_read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK,
_PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics,
_USAGE_CONTEXT, _log_usage,
- state_dir as _resolve_state_dir,
+ launcher_probe_metrics, state_dir as _resolve_state_dir,
write_hook_output as _write_hook_output,
llm_reviews_switched_off, agent_sdk_installed,
)
@@ -201,6 +201,13 @@ MAX_STOP_HOOK_FIRINGS = int(os.environ.get("MAX_STOP_HOOK_FIRINGS", "3"))
# diff; unbounded diffs burn tokens and risk 400 on context length.
MAX_DIFF_FILES = int(os.environ.get("MAX_DIFF_FILES", "30"))
+# Changed source paths past which the Stop review is skipped before any diff.
+# A set this large is a repo at $HOME or an unignored cache, not edits; no
+# platform takes that many paths in one git command, and only resolving them
+# takes seconds. Paths the review never reads (an unignored node_modules) do
+# not count: they must not hide the one edited source file beside them.
+MAX_REVIEW_SET_PATHS = int(os.environ.get("MAX_REVIEW_SET_PATHS", "100000"))
+
# Appended to all exit(2) guidance so the asyncRewake auto-turn doesn't
# cause the model to abandon the user's original request.
CONTINUATION_SUFFIX = (
@@ -213,6 +220,9 @@ CONTINUATION_SUFFIX = (
# Extra keys emit_metrics appends to every row this invocation emits.
_TAIL_METRICS: Dict[str, Any] = {}
+# The launcher's slow interpreter probes, if any. After everything else.
+_LAUNCHER_METRICS: Dict[str, Any] = launcher_probe_metrics()
+
# Reviewer context diagnostics from llm.agentic_review, most useful first.
_REVIEWER_CONTEXT_KEYS = ("rv_cwd_gone", "rv_tool_err", "rv_tool_calls")
@@ -310,6 +320,7 @@ def emit_metrics(
# managed-mcp.json) and the review was started again without it.
tail["strict_mcp_off"] = 1
tail.update(_TAIL_METRICS)
+ tail.update(_LAUNCHER_METRICS)
metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}}
out = {"metrics": metrics}
if rewake_summary:
@@ -508,7 +519,10 @@ def record_pending_warnings(session_id, file_path, rule_names):
def sweep_pending_warnings(session_id):
"""
Stop-hook final sweep. Re-read every file in pending_warnings, re-check
- patterns, and return (fixed, unresolved, unresolved_mask). Clears state.
+ patterns, and return (fixed, unresolved, unresolved_mask, fired_mask).
+ fired_mask has a bit for every built-in rule that matched an edit since
+ the last sweep (whether or not its reminder was shown again), so the two
+ masks give, per rule, fired and still matching. Clears state.
A file that's been deleted counts as fixed — the dangerous code is gone.
Never raises — this is telemetry and must not break the Stop hook.
"""
@@ -516,18 +530,24 @@ def sweep_pending_warnings(session_id):
try:
pending = state.get("pending_warnings")
if not isinstance(pending, dict) or not pending:
- return 0, 0, 0
+ return 0, 0, 0, 0
by_file = {}
for key in pending:
if not isinstance(key, str) or ":" not in key:
continue
fp, _, rule = key.rpartition(":")
+ if fp.endswith(":user"):
+ # User rules are named "user:<name>"; keep them apart
+ # from a built-in rule of the same name.
+ fp, rule = fp[:-len(":user")], "user:" + rule
by_file.setdefault(fp, set()).add(rule)
unresolved = []
+ fired = set()
fixed = 0
for fp, rules in by_file.items():
+ fired |= rules
try:
with open(fp, "r", errors="replace") as f:
still_matching = {r for r, _ in check_patterns(fp, f.read())}
@@ -543,13 +563,14 @@ def sweep_pending_warnings(session_id):
# Filter to known rules so a renamed/removed rule in old state
# doesn't KeyError rule_names_to_mask.
known = [r for r in unresolved if r in _RULE_NAME_TO_ID]
- return fixed, len(unresolved), rule_names_to_mask(known)
+ return (fixed, len(unresolved), rule_names_to_mask(known),
+ rule_names_to_mask(fired))
except Exception as e:
debug_log(f"sweep_pending_warnings failed: {e}")
- return 0, 0, 0
+ return 0, 0, 0, 0
result = with_locked_state(session_id, _sweep)
- return result if result is not None else (0, 0, 0)
+ return result if result is not None else (0, 0, 0, 0)
# =====================================================================
# Git baseline management
@@ -2356,13 +2377,25 @@ def handle_stop_hook(input_data):
# Sweep pattern-warning outcomes (pure local work; stop_hook_active is
# already guaranteed False here so no double-count guard needed).
sweep = {}
- warn_fixed, warn_unresolved, warn_unresolved_mask = sweep_pending_warnings(session_id)
+ (warn_fixed, warn_unresolved, warn_unresolved_mask,
+ warn_fired_mask) = sweep_pending_warnings(session_id)
if warn_fixed or warn_unresolved:
sweep = {
"warn_fixed": warn_fixed,
"warn_unresolved": warn_unresolved,
"warn_unresolved_mask": warn_unresolved_mask,
}
+ # The two masks also ride the tail, so the reviewed rows below, which
+ # leave `sweep` or its mask out, carry them when there is room under the
+ # key cap. Per rule they give how often it fired and how often the
+ # flagged code was still there at Stop. warn_fired_mask goes after
+ # warn_unresolved_mask: a row cut at the cap loses it first, and a row
+ # without it is left out of the per-rule read instead of counting its
+ # rules as fixed.
+ if warn_unresolved_mask:
+ _TAIL_METRICS["warn_unresolved_mask"] = warn_unresolved_mask
+ if warn_fired_mask:
+ _TAIL_METRICS["warn_fired_mask"] = warn_fired_mask
v2_metrics = {}
@@ -2488,6 +2521,12 @@ def handle_stop_hook(input_data):
debug_log("Stop hook: empty review set")
_skip(9, touched_paths_count=len(touched_paths))
debug_log(f"Stop hook: review_set={len(review_paths)} base={diff_base[:12]} dirty_now={v2_metrics['dirty_now_count']} changed_since={v2_metrics['changed_since_count']}")
+ if (len(review_paths) > MAX_REVIEW_SET_PATHS
+ and sum(_is_reviewable_source(os.path.relpath(p, repo_root))
+ for p in review_paths) > MAX_REVIEW_SET_PATHS):
+ debug_log(f"Stop hook: pathological review set (more than "
+ f"{MAX_REVIEW_SET_PATHS} paths), skipping")
+ _skip(8)
# Run from repo_root so the toplevel-relative review_paths resolve.
# Diff CONTENT against the turn-start stash (baseline_sha) so the LLM
# sees only this-turn edits — diffing against HEAD includes the user's
@@ -2499,7 +2538,8 @@ def handle_stop_hook(input_data):
content_base = baseline_sha or diff_base
diff_output = get_git_diff(repo_root, content_base, full_context=False,
paths=review_paths, untracked_paths=untracked)
- if diff_output is None and content_base != diff_base:
+ if (diff_output is None and content_base != diff_base
+ and "gave_up" not in gitutil._path_list_too_long):
debug_log(f"Stop hook: diff against {content_base[:12]} failed — falling back to {diff_base}")
diff_output = get_git_diff(repo_root, diff_base, full_context=False,
paths=review_paths, untracked_paths=untracked)
@@ -2516,6 +2556,12 @@ def handle_stop_hook(input_data):
baseline_sha = "HEAD"
if not diff_output or not diff_output.strip():
+ if "gave_up" in gitutil._path_list_too_long:
+ debug_log("Stop hook: changed paths do not fit the git commands, skipping")
+ _skip(8)
+ if "none_reviewable" in gitutil._path_list_too_long:
+ debug_log("Stop hook: no source code files among the changed paths")
+ _skip(7)
debug_log("Stop hook: no changes since baseline")
_skip(6)
@@ -2919,6 +2965,7 @@ def main():
"rule_id": int(_RULE_NAME_TO_ID.get(raw_names[0], -1)),
"rule_mask": rule_names_to_mask(raw_names),
**({"pv": _PV} if _PV else {}),
+ **_LAUNCHER_METRICS,
}
if all_guidance:
output["hookSpecificOutput"] = {
diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh
index a02c7d6c..e0c2730e 100755
--- a/plugins/security-guidance/hooks/sg-python.sh
+++ b/plugins/security-guidance/hooks/sg-python.sh
@@ -106,7 +106,7 @@ probe() {
exec "$@" -c 'import os, sys; t = (sys.argv[1:] or [""])[0]; sys.exit(3) if t and not (os.path.isfile(t) and os.access(t, os.R_OK)) else print(f"{sys.version_info[0]}.{sys.version_info[1]}")' "$SG_TARGET" 2>/dev/null
}
-# Use as `v=$(probe ...) || { note_unreadable "<name>"; continue; }`.
+# Use as `ask ... || { note_unreadable "<name>"; continue; }` (see ask below).
note_unreadable() {
[ $? -eq 3 ] && sg_unreadable="$sg_unreadable|$1|"
return 0
@@ -119,6 +119,49 @@ on_path() {
command -v "$1" >/dev/null 2>&1
}
+# How long the probes took, for the launcher_probe_max_ms / launcher_probe_ms
+# metrics the hook reports. Measurement only: `ask` is `v=$(probe ...)` with a
+# clock around it, and changes neither which interpreter runs nor how long a
+# probe may take. EPOCHREALTIME needs bash 5; older bash (macOS /bin/bash) only
+# has whole seconds, where a difference of 1 can be a few milliseconds: there
+# a single probe counts from 2 s, and the total is first probe to last.
+unset SG_LAUNCHER_PROBE_MS SG_LAUNCHER_PROBE_MAX_MS
+sg_probe_ms=0
+sg_probe_max_ms=0
+sg_probe_first=""
+sg_coarse=""
+sg_clock() {
+ # Sets $sg_now (ms) without starting a process.
+ case "${EPOCHREALTIME:-}" in
+ [0-9]*[.,][0-9][0-9][0-9][0-9][0-9][0-9]) # the decimal point follows the locale
+ sg_now=${EPOCHREALTIME//[!0-9]/}
+ sg_now=$((10#$sg_now / 1000)) ;;
+ *)
+ sg_coarse=1
+ sg_now=$((SECONDS * 1000)) ;;
+ esac
+}
+ask() {
+ # Sets $v; same exit status as probe.
+ local rc=0 t0 ms
+ sg_clock; t0=$sg_now
+ [ -n "$sg_probe_first" ] || sg_probe_first=$t0
+ v=$(probe "$@") || rc=$?
+ sg_clock; ms=$((sg_now - t0))
+ if [ -n "$sg_coarse" ]; then
+ [ "$ms" -ge 2000 ] || ms=0
+ sg_probe_ms=$((sg_now - sg_probe_first))
+ [ "$sg_probe_ms" -ge 2000 ] || sg_probe_ms=0
+ elif [ "$ms" -gt 0 ]; then
+ sg_probe_ms=$((sg_probe_ms + ms))
+ fi
+ [ "$ms" -le "$sg_probe_max_ms" ] || sg_probe_max_ms=$ms
+ if [ "$sg_probe_ms" -gt 0 ]; then
+ export SG_LAUNCHER_PROBE_MS=$sg_probe_ms SG_LAUNCHER_PROBE_MAX_MS=$sg_probe_max_ms
+ fi
+ return $rc
+}
+
# 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
@@ -139,7 +182,7 @@ is_sdk_compatible() {
# than this list are pass 2b.
for cmd in "python3.13" "python3.12" "python3.11" "python3.10"; do
on_path "$cmd" || continue
- v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; }
+ ask "$cmd" || { note_unreadable "$cmd"; continue; }
v=${v%$'\r'}
if is_sdk_compatible "$v"; then
exec "$cmd" "$@"
@@ -154,7 +197,7 @@ for cmd in "python3" "python" "py -3"; do
# shellcheck disable=SC2086
on_path $cmd || continue
# shellcheck disable=SC2086
- v=$(probe $cmd) || { note_unreadable "$cmd"; continue; }
+ ask $cmd || { note_unreadable "$cmd"; continue; }
v=${v%$'\r'}
if is_sdk_compatible "$v"; then
# shellcheck disable=SC2086
@@ -229,7 +272,7 @@ sg_tried="|"
for cmd in "${sg_candidates[@]}"; do
case "$sg_tried" in *"|$cmd|"*) continue ;; esac
sg_tried="$sg_tried$cmd|"
- v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; }
+ ask "$cmd" || { note_unreadable "$cmd"; continue; }
v=${v%$'\r'}
if is_sdk_compatible "$v"; then
exec "$cmd" "$@"
diff --git a/plugins/security-guidance/tests/test_launcher_probe_timing.py b/plugins/security-guidance/tests/test_launcher_probe_timing.py
new file mode 100644
index 00000000..69b867a6
--- /dev/null
+++ b/plugins/security-guidance/tests/test_launcher_probe_timing.py
@@ -0,0 +1,196 @@
+"""sg-python.sh times its interpreter probes and the hooks report slow ones.
+
+Measurement only: the launcher still waits for every probe and still picks
+the interpreter it picked before.
+
+The slow interpreter is a shell wrapper around the real one, so these tests
+need a POSIX shell.
+"""
+import json
+import os
+import shutil
+import subprocess
+import sys
+
+import pytest
+
+from conftest import HOOKS_DIR, edit_payload, metrics_of, run_hook, stop_payload
+
+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers")
+
+SHIM = HOOKS_DIR / "sg-python.sh"
+BASH = shutil.which("bash") or "/bin/bash"
+REAL = os.path.realpath(sys.executable)
+
+
+def _bash_major():
+ try:
+ return int(subprocess.run([BASH, "-c", "echo ${BASH_VERSINFO[0]}"],
+ capture_output=True, text=True, timeout=30).stdout)
+ except (OSError, ValueError, subprocess.SubprocessError):
+ return 0
+
+
+BASH5 = sys.platform != "win32" and _bash_major() >= 5
+
+# Prints what the launcher handed over, then its stdin.
+HOOK = (
+ "import os, sys\n"
+ "print('max=' + os.environ.get('SG_LAUNCHER_PROBE_MAX_MS', ''))\n"
+ "print('total=' + os.environ.get('SG_LAUNCHER_PROBE_MS', ''))\n"
+ "print('name=' + os.environ.get('SG_NAME', ''))\n"
+ "print('stdin=' + sys.stdin.read())\n"
+)
+
+WRAPPER = """#!{bash}
+# Answers the launcher's `-c` probe after DELAY seconds; RC != 0 fails it.
+if [ "${{1:-}}" = "-c" ]; then
+ sleep {delay}
+ [ {rc} -eq 0 ] || exit {rc}
+fi
+SG_NAME={name} exec '{real}' "$@"
+"""
+
+
+def _python(bindir, name, delay=0, rc=0):
+ bindir.mkdir(parents=True, exist_ok=True)
+ p = bindir / name
+ p.write_text(WRAPPER.format(bash=BASH, delay=delay, rc=rc, name=name, real=REAL))
+ p.chmod(0o755)
+
+
+def _run(bindir, script, extra_env=None, shim=SHIM):
+ env = {"PATH": f"{bindir}{os.pathsep}/usr/bin{os.pathsep}/bin", "HOME": os.environ.get("HOME", "/")}
+ env.update(extra_env or {})
+ r = subprocess.run([BASH, str(shim), str(script)], input="payload", capture_output=True,
+ text=True, timeout=60, env=env)
+ assert r.returncode == 0, r.stderr
+ return dict(line.split("=", 1) for line in r.stdout.splitlines())
+
+
+@pytest.fixture
+def script(tmp_path):
+ p = tmp_path / "hook.py"
+ p.write_text(HOOK)
+ return p
+
+
+@pytest.fixture
+def bindir(tmp_path):
+ """A PATH entry with only what the tests put there (plus sleep)."""
+ return tmp_path / "bin"
+
+
+def _only_these(bindir):
+ # Hide the system interpreters: PATH is bindir plus /usr/bin:/bin, so every
+ # name the launcher tries gets an entry here, failing unless a test set it.
+ for name in ("python3.13", "python3.12", "python3.11", "python3.10", "python3", "python", "py"):
+ if not (bindir / name).exists():
+ _python(bindir, name, rc=1)
+
+
+@pytest.mark.skipif(not BASH5, reason="millisecond clock needs bash 5")
+def test_fast_probes_are_timed_in_milliseconds(bindir, script):
+ _python(bindir, "python3")
+ _only_these(bindir)
+ out = _run(bindir, script)
+ assert out["name"] == "python3" and out["stdin"] == "payload"
+ assert 0 < int(out["max"]) <= int(out["total"])
+
+
+def test_slow_probe_is_waited_for_and_measured(bindir, script):
+ _python(bindir, "python3", delay=2.2)
+ _python(bindir, "python")
+ _only_these(bindir)
+ out = _run(bindir, script)
+ # Still the first name that answers, however long it took.
+ assert out["name"] == "python3" and out["stdin"] == "payload"
+ assert 2000 <= int(out["max"]) < 10000
+ assert int(out["total"]) >= int(out["max"])
+
+
+def test_slow_failing_probe_counts_towards_the_wait(bindir, script):
+ _python(bindir, "python3", delay=2.2, rc=49)
+ _python(bindir, "python")
+ _only_these(bindir)
+ out = _run(bindir, script)
+ assert out["name"] == "python"
+ assert int(out["max"]) >= 2000
+
+
+def test_inherited_values_are_not_reported_again(bindir, script):
+ _python(bindir, "python3")
+ _only_these(bindir)
+ out = _run(bindir, script, {"SG_LAUNCHER_PROBE_MAX_MS": "999999", "SG_LAUNCHER_PROBE_MS": "999999"})
+ assert out["max"] != "999999" and out["total"] != "999999"
+
+
+@pytest.fixture
+def whole_second_shim(tmp_path):
+ """The launcher as bash 3.2 runs it: no EPOCHREALTIME, only SECONDS."""
+ src = SHIM.read_text()
+ assert 'case "${EPOCHREALTIME:-}" in' in src
+ p = tmp_path / "sg-python-coarse.sh"
+ p.write_text(src.replace('case "${EPOCHREALTIME:-}" in', 'case "" in'))
+ return p
+
+
+def test_whole_second_clock_ignores_fast_probes(bindir, script, whole_second_shim):
+ _python(bindir, "python3")
+ _only_these(bindir)
+ out = _run(bindir, script, shim=whole_second_shim)
+ assert out["name"] == "python3"
+ # A probe of a few ms can straddle a second; that is not reported as 1 s.
+ assert out["max"] == "" and out["total"] == ""
+
+
+def test_whole_second_clock_measures_slow_probes(bindir, script, whole_second_shim):
+ _python(bindir, "python3", delay=2.2)
+ _only_these(bindir)
+ out = _run(bindir, script, shim=whole_second_shim)
+ assert out["name"] == "python3"
+ assert int(out["max"]) in (2000, 3000) and int(out["total"]) >= int(out["max"])
+
+
+@pytest.mark.parametrize("slowest,total,expected", [
+ ("4200", "4350", {"launcher_probe_ms": 4350, "launcher_probe_max_ms": 4200}),
+ ("900", "1500", {"launcher_probe_ms": 1500, "launcher_probe_max_ms": 900}),
+ ("999", "999", {}),
+ ("86400000", "86400000", {"launcher_probe_ms": 3600000, "launcher_probe_max_ms": 3600000}),
+ ("5000", "5", {}),
+ ("", "", {}),
+ ("junk", "5", {}),
+])
+def test_stop_hook_reports_only_slow_probes(hook_env, workspace, slowest, total, expected):
+ _, repo = workspace
+ env = {**hook_env, "SG_LAUNCHER_PROBE_MAX_MS": slowest, "SG_LAUNCHER_PROBE_MS": total}
+ rc, out, err = run_hook(stop_payload(repo), env)
+ m = metrics_of(out)
+ assert m is not None, err
+ assert {k: v for k, v in m.items() if k.startswith("launcher_probe")} == expected
+
+
+def test_launcher_keys_come_last(hook_env, workspace):
+ """Claude Code keeps the first 20 keys, so these never displace another."""
+ _, repo = workspace
+ env = {**hook_env, "SG_LAUNCHER_PROBE_MAX_MS": "4200", "SG_LAUNCHER_PROBE_MS": "4350"}
+ rc, out, err = run_hook(stop_payload(repo), env)
+ assert list(metrics_of(out))[-2:] == ["launcher_probe_ms", "launcher_probe_max_ms"]
+
+
+def test_edit_hook_reports_slow_probes_on_pattern_rows(hook_env, workspace):
+ _, repo = workspace
+ env = {**hook_env, "SG_LAUNCHER_PROBE_MAX_MS": "4200", "SG_LAUNCHER_PROBE_MS": "4350"}
+ payload = edit_payload(repo, repo / "app.py", new_string="import os\nos.system('ls ' + x)\n")
+ rc, out, err = run_hook(payload, env)
+ m = metrics_of(out)
+ assert m is not None and "rule_id" in m, (out, err)
+ assert m["launcher_probe_ms"] == 4350 and m["launcher_probe_max_ms"] == 4200
+
+
+def test_values_are_read_once(monkeypatch):
+ import _base
+ monkeypatch.setenv("SG_LAUNCHER_PROBE_MAX_MS", "7000")
+ monkeypatch.setenv("SG_LAUNCHER_PROBE_MS", "7100")
+ assert _base.launcher_probe_metrics() == {"launcher_probe_ms": 7100, "launcher_probe_max_ms": 7000}
+ assert "SG_LAUNCHER_PROBE_MS" not in os.environ and _base.launcher_probe_metrics() == {}
diff --git a/plugins/security-guidance/tests/test_pattern_fired_metrics.py b/plugins/security-guidance/tests/test_pattern_fired_metrics.py
new file mode 100644
index 00000000..c1e31300
--- /dev/null
+++ b/plugins/security-guidance/tests/test_pattern_fired_metrics.py
@@ -0,0 +1,90 @@
+import json
+
+from conftest import (
+ STUB_VULN, edit_payload, metrics_of, run_hook, stop_payload, ups_payload,
+)
+
+from patterns import RuleId
+
+EVAL = 1 << RuleId.EVAL_INJECTION
+SHELL = 1 << RuleId.PYTHON_SUBPROCESS_SHELL
+
+
+def _edit(repo, env, name, content):
+ (repo / name).write_text(content)
+ run_hook(edit_payload(repo, repo / name, content), env)
+
+
+def _turn(repo, env, edits, after=None):
+ run_hook(ups_payload(repo), env)
+ for name, content in edits.items():
+ _edit(repo, env, name, content)
+ for name, content in (after or {}).items():
+ (repo / name).write_text(content)
+ rc, so, se = run_hook(stop_payload(repo), env)
+ return metrics_of(so)
+
+
+class TestFiredRulesReachTheStopRow:
+ def test_clean_review(self, env, gateway, workspace):
+ _, repo = workspace
+ m = _turn(repo, env, {"calc.js": "const v = eval(src)\n"})
+ assert m["vulns_found"] == 0 and "review_ms" in m
+ assert m["warn_fired_mask"] == EVAL
+ assert m["warn_unresolved_mask"] == EVAL
+ assert list(m).index("warn_fired_mask") < 20
+
+ def test_fired_mask_follows_the_unresolved_mask(self, env, gateway, workspace):
+ """A row cut at the key cap loses the fired mask before the
+ unresolved one."""
+ _, repo = workspace
+ gateway.vulns = [STUB_VULN]
+ m = _turn(repo, env, {"calc.js": "const v = eval(src)\n"})
+ keys = list(m)
+ assert keys.index("warn_unresolved_mask") < keys.index("warn_fired_mask")
+ assert m["warn_fixed"] == 0 and m["warn_unresolved"] == 1
+
+ def test_review_with_findings(self, env, gateway, workspace):
+ _, repo = workspace
+ gateway.vulns = [STUB_VULN]
+ m = _turn(repo, env, {"calc.js": "const v = eval(src)\n"})
+ assert m["vulns_found"] == 1
+ assert m["warn_fired_mask"] == EVAL and m["warn_unresolved_mask"] == EVAL
+
+ def test_review_skipped(self, env, gateway, workspace):
+ _, repo = workspace
+ m = _turn(repo, {**env, "ENABLE_STOP_REVIEW": "0"},
+ {"calc.js": "const v = eval(src)\n"})
+ assert m["skipped"] is True
+ assert m["warn_fired_mask"] == EVAL and m["warn_unresolved_mask"] == EVAL
+
+ def test_fixed_rule_is_fired_but_not_unresolved(self, env, gateway, workspace):
+ _, repo = workspace
+ m = _turn(
+ repo, env,
+ {"calc.js": "const v = eval(src)\n",
+ "run.py": "import subprocess\nsubprocess.run(cmd, shell=True)\n"},
+ after={"calc.js": "const v = JSON.parse(src)\n"},
+ )
+ assert m["warn_fired_mask"] == EVAL | SHELL
+ assert m["warn_unresolved_mask"] == SHELL
+
+ def test_no_warning_no_keys(self, env, gateway, workspace):
+ _, repo = workspace
+ m = _turn(repo, env, {"ok.py": "def ok():\n return 1\n"})
+ assert "warn_fired_mask" not in m and "warn_unresolved_mask" not in m
+
+ def test_masks_are_reported_once(self, env, gateway, workspace):
+ _, repo = workspace
+ _turn(repo, env, {"calc.js": "const v = eval(src)\n"})
+ m = _turn(repo, env, {"ok.py": "def ok():\n return 2\n"})
+ assert "warn_fired_mask" not in m and "warn_unresolved_mask" not in m
+
+ def test_user_rule_is_not_counted_as_a_builtin_of_the_same_name(self, env, gateway, workspace):
+ _, repo = workspace
+ (repo / ".claude").mkdir()
+ (repo / ".claude" / "security-patterns.json").write_text(json.dumps({"patterns": [
+ {"rule_name": "eval_injection", "regex": "FORBIDDEN_CALL", "reminder": "no"}]}))
+ m = _turn(repo, {**env, "ENABLE_STOP_REVIEW": "0"}, {"a.py": "FORBIDDEN_CALL()\n"})
+ assert "warn_fired_mask" not in m
+ assert m["warn_fixed"] == 0 and m["warn_unresolved"] == 1
diff --git a/plugins/security-guidance/tests/test_patterns_file_shape.py b/plugins/security-guidance/tests/test_patterns_file_shape.py
new file mode 100644
index 00000000..a63494b6
--- /dev/null
+++ b/plugins/security-guidance/tests/test_patterns_file_shape.py
@@ -0,0 +1,116 @@
+"""A security-patterns file that parses to something other than a mapping is
+skipped on its own; rules from the other locations still load."""
+import json
+
+import pytest
+
+import extensibility
+
+from conftest import run_hook
+
+VALID = {"patterns": [{"rule_name": "demo_rule", "regex": "AKIA[0-9A-Z]{16}",
+ "reminder": "DEMO_RULE_REMINDER"}]}
+
+
+@pytest.fixture
+def project(tmp_path, monkeypatch):
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("USERPROFILE", str(home))
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+ monkeypatch.setattr(extensibility, "_user_patterns", [])
+ monkeypatch.setattr(extensibility, "_guidance_block", "")
+ proj = tmp_path / "proj"
+ (proj / ".claude").mkdir(parents=True)
+ (proj / ".claude" / "security-patterns.json").write_text(json.dumps(VALID))
+ return proj
+
+
+def loaded(proj):
+ extensibility.load_for_session(str(proj))
+ return [r["ruleName"] for r in extensibility.user_patterns()]
+
+
+def rule(name="x", **kw):
+ return dict(VALID["patterns"][0], rule_name=name, **kw)
+
+
+WRONG_SHAPE_JSON = [
+ json.dumps([rule()]),
+ "5",
+ '"just a string"',
+ '{"patterns": 5}',
+ '{"patterns": "demo"}',
+ '{"patterns": {"rule_name": "x"}}',
+ '{"patterns": {}}',
+ '{"patterns": null}',
+ "{not json",
+ json.dumps({"patterns": [rule(regex="a{99999999999}")]}),
+]
+
+
+@pytest.mark.parametrize("body", WRONG_SHAPE_JSON)
+def test_wrong_shape_local_json_keeps_the_project_rules(project, body):
+ (project / ".claude" / "security-patterns.local.json").write_text(body)
+ assert loaded(project) == ["user:demo_rule"]
+
+
+@pytest.mark.parametrize("body", [
+ "just a bare scalar\n",
+ "- rule_name: x\n regex: a\n reminder: r\n",
+ "patterns: 5\n",
+ "a: [1\n",
+ "when: 2001-13-45\n",
+])
+def test_wrong_shape_local_yaml_keeps_the_project_rules(project, body):
+ pytest.importorskip("yaml")
+ (project / ".claude" / "security-patterns.local.yaml").write_text(body)
+ assert loaded(project) == ["user:demo_rule"]
+
+
+def test_file_that_is_not_utf8_keeps_the_project_rules(project):
+ body = json.dumps({"patterns": [rule("local_rule")]}).encode("utf-16")
+ (project / ".claude" / "security-patterns.local.json").write_bytes(body)
+ assert loaded(project) == ["user:demo_rule"]
+
+
+@pytest.mark.parametrize("body", ["- a\n- b\n", "patterns: 5\n"])
+def test_unusable_yaml_does_not_hide_the_json_next_to_it(project, body):
+ pytest.importorskip("yaml")
+ (project / ".claude" / "security-patterns.yaml").write_text(body)
+ assert loaded(project) == ["user:demo_rule"]
+
+
+def test_one_bad_rule_does_not_drop_the_rest_of_its_file(project):
+ local = {"patterns": [rule("bad", regex="a{99999999999}"), rule("local_rule")]}
+ (project / ".claude" / "security-patterns.local.json").write_text(json.dumps(local))
+ assert loaded(project) == ["user:demo_rule", "user:local_rule"]
+
+
+def test_rules_from_a_valid_local_file_still_load(project):
+ local = {"patterns": [rule("local_rule")]}
+ (project / ".claude" / "security-patterns.local.json").write_text(json.dumps(local))
+ assert loaded(project) == ["user:demo_rule", "user:local_rule"]
+
+
+def test_wrong_shape_file_is_named_in_the_debug_log(project, monkeypatch):
+ lines = []
+ monkeypatch.setattr(extensibility, "debug_log", lines.append)
+ (project / ".claude" / "security-patterns.local.json").write_text("[1, 2]")
+ assert loaded(project) == ["user:demo_rule"]
+ assert any("security-patterns.local.json" in l and "got list" in l for l in lines)
+
+
+def test_edit_hook_still_warns_with_a_wrong_shape_file_present(project, hook_env):
+ (project / ".claude" / "security-patterns.local.json").write_text("[1, 2]")
+ env = dict(hook_env, HOME=str(project.parent / "home"), CLAUDE_PROJECT_DIR=str(project))
+ env.pop("CLAUDE_CONFIG_DIR", None)
+ payload = {
+ "session_id": "s1", "hook_event_name": "PostToolUse", "tool_name": "Write",
+ "tool_input": {"file_path": str(project / "cfg.py"),
+ "content": "KEY = 'AKIAABCDEFGHIJKLMNOP'\n"},
+ "cwd": str(project), "tool_response": {},
+ }
+ _rc, stdout, stderr = run_hook(payload, env)
+ assert "DEMO_RULE_REMINDER" in stdout + stderr
diff --git a/plugins/security-guidance/tests/test_stop_review_paths.py b/plugins/security-guidance/tests/test_stop_review_paths.py
new file mode 100644
index 00000000..b6f9793c
--- /dev/null
+++ b/plugins/security-guidance/tests/test_stop_review_paths.py
@@ -0,0 +1,319 @@
+"""The Stop review still runs when the changed paths of a turn do not fit in
+one git command."""
+import errno
+import os
+import subprocess
+import tempfile
+import types
+
+import pytest
+
+from conftest import (
+ GIT_ENV, VULN_PY, make_repo, metrics_of, run_hook, stop_payload,
+ ups_payload,
+)
+
+import diffstate
+import gitutil
+
+GIT_CMD_CHARS = sum(len(a) + 1 for a in gitutil.GIT_CMD)
+
+
+@pytest.fixture
+def git_env(tmp_path, monkeypatch):
+ """Git identity for in-process calls, and a temp dir of our own for the
+ index copies."""
+ d = tmp_path / "tmproot"
+ d.mkdir()
+ monkeypatch.setattr(tempfile, "tempdir", str(d))
+ monkeypatch.setattr(gitutil, "_path_list_too_long", set())
+ for k, v in GIT_ENV.items():
+ monkeypatch.setenv(k, v)
+
+
+def _more_than_one_command_holds(repo, exts):
+ """3,000 untracked files, cycling through `exts`, whose names add up to
+ more than a single command can carry on any platform (the largest limit
+ is about 2 MB, on Linux)."""
+ deep = repo / ("d" * 180) / ("e" * 180) / ("f" * 180) / ("g" * 180)
+ deep.mkdir(parents=True)
+ for i in range(3000):
+ (deep / f"file_{i:05d}{exts[i % len(exts)]}").write_text("x\n")
+
+
+def _unusual_argument_limit():
+ """The long-path tests are sized for the usual limits: 1 MB (macOS) to
+ 2 MB (Linux with an 8 MB stack)."""
+ try:
+ return not 1024 * 1024 <= os.sysconf("SC_ARG_MAX") <= 2 * 1024 * 1024 + 200000
+ except (AttributeError, ValueError, OSError):
+ return False
+
+
+long_paths = pytest.mark.skipif(
+ os.name == "nt" or _unusual_argument_limit(),
+ reason="needs paths longer than Windows allows by default, and the usual "
+ "1 to 2 MB limit on one command's arguments")
+
+
+def _refuse_long_commands(monkeypatch, limit, error):
+ """Make starting a command fail like the OS does when its arguments
+ exceed `limit` characters. Returns the list of commands run. Popen is
+ where subprocess.run and the bounded diff reader both start theirs."""
+ real_popen = subprocess.Popen
+ ran = []
+
+ def popen(cmd, *args, **kwargs):
+ if sum(len(a) + 1 for a in cmd) > limit:
+ raise error
+ ran.append(cmd)
+ return real_popen(cmd, *args, **kwargs)
+
+ monkeypatch.setattr(subprocess, "Popen", popen)
+ return ran
+
+
+class TestPathBatches:
+ def test_every_path_once_and_each_batch_bounded(self):
+ paths = [f"dir/file_{i}.py" for i in range(100000)]
+ batches = list(gitutil._path_batches(paths))
+ assert [p for b in batches for p in b] == paths
+ assert len(batches) > 1
+ assert all(sum(len(p) for p in b) <= gitutil._MAX_PATH_ARGS_BYTES
+ for b in batches)
+
+ def test_budget_is_in_bytes(self, monkeypatch):
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 100)
+ assert len(list(gitutil._path_batches(["\u6f22" * 20 + ".py"] * 3))) == 3
+
+ def test_one_overlong_path_still_goes_out(self):
+ long = "x" * (gitutil._MAX_PATH_ARGS_BYTES + 10)
+ assert list(gitutil._path_batches(["a", long, "b"])) == [["a"], [long], ["b"]]
+
+ def test_no_paths_no_batches(self):
+ assert list(gitutil._path_batches([])) == []
+
+
+class TestGetGitDiff:
+ def _review_set(self, tmp_path):
+ repo = make_repo(tmp_path / "repo", {f"t{i}.py": "x = 1\n" for i in range(6)})
+ for i in range(6):
+ (repo / f"t{i}.py").write_text("x = 2\n")
+ (repo / f"new{i}.py").write_text("y = 1\n")
+ paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {})
+ assert len(paths) == 12 and len(untracked) == 6
+ return root, base, paths, untracked
+
+ def test_one_command_when_the_paths_fit(self, tmp_path, git_env, monkeypatch):
+ root, base, paths, untracked = self._review_set(tmp_path)
+ ran = _refuse_long_commands(monkeypatch, 10**9, OSError(errno.E2BIG, "too long"))
+ diff = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ assert len(gitutil.parse_diff_into_files(diff)) == 12
+ assert len([c for c in ran if "diff" in c]) == 1
+ assert len([c for c in ran if "add" in c]) == 1
+
+ @pytest.mark.parametrize("error", [
+ OSError(errno.E2BIG, "Argument list too long"),
+ # What Python raises on Windows for ERROR_FILENAME_EXCED_RANGE.
+ type("WinTooLong", (FileNotFoundError,), {"winerror": 206})(errno.ENOENT, "too long"),
+ ], ids=["posix", "windows"])
+ def test_batches_when_one_command_is_refused(self, tmp_path, git_env, monkeypatch, error):
+ root, base, paths, untracked = self._review_set(tmp_path)
+ whole = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 60)
+ limit = GIT_CMD_CHARS + 100 # the six-path add fits, the twelve-path diff does not
+ ran = _refuse_long_commands(monkeypatch, limit, error)
+ batched = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ assert sorted(gitutil.parse_diff_into_files(batched)) == \
+ sorted(gitutil.parse_diff_into_files(whole))
+ assert len([c for c in ran if "diff" in c]) > 1
+ # The batches are read through the bounded reader, which counts them.
+ assert gitutil._diff_read["bytes"] > 0
+
+ def test_only_reviewable_paths_after_a_refusal(self, tmp_path, git_env, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ (repo / "app.py").write_text("x = 2\n")
+ for i in range(20):
+ (repo / f"note{i:02d}.txt").write_text("x\n")
+ paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {})
+ whole = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ assert whole.count("diff --git ") == 21
+ _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 100, OSError(errno.E2BIG, "too long"))
+ cut = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ assert cut.count("diff --git ") == 1
+ assert gitutil.parse_diff_into_files(cut) == gitutil.parse_diff_into_files(whole)
+
+ def test_rename_away_from_a_secret_shaped_name_stays_out_after_a_refusal(
+ self, tmp_path, git_env, monkeypatch):
+ secret = "".join(f"KEY_{i}=value-{i}\n" for i in range(20))
+ repo = make_repo(tmp_path / "repo", {".env": secret, "app.py": "x = 1\n"})
+ os.rename(repo / ".env", repo / "settings.py")
+ (repo / "app.py").write_text("x = 2\n")
+ (repo / "a_much_longer_module_name.py").write_text("y = 1\n")
+ for i in range(20):
+ (repo / f"note{i:02d}.txt").write_text("x\n")
+ paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {})
+ whole = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ reviewed = ["a_much_longer_module_name.py", "app.py"]
+ assert sorted(f for f, _ in gitutil.parse_diff_into_files(whole)) == reviewed
+ # Room for .env beside each batch, and not for the three .py together.
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 60)
+ ran = _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 120, OSError(errno.E2BIG, "too long"))
+ cut = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ diffs = [c for c in ran if "diff" in c]
+ assert len(diffs) > 1 and all(".env" in c for c in diffs)
+ assert sorted(f for f, _ in gitutil.parse_diff_into_files(cut)) == reviewed
+ assert "KEY_1=" not in "".join(d for _, d in gitutil.parse_diff_into_files(cut))
+
+ def test_gives_up_when_the_secret_shaped_paths_alone_are_too_many(
+ self, tmp_path, git_env, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {
+ "app.py": "x = 1\n", **{f"dir{i:02d}/.env": "K=v\n" for i in range(20)}})
+ (repo / "app.py").write_text("x = 2\n")
+ for i in range(20):
+ os.remove(repo / f"dir{i:02d}" / ".env")
+ paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {})
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 200)
+ ran = _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 100, OSError(errno.E2BIG, "too long"))
+ assert gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) is None
+ assert [c for c in ran if "diff" in c] == []
+ assert "gave_up" in gitutil._path_list_too_long
+
+ def test_secret_shaped_files_still_in_the_work_tree_do_not_ride_along(
+ self, tmp_path, git_env, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ (repo / "app.py").write_text("x = 2\n")
+ for i in range(20):
+ (repo / f"dir{i:02d}").mkdir()
+ (repo / f"dir{i:02d}" / ".env").write_text("K=v\n")
+ paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {})
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 200)
+ ran = _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 100, OSError(errno.E2BIG, "too long"))
+ cut = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ assert [f for f, _ in gitutil.parse_diff_into_files(cut)] == ["app.py"]
+ assert not any(".env" in a for c in ran for a in c)
+ assert not gitutil._path_list_too_long
+
+ def test_batches_shrink_to_a_lower_system_limit(self, monkeypatch):
+ monkeypatch.setattr(os, "sysconf", lambda name: 100000, raising=False)
+ budget = gitutil._path_args_budget({"A": "b" * 9997})
+ # Half of what the environment leaves, or the platform figure where
+ # that is lower (Windows).
+ assert budget == min(45000, gitutil._MAX_PATH_ARGS_BYTES)
+ paths = [f"dir/file_{i}.py" for i in range(10000)]
+ assert all(sum(len(p) + 9 for p in b) <= budget
+ for b in gitutil._path_batches(paths, budget))
+ # Never above the platform figure, never uselessly small.
+ monkeypatch.setattr(os, "sysconf", lambda name: 10**9, raising=False)
+ assert gitutil._path_args_budget({}) == gitutil._MAX_PATH_ARGS_BYTES
+ monkeypatch.setattr(os, "sysconf", lambda name: 100, raising=False)
+ assert gitutil._path_args_budget({}) == 4096
+
+ def test_gives_up_past_the_batch_limit(self, tmp_path, git_env, monkeypatch):
+ root, base, paths, untracked = self._review_set(tmp_path)
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 60)
+ monkeypatch.setattr(gitutil, "_MAX_PATH_BATCHES", 2)
+ ran = _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 100, OSError(errno.E2BIG, "too long"))
+ assert gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) is None
+ assert [c for c in ran if "diff" in c] == []
+
+ def test_other_start_failures_are_not_retried(self, tmp_path, git_env, monkeypatch):
+ root, base, paths, untracked = self._review_set(tmp_path)
+ ran = _refuse_long_commands(monkeypatch, 0, FileNotFoundError(errno.ENOENT, "git"))
+ assert gitutil.get_git_diff(root, base, paths=paths, untracked_paths=[]) is None
+ assert ran == []
+
+ def test_batches_share_one_time_limit(self, tmp_path, git_env, monkeypatch):
+ repo = make_repo(tmp_path / "repo")
+ clock = iter([0, 0, 31])
+ monkeypatch.setattr(gitutil, "time", types.SimpleNamespace(monotonic=lambda: next(clock)))
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 30)
+ ran = _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 60, OSError(errno.E2BIG, "too long"))
+ with pytest.raises(subprocess.TimeoutExpired):
+ gitutil._run_git_on_review_paths(
+ ["status"], ["a" * 40, "b" * 40, "c" * 40], timeout=30, cwd=str(repo))
+ assert len(ran) == 1
+
+ @long_paths
+ def test_more_paths_than_one_command_holds(self, tmp_path, git_env):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ (repo / "app.py").write_text("x = 2\n")
+ _more_than_one_command_holds(repo, [".py", ".txt"])
+ paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {})
+ assert sum(len(p) for p in untracked) > 2 * 1024 * 1024
+ diff = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ assert diff is not None
+ # app.py and the 1,500 .py files, from more than one command.
+ assert len(gitutil.parse_diff_into_files(diff)) == 1501
+ assert diff.count("diff --git ") == 1501
+
+
+class TestWholeHook:
+ @long_paths
+ def test_edit_reviewed_beside_more_paths_than_one_command_holds(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ _more_than_one_command_holds(repo, [".txt"])
+ rc, so, se = run_hook(stop_payload(repo), hook_env)
+ m = metrics_of(so)
+ assert m.get("skip_reason") is None, m
+ assert m.get("review_set_count") == 3001
+ assert stub_api.calls
+
+ def test_review_set_past_the_cap_skips_without_a_diff(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ (repo / "new.py").write_text(VULN_PY)
+ rc, so, se = run_hook(stop_payload(repo), {**hook_env, "MAX_REVIEW_SET_PATHS": "1"})
+ m = metrics_of(so)
+ assert m.get("skip_reason") == 8, m
+ # The skip taken after a diff reports how many files the diff held.
+ assert "diff_files_count" not in m
+ assert not stub_api.calls
+
+ def test_cap_counts_only_reviewable_paths(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ for i in range(20):
+ (repo / f"note{i:02d}.txt").write_text("x\n")
+ rc, so, se = run_hook(stop_payload(repo), {**hook_env, "MAX_REVIEW_SET_PATHS": "5"})
+ m = metrics_of(so)
+ assert m.get("skip_reason") is None, m
+ assert m.get("review_set_count") == 21
+ assert stub_api.calls
+
+ @long_paths
+ def test_giving_up_is_reported_as_too_many_paths(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ # 3,000 reviewable names of about 750 bytes: more than four commands.
+ _more_than_one_command_holds(repo, [".py"])
+ rc, so, se = run_hook(stop_payload(repo), hook_env)
+ m = metrics_of(so)
+ assert m.get("skip_reason") == 8, m
+ assert not stub_api.calls
+
+ @long_paths
+ def test_nothing_reviewable_is_reported_as_no_source_files(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ run_hook(ups_payload(repo), hook_env)
+ _more_than_one_command_holds(repo, [".txt"])
+ rc, so, se = run_hook(stop_payload(repo), hook_env)
+ m = metrics_of(so)
+ assert m.get("skip_reason") == 7, m
+ assert not stub_api.calls
+
+ def test_cap_reads_paths_from_the_repo_root(self, tmp_path, hook_env, stub_api):
+ # A directory above the repo named like a skipped one (build/) must
+ # not make every path look unreviewable.
+ repo = make_repo(tmp_path / "build" / "repo", {"app.py": "x = 1\n"})
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ (repo / "new.py").write_text(VULN_PY)
+ rc, so, se = run_hook(stop_payload(repo), {**hook_env, "MAX_REVIEW_SET_PATHS": "1"})
+ assert metrics_of(so).get("skip_reason") == 8
+ assert not stub_api.calls