summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-11-05 14:28:20 -0800
committerGitHub <noreply@github.com>2026-11-05 14:28:20 -0800
commiteba976de6eed86f916e2c3ccd6f176faf19c3bc7 (patch)
tree86843a325f1cae49ae38b2d0cf43b5e1e3d01f34 /plugins
parent0672a295389aa640fb0544ef03a768ac37b30daa (diff)
parent69c35c1f37db93d13dee0513587064fafc40be26 (diff)
Merge pull request #6965 from anthropics/mhegazy/sg-agentic-stop-on-auth
security-guidance: stop the commit reviewer on refused credentials, end hung reviews in time
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/llm.py110
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py137
-rw-r--r--plugins/security-guidance/tests/test_agentic_auth_stop.py148
-rw-r--r--plugins/security-guidance/tests/test_inflight_reviews.py116
-rw-r--r--plugins/security-guidance/tests/test_review_outcomes.py20
5 files changed, 446 insertions, 85 deletions
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index 53602119..c0a878f4 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -17,6 +17,7 @@ Two reassignable globals here are read by handlers in
``_last_review_truncated_bytes``. Handlers reference them as ``llm.X`` (not via
``from``-import) so they observe reassignment.
"""
+import contextlib
import hashlib
import json
import logging
@@ -285,6 +286,10 @@ def _urlopen(request, timeout):
return urllib.request.urlopen(request, timeout=timeout, context=_store_tls_context)
+def _is_remote_session() -> bool:
+ return os.environ.get("CLAUDE_CODE_REMOTE", "").lower() in ("1", "true", "yes", "on")
+
+
def _probe_anthropic(timeout: float = 5.0) -> bool:
req = urllib.request.Request(_anthropic_base_url() + "/", method="HEAD")
try:
@@ -423,7 +428,7 @@ def ensure_anthropic_reachable() -> bool:
global _anthropic_reachable
if _anthropic_reachable is not None:
return _anthropic_reachable
- if os.environ.get("CLAUDE_CODE_REMOTE", "").lower() not in ("1", "true", "yes", "on"):
+ if not _is_remote_session():
_anthropic_reachable = True
return True
if _probe_anthropic():
@@ -1080,9 +1085,8 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None,
_record_usage(getattr(msg, "usage", None) or {}, chosen_model,
cost_usd=getattr(msg, "total_cost_usd", None))
elif getattr(msg, "subtype", None) == "api_retry":
- data = getattr(msg, "data", None)
- status = data.get("error_status") if isinstance(data, dict) else None
- _retried_after.add(str(status) if isinstance(status, int) else "no response")
+ status = _api_retry_status(msg)
+ _retried_after.add(str(status) if status is not None else "no response")
return structured
# 60s ceiling: a single review request on a healthy 3P endpoint completes
@@ -1939,6 +1943,23 @@ def _run_inner_cli(start: Callable[[], Any], stderr_lines: List[str]) -> Any:
"starting it again without")
+class _ReviewerAuthFailed(Exception):
+ """The agentic reviewer's credentials were refused; retrying cannot help."""
+
+
+# Retry notices in a row, each after a 401, at which the review stops. One is
+# normal: the CLI renews a stored login after a 401 and tries again. Not used
+# in a remote session, where the CLI waits out a short sign-in outage on purpose.
+_AGENTIC_MAX_401_RETRIES = 3
+
+
+def _api_retry_status(msg: Any) -> Optional[int]:
+ """The HTTP status of the CLI's api_retry notice, if it gives one."""
+ data = getattr(msg, "data", None)
+ status = data.get("error_status") if isinstance(data, dict) else None
+ return status if isinstance(status, int) else None
+
+
def _agentic_spawn_env() -> Dict[str, str]:
"""opts.env for the SDK-spawned inner `claude` CLI.
@@ -2220,39 +2241,54 @@ def _agentic_review(
# Blocks are matched by shape so older SDK builds need no extra import.
file_tool_ids = set()
- async for msg in query(prompt=_once(), options=opts):
- if isinstance(msg, AssistantMessage):
- n += 1
- for b in getattr(msg, "content", None) or []:
- if (getattr(b, "name", None) in _REVIEWER_FILE_TOOLS
- and getattr(b, "id", None)):
- file_tool_ids.add(b.id)
- ctx["rv_tool_calls"] += 1
- elif isinstance(msg, ResultMessage):
- subtype = msg.subtype
- if msg.structured_output is not None:
- structured = msg.structured_output
- # SDK ResultMessage carries aggregate usage + cache-aware
- # cost across the whole multi-turn run; prefer its cost over
- # the price-table estimate. getattr guards older SDK builds.
- _record_usage(getattr(msg, "usage", None) or {}, model,
- cost_usd=getattr(msg, "total_cost_usd", None))
- for key, attr in (("rv_turns", "num_turns"), ("rv_api_ms", "duration_api_ms")):
- value = getattr(msg, attr, None)
- # Counting must never fail the review: anything that
- # is not a positive finite number adds nothing.
- if (isinstance(value, (int, float)) and not isinstance(value, bool)
- and 0 < value < float("inf")):
- ctx[key] += int(value)
- else:
- # Tool results come back as user messages.
- content = getattr(msg, "content", None)
- if isinstance(content, list):
- ctx["rv_tool_err"] += sum(
- 1 for b in content
- if getattr(b, "is_error", None) is True
- and getattr(b, "tool_use_id", None) in file_tool_ids
- )
+ auth_retries = 0
+ # Closed on the way out, also on a raise, so the CLI stops with the review.
+ async with contextlib.aclosing(query(prompt=_once(), options=opts)) as messages:
+ async for msg in messages:
+ if isinstance(msg, AssistantMessage):
+ # Old CLIs answer each refused request by asking the model
+ # again, hundreds of times; the message is the same on all.
+ if getattr(msg, "error", None) == "authentication_failed":
+ raise _ReviewerAuthFailed("authentication_failed")
+ auth_retries = 0
+ n += 1
+ for b in getattr(msg, "content", None) or []:
+ if (getattr(b, "name", None) in _REVIEWER_FILE_TOOLS
+ and getattr(b, "id", None)):
+ file_tool_ids.add(b.id)
+ ctx["rv_tool_calls"] += 1
+ elif isinstance(msg, ResultMessage):
+ subtype = msg.subtype
+ if msg.structured_output is not None:
+ structured = msg.structured_output
+ # SDK ResultMessage carries aggregate usage + cache-aware
+ # cost across the whole multi-turn run; prefer its cost over
+ # the price-table estimate. getattr guards older SDK builds.
+ _record_usage(getattr(msg, "usage", None) or {}, model,
+ cost_usd=getattr(msg, "total_cost_usd", None))
+ for key, attr in (("rv_turns", "num_turns"), ("rv_api_ms", "duration_api_ms")):
+ value = getattr(msg, attr, None)
+ # Counting must never fail the review: anything that
+ # is not a positive finite number adds nothing.
+ if (isinstance(value, (int, float)) and not isinstance(value, bool)
+ and 0 < value < float("inf")):
+ ctx[key] += int(value)
+ elif getattr(msg, "subtype", None) == "api_retry":
+ # A gateway's 401 without the API's x-should-retry: false
+ # keeps the CLI retrying for about three minutes.
+ auth_retries = auth_retries + 1 if _api_retry_status(msg) == 401 else 0
+ if (auth_retries >= _AGENTIC_MAX_401_RETRIES
+ and not _is_remote_session()):
+ raise _ReviewerAuthFailed(f"{auth_retries} retries after HTTP 401")
+ else:
+ # Tool results come back as user messages.
+ content = getattr(msg, "content", None)
+ if isinstance(content, list):
+ ctx["rv_tool_err"] += sum(
+ 1 for b in content
+ if getattr(b, "is_error", None) is True
+ and getattr(b, "tool_use_id", None) in file_tool_ids
+ )
return structured, n, subtype
def _run(system: str, prompt: str, *, schema: Dict[str, Any]
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index a42c0665..7c84357f 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -68,6 +68,7 @@ import re
import subprocess
import sys
import threading
+import time
import urllib.request
from datetime import datetime
from enum import IntEnum
@@ -1318,18 +1319,68 @@ 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.
+_HOOK_STARTED = time.monotonic()
+
+# Seconds into the hook after which neither side of a commit or push review's
+# race waits for the other any longer; well inside Claude Code's 10-minute hook
+# timeout.
_RACE_MAX_WAIT_S = 480
+# Seconds after which the review ends even if a side is still waiting on a
+# request that does not answer, with time left to tell the session before
+# Claude Code kills the hook. The inner CLI exits with the hook. The same limit
+# holds for a commit or push review's single-shot review outside a race.
+_RACE_END_S = 570
# api_error for a race that hit that deadline with no verdict.
_RACE_TIMED_OUT = -2
+def _hook_spent_s() -> float:
+ return time.monotonic() - _HOOK_STARTED
+
+def _single_shot_review(
+ diff_files: List[Tuple[str, str]],
+ previous_findings: List[Dict[str, Any]],
+) -> Tuple[Optional[str], List[Dict[str, Any]], Dict[str, Any]]:
+ """A single-shot review as (guidance, vulns, metrics); failures are in the
+ metrics, not raised."""
+ try:
+ g, v = analyze_code_security(
+ diff_files, is_diff=True, previous_findings=previous_findings
+ )
+ # Read on this thread: the outcome is per thread.
+ failed = llm.last_review_failed()
+ return g, v, {"agentic": False, "review_failed": failed,
+ "api_error": llm.last_review_status() if failed else None}
+ except Exception as e:
+ debug_log(f"single-shot review crashed: {type(e).__name__}: {e}")
+ return None, [], {"agentic": False, "review_failed": True, "api_error": None}
+
+def _single_shot_review_in_time(
+ diff_files: List[Tuple[str, str]],
+ previous_findings: List[Dict[str, Any]],
+) -> Tuple[Optional[str], List[Dict[str, Any]], bool, Optional[int]]:
+ """A single-shot review outside a race, as (guidance, vulns, failed, status).
+
+ It ends at _RACE_END_S into the hook, whatever is pending.
+ """
+ done: List[Any] = []
+ worker = threading.Thread(
+ target=lambda: done.append(_single_shot_review(diff_files, previous_findings)),
+ daemon=True,
+ )
+ worker.start()
+ worker.join(timeout=max(0.0, _RACE_END_S - _hook_spent_s()))
+ if not done:
+ debug_log("single-shot review: nothing returned in time")
+ return None, [], True, _RACE_TIMED_OUT
+ g, v, m = done[0]
+ return g, v, m["review_failed"], m["api_error"]
+
def _agentic_review_with_race(
repo_root: str,
diff_files: List[Tuple[str, str]],
rel_touched: List[str],
previous_findings: List[Dict[str, Any]],
+ spent_s: float = 0.0,
) -> Tuple[Optional[str], List[Dict[str, Any]], Dict[str, Any]]:
"""Race the agentic reviewer against a delayed single-shot fallback.
@@ -1341,10 +1392,13 @@ def _agentic_review_with_race(
verdict) is returned so the caller never starts another review. If agentic
finishes before the delay, the fallback never runs.
+ `spent_s`, the time the hook has already run, comes off the delay and both
+ limits: the hook's time limit does not restart with the race.
+
Metrics added:
race_winner : 1 = agentic won, 2 = fallback won (CC accepts only
bool/finite-number metric values — strings would discard the dict)
- race_delay_s : the configured delay
+ race_delay_s : the delay used
race_started : 1 if the fallback was actually launched, else 0
Only the commit-review and push-sweep handlers call this — external
@@ -1358,13 +1412,16 @@ def _agentic_review_with_race(
if os.environ.get("SG_AGENTIC_NO_RACE") == "1":
return agentic_review(repo_root, diff_files, rel_touched)
- delay_s = int(os.environ.get("SG_AGENTIC_RACE_DELAY_S", "180"))
+ delay_s = max(0, int(os.environ.get("SG_AGENTIC_RACE_DELAY_S", "180")) - int(spent_s))
+ if spent_s >= 1:
+ debug_log(f"Review race: {spent_s:.0f}s already spent, fallback starts after {delay_s}s")
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
+ deadline = _t.monotonic() + max(0.0, _RACE_MAX_WAIT_S - spent_s)
+ timed_out = (None, [], {"agentic": False, "review_failed": True, "api_error": _RACE_TIMED_OUT})
def _agentic() -> None:
try:
@@ -1382,33 +1439,26 @@ def _agentic_review_with_race(
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})
+ result = _single_shot_review(diff_files, previous_findings)
+ 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:
- g, v = analyze_code_security(
- diff_files, is_diff=True, previous_findings=previous_findings
- )
- # 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
+ q.put_nowait(("fallback", result))
+ except _queue.Full:
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()
+ try:
+ winner, (g, v, m) = q.get(timeout=max(0.0, _RACE_END_S - spent_s))
+ except _queue.Empty:
+ debug_log("review race: nothing returned in time")
+ winner, (g, v, m) = "fallback", timed_out
# What the agentic run saw of its directory, and how much work it did,
# is kept when the fallback's result replaces it below.
reviewer_context = (
@@ -1421,8 +1471,7 @@ def _agentic_review_with_race(
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})
+ winner, (g, v, m) = "fallback", timed_out
m = {**m, **reviewer_context} # a copy: don't mutate the callee's metrics dict
m["race_winner"] = 1 if winner == "agentic" else 2
m["race_delay_s"] = delay_s
@@ -1935,7 +1984,7 @@ def handle_commit_review_posttooluse(input_data):
if _agentic_commit_review_enabled():
rel_touched = [fp for fp, _ in diff_files]
concrete_guidance, vulns, _am = _agentic_review_with_race(
- repo_root, diff_files, rel_touched, previous_findings
+ repo_root, diff_files, rel_touched, previous_findings, spent_s=_hook_spent_s()
)
agentic_metrics.update(_am)
if _am.get("child_stderr"):
@@ -1949,17 +1998,13 @@ def handle_commit_review_posttooluse(input_data):
# 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
+ concrete_guidance, vulns, review_failed, api_status = _single_shot_review_in_time(
+ diff_files, 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
+ concrete_guidance, vulns, review_failed, api_status = _single_shot_review_in_time(
+ diff_files, previous_findings
)
- 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
@@ -2376,7 +2421,7 @@ def handle_push_sweep_posttooluse(input_data):
rel_touched = [fp for fp, _ in diff_files]
if _agentic_commit_review_enabled():
concrete_guidance, vulns, agentic_metrics = _agentic_review_with_race(
- repo_root, diff_files, rel_touched, previous_findings
+ repo_root, diff_files, rel_touched, previous_findings, spent_s=_hook_spent_s(),
)
if agentic_metrics.get("child_stderr"):
_TAIL_METRICS["child_stderr"] = agentic_metrics["child_stderr"]
@@ -2384,24 +2429,20 @@ def handle_push_sweep_posttooluse(input_data):
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
+ concrete_guidance, vulns, review_failed, api_status = _single_shot_review_in_time(
+ diff_files, 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
+ concrete_guidance, vulns, review_failed, api_status = _single_shot_review_in_time(
+ diff_files, 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),
+ **_base, **_wait_m, "pushed": len(push_range), "unreviewed": len(tail),
"files_reviewed": len(diff_files), "review_ms": review_ms,
}, api_status)
diff --git a/plugins/security-guidance/tests/test_agentic_auth_stop.py b/plugins/security-guidance/tests/test_agentic_auth_stop.py
new file mode 100644
index 00000000..a2108cfc
--- /dev/null
+++ b/plugins/security-guidance/tests/test_agentic_auth_stop.py
@@ -0,0 +1,148 @@
+"""The agentic reviewer stops as soon as its credentials are refused, instead
+of waiting for the inner CLI to give up, and leaves every other run alone."""
+import os
+import subprocess
+import sys
+import types
+
+import pytest
+
+import llm
+from conftest import write_cli
+
+
+class _Assistant:
+ def __init__(self, error=None):
+ self.content, self.error = [], error
+
+
+class _System:
+ subtype = "api_retry"
+
+ def __init__(self, status):
+ self.data = {"error_status": status}
+
+
+@pytest.fixture
+def sdk(monkeypatch, tmp_path):
+ """Replays `script.messages`, then a clean result, and counts what the
+ review read of them."""
+ script = types.SimpleNamespace(messages=[], read=0)
+
+ class ClaudeAgentOptions:
+ def __init__(self, **kwargs):
+ self.kwargs = kwargs
+
+ class ResultMessage:
+ subtype, usage, total_cost_usd = "success", {}, 0.0
+ structured_output = {"findings": []}
+
+ async def query(prompt, options):
+ for m in script.messages:
+ script.read += 1
+ yield m
+ yield ResultMessage()
+
+ mod = types.ModuleType("claude_agent_sdk")
+ mod.ClaudeAgentOptions, mod.ResultMessage, mod.query = ClaudeAgentOptions, ResultMessage, query
+ mod.AssistantMessage = _Assistant
+ monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "")
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state"))
+ monkeypatch.delenv("CLAUDE_CODE_REMOTE", raising=False)
+ return script
+
+
+def _review(repo):
+ return llm.agentic_review(str(repo), [("a.py", "+x = 1\n")], ["a.py"])[2]
+
+
+class TestStopsOnRefusedCredentials:
+ def test_first_auth_failure_ends_the_review(self, sdk, tmp_path):
+ sdk.messages = [_Assistant(error="authentication_failed") for _ in range(50)]
+ m = _review(tmp_path)
+ assert sdk.read == 1
+ assert m["agentic_fallback"] == "investigate:_ReviewerAuthFailed"
+
+ def test_repeated_401_retries_end_the_review(self, sdk, tmp_path):
+ sdk.messages = [_System(401) for _ in range(10)]
+ m = _review(tmp_path)
+ assert sdk.read == llm._AGENTIC_MAX_401_RETRIES
+ assert m["agentic_fallback"] == "investigate:_ReviewerAuthFailed"
+
+
+class TestLeavesOtherRunsAlone:
+ def test_a_remote_session_rides_out_401_retries(self, sdk, tmp_path, monkeypatch):
+ monkeypatch.setenv("CLAUDE_CODE_REMOTE", "true")
+ sdk.messages = [_System(401) for _ in range(10)]
+ assert "agentic_fallback" not in _review(tmp_path)
+
+ def test_a_login_renewed_after_one_401_goes_on(self, sdk, tmp_path):
+ sdk.messages = [_System(401), _Assistant()]
+ assert "agentic_fallback" not in _review(tmp_path)
+
+ def test_401s_that_are_not_in_a_row_do_not_add_up(self, sdk, tmp_path):
+ sdk.messages = [_System(401), _System(401), _Assistant()] * 3
+ assert "agentic_fallback" not in _review(tmp_path)
+
+ def test_other_retries_do_not_count(self, sdk, tmp_path):
+ sdk.messages = [_System(s) for s in (529, 429, None, 500, 529, 529)]
+ assert "agentic_fallback" not in _review(tmp_path)
+
+ def test_other_assistant_errors_do_not_stop_it(self, sdk, tmp_path):
+ sdk.messages = [_Assistant(error="rate_limit"), _Assistant(error="server_error")]
+ assert "agentic_fallback" not in _review(tmp_path)
+
+ def test_a_message_without_the_field_is_read_as_before(self, sdk, tmp_path):
+ class Old:
+ content = []
+ sys.modules["claude_agent_sdk"].AssistantMessage = Old
+ sdk.messages = [Old()]
+ assert "agentic_fallback" not in _review(tmp_path)
+
+
+_REFUSED_CLI = """
+import json, os, sys, time
+open(os.environ["SG_TEST_PID_FILE"], "w").write(str(os.getpid()))
+def send(m):
+ sys.stdout.write(json.dumps(m) + chr(10)); sys.stdout.flush()
+for line in sys.stdin:
+ m = json.loads(line)
+ if m.get("type") == "control_request":
+ send({"type": "control_response", "response": {"subtype": "success",
+ "request_id": m["request_id"], "response": {}}})
+ elif m.get("type") == "user":
+ for _ in range(500):
+ send({"type": "assistant", "error": "authentication_failed", "message": {
+ "role": "assistant", "model": "m", "content": [{"type": "text", "text": "401"}]}})
+ time.sleep(0.02)
+ time.sleep(60)
+"""
+
+_DRIVER = """
+import json, llm, os, sys, time
+start = time.time()
+metrics = llm.agentic_review(sys.argv[1], [("a.py", "+x = 1")], ["a.py"])[2]
+pid = int(open(os.environ["SG_TEST_PID_FILE"]).read())
+try:
+ os.kill(pid, 0); alive = True
+except OSError:
+ alive = False
+print(json.dumps({"fallback": metrics.get("agentic_fallback"), "alive": alive}), flush=True)
+os._exit(0)
+"""
+
+
+def test_real_sdk_closes_the_cli_quietly(tmp_path):
+ """Stops the real SDK's child, and prints no traceback for the hook's
+ stderr, which reaches the session."""
+ pytest.importorskip("claude_agent_sdk")
+ env = {**os.environ, "SG_TEST_PID_FILE": str(tmp_path / "pid"),
+ "SG_AGENTIC_CLI_PATH": str(write_cli(tmp_path, "claude", _REFUSED_CLI)),
+ "SECURITY_WARNINGS_STATE_DIR": str(tmp_path / "state"),
+ "PYTHONPATH": str(os.path.dirname(llm.__file__))}
+ r = subprocess.run([sys.executable, "-c", _DRIVER, str(tmp_path)], env=env,
+ capture_output=True, text=True, timeout=60)
+ assert "Traceback" not in r.stderr, r.stderr
+ assert '"fallback": "investigate:_ReviewerAuthFailed"' in r.stdout, (r.stdout, r.stderr)
+ assert '"alive": false' in r.stdout, r.stdout
diff --git a/plugins/security-guidance/tests/test_inflight_reviews.py b/plugins/security-guidance/tests/test_inflight_reviews.py
index 4c339a5f..fa998501 100644
--- a/plugins/security-guidance/tests/test_inflight_reviews.py
+++ b/plugins/security-guidance/tests/test_inflight_reviews.py
@@ -4,6 +4,7 @@ import json
import os
import subprocess
import sys
+import threading
import time
import pytest
@@ -152,6 +153,63 @@ def test_push_stops_waiting_after_the_limit(tmp_path, hook_env, stub_api):
assert len(_reviews(stub_api)) == 1
+def test_a_push_that_waited_ends_within_the_hook_limit(tmp_path, monkeypatch):
+ """The wait for a commit review and the race share one limit; a race that
+ restarts it runs the hook past Claude Code's timeout, with no notice."""
+ import security_reminder_hook as hook
+
+ repo, remote = _repo_with_remote(tmp_path)
+ _, sha, _, _ = _commit_and_push(repo, remote)
+ monkeypatch.setattr(hook, "_RACE_MAX_WAIT_S", 1.0)
+ monkeypatch.setattr(hook, "_RACE_END_S", 1.5)
+ monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False)
+ monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "0")
+ release = threading.Event()
+ monkeypatch.setattr(hook, "agentic_review", lambda *a, **k: release.wait(20))
+ monkeypatch.setattr(hook, "analyze_code_security", lambda *a, **k: release.wait(20))
+
+ started = time.monotonic()
+ try:
+ with _held_by_another_review(repo, sha):
+ _, waited = diffstate._reviewed_after_inflight(str(repo), [sha], 1.0, poll_s=0.05)
+ _, _, m = hook._agentic_review_with_race(
+ str(repo), [], [], [], spent_s=waited)
+ finally:
+ release.set()
+ assert 1.0 <= waited < 1.5
+ assert 1.5 <= time.monotonic() - started < 2.4
+ assert m["review_failed"] is True and m["api_error"] == hook._RACE_TIMED_OUT
+
+
+def test_the_push_handler_counts_its_wait(tmp_path, agentic_env, stub_api):
+ repo, remote = _repo_with_remote(tmp_path)
+ _, sha, _, push_out = _commit_and_push(repo, remote)
+ log = tmp_path / "race.log"
+ env = {**agentic_env, "SG_INFLIGHT_WAIT_S": "2", "SG_AGENTIC_RACE_DELAY_S": "60",
+ "SECURITY_GUIDANCE_DEBUG_LOG": str(log)}
+ with _held_by_another_review(repo, sha):
+ _, so, _ = run_hook(bash_payload(repo, "git push origin main", push_out), env)
+ assert metrics_of(so)["inflight_wait_s"] >= 2
+ assert "already spent, fallback starts after 5" in log.read_text()
+
+
+def test_the_fallback_starts_sooner_after_a_wait(tmp_path, monkeypatch):
+ import security_reminder_hook as hook
+
+ monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False)
+ monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "180")
+ release = threading.Event()
+ monkeypatch.setattr(hook, "agentic_review", lambda *a, **k: release.wait(20))
+ monkeypatch.setattr(hook, "analyze_code_security", lambda *a, **k: ("guidance", []))
+ monkeypatch.setattr(hook.llm, "last_review_failed", lambda: False)
+ try:
+ g, _, m = hook._agentic_review_with_race(str(tmp_path), [], [], [], spent_s=240.0)
+ finally:
+ release.set()
+ assert g == "guidance"
+ assert (m["race_winner"], m["race_delay_s"], m["race_started"]) == (2, 0, 1)
+
+
def test_push_does_not_wait_when_an_earlier_commit_needs_review_anyway(tmp_path, hook_env, stub_api):
repo, remote = _repo_with_remote(tmp_path)
base = git(repo, "rev-parse", "HEAD").strip()
@@ -376,3 +434,61 @@ def test_windows_lock_is_off_where_the_call_is_missing(monkeypatch):
monkeypatch.setattr(diffstate, "_win_lock_file_ex", None)
with pytest.raises(OSError):
diffstate._win_lock_nb(7, exclusive=True)
+
+
+_SHORT_LIMIT = (
+ "import sys\n"
+ "sys.path.insert(0, sys.argv[1])\n"
+ "import security_reminder_hook as hook\n"
+ "hook._RACE_END_S = float(sys.argv[2])\n"
+ "hook.main()\n"
+)
+
+
+def _run_with_limit(payload, env, limit_s):
+ started = time.monotonic()
+ r = subprocess.run(
+ [sys.executable, "-c", _SHORT_LIMIT, _HOOKS_DIR, str(limit_s)],
+ input=json.dumps(payload), capture_output=True, text=True, env=env, timeout=30)
+ return time.monotonic() - started, r
+
+
+def test_single_shot_after_a_fast_agentic_failure_ends_in_time(
+ tmp_path, hook_env, failing_inner_cli, stub_api):
+ """The agentic run fails before the fallback starts, and the single-shot
+ review that follows hangs: the session still hears before the hook limit."""
+ pytest.importorskip("claude_agent_sdk")
+ repo, _ = _repo_with_remote(tmp_path)
+ _, commit_out = commit_file(repo, "handlers.py", "def h(x):\n return x\n")
+ stub_api.delay = 6
+ env = {**hook_env, "SG_AGENTIC_COMMIT_REVIEW": "1", "SG_AGENTIC_CLI_PATH": failing_inner_cli,
+ "SG_AGENTIC_RACE_DELAY_S": "60"}
+ took, r = _run_with_limit(bash_payload(repo, "git commit -m change", commit_out), env, 4)
+ assert 4 <= took < 10, r.stderr
+ assert r.returncode == 2 and "did not finish in time" in r.stderr
+ assert metrics_of(r.stdout)["agentic_fallback"] == 2
+
+
+def test_single_shot_after_a_push_wait_ends_in_time(
+ tmp_path, hook_env, failing_inner_cli, stub_api):
+ pytest.importorskip("claude_agent_sdk")
+ repo, remote = _repo_with_remote(tmp_path)
+ _, sha, _, push_out = _commit_and_push(repo, remote)
+ stub_api.delay = 10
+ env = {**hook_env, "SG_AGENTIC_COMMIT_REVIEW": "1", "SG_AGENTIC_CLI_PATH": failing_inner_cli,
+ "SG_INFLIGHT_WAIT_S": "4", "SG_AGENTIC_RACE_DELAY_S": "60"}
+ with _held_by_another_review(repo, sha):
+ took, r = _run_with_limit(bash_payload(repo, "git push origin main", push_out), env, 8)
+ assert 8 <= took < 11.5, r.stderr # 12 s if the wait did not count
+ assert r.returncode == 2 and "did not finish in time" in r.stderr
+ assert metrics_of(r.stdout)["inflight_wait_s"] >= 4
+
+
+def test_single_shot_with_the_agentic_review_off_ends_in_time(tmp_path, hook_env, stub_api):
+ repo, _ = _repo_with_remote(tmp_path)
+ _, commit_out = commit_file(repo, "handlers.py", "def h(x):\n return x\n")
+ stub_api.delay = 6
+ env = {**hook_env, "SG_AGENTIC_COMMIT_REVIEW": "0"}
+ took, r = _run_with_limit(bash_payload(repo, "git commit -m change", commit_out), env, 4)
+ assert 4 <= took < 10, r.stderr
+ assert r.returncode == 2 and "did not finish in time" in r.stderr
diff --git a/plugins/security-guidance/tests/test_review_outcomes.py b/plugins/security-guidance/tests/test_review_outcomes.py
index 887ff9c0..806e9bdd 100644
--- a/plugins/security-guidance/tests/test_review_outcomes.py
+++ b/plugins/security-guidance/tests/test_review_outcomes.py
@@ -1,5 +1,6 @@
"""A review that got no verdict is never reported as clean."""
import json
+import threading
import time
import pytest
@@ -188,6 +189,25 @@ class TestFailedReviewIsNotClean:
run.calls = calls
return run
+ def test_review_ends_when_neither_side_returns(self, race, monkeypatch):
+ """A request that never answers holds both sides; the deadline holds anyway."""
+ monkeypatch.setattr(hook, "_RACE_MAX_WAIT_S", 0.1)
+ monkeypatch.setattr(hook, "_RACE_END_S", 0.2)
+ release = threading.Event()
+ monkeypatch.setattr(hook, "analyze_code_security", lambda *a, **k: release.wait(5))
+
+ def stuck_agentic(*a, **k):
+ release.wait(5)
+ started = time.monotonic()
+ try:
+ guidance, vulns, m = race(stuck_agentic)
+ finally:
+ release.set()
+ assert time.monotonic() - started < 2
+ assert (guidance, vulns) == (None, [])
+ assert m["review_failed"] is True
+ assert m["api_error"] == hook._RACE_TIMED_OUT
+
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."""