diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-15 22:04:43 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-19 16:29:37 +0000 |
| commit | cb1743691acefa86ca04fb567260f984a6dddf77 (patch) | |
| tree | d6e1ddcf5de1958ef7e8c5793be6efcbbfddaf2d /plugins | |
| parent | ea10b213686c90bb1984b2016937310e05336cf3 (diff) | |
security-guidance: do not save review runs as session transcripts
The agentic commit reviewer and reviews on 3rd-party providers run an
inner Claude Code through the Agent SDK, which saved each run as a
session transcript holding the review prompt and diff. Start it with
--no-session-persistence; SECURITY_GUIDANCE_PERSIST_SESSIONS=1 keeps the
transcripts. An inner CLI that predates the flag is run again without it.
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/README.md | 5 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 58 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_review_session_persistence.py | 125 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_reviewer_tools.py | 7 |
4 files changed, 188 insertions, 7 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md index b8a67ed4..fe97f479 100644 --- a/plugins/security-guidance/README.md +++ b/plugins/security-guidance/README.md @@ -57,6 +57,7 @@ SECURITY_REVIEW_MODEL=claude-opus-5-5 | `ENABLE_CODE_SECURITY_REVIEW=0` | on | Disable all LLM reviews (Stop hook + commit/push) | | `ENABLE_STOP_REVIEW=0` | on | Disable only the Stop-hook diff review, keeping commit/push reviews. Useful for multi-agent / shared-worktree setups where another agent can move HEAD between a worker's turns | | `ENABLE_COMMIT_REVIEW=0` | on | Disable layer 3 (agentic commit review) | +| `SECURITY_GUIDANCE_PERSIST_SESSIONS=1` | unset | Keep the reviewer's own Claude Code runs as session transcripts (see [Privacy and data handling](#privacy-and-data-handling)) | ### Hook output for other hosts @@ -108,6 +109,8 @@ Where that data goes depends on your Claude Code configuration: 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. +The agentic commit reviewer, and every review on a 3rd-party provider, runs an inner Claude Code through the Agent SDK. The plugin starts it with `--no-session-persistence`, so these runs are not saved as session transcripts under `~/.claude/projects/`. Set `SECURITY_GUIDANCE_PERSIST_SESSIONS=1` to keep them, for example to debug a review; a saved transcript contains the full review prompt, including diff hunks, and is removed by Claude Code's normal session cleanup (`cleanupPeriodDays`). A Claude Code older than 2.0.63 does not have the flag; the review then runs without it and is saved as before. + ### Review usage and cost The LLM reviews use your API path, so they cost tokens (or subscription usage) on top of your own session. The default reviewer is the newest Opus model. On the Anthropic API path the diff review on Stop calls the API directly, so it does not appear in Claude Code's own cost figures or transcripts. After each review the plugin writes one line to its debug log: @@ -131,6 +134,8 @@ 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`. +**Looking into one commit review** — set `SECURITY_GUIDANCE_PERSIST_SESSIONS=1` before the run; the reviewer's prompt, tool calls and answer are then kept as session transcripts under `~/.claude/projects/`. + **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 9fe8640c..6a20a08d 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -640,12 +640,16 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None) # of just "exit code 1". _captured_stderr: List[str] = [] + def _on_stderr(line: str) -> None: + _note_reviewer_stderr(line) + _captured_stderr.append(line) + async def _arun(): opts = ClaudeAgentOptions( system_prompt=CLAUDE_CODE_SYSTEM_PROMPT, cli_path=cli_path, allowed_tools=[], - extra_args=_only_tools_args(), + extra_args={**_only_tools_args(), **_reviewer_session_args()}, setting_sources=[], max_turns=2, model=chosen_model, @@ -657,7 +661,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None) default_model if chosen_model != default_model else None ), env=_agentic_spawn_env(), - stderr=lambda l: _captured_stderr.append(l), + stderr=_on_stderr, ) async def _once(): @@ -679,7 +683,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None) # comes). Bound the wait so a misconfigured 3P session doesn't stall the # whole hook. try: - result = _asyncio.run(_asyncio.wait_for(_arun(), timeout=60)) + result = _run_reviewer(lambda: _asyncio.wait_for(_arun(), timeout=60)) if _captured_stderr: debug_log(f"3P sdk-single-turn child stderr ({len(_captured_stderr)} lines):") for _l in _captured_stderr[:20]: @@ -1405,6 +1409,48 @@ def _send_sdk_logs_to_debug_log() -> None: sdk_logger.propagate = False +_SESSION_FLAG = "no-session-persistence" +# Set when an inner CLI that predates the flag rejects it at startup. +_session_flag_rejected = False + + +def _reviewer_session_args() -> Dict[str, Optional[str]]: + """Extra CLI flags for the SDK-spawned inner `claude`. + + Review runs are one-shot and never resumed, so by default the inner CLI + is told not to save them as session transcripts (they hold the full + review prompt, including diff hunks). SECURITY_GUIDANCE_PERSIST_SESSIONS=1 + keeps the transcripts, e.g. to debug a review. + """ + keep = os.environ.get("SECURITY_GUIDANCE_PERSIST_SESSIONS", "").strip().lower() + if _session_flag_rejected or keep in ("1", "on", "true", "yes"): + return {} + return {_SESSION_FLAG: None} + + +def _note_reviewer_stderr(line: object) -> None: + global _session_flag_rejected + text = str(line) + if _SESSION_FLAG in text and "unknown option" in text.lower(): + _session_flag_rejected = True + + +def _run_reviewer(make_coro: Any) -> Any: + """asyncio.run(make_coro()); when the inner CLI turns out to predate + --no-session-persistence, run once more without the flag so the review + still happens.""" + import asyncio as _asyncio + rejected_before = _session_flag_rejected + try: + return _asyncio.run(make_coro()) + except Exception: + if rejected_before or not _session_flag_rejected: + raise + debug_log("reviewer's CLI does not know --no-session-persistence; " + "running without it") + return _asyncio.run(make_coro()) + + # The agentic reviewer reads a diff it must not trust, so it gets # file-reading tools and nothing else. _REVIEWER_TOOLS = ("Read", "Grep", "Glob") @@ -1646,6 +1692,7 @@ def _agentic_review( return {"child_stderr": child_stderr_lines[0]} if child_stderr_lines[0] else {} def _on_child_stderr(line: str) -> None: + _note_reviewer_stderr(line) child_stderr_lines[0] += 1 metrics["child_stderr"] = child_stderr_lines[0] if child_stderr_lines[0] <= 20: @@ -1667,7 +1714,8 @@ def _agentic_review( # Pre-approved, and the only tools the reviewer has: no # permission mode can then let it write, run or fetch anything. allowed_tools=list(_REVIEWER_TOOLS), - extra_args=_only_tools_args(_REVIEWER_TOOLS), + extra_args={**_only_tools_args(_REVIEWER_TOOLS), + **_reviewer_session_args()}, setting_sources=[], max_turns=turns if turns is not None else max_turns, model=model, @@ -1756,7 +1804,7 @@ def _agentic_review( def _run(system: str, prompt: str, *, schema: Dict[str, Any] ) -> Tuple[Optional[Dict[str, Any]], int, Optional[str]]: - return _asyncio.run(_arun(system, prompt, schema=schema)) + return _run_reviewer(lambda: _arun(system, prompt, schema=schema)) # Stage 1: investigate — SDK enforces _FINDINGS_SCHEMA and retries the # agent on mismatch, so `inv` is either a validated dict or None. diff --git a/plugins/security-guidance/tests/test_review_session_persistence.py b/plugins/security-guidance/tests/test_review_session_persistence.py new file mode 100644 index 00000000..51e6e74f --- /dev/null +++ b/plugins/security-guidance/tests/test_review_session_persistence.py @@ -0,0 +1,125 @@ +"""Review runs through the Agent SDK are not saved as Claude Code session +transcripts unless SECURITY_GUIDANCE_PERSIST_SESSIONS is set.""" +import subprocess +import sys + +import pytest + +from conftest import ( + HOOKS_DIR, STUB_VULN, VULN_PY, bash_payload, commit_file, run_hook, +) + +import llm + +FLAG = "--no-session-persistence" +SINGLE_TURN = ( + "import sys; sys.path.insert(0, sys.argv[1]); import llm, review_api; " + "llm._call_claude_via_sdk('review', review_api.FINDINGS_SCHEMA)" +) + + +def _stub_cli(tmp_path, reject_flag=False): + """An inner CLI that records each launch's arguments on one line and + exits 1. With reject_flag it first refuses the flag the way a Claude Code + older than the flag does.""" + log = tmp_path / "inner-cli-launches" + reject = ( + f'case " $* " in *" {FLAG} "*) ' + f'echo "error: unknown option \'{FLAG}\'" >&2; exit 1;; esac\n' + ) if reject_flag else "" + cli = tmp_path / "claude" + cli.write_text(f'#!/bin/sh\necho "$*" >> "{log}"\n{reject}exit 1\n') + cli.chmod(0o755) + return str(cli), log + + +def _reviews(log): + """Argument lines of the review launches (the SDK also probes `-v`).""" + return [l for l in log.read_text().splitlines() if "--input-format" in l] + + +@pytest.fixture +def sdk_env(env): + pytest.importorskip("claude_agent_sdk") + e = {**env, "SG_AGENTIC_COMMIT_REVIEW": "1"} + e.pop("SECURITY_GUIDANCE_PERSIST_SESSIONS", None) + return e + + +def _commit(repo, env): + _, out = commit_file(repo, "app.py", VULN_PY) + return run_hook(bash_payload(repo, "git commit -m change", out), env) + + +def _single_turn(env): + subprocess.run([sys.executable, "-c", SINGLE_TURN, str(HOOKS_DIR)], + env=env, capture_output=True, text=True, timeout=120) + + +class TestSessionArgs: + @pytest.mark.parametrize("value", [None, "", "0", "off"]) + def test_not_saved_by_default(self, monkeypatch, value): + monkeypatch.setattr(llm, "_session_flag_rejected", False) + if value is None: + monkeypatch.delenv("SECURITY_GUIDANCE_PERSIST_SESSIONS", raising=False) + else: + monkeypatch.setenv("SECURITY_GUIDANCE_PERSIST_SESSIONS", value) + assert llm._reviewer_session_args() == {"no-session-persistence": None} + + @pytest.mark.parametrize("value", ["1", " on ", "TRUE", "yes"]) + def test_opt_in_keeps_sessions(self, monkeypatch, value): + monkeypatch.setattr(llm, "_session_flag_rejected", False) + monkeypatch.setenv("SECURITY_GUIDANCE_PERSIST_SESSIONS", value) + assert llm._reviewer_session_args() == {} + + def test_only_a_rejection_of_this_flag_counts(self, monkeypatch): + monkeypatch.setattr(llm, "_session_flag_rejected", False) + llm._note_reviewer_stderr("error: unknown option '--other'") + assert llm._session_flag_rejected is False + llm._note_reviewer_stderr(f"error: unknown option '{FLAG}'") + assert llm._session_flag_rejected is True + + +class TestInnerCliArguments: + def test_commit_reviewer_gets_the_flag(self, sdk_env, gateway, workspace, tmp_path): + cli, log = _stub_cli(tmp_path) + gateway.vulns = [STUB_VULN] + _commit(workspace[1], {**sdk_env, "SG_AGENTIC_CLI_PATH": cli}) + reviews = _reviews(log) + assert reviews and all(FLAG in r for r in reviews) + + def test_commit_reviewer_opt_in_drops_the_flag(self, sdk_env, gateway, workspace, tmp_path): + cli, log = _stub_cli(tmp_path) + gateway.vulns = [STUB_VULN] + _commit(workspace[1], {**sdk_env, "SG_AGENTIC_CLI_PATH": cli, + "SECURITY_GUIDANCE_PERSIST_SESSIONS": "1"}) + reviews = _reviews(log) + assert reviews and not any(FLAG in r for r in reviews) + + def test_single_turn_review_gets_the_flag(self, sdk_env, tmp_path): + cli, log = _stub_cli(tmp_path) + _single_turn({**sdk_env, "SG_AGENTIC_CLI_PATH": cli}) + reviews = _reviews(log) + assert reviews and all(FLAG in r for r in reviews) + + def test_single_turn_review_opt_in_drops_the_flag(self, sdk_env, tmp_path): + cli, log = _stub_cli(tmp_path) + _single_turn({**sdk_env, "SG_AGENTIC_CLI_PATH": cli, + "SECURITY_GUIDANCE_PERSIST_SESSIONS": "1"}) + reviews = _reviews(log) + assert reviews and not any(FLAG in r for r in reviews) + + +class TestInnerCliOlderThanTheFlag: + def test_commit_reviewer_runs_again_without_it(self, sdk_env, gateway, workspace, tmp_path): + cli, log = _stub_cli(tmp_path, reject_flag=True) + gateway.vulns = [STUB_VULN] + _commit(workspace[1], {**sdk_env, "SG_AGENTIC_CLI_PATH": cli}) + reviews = _reviews(log) + assert [FLAG in r for r in reviews] == [True, False] + + def test_single_turn_review_runs_again_without_it(self, sdk_env, tmp_path): + cli, log = _stub_cli(tmp_path, reject_flag=True) + _single_turn({**sdk_env, "SG_AGENTIC_CLI_PATH": cli}) + reviews = _reviews(log) + assert [FLAG in r for r in reviews] == [True, False] diff --git a/plugins/security-guidance/tests/test_reviewer_tools.py b/plugins/security-guidance/tests/test_reviewer_tools.py index 3e2aa86c..547a5e87 100644 --- a/plugins/security-guidance/tests/test_reviewer_tools.py +++ b/plugins/security-guidance/tests/test_reviewer_tools.py @@ -9,6 +9,7 @@ import llm READ_ONLY = {"tools": "Read,Grep,Glob", "strict-mcp-config": None} NO_TOOLS = {"tools": "", "strict-mcp-config": None} +NOT_SAVED = {"no-session-persistence": None} def test_tool_flags(): @@ -59,6 +60,7 @@ def sdk(monkeypatch, tmp_path): mod.AssistantMessage = type("AssistantMessage", (), {}) monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod) monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "") + monkeypatch.delenv("SECURITY_GUIDANCE_PERSIST_SESSIONS", raising=False) monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state")) for var in ("CONTEXT_DIR", "DEBUG_DIR", "MODEL", "ITER2", "FILTER", "NO_ADJUDICATE", "DIFF_INTERSECT", "EXCLUDE_MEDIUM", "MAX_TURNS"): @@ -72,7 +74,7 @@ def test_every_agentic_stage_gets_only_the_read_tools(sdk, tmp_path): # investigate, second investigate pass, refute assert len(sdk) == 3 for opts in sdk: - assert opts["extra_args"] == READ_ONLY + assert opts["extra_args"] == {**READ_ONLY, **NOT_SAVED} assert opts["allowed_tools"] == ["Read", "Grep", "Glob"] assert "permission_mode" not in opts @@ -81,4 +83,5 @@ def test_single_turn_sdk_review_gets_no_tools(sdk): schema = {"type": "object", "properties": {}} assert llm._call_claude_via_sdk("review this", schema) is not None assert len(sdk) == 1 - assert sdk[0]["extra_args"] == NO_TOOLS and sdk[0]["allowed_tools"] == [] + assert sdk[0]["extra_args"] == {**NO_TOOLS, **NOT_SAVED} + assert sdk[0]["allowed_tools"] == [] |
