summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-10-13 13:33:44 -0700
committerGitHub <noreply@github.com>2026-10-13 13:33:44 -0700
commitd44ca8eb76581bfc5be38cc4c9b7e75be3c22046 (patch)
tree58ebdca083b24bb2b162a75576f64b16e84be7a6 /plugins
parentf359d43b406057f1a8cdbc4ea93b827642c162e6 (diff)
parent3057edc902d79b2ddedd4043c566b0b6dceb4ca3 (diff)
Merge pull request #6375 from anthropics/mhegazy/sg-review-failures
security-guidance: never report a failed review as clean
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/README.md2
-rw-r--r--plugins/security-guidance/hooks/llm.py43
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py236
-rw-r--r--plugins/security-guidance/tests/conftest.py78
-rw-r--r--plugins/security-guidance/tests/test_review_outcomes.py298
5 files changed, 611 insertions, 46 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md
index 58736a85..228fef11 100644
--- a/plugins/security-guidance/README.md
+++ b/plugins/security-guidance/README.md
@@ -108,7 +108,7 @@ This is a best-effort assistive tool, not a guarantee. Treat findings as suggest
**Plugin doesn't seem to fire** — check that `~/.claude/claude-security-guidance.md` (or hook activity) shows in debug logs. Run Claude Code with `--debug-file /tmp/claude/debug.txt` and grep for `security_reminder_hook`. The plugin also writes its own log to `~/.claude/security/log.txt`.
-**Review never finds anything** — verify your API path works. On 3P providers, if you set `SECURITY_REVIEW_MODEL`, check it is a provider-specific id your account can invoke. On LLM gateways, check the gateway's logs for `POST /v1/messages` traffic from the plugin.
+**Review never finds anything** — verify your API path works. When a commit or push review gets no usable answer from the model, Claude is told once per session for each kind of review and failure (for example "Commit security review did not complete: …"), and the reason is logged. If a commit whose review failed is pushed later from Claude Code, the push review checks it. On 3P providers, if you set `SECURITY_REVIEW_MODEL`, check it is a provider-specific id your account can invoke. On LLM gateways, check the gateway's logs for `POST /v1/messages` traffic from the plugin.
**Too many false positives** — set `SECURITY_REVIEW_MODEL` to a cheaper model (`claude-sonnet-5-5`) and re-evaluate; if precision is the priority, stay on the default.
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index 3c1eb5e3..925ba547 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -24,6 +24,7 @@ import os
import re
import sys
import tempfile
+import threading
import time
import urllib.request
from typing import Optional, Tuple, Dict, Any, List
@@ -153,6 +154,24 @@ CLAUDE_CODE_SYSTEM_PROMPT = "You are a Claude agent, built on Anthropic's Claude
# each call. None = no error; int = HTTP status code; -1 = network/timeout;
_last_call_claude_http_error = None
+# Outcome of this thread's last analyze_code_security call. Per thread because
+# the commit review's race runs that call on a thread of its own.
+_review_status = threading.local()
+
+
+def last_review_failed() -> bool:
+ """True when this thread's last analyze_code_security call got no verdict
+ from the model (every call failed, or the reply could not be read), which
+ a caller must not treat as "nothing found"."""
+ return getattr(_review_status, "failed", False)
+
+
+def last_review_status() -> Optional[int]:
+ """A copy of the module-wide _last_call_claude_http_error, taken when this
+ thread's last analyze_code_security call got no verdict (an overlapping call
+ on another thread can change the global); None if the reply was unreadable."""
+ return getattr(_review_status, "status", None)
+
# =====================================================================
# Outbound connectivity probe
@@ -1111,7 +1130,11 @@ def analyze_code_security(files: List[Tuple[str, str]], is_diff: bool = False, p
previous_findings: list of category strings from earlier stop hook firings this turn,
used to prompt the reviewer to verify those issues were actually fixed.
Returns (formatted guidance string or None, list of vuln dicts with severity/category).
+ Also returns (None, []) when the model gave no verdict; last_review_failed()
+ tells the two apart.
"""
+ _review_status.failed = False
+ _review_status.status = None
if not HAS_API_CREDENTIALS or not files:
return None, []
@@ -1229,11 +1252,21 @@ Respond with a JSON object. If vulnerabilities are found, set hasVulnerabilities
}
prompt += extensibility.guidance_block()
- analysis = _call_claude_dual_or(prompt, output_schema,
- bool_key="hasVulnerabilities",
- list_key="vulnerabilities",
- cacheable_prefix=_CODE_REVIEW_RUBRIC)
- if not analysis or not analysis.get("hasVulnerabilities") or not analysis.get("vulnerabilities"):
+ try:
+ analysis = _call_claude_dual_or(prompt, output_schema,
+ bool_key="hasVulnerabilities",
+ list_key="vulnerabilities",
+ cacheable_prefix=_CODE_REVIEW_RUBRIC)
+ except Exception as e:
+ debug_log(f"LLM code review: call raised {type(e).__name__}: {e}")
+ analysis = None
+ # A reply without the schema's required flag is not a verdict either.
+ if not isinstance(analysis, dict) or "hasVulnerabilities" not in analysis:
+ _review_status.failed = True
+ _review_status.status = _last_call_claude_http_error
+ debug_log("LLM code review: no verdict from the model")
+ return None, []
+ if not analysis.get("hasVulnerabilities") or not analysis.get("vulnerabilities"):
debug_log("LLM code review: no vulnerabilities found")
return None, []
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index e8df7a1c..dda5d511 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -893,6 +893,17 @@ def _push_section(bash_output):
section = section[:end]
return section
+def _push_in_output(bash_output):
+ """True when Bash output shows a git push that updated a remote branch."""
+ section = _push_section(bash_output or "")
+ if not section.lstrip("\n").startswith("To "):
+ return False
+ return bool(_PUSH_RANGE_RE.search(section)) or "[new branch]" in section
+
+# Only words the failed-review notice; `gh pr create` alone is not routed to
+# the push review.
+_MAY_PUSH_VIA_GH_RE = re.compile(r"\bgh\s+pr\s+create\b")
+
def _detect_prev_upstream(repo_root, bash_output):
"""Where the remote was BEFORE this push.
@@ -956,6 +967,13 @@ def is_commit_review_enabled():
COMMIT_REVIEW_ENABLED = is_commit_review_enabled()
+# Seconds from the start of a commit or push review's race after which
+# neither side waits for the other any longer; well inside Claude Code's
+# 10-minute hook timeout.
+_RACE_MAX_WAIT_S = 480
+# api_error for a race that hit that deadline with no verdict.
+_RACE_TIMED_OUT = -2
+
def _agentic_review_with_race(
repo_root: str,
diff_files: List[Tuple[str, str]],
@@ -965,8 +983,12 @@ def _agentic_review_with_race(
"""Race the agentic reviewer against a delayed single-shot fallback.
Agentic starts at t=0. After SG_AGENTIC_RACE_DELAY_S (default 180s), the
- single-shot diff reviewer also starts. Whichever finishes first wins. If
- agentic finishes before the delay elapses, the fallback never runs.
+ single-shot diff reviewer also starts. Whichever finishes first wins,
+ except that a single-shot review with no verdict waits for agentic up to
+ _RACE_MAX_WAIT_S from the start, and that if agentic fails after the
+ fallback started, the fallback's result (or, past the deadline, no
+ verdict) is returned so the caller never starts another review. If agentic
+ finishes before the delay, the fallback never runs.
Metrics added:
race_winner : 1 = agentic won, 2 = fallback won (CC accepts only
@@ -974,8 +996,8 @@ def _agentic_review_with_race(
race_delay_s : the configured delay
race_started : 1 if the fallback was actually launched, else 0
- Only the commit-review handler calls this — external harnesses invoke
- agentic_review() directly and are unaffected. SG_AGENTIC_NO_RACE=1
+ Only the commit-review and push-sweep handlers call this — external
+ harnesses invoke agentic_review() directly and are unaffected. SG_AGENTIC_NO_RACE=1
disables the race for any other caller that wants pure agentic.
"""
import queue as _queue
@@ -988,6 +1010,10 @@ def _agentic_review_with_race(
delay_s = int(os.environ.get("SG_AGENTIC_RACE_DELAY_S", "180"))
q: "_queue.Queue[Tuple[str, Any]]" = _queue.Queue(maxsize=1)
fallback_started = _th.Event()
+ fallback_done = _th.Event()
+ agentic_done = _th.Event()
+ fallback_result: Dict[str, Any] = {}
+ deadline = _t.monotonic() + _RACE_MAX_WAIT_S
def _agentic() -> None:
try:
@@ -998,33 +1024,131 @@ def _agentic_review_with_race(
q.put_nowait(("agentic", r))
except _queue.Full:
pass
+ agentic_done.set()
def _fallback() -> None:
_t.sleep(delay_s)
- if not q.empty():
+ if agentic_done.is_set():
return # agentic finished within the delay — never start fallback
fallback_started.set()
+ result = (None, [], {"agentic": False, "review_failed": True, "api_error": None})
try:
g, v = analyze_code_security(
diff_files, is_diff=True, previous_findings=previous_findings
)
- except Exception as e: # pragma: no cover
- g, v = None, []
- try:
- q.put_nowait(("fallback", (g, v, {"agentic": False})))
- except _queue.Full:
+ # Read on this thread: the outcome is per thread.
+ failed = llm.last_review_failed()
+ result = (g, v, {"agentic": False, "review_failed": failed,
+ "api_error": llm.last_review_status() if failed else None})
+ except Exception: # pragma: no cover
pass
+ finally:
+ fallback_result["r"] = result
+ fallback_done.set()
+ if result[2]["review_failed"]:
+ # A failed fallback does not win: the agentic review's inner
+ # CLI may still get a verdict where direct calls cannot.
+ agentic_done.wait(timeout=max(0.0, deadline - _t.monotonic()))
+ try:
+ q.put_nowait(("fallback", result))
+ except _queue.Full:
+ pass
_th.Thread(target=_agentic, daemon=True).start()
_th.Thread(target=_fallback, daemon=True).start()
winner, (g, v, m) = q.get()
+ if winner == "agentic" and m.get("agentic_fallback") and fallback_started.is_set():
+ # The caller would rerun the single-shot review the fallback has
+ # already started; use its result instead.
+ if fallback_done.wait(timeout=max(0.0, deadline - _t.monotonic())):
+ winner, (g, v, m) = "fallback", fallback_result["r"]
+ else:
+ winner, (g, v, m) = "fallback", (None, [], {
+ "agentic": False, "review_failed": True, "api_error": _RACE_TIMED_OUT})
m = dict(m) # don't mutate the callee's metrics dict
m["race_winner"] = 1 if winner == "agentic" else 2
m["race_delay_s"] = delay_s
m["race_started"] = 1 if fallback_started.is_set() else 0
return g, v, m
+def _review_failure_reason(status):
+ """(failure type, reason, likely cause or "") for a review with no verdict.
+
+ `status` is llm.last_review_status(): an HTTP status, -1 for a network
+ error or timeout, None when the reply could not be read; or
+ _RACE_TIMED_OUT.
+ """
+ gateway = (", or an LLM gateway may need its key in ANTHROPIC_CUSTOM_HEADERS"
+ if os.environ.get("ANTHROPIC_BASE_URL") else "")
+ if status == _RACE_TIMED_OUT:
+ return ("timeout", "the review did not finish in time", "")
+ if llm._is_3p_provider():
+ return ("provider", "the review through the cloud provider got no answer",
+ "The plugin's log has the provider's error.")
+ if status == 401:
+ return ("auth", "the API rejected the plugin's credentials (HTTP 401)",
+ f"The sign-in may have expired or been revoked{gateway}.")
+ if status == 403:
+ return ("auth", "the API refused access (HTTP 403)",
+ f"The account may lack access to the review model{gateway}.")
+ if status == 429 or (isinstance(status, int) and status >= 500):
+ return ("busy", f"the API was busy or unavailable (HTTP {status})",
+ "This is usually temporary.")
+ if status == -1:
+ return ("network", "the model could not be reached (network error or timeout)", "")
+ if isinstance(status, int):
+ pinned = os.environ.get("SECURITY_REVIEW_MODEL", "").strip()
+ return ("request", f"the API refused the request (HTTP {status})",
+ f"SECURITY_REVIEW_MODEL ({pinned}) may name a model this account "
+ "cannot use." if pinned else "")
+ return ("reply", "the model's reply could not be read", "")
+
+
+def _exit_review_failed(kind, session_id, metrics, status, pushed="no"):
+ """End a commit ("Commit") or push ("Push") review that got no verdict.
+
+ Never reports the code as clean. Tells Claude once per session for each
+ kind of review and failure; repeats are only logged. `pushed` ("yes",
+ "maybe" or "no"): whether the commit's own command also pushed it. Exits.
+ """
+ failure, reason, cause = _review_failure_reason(status)
+ debug_log(f"{kind} review: got no verdict ({reason}); not marked reviewed")
+ metrics = {"review_failed": True,
+ **({"api_error": status} if status is not None else {}),
+ **metrics, "vulns_found": 0}
+ # A commit its own command pushed gets its own notice: no later push
+ # re-checks it.
+ told_key = f"review_failed:{kind}:{failure}" + (":pushed" if pushed == "yes" else "")
+ if not atomic_check_and_mark_warning(session_id, told_key):
+ emit_metrics(metrics)
+ sys.exit(0)
+ subject = "this push" if kind == "Push" else "this commit"
+ if kind == "Push":
+ after = ("It was for the pushed commits not already reviewed when they "
+ "were committed, and a later push will not re-check them.")
+ elif pushed == "yes":
+ after = "The same command pushed it, so a later push will not re-check it."
+ elif not PUSH_SWEEP_ENABLED:
+ after = ""
+ elif pushed == "maybe":
+ after = ("If the same command pushed it, a later push will not re-check "
+ "it; otherwise a later push from Claude Code will.")
+ else:
+ after = "If it is pushed later from Claude Code, the push review will check it."
+ notice = " ".join(part for part in (
+ f"The security review of {subject} did not complete: {reason}.", cause, after,
+ f"Tell the user this in one sentence, and that details are in {DEBUG_LOG_FILE}.",
+ ) if part)
+ # The notice goes on stderr: Claude Code shows Claude an asyncRewake
+ # hook's stderr, else its stdout, which carries the metrics line.
+ sys.stderr.write(PROVENANCE_BANNER + "\n\n" + notice + "\n")
+ sys.stderr.flush()
+ emit_metrics(metrics,
+ rewake_summary=(f"{kind} security review did not complete: {reason}. "
+ f"Log: {DEBUG_LOG_FILE}"))
+ sys.exit(2)
+
def handle_commit_review_posttooluse(input_data):
"""PostToolUse handler for Bash — reviews git commits for security issues.
@@ -1396,43 +1520,29 @@ def handle_commit_review_posttooluse(input_data):
repo_root, diff_files, rel_touched, previous_findings
)
agentic_metrics.update(_am)
+ review_failed = bool(agentic_metrics.get("review_failed"))
+ api_status = agentic_metrics.get("api_error")
# Fall back to single-shot only on agentic FAILURE (SDK/investigate
# crash). If agentic completed and returned 0 findings, trust that.
if agentic_metrics.get("agentic_fallback"):
concrete_guidance, vulns = analyze_code_security(
diff_files, is_diff=True, previous_findings=previous_findings
)
+ review_failed = llm.last_review_failed()
+ api_status = llm.last_review_status()
else:
concrete_guidance, vulns = analyze_code_security(
diff_files, is_diff=True, previous_findings=previous_findings
)
-
- # push-sweep state: record this commit as reviewed (full 40-hex sha) so a
- # later `git push` can advance its diff base past it. Recorded here — after
- # the review ran but before any exit path — so it's marked regardless of
- # whether findings were emitted. `shas` holds abbreviated refs from
- # `[branch sha]`; resolve to full so set-membership in the push-sweep is
- # exact. Best-effort; failures here never block the review result.
- 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, timeout=5,
- )
- if r.returncode == 0:
- 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
+ review_failed = llm.last_review_failed()
+ api_status = llm.last_review_status()
review_ms = int((_time.time() - review_start) * 1000)
# `survived` is the raw self-refute count BEFORE the high/critical-only
# severity filter; `survived_after_sev` is the count the user actually
# sees. Include `survived_after_sev` ONLY when the filter actually
# dropped candidates — otherwise it's redundant with `survived` and eats
- # into CC's 10-key emit cap, pushing files_reviewed/review_ms out of the
+ # into CC's metric-key cap, pushing files_reviewed/review_ms out of the
# emitted metrics.
#
# CC accepts only booleans and finite numbers as metric values.
@@ -1468,6 +1578,36 @@ def handle_commit_review_posttooluse(input_data):
else {}
)
+ if review_failed:
+ # Not marked reviewed, so a later push review from Claude Code still
+ # covers it.
+ _exit_review_failed("Commit", session_id, {
+ **_base, **_agentic_m,
+ "files_reviewed": len(diff_files), "review_ms": review_ms,
+ }, api_status, pushed=(
+ "yes" if _push_in_output(bash_output)
+ else "maybe" if _GIT_PUSH_RE.search(command) or _MAY_PUSH_VIA_GH_RE.search(command)
+ else "no"))
+
+ # push-sweep state: record this commit as reviewed (full 40-hex sha) so a
+ # later `git push` can advance its diff base past it. Recorded only after a
+ # review that got a verdict, whether or not it found anything. `shas` holds abbreviated refs from
+ # `[branch sha]`; resolve to full so set-membership in the push-sweep is
+ # exact. Best-effort; failures here never block the review result.
+ 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, timeout=5,
+ )
+ if r.returncode == 0:
+ 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
+
if not concrete_guidance:
debug_log("Commit review: no security issues found")
emit_metrics({
@@ -1796,16 +1936,29 @@ def handle_push_sweep_posttooluse(input_data):
concrete_guidance, vulns, agentic_metrics = _agentic_review_with_race(
repo_root, diff_files, rel_touched, previous_findings
)
+ review_failed = bool(agentic_metrics.get("review_failed"))
+ api_status = agentic_metrics.get("api_error")
if agentic_metrics.get("agentic_fallback"):
concrete_guidance, vulns = analyze_code_security(
diff_files, is_diff=True, previous_findings=previous_findings
)
+ review_failed = llm.last_review_failed()
+ api_status = llm.last_review_status()
else:
concrete_guidance, vulns = analyze_code_security(
diff_files, is_diff=True, previous_findings=previous_findings
)
+ review_failed = llm.last_review_failed()
+ api_status = llm.last_review_status()
agentic_metrics = {}
review_ms = int((_time.time() - review_start) * 1000)
+ if review_failed:
+ # Not marked reviewed. A later push does not re-check these commits:
+ # its range starts from the new upstream.
+ _exit_review_failed("Push", session_id, {
+ **_base, "pushed": len(push_range), "unreviewed": len(tail),
+ "files_reviewed": len(diff_files), "review_ms": review_ms,
+ }, api_status)
# The tail is now covered by this net-diff review.
_append_reviewed_shas(repo_root, tail, vulns_found=len(vulns or []))
@@ -1814,7 +1967,7 @@ def handle_push_sweep_posttooluse(input_data):
session_id, vulns or [], prompted=_finding_keys(previous_findings)
)
- # Metrics — keep within the 10-key cap; agentic sub-metrics are dropped
+ # Metrics — keep within CC's metric-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); the emit
@@ -2180,20 +2333,23 @@ def handle_stop_hook(input_data):
hook_event_name=hook_event_name)
sys.exit(2)
- if llm._last_call_claude_http_error is not None:
- debug_log(f"Stop hook: API call failed with status {llm._last_call_claude_http_error}")
+ stop_review_failed = llm.last_review_failed()
+ if stop_review_failed:
+ debug_log(f"Stop hook: review got no verdict "
+ f"({_review_failure_reason(llm.last_review_status())[1]})")
restore_unreviewed_stop_state(session_id, touched_paths, snap_baseline)
else:
debug_log("Stop hook: no security issues found")
if is_subagent:
record_reviewed_diff(session_id, diff_hash)
- # CC truncates metrics to 10 keys by
- # insertion order. The previous **sweep,**v2_metrics tail meant the 3
- # v2_metrics keys were always sliced off this most-common path, so the
- # diff-strategy diagnostics never reached telemetry. Drop sweep here (it's
- # PostToolUse-warning state, orthogonal to diff-strategy comparison).
- # 6 base + optional api_error + 3 v2_metrics = ≤10.
+ # CC keeps the first 20 metric keys (10 in older versions), in insertion
+ # order, after the pv and usage keys emit_metrics puts first. The previous
+ # **sweep,**v2_metrics tail meant the 3 v2_metrics keys were always sliced
+ # off this most-common path, so the diff-strategy diagnostics never reached
+ # telemetry. Drop sweep here (it's PostToolUse-warning state, orthogonal to
+ # diff-strategy comparison).
emit_metrics({
+ **({"review_failed": True} if stop_review_failed else {}),
"vulns_found": 0,
"diff_strategy_v2": True,
"files_reviewed": len(diff_files),
diff --git a/plugins/security-guidance/tests/conftest.py b/plugins/security-guidance/tests/conftest.py
index 2cf4dd1c..11af0273 100644
--- a/plugins/security-guidance/tests/conftest.py
+++ b/plugins/security-guidance/tests/conftest.py
@@ -212,3 +212,81 @@ def ups_payload(cwd, session_id="s1"):
"prompt": "hi",
"cwd": str(cwd),
}
+
+
+# ── a local Anthropic-compatible endpoint the hook can be pointed at ──────
+
+class _Gateway(http.server.BaseHTTPRequestHandler):
+ """An Anthropic-compatible endpoint. With `required` set it answers 401
+ unless that header arrives, like a LiteLLM proxy keyed on a custom header."""
+
+ def _handle(self):
+ n = int(self.headers.get("Content-Length") or 0)
+ if n:
+ self.rfile.read(n)
+ srv = self.server
+ srv.requests.append((self.command, self.path, {k.lower(): v for k, v in self.headers.items()}))
+ name, value = srv.required or (None, None)
+ if name and self.headers.get(name) != value:
+ return self._send(401, {"type": "error", "error": {
+ "type": "authentication_error", "message": "Invalid proxy server token"}})
+ if srv.status != 200:
+ return self._send(srv.status, {"type": "error", "error": {"type": "api_error"}})
+ if self.command == "GET":
+ return self._send(200, {"data": [{"id": "claude-opus-5-5"}], "has_more": False})
+ text = (srv.reply if srv.reply is not None else json.dumps(
+ {"hasVulnerabilities": bool(srv.vulns), "vulnerabilities": srv.vulns}))
+ self._send(200, {
+ "id": "msg_stub", "type": "message", "role": "assistant",
+ "model": "stub", "stop_reason": "end_turn",
+ "content": [{"type": "text", "text": text}],
+ "usage": {"input_tokens": 1, "output_tokens": 1},
+ })
+
+ do_GET = do_POST = do_HEAD = _handle
+
+ def _send(self, status, payload):
+ body = json.dumps(payload).encode()
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *a):
+ pass
+
+
+@pytest.fixture
+def gateway():
+ srv = http.server.HTTPServer(("127.0.0.1", 0), _Gateway)
+ srv.requests, srv.required, srv.status, srv.reply, srv.vulns = [], None, 200, None, []
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ try:
+ yield srv
+ finally:
+ srv.shutdown()
+
+
+@pytest.fixture
+def env(hook_env, gateway):
+ e = dict(hook_env)
+ e["ANTHROPIC_BASE_URL"] = f"http://127.0.0.1:{gateway.server_port}"
+ e.pop("SECURITY_REVIEW_MODEL", None)
+ return e
+
+
+@pytest.fixture
+def failing_inner_cli(tmp_path):
+ """An inner CLI that prints a warning on stderr and exits 1; the review
+ then falls back to a single-shot call."""
+ cli = tmp_path / "claude"
+ cli.write_text("#!/bin/sh\necho 'claude.ai connectors are disabled' >&2\nexit 1\n")
+ cli.chmod(0o755)
+ return str(cli)
+
+
+@pytest.fixture
+def agentic_env(env, failing_inner_cli):
+ pytest.importorskip("claude_agent_sdk")
+ return {**env, "SG_AGENTIC_COMMIT_REVIEW": "1", "SG_AGENTIC_CLI_PATH": failing_inner_cli}
diff --git a/plugins/security-guidance/tests/test_review_outcomes.py b/plugins/security-guidance/tests/test_review_outcomes.py
new file mode 100644
index 00000000..887ff9c0
--- /dev/null
+++ b/plugins/security-guidance/tests/test_review_outcomes.py
@@ -0,0 +1,298 @@
+"""A review that got no verdict is never reported as clean."""
+import json
+import time
+
+import pytest
+
+from conftest import (
+ STUB_VULN, VULN_PY, bash_payload, commit_file, edit_payload, git,
+ metrics_of, run_hook, stop_payload, ups_payload,
+)
+
+import llm
+import security_reminder_hook as hook
+
+
+def _reviewed(repo):
+ p = repo / ".git" / "sg-reviewed-shas"
+ return p.read_text() if p.exists() else ""
+
+
+def _rewake_body(stdout, stderr):
+ """What Claude Code shows Claude for an exit-2 asyncRewake hook: stderr,
+ else stdout."""
+ return stderr or stdout
+
+
+def _commit(repo, env, content=VULN_PY, session_id="s1"):
+ sha, out = commit_file(repo, "app.py", content)
+ rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out,
+ session_id=session_id), env)
+ return sha, rc, so, se
+
+
+class TestFailedReviewIsNotClean:
+ def test_commit_left_unreviewed_and_user_told(self, env, gateway, workspace):
+ _, repo = workspace
+ gateway.status = 401
+ sha, rc, so, se = _commit(repo, env)
+ m = metrics_of(so)
+ assert m["review_failed"] is True and m["api_error"] == 401 and m["vulns_found"] == 0
+ assert sha not in _reviewed(repo)
+ assert rc == 2
+ body = _rewake_body(so, se)
+ assert ("The security review of this commit did not complete: "
+ "the API rejected the plugin's credentials (HTTP 401).") in body
+ assert "ANTHROPIC_CUSTOM_HEADERS" in body # ANTHROPIC_BASE_URL is set
+ assert "If it is pushed later from Claude Code, the push review will check it." in body
+ assert "log.txt" in body
+ summary = json.loads(so.strip().splitlines()[-1])["rewakeSummary"]
+ assert summary.startswith("Commit security review did not complete: "
+ "the API rejected the plugin's credentials (HTTP 401). Log: ")
+
+ def test_commit_pushed_by_the_same_command(self, env, gateway, workspace):
+ """The push hook does not run for `git commit && git push`, so no later
+ push review covers this commit."""
+ _, repo = workspace
+ gateway.status = 401
+ sha, out = commit_file(repo, "app.py", VULN_PY)
+ out += f"To /srv/remote.git\n 1111111..{sha[:7]} main -> main\n"
+ rc, so, se = run_hook(bash_payload(repo, "git commit -m change && git push", out), env)
+ assert rc == 2
+ assert "The same command pushed it, so a later push will not re-check it." in se
+ assert "If it is pushed later" not in se
+
+ @pytest.mark.parametrize("command", [
+ 'git commit -m "retry git push on 403"', # push only in the message
+ "git commit -m change && git push", # push rejected or output hidden
+ ])
+ def test_push_in_the_command_without_push_output(self, env, gateway, workspace, command):
+ _, repo = workspace
+ gateway.status = 401
+ sha, out = commit_file(repo, "app.py", VULN_PY)
+ rc, so, se = run_hook(bash_payload(repo, command, out), env)
+ assert rc == 2
+ assert "The same command pushed it" not in se
+ assert ("If the same command pushed it, a later push will not re-check it; "
+ "otherwise a later push from Claude Code will.") in se
+
+ def test_told_once_per_session_for_each_kind_of_failure(self, env, gateway, workspace):
+ _, repo = workspace
+ gateway.status = 401
+ _commit(repo, env)
+ sha2, rc, so, se = _commit(repo, env, VULN_PY + "# 2\n")
+ assert rc == 0 and se == ""
+ assert metrics_of(so)["review_failed"] is True
+ assert sha2 not in _reviewed(repo)
+ gateway.status = 503 # a different kind of failure is still told
+ sha3, rc, so, se = _commit(repo, env, VULN_PY + "# 3\n")
+ assert rc == 2 and "busy or unavailable (HTTP 503)" in se
+ assert sha3 not in _reviewed(repo)
+
+ def test_unreadable_reply_is_a_failed_review(self, env, gateway, workspace):
+ _, repo = workspace
+ gateway.reply = "I can't help with that."
+ sha, rc, so, se = _commit(repo, env)
+ assert metrics_of(so)["review_failed"] is True
+ assert sha not in _reviewed(repo)
+
+ def test_reply_without_the_verdict_flag_is_a_failed_review(self, env, gateway, workspace):
+ _, repo = workspace
+ gateway.reply = json.dumps({"findings": []})
+ sha, rc, so, se = _commit(repo, env)
+ assert metrics_of(so)["review_failed"] is True
+ assert sha not in _reviewed(repo)
+
+ def test_unexpected_error_in_the_call_is_a_failed_review(self, monkeypatch):
+ def boom(*a, **k):
+ raise ConnectionResetError("dropped")
+ monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True)
+ monkeypatch.setattr(llm, "_call_claude_dual_or", boom)
+ assert llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True) == (None, [])
+ assert llm.last_review_failed()
+
+ def test_pushed_commit_is_told_after_an_unpushed_one(self, env, gateway, workspace):
+ _, repo = workspace
+ gateway.status = 401
+ _commit(repo, env)
+ sha, out = commit_file(repo, "app.py", VULN_PY + "# 2\n")
+ out += "To github.com:o/r.git\n 1111111..2222222 main -> main\n"
+ rc, so, se = run_hook(bash_payload(repo, "git commit -am x && git push", out), env)
+ assert rc == 2 and "The same command pushed it" in se
+
+ def test_clean_review_still_marks_the_commit(self, env, gateway, workspace):
+ _, repo = workspace
+ sha, rc, so, se = _commit(repo, env)
+ m = metrics_of(so)
+ assert rc == 0 and "review_failed" not in m and m["vulns_found"] == 0
+ assert sha in _reviewed(repo)
+
+ def test_push_sweep_leaves_the_range_unreviewed(self, env, gateway, workspace, tmp_path):
+ """Also told after a commit review failed the same way: a failed push
+ review is not re-checked later, so it has its own notice."""
+ ws, repo = workspace
+ remote = tmp_path / "remote.git"
+ git(ws, "init", "-q", "--bare", str(remote))
+ git(repo, "remote", "add", "origin", str(remote))
+ git(repo, "push", "-q", "-u", "origin", "main")
+ base = git(repo, "rev-parse", "HEAD").strip()
+ gateway.status = 401
+ sha, rc, so, se = _commit(repo, env)
+ assert rc == 2
+ git(repo, "push", "-q", "origin", "main")
+ push_stdout = f"To {remote}\n {base[:7]}..{sha[:7]} main -> main\n"
+ rc, so, se = run_hook(bash_payload(repo, "git push origin main", push_stdout), env)
+ m = metrics_of(so)
+ assert m["push_sweep"] is True and m["review_failed"] is True, m
+ assert sha not in _reviewed(repo)
+ assert rc == 2
+ assert "The security review of this push did not complete" in se
+ assert ("It was for the pushed commits not already reviewed when they were "
+ "committed, and a later push will not re-check them.") in se
+
+ def test_subagent_review_failure_keeps_the_diff_unreviewed(self, env, gateway, workspace):
+ """A SubagentStop review that finds nothing records its diff as
+ reviewed; one that got no verdict must not, or it is never retried."""
+ _, repo = workspace
+ gateway.reply = "not json"
+ run_hook(ups_payload(repo), env)
+ (repo / "app.py").write_text(VULN_PY)
+ run_hook(edit_payload(repo, repo / "app.py", VULN_PY), env)
+ rc, so, se = run_hook(stop_payload(repo, event="SubagentStop"), env)
+ assert rc == 0, (so, se)
+ gateway.reply, gateway.vulns = None, [STUB_VULN]
+ rc, so, se = run_hook(stop_payload(repo, event="SubagentStop"), env)
+ assert rc == 2 and "command_injection" in se, (so, se)
+
+ @pytest.fixture
+ def race(self, monkeypatch):
+ """Runs the race with the fallback starting at once; agentic_review
+ and the single-shot review are stand-ins."""
+ calls = []
+ monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "0")
+ monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False)
+
+ def failing_single_shot(*a, **k):
+ calls.append("single_shot")
+ llm._review_status.failed = True
+ return None, []
+
+ monkeypatch.setattr(hook, "analyze_code_security", failing_single_shot)
+
+ def run(agentic):
+ monkeypatch.setattr(hook, "agentic_review", agentic)
+ llm._review_status.failed = False
+ result = hook._agentic_review_with_race("/nonexistent", [("a.py", "+x")], ["a.py"], [])
+ assert llm.last_review_failed() is False # the flag stays on its own thread
+ return result
+ run.calls = calls
+ return run
+
+ def test_failed_fallback_waits_for_agentic(self, race):
+ """Direct calls can fail where the agentic reviewer's CLI works (it
+ may hold a credential the direct calls lack); its verdict must count."""
+ def slow_agentic(*a, **k):
+ time.sleep(1)
+ return None, [], {"agentic": True}
+
+ g, v, m = race(slow_agentic)
+ assert m["race_winner"] == 1 and not m.get("review_failed")
+
+ def test_both_failing_reports_the_fallback_once(self, race):
+ def failing_agentic(*a, **k):
+ time.sleep(1)
+ return None, [], {"agentic_fallback": "investigate:ProcessError"}
+
+ g, v, m = race(failing_agentic)
+ assert m["race_winner"] == 2 and m["review_failed"] is True
+ assert "agentic_fallback" not in m # the caller must not rerun it
+ assert race.calls == ["single_shot"]
+
+ def test_no_fallback_after_agentic_finished(self, race, monkeypatch):
+ """Once agentic has answered, the delayed fallback never starts, even
+ after the caller has taken agentic's result off the queue."""
+ monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "1")
+
+ def quick_failing_agentic(*a, **k):
+ return None, [], {"agentic_fallback": "investigate:ProcessError"}
+
+ g, v, m = race(quick_failing_agentic)
+ assert m["race_winner"] == 1
+ time.sleep(1.5)
+ assert race.calls == []
+
+ def test_agentic_failing_while_the_fallback_overruns(self, race, monkeypatch):
+ """Past the deadline the race reports no verdict instead of letting the
+ caller start yet another review."""
+ monkeypatch.setattr(hook, "_RACE_MAX_WAIT_S", 2)
+
+ def slow_single_shot(*a, **k):
+ race.calls.append("single_shot")
+ time.sleep(10)
+ return None, []
+
+ monkeypatch.setattr(hook, "analyze_code_security", slow_single_shot)
+
+ def failing_agentic(*a, **k):
+ time.sleep(0.5)
+ return None, [], {"agentic_fallback": "investigate:ProcessError"}
+
+ t0 = time.monotonic()
+ g, v, m = race(failing_agentic)
+ assert time.monotonic() - t0 < 5
+ assert m["review_failed"] is True and m["api_error"] == hook._RACE_TIMED_OUT
+ assert "agentic_fallback" not in m
+ assert hook._review_failure_reason(m["api_error"])[1] == "the review did not finish in time"
+
+ def test_failed_fallback_stops_waiting_at_the_deadline(self, race, monkeypatch):
+ monkeypatch.setattr(hook, "_RACE_MAX_WAIT_S", 1)
+
+ def hung_agentic(*a, **k):
+ time.sleep(30)
+
+ g, v, m = race(hung_agentic)
+ assert m["race_winner"] == 2 and m["review_failed"] is True
+
+
+class TestFailureReason:
+ @pytest.mark.parametrize("status,failure,reason", [
+ (401, "auth", "the API rejected the plugin's credentials (HTTP 401)"),
+ (403, "auth", "the API refused access (HTTP 403)"),
+ (529, "busy", "the API was busy or unavailable (HTTP 529)"),
+ (-1, "network", "the model could not be reached (network error or timeout)"),
+ (404, "request", "the API refused the request (HTTP 404)"),
+ (None, "reply", "the model's reply could not be read"),
+ ])
+ def test_first_party(self, monkeypatch, status, failure, reason):
+ for var in llm._PROVIDER_ENV_VARS:
+ monkeypatch.delenv(var, raising=False)
+ assert hook._review_failure_reason(status)[:2] == (failure, reason)
+
+ def test_cloud_provider(self, monkeypatch):
+ monkeypatch.setenv("CLAUDE_CODE_USE_BEDROCK", "1")
+ for status in (-1, None):
+ assert hook._review_failure_reason(status)[:2] == (
+ "provider", "the review through the cloud provider got no answer")
+
+ def test_causes_name_only_settings_in_use(self, monkeypatch):
+ for var in llm._PROVIDER_ENV_VARS:
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)
+ monkeypatch.delenv("SECURITY_REVIEW_MODEL", raising=False)
+ assert "ANTHROPIC_CUSTOM_HEADERS" not in hook._review_failure_reason(401)[2]
+ assert hook._review_failure_reason(404)[2] == ""
+ monkeypatch.setenv("ANTHROPIC_BASE_URL", "http://gateway")
+ monkeypatch.setenv("SECURITY_REVIEW_MODEL", "claude-x")
+ assert "ANTHROPIC_CUSTOM_HEADERS" in hook._review_failure_reason(401)[2]
+ assert "SECURITY_REVIEW_MODEL (claude-x)" in hook._review_failure_reason(404)[2]
+
+
+class TestAgenticReviewerOn:
+ def test_failed_review_is_not_clean(self, agentic_env, gateway, workspace):
+ _, repo = workspace
+ gateway.status = 401
+ sha, rc, so, se = _commit(repo, agentic_env)
+ m = metrics_of(so)
+ assert m["review_failed"] is True and m["agentic_fallback"] == 2, m
+ assert sha not in _reviewed(repo)
+ assert rc == 2 and "HTTP 401" in se