summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-10-13 13:46:31 -0700
committerGitHub <noreply@github.com>2026-10-13 20:46:31 +0000
commit8d392c8169665866be1d95f2bfeda5aaae7149dd (patch)
treefe9463366f386249da8a8637c7d4d88095207e05 /plugins
parent99951e9e4678548f90531dfc80be2e95e4618ff0 (diff)
security-guidance: deliver commit and push findings on stderr (#6379)
Commit and push findings went only into hookSpecificOutput.additionalContext, which Claude Code's asyncRewake path never reads: it shows Claude stderr, or stdout when stderr is empty. When the agentic reviewer's inner CLI printed a warning to stderr, Claude got that warning instead of the findings (anthropics/claude-code#99839, also anthropics/claude-code#92987). Findings now go to stderr for every event, as the Stop path already did. The inner CLI's stderr and the Agent SDK's own log lines go to the plugin's debug log.
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/README.md2
-rw-r--r--plugins/security-guidance/hooks/llm.py42
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py90
-rw-r--r--plugins/security-guidance/tests/test_findings_delivery.py87
4 files changed, 163 insertions, 58 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md
index 3e68cf74..518af894 100644
--- a/plugins/security-guidance/README.md
+++ b/plugins/security-guidance/README.md
@@ -98,7 +98,7 @@ Where that data goes depends on your Claude Code configuration:
- **LLM gateway** (`ANTHROPIC_BASE_URL` set): sent to your gateway URL instead, with the headers in `ANTHROPIC_CUSTOM_HEADERS` (except `anthropic-beta`). The gateway operator's terms apply.
- **3rd-party providers** (Bedrock / Vertex / Foundry / Mantle): sent to your configured provider endpoint. The provider's data-handling terms apply (e.g., AWS / GCP / Azure).
-The plugin writes its own debug log to `~/.claude/security/log.txt` (override with `SECURITY_GUIDANCE_DEBUG_LOG`). The log contains diffstate metadata and finding categories — no full file contents or model prompts — and rotates at 1 MB. Nothing is uploaded.
+The plugin writes its own debug log to `~/.claude/security/log.txt` (override with `SECURITY_GUIDANCE_DEBUG_LOG`). The log contains diffstate metadata, finding categories, the Agent SDK's own warnings and errors, and up to 20 lines per review that the agentic reviewer's inner Claude Code prints to stderr — no full file contents or model prompts — and rotates at 1 MB. Nothing is uploaded.
## Limitations
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index 25adfe00..e021c495 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -20,12 +20,14 @@ Two reassignable globals here are read by handlers in
import glob
import hashlib
import json
+import logging
import os
import re
import sys
import tempfile
import threading
import time
+import traceback
import urllib.request
from typing import Optional, Tuple, Dict, Any, List
@@ -609,6 +611,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None)
_record_http_error(-1)
return None
+ _send_sdk_logs_to_debug_log()
cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") or None
default_model = default_review_model()
chosen_model = model or default_model
@@ -1356,6 +1359,32 @@ _FINDINGS_SCHEMA = review_api.FINDINGS_SCHEMA
_SURVIVED_SCHEMA = review_api.SURVIVED_SCHEMA
+class _DebugLogHandler(logging.Handler):
+ def emit(self, record):
+ try:
+ text = record.getMessage()
+ if record.exc_info:
+ text += " | " + "".join(
+ traceback.format_exception_only(*record.exc_info[:2])).strip()
+ except Exception:
+ return # never handleError(): it prints to stderr
+ debug_log(f"agent sdk: {text}")
+
+
+_sdk_log_lock = threading.Lock()
+
+
+def _send_sdk_logs_to_debug_log() -> None:
+ """Route the Agent SDK's own log records to the debug log, and stop them
+ propagating. With no handler, Python prints its errors to this hook's
+ stderr, which Claude Code shows Claude as the review notice."""
+ sdk_logger = logging.getLogger("claude_agent_sdk")
+ with _sdk_log_lock:
+ if not any(isinstance(h, _DebugLogHandler) for h in sdk_logger.handlers):
+ sdk_logger.addHandler(_DebugLogHandler())
+ sdk_logger.propagate = False
+
+
def _agentic_spawn_env() -> Dict[str, str]:
"""opts.env for the SDK-spawned inner `claude` CLI.
@@ -1454,6 +1483,7 @@ def agentic_review(
debug_log(f"agentic_review: SDK unavailable ({e}); falling back")
return None, [], {"agentic_fallback": f"import:{type(e).__name__}"}
+ _send_sdk_logs_to_debug_log()
# Overridable via SG_AGENTIC_MODEL.
model = os.environ.get("SG_AGENTIC_MODEL") or _CLI_OPUS_ALIAS
max_turns = int(os.environ.get("SG_AGENTIC_MAX_TURNS", "18"))
@@ -1538,6 +1568,17 @@ def agentic_review(
except Exception:
pass
+ # Without a callback the inner CLI writes to this hook's stderr, which
+ # Claude Code shows Claude as the review notice. Log it instead.
+ child_stderr_lines = [0]
+
+ def _on_child_stderr(line: str) -> None:
+ child_stderr_lines[0] += 1
+ if child_stderr_lines[0] <= 20:
+ debug_log(f"agentic reviewer's CLI stderr | {str(line).rstrip()}")
+ elif child_stderr_lines[0] == 21:
+ debug_log("agentic reviewer's CLI stderr | (further lines not logged)")
+
async def _arun(system: str, prompt: str, *, schema: Dict[str, Any],
turns: Optional[int] = None
) -> Tuple[Optional[Dict[str, Any]], int, Optional[str]]:
@@ -1594,6 +1635,7 @@ def agentic_review(
# the review run end-to-end; the others are belt-and-suspenders
# for the same fd-passing pattern.
env=_agentic_spawn_env(),
+ stderr=_on_child_stderr,
)
n = 0
structured: Optional[Dict[str, Any]] = None
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index dda5d511..f36cb475 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -228,31 +228,22 @@ def emit_metrics(
task-notification one-liner. Must be in the same JSON line as the metrics
because CC stops scanning stdout after the first {-prefixed line.
- `additional_context` (asyncRewake findings): model-visible guidance text.
- Delivery channel depends on `hook_event_name` because CC's hook-output
- contract is NOT symmetric across events:
-
- - PostToolUse (commit-review, push-sweep): surfaced via the modern
- hookSpecificOutput.additionalContext protocol. `PostToolUse` is a
- member of CC's hookSpecificOutput discriminated union
- (coreSchemas.ts), so the JSON validates and metrics/rewakeSummary
- are consumed. See #1375 / #1783 for why this replaced the legacy
- stderr + exit(2) shape for PostToolUse.
-
- - Stop / SubagentStop: there is NO `Stop` member in that union, so
- emitting hookSpecificOutput{hookEventName:"Stop"} makes the whole
- line fail isSyncHookJSONOutput validation — which on the asyncRewake
- path silently drops metrics AND rewakeSummary, and (because the
- legacy stderr write was removed) leaks the raw JSON to the model as
- the rewake body. CC's asyncRewake delivery actually reads
- `stderr || stdout` for the model-visible body and only scans stdout
- JSON for metrics+rewakeSummary — it never reads additionalContext
- on this path. So for Stop we use the documented clean pattern:
- guidance on stderr, valid JSON (metrics + rewakeSummary +
- top-level decision/reason) on stdout. The top-level decision:"block"
- + reason also covers the sync-fallback path (single-shot `claude -p`,
- where asyncRewake degrades to a sync Stop hook that reads
- decision/reason). See #2159.
+ `additional_context` (asyncRewake findings, exit-2 callers only):
+ model-visible guidance text, written to stderr for every event. CC's
+ asyncRewake delivery reads `stderr || stdout` for the model-visible body
+ and only scans stdout JSON for metrics+rewakeSummary — it never reads
+ additionalContext on this path. stdout keeps one valid JSON line so
+ metrics + rewakeSummary survive:
+
+ - Stop / SubagentStop: also top-level decision:"block" + reason, for
+ the sync-fallback path (single-shot `claude -p`, where asyncRewake
+ degrades to a sync Stop hook that reads decision/reason). There is
+ no `Stop` member in CC's hookSpecificOutput union, so that field
+ must not be used here.
+
+ - PostToolUse (commit-review, push-sweep): stderr only. In the
+ sync-fallback path CC shows the model an exit-2 PostToolUse hook's
+ stderr, so additionalContext would repeat the text.
Empty/None additional_context emits neither channel (back-compat for
metrics-only callers).
@@ -263,8 +254,8 @@ def emit_metrics(
surface; systemMessage adds a per-fire override when the static
rewakeMessage isn't specific enough for the finding being shown.
- `hook_event_name` (used only when additional_context is set): selects the
- delivery channel above. Defaults to "PostToolUse" (commit-review and
+ `hook_event_name` (used only when additional_context is set): whether to
+ add decision/reason as above. Defaults to "PostToolUse" (commit-review and
push-sweep are the most common callers); handle_stop_hook passes "Stop".
"""
head = {}
@@ -277,23 +268,13 @@ def emit_metrics(
if rewake_summary:
out["rewakeSummary"] = rewake_summary
if additional_context:
+ # Guidance on stderr, the asyncRewake body channel (`stderr || stdout`).
+ sys.stderr.write(additional_context)
+ sys.stderr.flush()
if hook_event_name in ("Stop", "SubagentStop"):
- # Stop is NOT in CC's hookSpecificOutput union — emitting it there
- # fails schema validation and drops metrics+rewakeSummary (#2159).
- # Clean pattern: guidance on stderr (the asyncRewake body channel,
- # delivered via `stderr || stdout`), top-level decision/reason for
- # the sync-fallback path. stdout JSON stays valid so metrics +
- # rewakeSummary survive.
- sys.stderr.write(additional_context)
- sys.stderr.flush()
+ # Sync-fallback path for Stop reads decision/reason.
out["decision"] = "block"
out["reason"] = additional_context
- else:
- # PostToolUse et al. — valid union member; modern protocol.
- out["hookSpecificOutput"] = {
- "hookEventName": hook_event_name,
- "additionalContext": additional_context,
- }
if system_message:
out["systemMessage"] = system_message
print(json.dumps(out), flush=True)
@@ -1665,9 +1646,8 @@ def handle_commit_review_posttooluse(input_data):
sev[s] += 1
# Rebuild guidance from new_vulns only — concrete_guidance from the LLM
- # still lists deduped entries. Pass via additional_context so CC surfaces
- # the reason via hookSpecificOutput.additionalContext instead of empty
- # stdout (#1783) / stderr-only "json output validation failed" (#1375).
+ # still lists deduped entries. emit_metrics writes it to stderr, the body
+ # of the asyncRewake notice.
_commit_guidance = (PROVENANCE_BANNER + "\n\n"
+ _format_vulns_guidance(new_vulns)
+ CONTINUATION_SUFFIX + "\n")
@@ -1682,8 +1662,6 @@ def handle_commit_review_posttooluse(input_data):
# exit(2) is preserved per the asyncRewake protocol — it's what CC
# uses as the "force fix" signal that triggers the rewakeMessage flow.
- # The stderr.write was removed; additional_context above now carries
- # the same text via the modern JSON channel. See #1358/#1375/#1783.
sys.exit(2)
def handle_push_sweep_posttooluse(input_data):
@@ -1972,9 +1950,9 @@ def handle_push_sweep_posttooluse(input_data):
# to the per-commit fires for agentic detail). rewake_summary must ride
# this line (CC reads only the first {-prefixed stdout line); the emit
# is deferred to the two exit points below so the with-vulns path can
- # also pass additional_context in the same JSON line (#1375/#1783) —
- # the by-design "CC keeps only the first JSON line" constraint means
- # we can't emit twice. Builds the shared metrics dict here; vulns path
+ # also pass additional_context in the same emit_metrics call — the
+ # by-design "CC keeps only the first JSON line" constraint means we
+ # can't emit twice. Builds the shared metrics dict here; vulns path
# adds additional_context, no-vulns path emits as-is.
_push_metrics = {
**_base, "pushed": len(push_range), "unreviewed": len(tail),
@@ -2040,9 +2018,9 @@ def handle_push_sweep_posttooluse(input_data):
else:
guidance = concrete_guidance or _format_vulns_guidance(reported) or ""
# Emit metrics + additional_context together — single JSON line is the
- # contract CC's hook parser expects. exit(2) preserved as the asyncRewake
- # "force fix" trigger (see comment near handle_commit_review_posttooluse).
- # See #1358 / #1375 / #1783.
+ # contract CC's hook parser expects; the guidance itself goes to stderr.
+ # exit(2) preserved as the asyncRewake "force fix" trigger (see comment
+ # near handle_commit_review_posttooluse).
emit_metrics(_push_metrics, rewake_summary=_push_rewake_summary,
additional_context=(PROVENANCE_BANNER + "\n\n"
+ guidance + CONTINUATION_SUFFIX + "\n"),
@@ -2308,11 +2286,9 @@ def handle_stop_hook(input_data):
# untracked_baseline_n is the signal for whether the UPS-time
# untracked-snapshot capture actually ran.
sweep_trimmed = {k: v for k, v in sweep.items() if k != "warn_unresolved_mask"}
- # Pass guidance via additional_context so CC surfaces the findings via
- # hookSpecificOutput.additionalContext instead of stderr-only (which
- # was the cause of "json output validation failed" / empty-reason UI in
- # #1375 / #1783). exit(2) preserved as the asyncRewake "force fix"
- # signal — that's the documented mechanism. See #1358 / #1375 / #1783.
+ # Guidance goes to stderr plus top-level decision/reason (see
+ # emit_metrics). exit(2) preserved as the asyncRewake "force fix"
+ # signal — that's the documented mechanism.
emit_metrics({
"vulns_found": len(vulns),
"untracked_baseline_n": len(untracked_at_baseline),
diff --git a/plugins/security-guidance/tests/test_findings_delivery.py b/plugins/security-guidance/tests/test_findings_delivery.py
new file mode 100644
index 00000000..b71fc8d6
--- /dev/null
+++ b/plugins/security-guidance/tests/test_findings_delivery.py
@@ -0,0 +1,87 @@
+"""Findings reach Claude on the channel Claude Code reads for an asyncRewake
+hook (`stderr || stdout`, never additionalContext)."""
+import json
+import sys
+import types
+
+from conftest import (
+ STUB_VULN, VULN_PY, bash_payload, commit_file, metrics_of, run_hook,
+)
+
+import llm
+import security_reminder_hook as hook
+
+
+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 TestAgenticReviewerOn:
+ def test_findings_not_replaced_by_the_inner_cli_warning(self, agentic_env, gateway, workspace):
+ _, repo = workspace
+ gateway.vulns = [STUB_VULN]
+ sha, rc, so, se = _commit(repo, agentic_env)
+ assert rc == 2, (so, se)
+ assert metrics_of(so)["agentic_fallback"] == 2
+ body = _rewake_body(so, se)
+ assert "command_injection" in body
+ assert "connectors are disabled" not in body
+ assert "Fatal error in message reader" not in body # the SDK's own log line
+
+
+class TestFindingsReachClaude:
+ def test_commit_findings_are_the_rewake_body(self, env, gateway, workspace):
+ _, repo = workspace
+ gateway.vulns = [STUB_VULN]
+ sha, rc, so, se = _commit(repo, env)
+ assert rc == 2
+ body = _rewake_body(so, se)
+ assert "Security Review: Potential vulnerabilities detected" in body
+ assert "command_injection" in body
+ out = json.loads(so.strip().splitlines()[-1])
+ assert out["metrics"]["vulns_found"] == 1
+ assert out["rewakeSummary"].startswith("Commit security review found")
+ assert "hookSpecificOutput" not in out # not repeated where the sync path would show it twice
+
+ def test_stop_findings_also_go_in_decision_and_reason(self, capsys):
+ hook.emit_metrics({"vulns_found": 1}, additional_context="FINDINGS", hook_event_name="Stop")
+ cap = capsys.readouterr()
+ assert cap.err == "FINDINGS"
+ out = json.loads(cap.out)
+ assert out["decision"] == "block" and out["reason"] == "FINDINGS"
+
+ def test_agentic_review_captures_the_inner_cli_stderr(self, monkeypatch, tmp_path, capfd):
+ spawned = []
+
+ class ClaudeAgentOptions:
+ def __init__(self, **kwargs):
+ self.kwargs = kwargs
+ spawned.append(kwargs)
+
+ class ResultMessage:
+ subtype, usage, total_cost_usd = "success", {}, 0.0
+ structured_output = {"findings": []}
+
+ async def query(prompt, options):
+ # What the inner CLI prints on stderr; with a callback set the SDK
+ # pipes it to the callback instead of the hook's own stderr.
+ options.kwargs["stderr"]("claude.ai connectors are disabled")
+ yield ResultMessage()
+
+ sdk = types.ModuleType("claude_agent_sdk")
+ sdk.ClaudeAgentOptions, sdk.ResultMessage, sdk.query = ClaudeAgentOptions, ResultMessage, query
+ sdk.AssistantMessage = type("AssistantMessage", (), {})
+ monkeypatch.setitem(sys.modules, "claude_agent_sdk", sdk)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "")
+ llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"])
+ assert callable(spawned[0].get("stderr"))
+ assert "connectors" not in capfd.readouterr().err