summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-11-04 20:08:40 +0000
committerClaude <noreply@anthropic.com>2026-11-04 20:08:40 +0000
commit69c35c1f37db93d13dee0513587064fafc40be26 (patch)
tree818a674f08d3e361ca5166cf2000b224152550b8 /plugins
parent18750c0f8aeea95d5c53ab41bb5e427b79582e65 (diff)
security-guidance: end a commit or push review's single-shot review at the hook's time limitmhegazy/sg-agentic-stop-on-auth
A single-shot review that follows a fast agentic failure, or runs with the agentic review off, had no deadline: with no answer it ran 739 s, past Claude Code's 600 s kill, so the session heard nothing. It now ends at 570 s into the hook with the usual notice. The limit counts from hook start, so a push review's wait and the work before the review count. Failed push rows keep inflight_wait_s, and CLAUDE_CODE_REMOTE is read the same way in both places. Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/llm.py8
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py119
-rw-r--r--plugins/security-guidance/tests/test_inflight_reviews.py58
3 files changed, 137 insertions, 48 deletions
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index f1f88427..824ed2a3 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -283,6 +283,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:
@@ -421,7 +425,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():
@@ -2170,7 +2174,7 @@ def _agentic_review(
# 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 os.environ.get("CLAUDE_CODE_REMOTE")):
+ and not _is_remote_session()):
raise _ReviewerAuthFailed(f"{auth_retries} retries after HTTP 401")
else:
# Tool results come back as user messages.
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index f67c181c..17987add 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
@@ -1266,17 +1267,62 @@ def is_commit_review_enabled():
COMMIT_REVIEW_ENABLED = is_commit_review_enabled()
-# Seconds into a commit or push review after which neither side of its race
-# waits for the other any longer; well inside Claude Code's 10-minute hook
-# timeout. Time the hook spent before the race counts.
+_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.
+# 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]],
@@ -1294,13 +1340,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 already waited, comes off the delay and both
+ `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
@@ -1315,7 +1361,7 @@ def _agentic_review_with_race(
return agentic_review(repo_root, diff_files, rel_touched)
delay_s = max(0, int(os.environ.get("SG_AGENTIC_RACE_DELAY_S", "180")) - int(spent_s))
- if 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()
@@ -1341,28 +1387,17 @@ 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()
@@ -1859,7 +1894,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"):
@@ -1873,17 +1908,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
@@ -2300,7 +2331,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, spent_s=_waited,
+ 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"]
@@ -2308,24 +2339,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_inflight_reviews.py b/plugins/security-guidance/tests/test_inflight_reviews.py
index 570f9bd6..fa998501 100644
--- a/plugins/security-guidance/tests/test_inflight_reviews.py
+++ b/plugins/security-guidance/tests/test_inflight_reviews.py
@@ -434,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