summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/hooks/llm.py
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-13 21:39:36 +0000
committerClaude <noreply@anthropic.com>2026-10-15 21:57:22 +0000
commitb0dcb447d8989a6eaefc79df9b83f5b2811cff75 (patch)
tree1e647d187d4d9b4ddb2fe0239ff1d08bb54615fa /plugins/security-guidance/hooks/llm.py
parent83e004a98e1fc268a94cc6a74b1b054630542696 (diff)
security-guidance: report commit reviewer context in review telemetrymhegazy/sg-reviewer-context-telemetry
Count-only keys on agentic review rows: Read/Grep/Glob calls made, how many came back as errors, and whether the reviewer's directory was missing before or during the review. Appended last in the row so they never displace an existing key.
Diffstat (limited to 'plugins/security-guidance/hooks/llm.py')
-rw-r--r--plugins/security-guidance/hooks/llm.py53
1 files changed, 51 insertions, 2 deletions
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index 3f7607c6..21279426 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -1452,13 +1452,46 @@ def _agentic_spawn_env() -> Dict[str, str]:
return env
+# The tools the agentic reviewer is given to look around the repo.
+_REVIEWER_FILE_TOOLS = ("Read", "Grep", "Glob")
+
+
+def _agentic_context_dir(repo_dir: str) -> str:
+ """The directory the agentic reviewer runs in."""
+ return os.environ.get("SG_AGENTIC_CONTEXT_DIR") or repo_dir
+
+
def agentic_review(
repo_dir: str, diff_files: List[Tuple[str, str]], touched_paths: List[str],
) -> Tuple[Optional[str], List[Dict[str, Any]], Dict[str, Any]]:
+ """Run the two-stage agentic review (_agentic_review) and add reviewer
+ context diagnostics to its metrics. Counts only, no paths:
+
+ rv_cwd_gone 1 = the directory the reviewer runs in was missing
+ before the review, 2 = it went missing during it
+ rv_tool_err Read/Grep/Glob calls that came back as errors
+ rv_tool_calls Read/Grep/Glob calls made
+
+ The counts cover all stages of the review. Keys are left out when 0."""
+ context_dir = _agentic_context_dir(repo_dir)
+ gone = 0 if os.path.isdir(context_dir) else 1
+ ctx = {"rv_tool_err": 0, "rv_tool_calls": 0}
+ guidance, vulns, metrics = _agentic_review(repo_dir, diff_files, touched_paths, ctx)
+ if not gone and not os.path.isdir(context_dir):
+ gone = 2
+ ctx_m = {"rv_cwd_gone": gone, **ctx}
+ return guidance, vulns, {**metrics, **{k: v for k, v in ctx_m.items() if v}}
+
+
+def _agentic_review(
+ repo_dir: str, diff_files: List[Tuple[str, str]], touched_paths: List[str],
+ ctx: Dict[str, int],
+) -> Tuple[Optional[str], List[Dict[str, Any]], Dict[str, Any]]:
"""Two-stage Agent-SDK review: investigate (Read/Grep/Glob over the repo)
then a self-refute filter pass. Returns (guidance_or_None, vulns,
metrics). On SDK unavailability returns (None, [], {"agentic_fallback":
- reason}) so the caller can fall back to the single-shot path."""
+ reason}) so the caller can fall back to the single-shot path. Adds to
+ the `ctx` counters (see agentic_review) as the reviewer makes tool calls."""
import time as _t
# Note: do NOT pop ANTHROPIC_AUTH_TOKEN from os.environ here. The race
@@ -1510,7 +1543,7 @@ def agentic_review(
# eval harness it's a temp dir with ONLY touched_paths — the agent can't
# trace cross-file data flow. The harness sets SG_AGENTIC_CONTEXT_DIR to a
# full repo (worktree at the commit, or the live clone at HEAD).
- context_dir = os.environ.get("SG_AGENTIC_CONTEXT_DIR") or repo_dir
+ context_dir = _agentic_context_dir(repo_dir)
context_note = ""
if context_dir != repo_dir:
context_note = (
@@ -1675,9 +1708,16 @@ def agentic_review(
yield {"type": "user",
"message": {"role": "user", "content": prompt}}
+ # 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:
@@ -1687,6 +1727,15 @@ def agentic_review(
# 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))
+ 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]