summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-10-20 20:35:31 +0000
committerClaude <noreply@anthropic.com>2026-10-20 20:35:31 +0000
commit03bab72cbdce7039f452b15417de84989858b9e0 (patch)
tree52ee1c021528a3ab569fc6fea6581b0f0e3bf318 /plugins
parented055202f5eed104410a42b34a49a8de8eb40ca8 (diff)
parentf15240feee15b8fe020d38fd46ab5becc97c80a0 (diff)
Merge branch 'mhegazy/sg-gateway-login' into mhegazy/sg-sdk-bootstrap-switches
Resolves the overlap with the bootstrap working-directory change and the gateway sign-in route: the import probe keeps the state-dir working directory, and llm.py keeps both imports.
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/README.md20
-rw-r--r--plugins/security-guidance/hooks/_base.py11
-rw-r--r--plugins/security-guidance/hooks/diffstate.py67
-rw-r--r--plugins/security-guidance/hooks/ensure_agent_sdk.py30
-rw-r--r--plugins/security-guidance/hooks/gitutil.py72
-rw-r--r--plugins/security-guidance/hooks/llm.py344
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py253
-rwxr-xr-xplugins/security-guidance/hooks/sg-python.sh21
-rw-r--r--plugins/security-guidance/tests/conftest.py48
-rw-r--r--plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py75
-rw-r--r--plugins/security-guidance/tests/test_gateway_sign_in.py396
-rw-r--r--plugins/security-guidance/tests/test_launcher_newer_python.py55
-rw-r--r--plugins/security-guidance/tests/test_nested_repos.py162
-rw-r--r--plugins/security-guidance/tests/test_no_credentials_notice.py215
-rw-r--r--plugins/security-guidance/tests/test_notebook_edit_patterns.py193
-rw-r--r--plugins/security-guidance/tests/test_reviewer_tools.py123
-rw-r--r--plugins/security-guidance/tests/test_secret_shaped_paths.py20
-rw-r--r--plugins/security-guidance/tests/test_stop_baseline_checkout.py282
18 files changed, 2253 insertions, 134 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md
index b8a67ed4..caef1866 100644
--- a/plugins/security-guidance/README.md
+++ b/plugins/security-guidance/README.md
@@ -20,7 +20,7 @@ Marketplace ships enabled by default in Claude Code — no setup beyond having t
- Claude Code CLI ≥ v2.1.144
- Python 3.8+ on `PATH` (`python3`, `python`, or `py -3` — the plugin picks the first that works)
-- A working API path (subscription, API key, or 3P provider config)
+- Credentials for the LLM reviews: your Claude Code sign-in (a Claude apps gateway sign-in needs Claude Code 2.1.195 or later), an API key, or 3P provider config (see [Credentials](#credentials))
## Configuration
@@ -31,7 +31,7 @@ All configuration is via environment variables. None are required for default be
By default both reviews run on the newest Claude Opus, and move to the next one when it is released — there is no model version to bump:
- The LLM diff review asks your API endpoint (`GET /v1/models`) which Opus models it serves and uses the newest. The answer is cached for a day in the plugin's state directory. If the endpoint can't answer, the review uses `claude-opus-5-5`.
-- The agentic commit reviewer, and every review on Bedrock, Vertex, and Foundry, runs through your installed Claude Code and uses its `opus` alias — the same model `/model opus` selects, including any `ANTHROPIC_DEFAULT_OPUS_MODEL` you have set.
+- The agentic commit reviewer, and every review in a session signed in to a Claude apps gateway with `/login`, run through your installed Claude Code. Other reviews on Bedrock, Vertex, and Foundry run through the copy of Claude Code bundled with the Agent SDK, or `SG_AGENTIC_CLI_PATH` if set. All of them use Claude Code's `opus` alias: the model `/model opus` selects, including any `ANTHROPIC_DEFAULT_OPUS_MODEL` you have set. On a gateway that alias may name an older Opus than the newest one.
To pin a model, or to use a cheaper one:
@@ -48,6 +48,17 @@ SECURITY_REVIEW_MODEL=claude-opus-5-5
`SECURITY_REVIEW_MODEL` controls the LLM diff review. `SG_AGENTIC_MODEL` (same syntax) controls the agentic commit reviewer.
+### Credentials
+
+The pattern warnings need no credentials. The LLM reviews (the diff review on Stop and the commit/push reviewer) use the first of these that applies:
+
+- **A cloud provider (Bedrock, Vertex, Foundry)** — if Claude Code is configured for one, reviews run through Claude Code with that provider config.
+- **`ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` in the environment** — used as is, against `ANTHROPIC_BASE_URL` if you set one.
+- **Signed in to Claude Code (`/login`)** — Claude Code passes your sign-in to the plugin's hooks, and reviews use that account.
+- **Signed in to a Claude apps gateway (`/login`)** — Claude Code passes no sign-in to plugins on a gateway, so reviews run through your installed Claude Code, which uses its own stored sign-in. The plugin never reads it. The plugin looks for Claude Code at `~/.local/bin/claude`, where the native installer puts it on macOS and Linux; on Windows, or for any other install, set `SG_AGENTIC_CLI_PATH` to its full path.
+
+Claude Code does not pass your sign-in to plugins in a session started with `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, `DISABLE_TELEMETRY`, or `DO_NOT_TRACK` set. If no credentials reach the plugin, for that or any other reason, and the plugin cannot review through a Claude apps gateway sign-in, the LLM reviews are skipped and only the pattern warnings run. The plugin tells you so when Claude edits a file in a git repo, at most once a week. Set `ENABLE_CODE_SECURITY_REVIEW=0` if that is what you want; it also hides the notice.
+
### Enabling/disabling layers
| Variable | Default | What it does |
@@ -104,9 +115,10 @@ The plugin sends data to a model endpoint to perform its reviews. Specifically,
Where that data goes depends on your Claude Code configuration:
- **Default (Anthropic API / subscription):** sent to `api.anthropic.com` and handled under Anthropic's [Commercial Terms](https://www.anthropic.com/legal/commercial-terms) and [Privacy Policy](https://www.anthropic.com/legal/privacy).
- **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.
+- **Claude apps gateway, signed in with `/login`:** your installed Claude Code sends the reviews to the gateway, using its own stored sign-in. The plugin never reads the sign-in. 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, 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 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 of stderr from each Claude Code run the plugin starts for a review (20 in all for each agentic commit review, which starts several runs) — no full file contents or model prompts — and rotates at 1 MB. Nothing is uploaded.
### Review usage and cost
@@ -131,7 +143,7 @@ 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`.
-**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.
+**Review never finds anything** — verify your API path works, and that credentials reach the plugin (see [Credentials](#credentials)): `~/.claude/security/log.txt` says `no API credentials` when they don't. 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. In a session signed in to a Claude apps gateway with `/login`, reviews run only when `claude auth status` shows the gateway and that you are logged in. They run through the Claude Code at `~/.local/bin/claude`, where the native installer puts it on macOS and Linux. On Windows, or for any other install, set `SG_AGENTIC_CLI_PATH` to its full path.
**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/_base.py b/plugins/security-guidance/hooks/_base.py
index 6f2944be..59e8e569 100644
--- a/plugins/security-guidance/hooks/_base.py
+++ b/plugins/security-guidance/hooks/_base.py
@@ -34,11 +34,12 @@ def state_dir():
"""
explicit = os.environ.get("SECURITY_WARNINGS_STATE_DIR")
if explicit:
- return os.path.expanduser(explicit)
- cc_config = os.environ.get("CLAUDE_CONFIG_DIR")
- if cc_config:
- return os.path.expanduser(os.path.join(cc_config, "security"))
- return os.path.expanduser("~/.claude/security")
+ d = explicit
+ elif os.environ.get("CLAUDE_CONFIG_DIR"):
+ d = os.path.join(os.environ["CLAUDE_CONFIG_DIR"], "security")
+ else:
+ d = "~/.claude/security"
+ return os.path.abspath(os.path.expanduser(d))
def llm_reviews_switched_off():
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index f2d9dbe4..02b073e8 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -17,6 +17,7 @@ from gitutil import (
_git_rev_parse_head, _is_ancestor, _git_name_only, _temp_index,
)
from session_state import with_locked_state
+from extensibility import _same_dir
# =====================================================================
@@ -96,6 +97,10 @@ def consume_stop_state(session_id, clear=True):
"touched_paths": list(state.get("touched_paths", [])),
"baseline_sha": state.get("baseline_sha"),
"head_at_capture": state.get("head_at_capture"),
+ # Where and when the prompt hook captured it; see baseline_origin.
+ "baseline_root": state.get("baseline_root"),
+ "prompt_at": state.get("prompt_at"),
+ "baseline_kept": state.get("baseline_kept") or 0,
"untracked_at_baseline": (
dict(state["untracked_at_baseline"])
if isinstance(state.get("untracked_at_baseline"), dict) else {}
@@ -117,7 +122,8 @@ def consume_stop_state(session_id, clear=True):
return with_locked_state(session_id, _snap) or {
"touched_paths": [], "baseline_sha": None, "head_at_capture": None,
- "untracked_at_baseline": {},
+ "untracked_at_baseline": {}, "baseline_root": None, "prompt_at": None,
+ "baseline_kept": 0,
"fire_count": 0, "fire_count_expired": False, "previous_findings": [],
"reviewed_diff_hash": None, "state_resets": 0, "state_overwrites": 0,
}
@@ -153,6 +159,48 @@ def restore_unreviewed_stop_state(session_id, paths, baseline_sha):
with_locked_state(session_id, _restore)
+# state["baseline_kept"]: why a prompt left an earlier turn's baseline in
+# place. Only telemetry reads it.
+KEPT_NO_CAPTURE = 1 # it could not capture one (not a repo, or git failed)
+KEPT_UNREVIEWED = 2 # the previous turn's edits were never reviewed
+
+# baseline_origin() values that mean "captured in another checkout".
+FOREIGN_ORIGINS = (1, 2, 3)
+
+
+def baseline_origin(repo_root, baseline_sha, baseline_root):
+ """Where the session's baseline was captured, relative to the checkout a
+ Stop review is about to read (`repo_root`):
+
+ 0 that checkout (or the origin was not recorded)
+ 1 another worktree of the same repository
+ 2 another repository
+ 3 another folder, which is gone or cannot be read as a checkout
+ 4 there is no baseline
+
+ `baseline_root` is the repo root the prompt hook stored beside the SHA."""
+ if not baseline_sha:
+ return 4
+ if not baseline_root or not isinstance(baseline_root, str):
+ return 0
+ if _same_dir(baseline_root, repo_root):
+ return 0
+ if not os.path.isdir(baseline_root):
+ return 3
+ here, there = _git_dir(repo_root), _git_dir(baseline_root)
+ if not here or not there:
+ return 3
+ return 1 if _same_dir(here, there) else 2
+
+
+def baseline_origin_metric(origin, kept):
+ """The `bl_origin` number on Stop rows: baseline_origin, plus 10 or 20
+ (KEPT_*) when the baseline is an earlier turn's."""
+ if origin == 4 or kept not in (KEPT_NO_CAPTURE, KEPT_UNREVIEWED):
+ return origin
+ return origin + 10 * kept
+
+
def get_baseline_file_content(session_id, file_path, cwd):
"""Get the content of a file at the baseline SHA. Returns None if unavailable.
@@ -605,7 +653,8 @@ def _list_untracked(cwd):
debug_log(f"_list_untracked error: {e}")
return {}
-def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_baseline=None):
+def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_baseline=None,
+ since_ns=None):
"""v2 diff strategy: derive the review set from git state alone.
review_set = (files dirty vs current HEAD, plus files committed this turn
@@ -620,6 +669,10 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel
A file is excluded only if it was untracked at baseline AND its mtime is
unchanged — an in-place edit during the turn is still reviewed.
+ since_ns: for a checkout the prompt hook took no baseline or snapshot of
+ (the turn moved into it), the time the turn began. A dirty or untracked
+ file last written before then was already that way and is left out.
+
Known limitation: a Bash-only turn that's interrupted before Stop fires
leaves touched_paths empty, so the next UPS re-baselines past those edits.
v1 never reviews Bash-only turns at all, so v2 is no worse there.
@@ -662,6 +715,16 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel
return max(st.st_mtime_ns, st.st_ctime_ns) < capped_at_ns - _CAPPED_BASELINE_SLACK_NS
preexisting_unchanged = {p for p in untracked if _unchanged_since_baseline(p)}
+ if since_ns:
+ def _written_before_turn(p):
+ try:
+ st = os.stat(os.path.join(repo, p))
+ except OSError:
+ return False
+ return max(st.st_mtime_ns, st.st_ctime_ns) < since_ns - _CAPPED_BASELINE_SLACK_NS
+
+ preexisting_unchanged |= {p for p in untracked if _written_before_turn(p)}
+ tracked_dirty = {p for p in tracked_dirty if not _written_before_turn(p)}
new_untracked = untracked - preexisting_unchanged
dirty_now = tracked_dirty | new_untracked
diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py
index dd2ddf0c..fadeae00 100644
--- a/plugins/security-guidance/hooks/ensure_agent_sdk.py
+++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py
@@ -30,6 +30,24 @@ from pathlib import Path
from _base import portable_output, state_dir as _resolve_state_dir, write_hook_output
from _base import llm_reviews_switched_off
+
+def _spawn_cwd() -> str:
+ """Working directory for every Python this file starts.
+
+ `python -c` and `python -m` put the working directory first on the import
+ path, and hooks run in the user's repository, so a repository file named
+ `claude_agent_sdk.py`, `venv.py` or `pip.py` would be imported in place
+ of the real module. The state dir is the plugin's own (the venv is built
+ there, so the interpreter can reach it); the plugin folder is the
+ fallback when it can't be created.
+ """
+ d = _resolve_state_dir()
+ try:
+ os.makedirs(d, exist_ok=True)
+ return d
+ except OSError:
+ return str(Path(__file__).resolve().parent.parent)
+
# Outcome codes for the sdk_bootstrap metric. Values are stable for telemetry.
NOOP_SYSTEM = 0 # claude_agent_sdk already importable in system python
NOOP_VENV = 1 # venv already built and SDK imports from it
@@ -315,7 +333,7 @@ def _probe_has_pip() -> bool:
try:
r = subprocess.run(
[sys.executable, "-m", "pip", "--version"],
- capture_output=True, timeout=10,
+ capture_output=True, timeout=10, cwd=_spawn_cwd(),
)
return r.returncode == 0
except Exception:
@@ -427,7 +445,7 @@ def _target_sdk_importable(state_dir) -> bool:
[sys.executable, "-c",
"import sys; sys.path.insert(0, sys.argv[1]); " + _SDK_IMPORT_PROBE,
str(target)],
- capture_output=True, timeout=10,
+ capture_output=True, timeout=10, cwd=_spawn_cwd(),
)
return r.returncode == 0
except Exception:
@@ -452,7 +470,7 @@ def _build_via_target(state_dir) -> tuple[int, str, str]:
"--target", str(target), "--upgrade",
"--disable-pip-version-check", "--prefer-binary", "--no-cache-dir",
"claude-agent-sdk"],
- capture_output=True, timeout=120, check=True,
+ capture_output=True, timeout=120, check=True, cwd=_spawn_cwd(),
)
return BUILT_TARGET, "", ""
except subprocess.CalledProcessError as e:
@@ -634,7 +652,7 @@ def main() -> tuple[int, str, str]:
try:
r = subprocess.run(
[str(venv_py), "-c", _SDK_IMPORT_PROBE],
- capture_output=True, timeout=10,
+ capture_output=True, timeout=10, cwd=_spawn_cwd(),
)
if r.returncode == 0:
return NOOP_VENV, "", ""
@@ -671,7 +689,7 @@ def main() -> tuple[int, str, str]:
err_phase = "venv"
subprocess.run(
[sys.executable, "-m", "venv", "--clear", str(venv)],
- capture_output=True, timeout=60, check=True,
+ capture_output=True, timeout=60, check=True, cwd=_spawn_cwd(),
)
# Some machines route pip through a private registry; we
# don't pass --index-url here so we inherit that default. Outside
@@ -695,7 +713,7 @@ def main() -> tuple[int, str, str]:
[str(venv_py), "-m", "pip", "install", "--quiet",
"--disable-pip-version-check", "--prefer-binary", "--no-cache-dir",
"claude-agent-sdk"],
- capture_output=True, timeout=120, check=True,
+ capture_output=True, timeout=120, check=True, cwd=_spawn_cwd(),
)
return BUILT, "", ""
except subprocess.CalledProcessError as e:
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index bc4d753b..8702e4da 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -48,11 +48,27 @@ GIT_CMD = [
"-c", "diff.noprefix=false",
"-c", "diff.srcPrefix=a/",
"-c", "diff.dstPrefix=b/",
+ # A directory with its own `.git` inside the work tree (a submodule, a
+ # vendored checkout, an unpacked archive) is another repository with its
+ # own config. To report it as modified, or to show its changes inline
+ # (diff.submodule=diff), git starts a second git inside it, which reads
+ # that config and runs the commands it names. The hook stays out of it:
+ # such a directory is left out of the review set, and a commit that moves
+ # one shows as the two commit ids.
+ "-c", "diff.ignoreSubmodules=all",
+ "-c", "diff.submodule=short",
]
+# diff.ignoreSubmodules is a default that the repository's own settings for
+# one submodule (.gitmodules, submodule.<name>.ignore) override. The option
+# cannot be overridden. Pass it to every `git status` and work-tree `git diff`.
+IGNORE_SUBMODULES = "--ignore-submodules=all"
+
SAFE_GIT_CONFIG = (
("core.fsmonitor", "false"),
("core.hooksPath", "/dev/null"),
+ ("diff.ignoreSubmodules", "all"),
+ ("diff.submodule", "short"),
)
# The hook's git runs in the background beside the session's own git. Without
@@ -448,8 +464,11 @@ def _copied_index(cwd, real_index, tmpdir, untracked_paths):
# `git status` and here would silently drop ALL untracked files
# from the diff. --ignore-missing only works with --dry-run, so
# filter to surviving paths (lexists so dangling symlinks count).
+ # A nested repository (`dir/`) would be added as a submodule
+ # entry; see diff.ignoreSubmodules in GIT_CMD.
surviving = [p for p in untracked_paths
- if os.path.lexists(os.path.join(cwd, p))]
+ if not p.endswith("/")
+ and os.path.lexists(os.path.join(cwd, p))]
add_args = ["--"] + surviving if surviving else None
else:
add_args = None
@@ -487,6 +506,41 @@ def _git_toplevel(cwd):
return None
+def _git_toplevel_and_head(cwd):
+ """(repo root, HEAD SHA) for `cwd` from one git call, or (None, None)
+ when git cannot give both (not a work tree, no commits)."""
+ try:
+ r = subprocess.run(
+ [*GIT_CMD, "rev-parse", "--show-toplevel", "HEAD"],
+ cwd=cwd, capture_output=True, timeout=5,
+ )
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
+ return None, None
+ if r.returncode != 0:
+ return None, None
+ # See #2099: the first line is a PATH, so decode the bytes manually.
+ top, _, head = r.stdout.decode("utf-8", errors="replace").strip().rpartition("\n")
+ return (top.strip() or None), (head.strip() or None)
+
+
+def _git_head_at(cwd, epoch):
+ """The SHA this checkout's HEAD pointed at just before `epoch` (seconds),
+ read from its own reflog. A checkout created after `epoch` answers with
+ the commit it was created at. None when git cannot say (no reflog)."""
+ try:
+ # Reflog times are whole seconds: ask for the second before, so a
+ # commit made in the same second as `epoch` counts as after it.
+ r = subprocess.run(
+ [*GIT_CMD, "rev-parse", "--verify", "-q", f"HEAD@{{@{int(epoch) - 1}}}"],
+ cwd=cwd, capture_output=True, timeout=5,
+ )
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError,
+ TypeError, ValueError, OverflowError):
+ return None
+ sha = r.stdout.decode("utf-8", errors="replace").strip()
+ return sha if r.returncode == 0 and sha else None
+
+
def _git_dir(repo_root):
"""Absolute shared `.git` directory for repo_root.
@@ -673,7 +727,7 @@ def _git_name_only(cwd, base, include_untracked=False):
def _run(env):
# core.quotePath=false comes from GIT_CMD globally (see definition).
result = subprocess.run(
- [*GIT_CMD, "diff", "--name-only", "-z", base],
+ [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--name-only", "-z", base],
cwd=cwd, capture_output=True, timeout=30,
env=env,
)
@@ -714,7 +768,7 @@ def _git_status_porcelain(cwd):
try:
# core.quotePath=false comes from GIT_CMD globally (see definition).
r = subprocess.run(
- [*GIT_CMD, "status", "--porcelain=v1", "-uall", "-z"],
+ [*GIT_CMD, "status", IGNORE_SUBMODULES, "--porcelain=v1", "-uall", "-z"],
cwd=cwd, capture_output=True, timeout=30,
)
if r.returncode != 0:
@@ -732,7 +786,10 @@ def _git_status_porcelain(cwd):
continue
xy, path = e[:2], e[3:]
if xy == "??":
- untracked.add(path)
+ # With -uall only a nested repository is listed as `dir/`.
+ # It is not a file to review; see diff.ignoreSubmodules.
+ if not path.endswith("/"):
+ untracked.add(path)
else:
tracked.add(path)
# Rename/copy entries are XY old\0new\0 — second NUL field is
@@ -791,7 +848,7 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa
return ""
# core.quotePath=false comes from GIT_CMD globally (see definition).
- cmd = [*GIT_CMD, "diff", "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec
+ cmd = [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec
try:
if untracked_paths is not None and not untracked_paths:
# Nothing to `add -N`, and the diff only reads the index.
@@ -874,9 +931,12 @@ _SSH_PRIVATE_KEY_BASENAMES = frozenset((
'id_ed25519_sk', 'id_xmss',
))
_PRIVATE_KEY_NAME_SUFFIXES = ('_rsa', '_dsa', '_ecdsa', '_ed25519')
+# `.credentials.json` and `.claude.json` are Claude Code's own files: sign-in
+# tokens, a saved API key, MCP server secrets. Claude Code rewrites them as it
+# runs, so they show up as changed when its config directory is a git repo.
_CREDENTIAL_BASENAMES = frozenset((
'credentials', '.netrc', '.pgpass', '.npmrc', '.pypirc',
- '.git-credentials', '.dockercfg',
+ '.git-credentials', '.dockercfg', '.credentials.json', '.claude.json',
))
# chezmoi encodes a target file's attributes as stacked name prefixes
# (`private_dot_netrc`, `encrypted_private_token`); `dot_` stands for a
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index dfddf6a0..76d04c54 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -22,6 +22,7 @@ import json
import logging
import os
import re
+import subprocess
import sys
import tempfile
import threading
@@ -29,12 +30,12 @@ import time
import traceback
import urllib.parse
import urllib.request
-from typing import Optional, Tuple, Dict, Any, List
+from typing import Optional, Tuple, Dict, Any, List, Callable
import extensibility
import review_api
from _base import debug_log, _record_usage, _record_http_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir, agent_sdk_site_dirs # noqa: F401
-from session_state import with_locked_state
+from session_state import load_state, with_locked_state
from gitutil import git_config_env, SAFE_GIT_CONFIG
@@ -317,10 +318,12 @@ def _custom_headers() -> List[Tuple[str, str]]:
def gateway_cfg() -> int:
- """How the plugin's own API calls are routed, for telemetry: bit 1 when
+ """How the plugin's reviews are routed, for telemetry: bit 1 when
ANTHROPIC_BASE_URL names a host other than api.anthropic.com, bit 2 when
- at least one ANTHROPIC_CUSTOM_HEADERS line is sent. 0 when neither. A
- number only: no host, header name or value."""
+ at least one ANTHROPIC_CUSTOM_HEADERS line is sent, bit 4 when reviews
+ run through the user's claude on a Claude apps gateway sign-in (see
+ gateway_review_cli). 0 when none. A number only: no host, header name
+ or value."""
cfg = 0
base = _anthropic_base_url()
try:
@@ -331,6 +334,8 @@ def gateway_cfg() -> int:
cfg |= 1
if any(name.lower() != "anthropic-beta" for name, _ in _custom_headers()):
cfg |= 2
+ if _gateway_cli:
+ cfg |= 4
return cfg
@@ -553,16 +558,17 @@ def _write_review_model_cache(path, endpoint_key, model, now):
def default_review_model() -> str:
"""Model for a review the user hasn't pinned with SECURITY_REVIEW_MODEL.
- 3P providers go through the Agent SDK, so the CLI alias does the work.
- 1P and gateways get the newest Opus the endpoint lists, looked up at most
- once per _REVIEW_MODEL_TTL_SECONDS; _PINNED_REVIEW_MODEL when the lookup
- can't answer. Never raises.
+ 3P providers and Claude apps gateway sign-ins go through the Agent SDK,
+ so the CLI alias does the work. 1P and LLM gateways set with
+ ANTHROPIC_BASE_URL get the newest Opus the endpoint lists, looked up at
+ most once per _REVIEW_MODEL_TTL_SECONDS; _PINNED_REVIEW_MODEL when the
+ lookup can't answer. Never raises.
"""
global _review_model_memo
explicit = os.environ.get("SECURITY_REVIEW_MODEL", "").strip()
if explicit:
return explicit
- if _is_3p_provider():
+ if _is_3p_provider() or _gateway_cli:
return _CLI_OPUS_ALIAS
if not HAS_API_CREDENTIALS:
return _PINNED_REVIEW_MODEL
@@ -586,16 +592,165 @@ def default_review_model() -> str:
return _review_model_memo
-def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None):
+# A session signed in to a Claude apps gateway with /login gives hooks no
+# credential, but a child `claude` restores that sign-in by itself, so reviews
+# can run through the user's CLI without a credential entering this process.
+
+# `claude auth status` may wait for a settings helper script an administrator
+# configured, which Claude Code gives 10 s by default.
+_GATEWAY_CHECK_TIMEOUT_S = 15
+_GATEWAY_STATE_KEY = "gateway_sign_in"
+# The CLI that reviews for a signed-in gateway session, "" when this process
+# decided not to use the gateway route, None before it has decided.
+_gateway_cli: Optional[str] = None
+# True when this process asked the CLI about the sign-in and got no usable
+# answer: the reviews are skipped, but the session may well be signed in.
+_gateway_check_unanswered = False
+# True once a review through the gateway route ran out of time. What makes
+# it do so (a rejected sign-in, a gateway that cannot be reached) does not
+# depend on the model, so the Sonnet attempt is not made after it.
+_gateway_review_timed_out = False
+
+
+def _user_cli_path() -> Optional[str]:
+ """The user's own `claude`: SG_AGENTIC_CLI_PATH if set ("" selects the
+ SDK's bundled CLI), else the first of the absolute paths below that
+ exists, else None."""
+ cli_path = os.environ.get("SG_AGENTIC_CLI_PATH")
+ if cli_path is not None:
+ return cli_path
+ # CLAUDE_CODE_EXECPATH is the absolute path to the running CC binary
+ # itself (e.g. ~/.local/share/claude/versions/2.1.x — that's the binary,
+ # not a directory). Claude Code sets it for the Bash tool's shells, not for
+ # hooks, so hooks usually find the CLI at a fixed path below. We do NOT
+ # fall back to shutil.which("claude") because the hook's cwd is the
+ # user's (potentially attacker-supplied) repo, and Windows shutil.which
+ # searches cwd first — a checked-in ./claude.exe would get spawned.
+ # Absolute-path probes only.
+ for p in (
+ os.environ.get("CLAUDE_CODE_EXECPATH"),
+ os.path.expanduser("~/.local/bin/claude"),
+ "/root/.local/bin/claude",
+ # Claude Code Remote container install path.
+ "/opt/claude-code/bin/claude",
+ ):
+ if p and os.path.isfile(p):
+ return p
+ return None
+
+
+def _tolerate_unknown_sdk_messages() -> None:
+ """Make the SDK's message parser pass unknown message types through
+ instead of raising: a CLI newer than the SDK emits types the SDK does not
+ know (e.g. rate_limit_event)."""
+ try:
+ from claude_agent_sdk._internal import message_parser as _mp
+ import claude_agent_sdk._internal.client as _sdk_client
+ from claude_agent_sdk import SystemMessage as _SysMsg
+
+ _orig_parse = _mp.parse_message
+ if getattr(_orig_parse, "_sg_tolerant", False):
+ return
+
+ def _tolerant(data):
+ try:
+ return _orig_parse(data)
+ except Exception:
+ return _SysMsg(subtype=data.get("type", "unknown"), data=data)
+
+ _tolerant._sg_tolerant = True
+ _mp.parse_message = _tolerant
+ _sdk_client.parse_message = _tolerant
+ except Exception:
+ pass
+
+
+def _gateway_signed_in(cli: str) -> Optional[bool]:
+ """Whether `cli auth status --json` reports a session signed in to a
+ Claude apps gateway. None when the CLI gave no usable answer (an error, a
+ timeout, or output that is not a JSON object)."""
+ try:
+ # A process the CLI starts can keep stdout open after the CLI exits;
+ # reading a pipe would then wait out the timeout and lose the answer.
+ with tempfile.TemporaryFile() as out:
+ subprocess.run(
+ [cli, "auth", "status", "--json"], stdin=subprocess.DEVNULL,
+ stdout=out, stderr=subprocess.DEVNULL,
+ env={**os.environ, **_agentic_spawn_env()},
+ cwd=os.path.expanduser("~"),
+ timeout=_GATEWAY_CHECK_TIMEOUT_S, check=False,
+ )
+ out.seek(0)
+ status = json.loads(out.read(64 * 1024))
+ except Exception as e:
+ debug_log(f"gateway check: no usable answer from {cli} ({type(e).__name__})")
+ return None
+ if not isinstance(status, dict):
+ debug_log("gateway check: answer was not a JSON object")
+ return None
+ provider, logged_in = status.get("apiProvider"), status.get("loggedIn")
+ debug_log(f"gateway check: apiProvider={str(provider)[:40]!r} loggedIn={repr(logged_in)[:10]}")
+ # A managed machine that names a gateway but was never signed in also
+ # reports "gateway".
+ return provider == "gateway" and logged_in is True
+
+
+def gateway_review_cli(session_id) -> Optional[str]:
+ """The CLI to review through when the plugin has no credential but the
+ session is signed in to a Claude apps gateway; None otherwise. A yes or
+ no from the CLI is kept for the rest of the session, so signing in or
+ out mid-session takes effect in the next one. When the CLI gives no
+ usable answer, nothing is saved, so the next hook asks again."""
+ global _gateway_cli, _gateway_check_unanswered
+ if _gateway_cli is not None:
+ return _gateway_cli or None
+ cli = _user_cli_path() or ""
+ ok = None
+ # No skip for CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC, as on Bedrock and Vertex:
+ # the gateway docs suggest setting it, and the review goes through the
+ # gateway like the session's own requests.
+ if not os.path.isabs(cli):
+ debug_log("gateway check: skipped, SG_AGENTIC_CLI_PATH is not a full path"
+ if "SG_AGENTIC_CLI_PATH" in os.environ
+ else "gateway check: skipped, no claude at ~/.local/bin/claude or the other "
+ "usual full paths (SG_AGENTIC_CLI_PATH can name one)")
+ else:
+ cached = load_state(session_id).get(_GATEWAY_STATE_KEY)
+ if (isinstance(cached, dict) and cached.get("cli") == cli
+ and isinstance(cached.get("ok"), bool)):
+ ok = cached["ok"]
+ debug_log(f"gateway check: using this session's saved answer (signed in: {ok})")
+ else:
+ ok = _gateway_signed_in(cli)
+ _gateway_check_unanswered = ok is None
+ if ok is not None:
+ def _save(state):
+ state[_GATEWAY_STATE_KEY] = {"cli": cli, "ok": ok}
+ with_locked_state(session_id, _save)
+ _gateway_cli = cli if ok else ""
+ return _gateway_cli or None
+
+
+def can_review(session_id) -> bool:
+ """True when the plugin has a credential, or has none but the session is
+ signed in to a Claude apps gateway. Call it before reviewing: the review
+ takes the gateway route only after it has said yes in this process."""
+ return HAS_API_CREDENTIALS or gateway_review_cli(session_id) is not None
+
+
+def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None,
+ cli_path=None):
"""Single-turn SDK call as a substitute for the HTTP _call_claude path on
- 3P providers. Uses the same `output_format` JSON-schema contract so the
- return value shape is identical (parsed dict or None).
+ 3P providers, and, with `cli_path` set, for a session signed in to a
+ Claude apps gateway. Uses the same `output_format` JSON-schema contract so
+ the return value shape is identical (parsed dict or None).
No tools (see _only_tools_args) — the security review only needs
structured output, not Read/Grep/Glob. Single turn keeps cost predictable.
"""
- global _last_call_claude_http_error
+ global _last_call_claude_http_error, _gateway_review_timed_out
_last_call_claude_http_error = None
+ route = "gateway" if cli_path else "3P"
try:
import asyncio as _asyncio
@@ -620,13 +775,16 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None)
query,
)
except Exception as e:
- debug_log(f"3P sdk-single-turn: SDK unavailable ({e})")
+ debug_log(f"{route} sdk-single-turn: SDK unavailable ({e})")
_last_call_claude_http_error = -1
_record_http_error(-1)
return None
_send_sdk_logs_to_debug_log()
- cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") or None
+ if cli_path:
+ _tolerate_unknown_sdk_messages()
+ else:
+ cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") or None
default_model = default_review_model()
chosen_model = model or default_model
@@ -634,6 +792,8 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None)
# error (auth missing, model id wrong, etc.) in the debug log instead
# of just "exit code 1".
_captured_stderr: List[str] = []
+ # HTTP statuses (or "no response") the CLI said it retried an API request after.
+ _retried_after: set = set()
async def _arun():
opts = ClaudeAgentOptions(
@@ -666,31 +826,46 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None)
structured = msg.structured_output
_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")
return structured
# 60s ceiling: a single review request on a healthy 3P endpoint completes
# in 5-15s; >60s means the child claude is hung (e.g. user has the 3P env
# var set but no provider creds → child waits for an auth that never
# 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))
+ # whole hook. A gateway review gets the 120 s a direct HTTP review gets.
+ timeout_s = 120 if route == "gateway" else 60
+
+ def _log_child_stderr():
if _captured_stderr:
- debug_log(f"3P sdk-single-turn child stderr ({len(_captured_stderr)} lines):")
+ debug_log(f"{route} sdk-single-turn child stderr ({len(_captured_stderr)} lines):")
for _l in _captured_stderr[:20]:
debug_log(f" | {_l.rstrip()}")
+
+ try:
+ result = _run_inner_cli(
+ lambda: _asyncio.run(_asyncio.wait_for(_arun(), timeout=timeout_s)),
+ _captured_stderr)
+ _log_child_stderr()
return result
except _asyncio.TimeoutError:
- debug_log("3P sdk-single-turn: timeout after 60s")
+ # The CLI retries a refused or unreachable API by itself and reports
+ # each retry in its output, not on stderr.
+ debug_log(f"{route} sdk-single-turn: timeout after {timeout_s}s"
+ + (f"; the CLI's API requests were retried after status "
+ f"{', '.join(sorted(_retried_after))}" if _retried_after else ""))
+ _log_child_stderr()
+ if route == "gateway":
+ _gateway_review_timed_out = True
_last_call_claude_http_error = -1
_record_http_error(-1)
return None
except Exception as e:
- debug_log(f"3P sdk-single-turn: query failed ({e})")
- if _captured_stderr:
- debug_log(f"3P sdk-single-turn child stderr ({len(_captured_stderr)} lines):")
- for _l in _captured_stderr[:20]:
- debug_log(f" | {_l.rstrip()}")
+ debug_log(f"{route} sdk-single-turn: query failed ({e})")
+ _log_child_stderr()
_last_call_claude_http_error = -1
_record_http_error(-1)
return None
@@ -729,6 +904,13 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000,
max_tokens=max_tokens, model=model)
if not HAS_API_CREDENTIALS:
+ if _gateway_cli:
+ # Signed in to a Claude apps gateway: the user's CLI reviews with
+ # its own stored sign-in (see gateway_review_cli).
+ if cacheable_prefix:
+ prompt = cacheable_prefix + "\n\n" + prompt
+ return _call_claude_via_sdk(prompt, output_schema, max_tokens=max_tokens,
+ model=model, cli_path=_gateway_cli)
return None
global _auth_prefer_token
@@ -886,6 +1068,9 @@ def _call_claude_dual_or(prompt, output_schema, *, bool_key: str, list_key: str,
explicit = os.environ.get("SECURITY_REVIEW_MODEL", "").strip()
primary = default_review_model()
+ # Through the user's CLI, the alias gives the Sonnet id the user's own
+ # sessions use on the gateway, including any ANTHROPIC_DEFAULT_SONNET_MODEL.
+ fallback = "sonnet" if _gateway_cli else "claude-sonnet-4-6"
if not _dual_or_enabled():
# Single-call path. Reuse the same sonnet-fallback retry as a dual_or
@@ -893,10 +1078,10 @@ def _call_claude_dual_or(prompt, output_schema, *, bool_key: str, list_key: str,
r = _call_claude(prompt, output_schema, thinking_budget=thinking_budget,
max_tokens=max_tokens, model=primary, retry_5xx=False,
cacheable_prefix=cacheable_prefix)
- if r is None and not explicit:
+ if r is None and not explicit and not _gateway_review_timed_out:
debug_log(f"single: {primary} failed, falling back to sonnet")
r = _call_claude(prompt, output_schema, thinking_budget=thinking_budget,
- max_tokens=max_tokens, model="claude-sonnet-4-6",
+ max_tokens=max_tokens, model=fallback,
retry_5xx=True, cacheable_prefix=cacheable_prefix)
return r
@@ -904,10 +1089,10 @@ def _call_claude_dual_or(prompt, output_schema, *, bool_key: str, list_key: str,
r = _call_claude(prompt, output_schema, thinking_budget=thinking_budget,
max_tokens=max_tokens, model=primary, retry_5xx=False,
cacheable_prefix=cacheable_prefix)
- if r is None and not explicit:
+ if r is None and not explicit and not _gateway_review_timed_out:
debug_log(f"dual_or: {primary} leg failed, falling back to sonnet")
r = _call_claude(prompt, output_schema, thinking_budget=thinking_budget,
- max_tokens=max_tokens, model="claude-sonnet-4-6",
+ max_tokens=max_tokens, model=fallback,
retry_5xx=True, cacheable_prefix=cacheable_prefix)
return r
@@ -1197,7 +1382,7 @@ def analyze_code_security(files: List[Tuple[str, str]], is_diff: bool = False, p
"""
_review_status.failed = False
_review_status.status = None
- if not HAS_API_CREDENTIALS or not files:
+ if not (HAS_API_CREDENTIALS or _gateway_cli) or not files:
return None, []
# Build language context from file extensions
@@ -1414,7 +1599,42 @@ def _only_tools_args(tools: Tuple[str, ...] = ()) -> Dict[str, Optional[str]]:
the permission mode that CLI starts in. Passed as CLI flags because not
every Agent SDK build that can run a review has a `tools` option.
"""
- return {"tools": ",".join(tools), "strict-mcp-config": None}
+ args: Dict[str, Optional[str]] = {"tools": ",".join(tools)}
+ if _send_strict_mcp:
+ args["strict-mcp-config"] = None
+ else:
+ # The servers an administrator delivers still start; their tools are
+ # kept from the reviewer.
+ args["disallowedTools"] = "mcp__*"
+ return args
+
+
+# Claude Code exits at startup when given --strict-mcp-config on a machine
+# whose administrator delivers the MCP servers (managed-mcp.json). The flag
+# is sent until an inner CLI refuses it.
+_send_strict_mcp = True
+
+
+def _names_strict_mcp_flag(stderr_line: Any) -> bool:
+ return "--strict-mcp-config" in str(stderr_line)
+
+
+def _run_inner_cli(start: Callable[[], Any], stderr_lines: List[str]) -> Any:
+ """start() runs one inner CLI to its result; stderr_lines receives what
+ that CLI writes to stderr. A start the CLI refused over
+ --strict-mcp-config is made once more without the flag, and the flag is
+ left out for the rest of this process."""
+ global _send_strict_mcp
+ del stderr_lines[:]
+ try:
+ return start()
+ except Exception:
+ if not any(_names_strict_mcp_flag(l) for l in stderr_lines):
+ raise
+ _send_strict_mcp = False
+ debug_log("inner CLI refused --strict-mcp-config; starting it again without the flag")
+ del stderr_lines[:]
+ return start()
def _agentic_spawn_env() -> Dict[str, str]:
@@ -1435,6 +1655,9 @@ def _agentic_spawn_env() -> Dict[str, str]:
is the only credential.
"""
env = {
+ # Policy settings can enable this plugin inside the reviewing CLI too;
+ # its hooks there must not start reviews of their own.
+ "SECURITY_GUIDANCE_DISABLE": "1",
"FALLBACK_FOR_ALL_PRIMARY_MODELS": "1",
"CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR": "",
"CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR": "",
@@ -1588,59 +1811,26 @@ def _agentic_review(
# `[Request interrupted by user]` and gives up). The CLI that launched
# this hook is by definition >= the plugin's tested floor, so it's
# always at least as capable.
- #
- # CLAUDE_CODE_EXECPATH is the absolute path to the running CC binary
- # itself (e.g. ~/.local/share/claude/versions/2.1.x — that's the binary,
- # not a directory). It is the exact CLI that loaded this hook. We do NOT
- # fall back to shutil.which("claude") because the hook's cwd is the
- # user's (potentially attacker-supplied) repo, and Windows shutil.which
- # searches cwd first — a checked-in ./claude.exe would get spawned.
- # Absolute-path probes only.
- #
- # Also monkeypatch the SDK's message parser to tolerate unknown message
- # types (newer CLI emits rate_limit_event which older SDK raises on).
- cli_path = os.environ.get("SG_AGENTIC_CLI_PATH")
- if cli_path is None:
- for p in (
- os.environ.get("CLAUDE_CODE_EXECPATH"),
- os.path.expanduser("~/.local/bin/claude"),
- "/root/.local/bin/claude",
- # Claude Code Remote container install path. CLAUDE_CODE_EXECPATH
- # is not exported to hook subprocesses there, so without this
- # candidate cli_path resolves to None and the SDK uses its
- # bundled CLI — which lags the running CC by builds.
- "/opt/claude-code/bin/claude",
- ):
- if p and os.path.isfile(p):
- cli_path = p
- break
+ cli_path = _gateway_cli or _user_cli_path()
if cli_path:
- try:
- from claude_agent_sdk._internal import message_parser as _mp
- import claude_agent_sdk._internal.client as _sdk_client
- from claude_agent_sdk import SystemMessage as _SysMsg
-
- _orig_parse = _mp.parse_message
-
- def _tolerant(data):
- try:
- return _orig_parse(data)
- except Exception:
- return _SysMsg(subtype=data.get("type", "unknown"), data=data)
-
- _mp.parse_message = _tolerant
- _sdk_client.parse_message = _tolerant
- except Exception:
- pass
+ _tolerate_unknown_sdk_messages()
# 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]
+ # Lines of the current start that name --strict-mcp-config (_run_inner_cli).
+ flag_refusals: List[str] = []
def _child_stderr_metric() -> Dict[str, int]:
return {"child_stderr": child_stderr_lines[0]} if child_stderr_lines[0] else {}
def _on_child_stderr(line: str) -> None:
+ if _names_strict_mcp_flag(line):
+ # Not counted: where the flag is refused, every review gets this
+ # line once, from the start that is then made again.
+ flag_refusals.append(str(line))
+ debug_log(f"agentic reviewer's CLI stderr | {str(line).rstrip()}")
+ return
child_stderr_lines[0] += 1
metrics["child_stderr"] = child_stderr_lines[0]
if child_stderr_lines[0] <= 20:
@@ -1751,7 +1941,9 @@ 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_inner_cli(
+ lambda: _asyncio.run(_arun(system, prompt, schema=schema)),
+ flag_refusals)
# 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/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index fcb04973..3c38e664 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -49,7 +49,9 @@ Other:
- SECURITY_REVIEW_MODEL: Model for LLM review (default: the newest Opus)
- ANTHROPIC_API_KEY: Required for LLM-based reviews
- ANTHROPIC_AUTH_TOKEN: Alternative to API key — OAuth access token sent as Bearer auth.
- Claude Code passes this automatically for OAuth-authenticated users.
+ Claude Code passes this to the plugin's hooks for signed-in users, unless
+ telemetry or nonessential traffic is turned off. With neither, the LLM
+ reviews are skipped and the user is told once (see README, Credentials).
"""
try:
@@ -103,6 +105,7 @@ from gitutil import ( # noqa: E402,F401
GIT_CMD, apply_safe_git_env, remove_copies_on_termination,
_git_rev_parse_head, _find_git_index, _diff_pathspec, _temp_index,
_git_toplevel, _git_dir, _git_rev_list_range, _git_diff_range,
+ _git_toplevel_and_head, _git_head_at,
_detect_main_branch, _git_reflog_recent_commits, _git_name_only,
_git_status_porcelain, _is_ancestor, get_git_diff,
SOURCE_CODE_EXTENSIONS, SOURCE_CODE_BASENAMES,
@@ -122,6 +125,8 @@ from diffstate import ( # noqa: E402,F401
_reviewed_shas_path, _load_reviewed_shas, _append_reviewed_shas,
_full_shas, _mark_inflight, _load_inflight_shas, _reviewed_after_inflight,
UNTRACKED_BASELINE_CAP, _list_untracked, compute_v2_review_set,
+ baseline_origin, baseline_origin_metric, FOREIGN_ORIGINS,
+ KEPT_NO_CAPTURE, KEPT_UNREVIEWED,
)
from reporesolve import ( # noqa: E402,F401
RES_NONE, RES_CWD, RES_COMMAND, RES_SHA_SCAN, RES_TOUCHED_PATHS, RES_HINT,
@@ -298,6 +303,10 @@ def emit_metrics(
cfg = llm.gateway_cfg()
if cfg:
tail["gateway_cfg"] = cfg
+ if not llm._send_strict_mcp:
+ # An inner CLI refused --strict-mcp-config (a machine with a
+ # managed-mcp.json) and the review was started again without it.
+ tail["strict_mcp_off"] = 1
tail.update(_TAIL_METRICS)
metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}}
out = {"metrics": metrics}
@@ -315,6 +324,81 @@ def emit_metrics(
out["systemMessage"] = system_message
_write_hook_output(out)
+
+def _llm_review_off(session_id):
+ """Why no LLM review can run: (log text, extra metrics), or None."""
+ if not ENABLE_CODE_SECURITY_REVIEW:
+ return "LLM review disabled", {}
+ if not llm.can_review(session_id):
+ return ("no API credentials and no Claude apps gateway sign-in",
+ {"no_creds": True})
+ return None
+
+
+# Claude Code hands a signed-in user's credentials to this plugin's hooks,
+# but not in a session started with one of these set.
+_NO_CREDENTIALS_NOTICE_INTERVAL_SEC = 7 * 24 * 3600
+
+
+def _credential_withholding_env_vars():
+ names = [v for v in ("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
+ "DISABLE_TELEMETRY") if os.environ.get(v)]
+ if os.environ.get("DO_NOT_TRACK", "").strip().lower() in (
+ "1", "true", "yes", "on"):
+ names.append("DO_NOT_TRACK")
+ return names
+
+
+def _no_credentials_notice(file_path, session_id):
+ """Text telling the user the LLM reviews are not running, or None.
+
+ With no credential and no Claude apps gateway sign-in, every Stop,
+ commit and push review is skipped, and nothing else tells the user.
+ Returned for an edit inside a git repo (the reviews only look at those),
+ at most once a week per install: the marker file in the state dir holds
+ the time of the last notice, or of the last check that found the reviews
+ running through a Claude apps gateway sign-in. A marker that can't be
+ written means no notice rather than one on every edit. The caller is the
+ Edit/Write hook because the review hooks run in the background, where
+ Claude Code does not show a systemMessage.
+ """
+ import time as _time
+ try:
+ marker = os.path.join(_resolve_state_dir(), ".no_credentials_notice")
+ try:
+ age = _time.time() - os.path.getmtime(marker)
+ if 0 <= age < _NO_CREDENTIALS_NOTICE_INTERVAL_SEC:
+ return None
+ except OSError:
+ pass
+ if not _git_toplevel(os.path.dirname(os.path.abspath(file_path))):
+ return None
+ os.makedirs(os.path.dirname(marker), exist_ok=True)
+ with open(marker, "w"):
+ pass
+ # In a session signed in to a Claude apps gateway the reviews do run,
+ # through the user's claude (llm.gateway_review_cli). `claude auth
+ # status` runs only after the marker is written, so an edit waits for
+ # it at most once a week.
+ if llm.can_review(session_id):
+ return None
+ except OSError:
+ return None
+ withheld_by = _credential_withholding_env_vars()
+ if withheld_by:
+ why = ("Claude Code does not pass your sign-in to plugins while "
+ + " or ".join(withheld_by) + " is set")
+ else:
+ why = "No Anthropic credentials were passed to the plugin's hooks"
+ rest = (", so only the pattern warnings on edits are active"
+ if ENABLE_PATTERN_RULES else "")
+ return (
+ "security-guidance: the AI security review of your changes is not "
+ f"running. {why}{rest}. See \"Credentials\" in the plugin README. "
+ "Set ENABLE_CODE_SECURITY_REVIEW=0 to turn the review off and hide "
+ "this notice, which is shown at most once a week."
+ )
+
# =====================================================================
# State management
# =====================================================================
@@ -473,11 +557,30 @@ def sweep_pending_warnings(session_id):
# Pattern matching
# =====================================================================
+def _notebook_cell_sources(content):
+ """Cell sources of a saved notebook, or None when content is not one (a
+ single cell's source, say)."""
+ if not isinstance(content, str) or not content.lstrip("\ufeff \t\r\n").startswith("{"):
+ return None
+ try:
+ sources = [cell.get("source", "") for cell in json.loads(content.lstrip("\ufeff"))["cells"]]
+ return "\n".join(src if isinstance(src, str) else "".join(src) for src in sources)
+ except Exception:
+ return None
+
def check_patterns(file_path, content):
"""Check if file path or content matches any security patterns. Returns ALL matches."""
normalized_path = file_path.lstrip("/")
matches = []
+ # A saved notebook is JSON: its string escapes hide code from the rules
+ # ("\nos.system(" has no word boundary) and its outputs can run to
+ # megabytes. Check the cells as written instead.
+ if normalized_path.endswith(".ipynb"):
+ cell_sources = _notebook_cell_sources(content)
+ if cell_sources is not None:
+ content = cell_sources
+
for pattern in list(SECURITY_PATTERNS) + extensibility.user_patterns():
# path_filter is a gate: when present, the rule only applies to
# matching paths. Distinct from path_check, which is itself a
@@ -516,7 +619,7 @@ def check_patterns(file_path, content):
return matches
-def extract_content_from_input(tool_name, tool_input):
+def extract_content_from_input(tool_name, tool_input, tool_response=None):
"""Extract content to check from tool input based on tool type."""
if tool_name == "Write":
return tool_input.get("content", "")
@@ -527,6 +630,15 @@ def extract_content_from_input(tool_name, tool_input):
if edits:
return " ".join(edit.get("new_string", "") for edit in edits)
return ""
+ elif tool_name == "NotebookEdit":
+ # A deleted cell adds no code. A failed edit comes back as an error
+ # in the response, with the notebook unchanged.
+ if tool_input.get("edit_mode") == "delete":
+ return ""
+ if isinstance(tool_response, dict) and tool_response.get("error"):
+ return ""
+ new_source = tool_input.get("new_source", "")
+ return new_source if isinstance(new_source, str) else ""
return ""
# =====================================================================
@@ -576,14 +688,24 @@ def handle_user_prompt_submit(input_data):
# something tracked is dirtied.
return _f_sha.result(), _f_ut.result() or {}
+ import time as _time
+ captured_at = _time.time()
sha, untracked_now = _capture(cwd)
+ # No repo here and none remembered: the listing above failed, it did not
+ # come back empty.
+ no_repo = False
if not sha and not _git_toplevel(cwd):
hint = load_repo_hint(session_id)
if hint:
debug_log(f"UPS: cwd is not a git repo; using repo hint {hint!r}")
cwd = hint
sha, untracked_now = _capture(cwd)
- head = _git_rev_parse_head(cwd)
+ else:
+ no_repo = True
+ # The repo root rides on the same git call as HEAD.
+ root, head = (None, None) if no_repo else _git_toplevel_and_head(cwd)
+ if sha and not head:
+ head = _git_rev_parse_head(cwd)
# If the previous turn's Stop hook never ran (user interrupt, follow-up
# during work, tool-reject, model crash, maxTurns, PostToolUse block…),
@@ -606,10 +728,25 @@ def handle_user_prompt_submit(input_data):
# untracked file in the tree as written this turn.
if untracked_now is not None and "untracked_at_baseline" not in state:
state["untracked_at_baseline"] = untracked_now
+ # Once a prompt failed to capture, the baseline is old whatever
+ # later prompts did.
+ state["baseline_kept"] = (
+ KEPT_NO_CAPTURE
+ if not sha or state.get("baseline_kept") == KEPT_NO_CAPTURE
+ else KEPT_UNREVIEWED)
return
if sha:
state["baseline_sha"] = sha
state["head_at_capture"] = head
+ # A Stop review that ends up in another checkout does not use
+ # this baseline.
+ state["baseline_root"] = root
+ state.pop("baseline_kept", None)
+ elif state.get("baseline_sha"):
+ state["baseline_kept"] = KEPT_NO_CAPTURE
+ # When the turn began: what a Stop review in another checkout has
+ # to go on.
+ state["prompt_at"] = captured_at
# untracked_at_baseline is independent of whether the stash produced
# a SHA, so compute_v2_review_set's preexisting-untracked exclusion
# works in untracked-only trees. None means no snapshot was taken
@@ -617,7 +754,10 @@ def handle_user_prompt_submit(input_data):
# baseline.
if untracked_now is None:
state.pop("untracked_at_baseline", None)
- else:
+ elif not no_repo:
+ # no_repo: the earlier baseline stays (above), and so does the
+ # snapshot that belongs to it. An empty one in its place would
+ # make every untracked file in that repo look new.
state["untracked_at_baseline"] = untracked_now
with_locked_state(session_id, _save)
@@ -1139,6 +1279,12 @@ def _review_failure_reason(status):
if llm._is_3p_provider():
return ("provider", "the review through the cloud provider got no answer",
"The plugin's log has the provider's error.")
+ if llm._gateway_cli:
+ pinned = os.environ.get("SECURITY_REVIEW_MODEL", "").strip()
+ return ("gateway", "the review through Claude Code on the Claude apps gateway returned no result",
+ "The plugin's log has the reason. If it says the sign-in has expired, run /login again."
+ + (f" SECURITY_REVIEW_MODEL ({pinned}) may also name a model the gateway does "
+ "not serve." if pinned else ""))
if status == 401:
return ("auth", "the API rejected the plugin's credentials (HTTP 401)",
f"The sign-in may have expired or been revoked{gateway}.")
@@ -1331,9 +1477,10 @@ def handle_commit_review_posttooluse(input_data):
emit_metrics({"skipped": True, "skip_reason": 32, **_base})
sys.exit(0)
- if not ENABLE_CODE_SECURITY_REVIEW or not HAS_API_CREDENTIALS:
- debug_log("Commit review: LLM review disabled or no API credentials")
- emit_metrics({"skipped": True, "skip_reason": 22, **_base})
+ off = _llm_review_off(session_id)
+ if off:
+ debug_log(f"Commit review: {off[0]}")
+ emit_metrics({"skipped": True, "skip_reason": 22, **off[1], **_base})
sys.exit(0)
if not ensure_anthropic_reachable():
@@ -1799,8 +1946,9 @@ def handle_push_sweep_posttooluse(input_data):
if interrupted:
emit_metrics({"skipped": True, "skip_reason": 21, **_base})
sys.exit(0)
- if not ENABLE_CODE_SECURITY_REVIEW or not HAS_API_CREDENTIALS:
- emit_metrics({"skipped": True, "skip_reason": 22, **_base})
+ off = _llm_review_off(session_id)
+ if off:
+ emit_metrics({"skipped": True, "skip_reason": 22, **off[1], **_base})
sys.exit(0)
if not cwd:
emit_metrics({"skipped": True, "skip_reason": 25, **_base})
@@ -2221,9 +2369,12 @@ def handle_stop_hook(input_data):
debug_log(f"Stop hook: already fired {fire_count} times (max {MAX_STOP_HOOK_FIRINGS}), skipping")
_skip(2)
- if not ENABLE_CODE_SECURITY_REVIEW or not HAS_API_CREDENTIALS:
- debug_log("Stop hook: LLM review disabled or no API credentials")
- _skip(3)
+ off = _llm_review_off(session_id)
+ if off:
+ debug_log(f"Stop hook: {off[0]}")
+ # When the sign-in check gave no answer, this turn's changes are kept
+ # for the next Stop review.
+ _skip(3, restore=llm._gateway_check_unanswered, **off[1])
# Stop-hook-only kill switch — placed after consume_stop_state so
# touched_paths is still cleared each turn (a disabled Stop hook that
@@ -2260,9 +2411,40 @@ def handle_stop_hook(input_data):
save_repo_hint(session_id, repo_cwd)
cwd = repo_cwd
+ # The baseline belongs to the checkout the prompt hook captured it in.
+ # When the turn ends in another one (the session entered a worktree, or
+ # the edits were in a different repo), it says nothing about what changed
+ # here: this checkout's older commits would look like commits made this
+ # turn, and its files would be diffed against the other checkout's. Use
+ # what this checkout can say for itself instead: its own HEAD when the
+ # turn began (from its reflog) for commits, HEAD for file contents, and
+ # file times for which uncommitted files were already there.
+ origin = None
+ if repo_cwd:
+ try:
+ origin = baseline_origin(repo_cwd, snap_baseline, snap["baseline_root"])
+ except Exception as e:
+ debug_log(f"Stop hook: baseline origin check failed: {e}")
+ foreign_baseline = origin in FOREIGN_ORIGINS
+ since_ns = None
+ if foreign_baseline:
+ at = snap["prompt_at"]
+ at = at if isinstance(at, (int, float)) and 0 < at < 1e11 else None
+ baseline_sha = None
+ head_at_capture = _git_head_at(repo_cwd, at) if at else None
+ untracked_at_baseline = {}
+ since_ns = int(at * 1e9) if at else None
+ debug_log(f"Stop hook: baseline {str(snap_baseline)[:12]} is from another "
+ f"checkout (origin {origin}); this one was at "
+ f"{str(head_at_capture)[:12]} when the turn began")
+
review_paths, diff_base, repo_root, untracked, v2_metrics = compute_v2_review_set(
- cwd, baseline_sha, head_at_capture, untracked_at_baseline
+ cwd, baseline_sha, head_at_capture, untracked_at_baseline, since_ns=since_ns
)
+ # Sent even when 0, once git status has worked.
+ if origin is not None and v2_metrics.get("dirty_now_count", -1) >= 0:
+ _TAIL_METRICS["bl_origin"] = baseline_origin_metric(origin, snap["baseline_kept"])
+
v2_metrics = {**res_metrics, **v2_metrics}
if not review_paths:
debug_log("Stop hook: empty review set")
@@ -2369,6 +2551,10 @@ def handle_stop_hook(input_data):
# Update baseline so next stop hook iteration only sees new changes
new_sha = None if is_subagent else capture_git_baseline(cwd)
new_untracked_baseline = _list_untracked(cwd) if new_sha else None
+ # After a baseline from another checkout, the rest of it is replaced
+ # too, below.
+ new_head = (_git_rev_parse_head(cwd)
+ if new_sha and foreign_baseline and not head_at_capture else None)
def _record_fire(state):
if is_subagent:
@@ -2393,6 +2579,13 @@ def handle_stop_hook(input_data):
if new_sha:
state["baseline_sha"] = new_sha
state["untracked_at_baseline"] = new_untracked_baseline
+ state["baseline_root"] = repo_root
+ state.pop("baseline_kept", None)
+ if foreign_baseline:
+ # The stored HEAD is the other checkout's. Keep the one
+ # this review used, so a later Stop this turn still sees
+ # commits made (or amended) here since the prompt.
+ state["head_at_capture"] = head_at_capture or new_head
with_locked_state(session_id, _record_fire)
if new_sha:
@@ -2625,7 +2818,8 @@ def main():
record_touched_path(session_id, file_path)
- content = extract_content_from_input(tool_name, tool_input)
+ content = extract_content_from_input(
+ tool_name, tool_input, input_data.get("tool_response"))
all_guidance = []
raw_pattern_matches = []
@@ -2665,30 +2859,31 @@ def main():
# rule_id: RuleId of the first raw match (values stay small/enumerable in telemetry)
# rule_mask: bitmask of ALL raw matches — POPCOUNT gives raw hit count,
# (mask >> N) & 1 tests for a specific rule
+ output = {}
if raw_pattern_matches:
raw_names = [r for r, _ in raw_pattern_matches]
- output = {"metrics": {
+ output["metrics"] = {
"pattern_hits": len(all_guidance),
# User-defined patterns (rule_name="user:*") have no static
# RuleId; emit -1 so the metrics pipeline can distinguish.
"rule_id": int(_RULE_NAME_TO_ID.get(raw_names[0], -1)),
"rule_mask": rule_names_to_mask(raw_names),
**({"pv": _PV} if _PV else {}),
- }}
- if all_guidance:
- output["hookSpecificOutput"] = {
- "hookEventName": "PostToolUse",
- "additionalContext": PROVENANCE_TAG + "\n\n" + "\n\n".join(all_guidance),
- }
+ }
+ if all_guidance:
+ output["hookSpecificOutput"] = {
+ "hookEventName": "PostToolUse",
+ "additionalContext": PROVENANCE_TAG + "\n\n" + "\n\n".join(all_guidance),
+ }
+ # The LLM reviews are on but can't run: say so.
+ if (ENABLE_CODE_SECURITY_REVIEW and not HAS_API_CREDENTIALS
+ and (ENABLE_STOP_REVIEW or COMMIT_REVIEW_ENABLED
+ or PUSH_SWEEP_ENABLED)):
+ notice = _no_credentials_notice(file_path, session_id)
+ if notice:
+ output["systemMessage"] = notice
+ if output:
_write_hook_output(output)
- elif all_guidance:
- # Defensive: pattern rules disabled but guidance somehow set (shouldn't happen)
- print(json.dumps({
- "hookSpecificOutput": {
- "hookEventName": "PostToolUse",
- "additionalContext": PROVENANCE_TAG + "\n\n" + "\n\n".join(all_guidance),
- }
- }))
sys.exit(0)
diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh
index f1b9d68c..a02c7d6c 100755
--- a/plugins/security-guidance/hooks/sg-python.sh
+++ b/plugins/security-guidance/hooks/sg-python.sh
@@ -135,7 +135,8 @@ is_sdk_compatible() {
# Pass 1 — try minor-versioned binaries in descending order. These are only
# present if the user explicitly installed them (Homebrew / python.org / pyenv),
# so picking one here always upgrades over the system `python3`. Highest
-# available wins; the user doesn't have to PATH-prefer it.
+# of these wins; the user doesn't have to PATH-prefer it. Releases newer
+# than this list are pass 2b.
for cmd in "python3.13" "python3.12" "python3.11" "python3.10"; do
on_path "$cmd" || continue
v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; }
@@ -165,6 +166,22 @@ for cmd in "python3" "python" "py -3"; do
esac
done
+# Pass 2b — minor versions newer than the pass 1 list, so a machine whose
+# only SDK-compatible Python is a recent release (system `python3` 3.9 next to
+# Homebrew's python3.14) is not left on pass 3. Tried only when nothing
+# above is compatible: an interpreter that already works is never traded for
+# a newer one, which may not have the SDK or wheels for its dependencies yet.
+# Oldest first for the same reason. Missing names cost no process (on_path).
+# See #4907, #5024.
+for cmd in "python3.14" "python3.15" "python3.16" "python3.17" "python3.18" "python3.19"; do
+ on_path "$cmd" || continue
+ v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; }
+ v=${v%$'\r'}
+ if is_sdk_compatible "$v"; then
+ exec "$cmd" "$@"
+ fi
+done
+
# Pass 3 — fallback to any Python 3, even <3.10. Pattern-based checks
# (PostToolUse regex on Edit/Write) only need 3.6+ and are useful on their
# own; the SDK-dependent paths will detect the version mismatch and degrade
@@ -237,7 +254,7 @@ if [ -n "$sg_unreadable" ]; then
exit 1
fi
echo "security-guidance: no working Python 3 interpreter found." >&2
-echo " tried: python3.13, python3.12, python3.11, python3.10, python3, python, py -3" >&2
+echo " tried: python3.13 to python3.10, python3, python, py -3, python3.14 to python3.19" >&2
echo " on Windows, install Python from https://python.org (NOT the Microsoft Store)" >&2
echo " on macOS, install Python 3.10+ via Homebrew (\`brew install python\`)" >&2
exit 1
diff --git a/plugins/security-guidance/tests/conftest.py b/plugins/security-guidance/tests/conftest.py
index 998401c2..f1addb9b 100644
--- a/plugins/security-guidance/tests/conftest.py
+++ b/plugins/security-guidance/tests/conftest.py
@@ -1,10 +1,14 @@
import http.server
+import io
import json
import os
+import struct
import subprocess
import sys
+import sysconfig
import threading
import time
+import zipfile
from pathlib import Path
import pytest
@@ -137,6 +141,9 @@ def hook_env(tmp_path, stub_api):
"ANTHROPIC_BASE_URL": f"http://127.0.0.1:{stub_api.server_port}",
"NO_PROXY": "*", "no_proxy": "*",
"SG_AGENTIC_COMMIT_REVIEW": "0",
+ # Points the plugin at a claude that does not exist, so no hook test
+ # runs this machine's own claude.
+ "SG_AGENTIC_CLI_PATH": str(tmp_path / "no-claude"),
"SECURITY_GUIDANCE_COMMIT_REVIEW": "on",
"SG_PUSH_SWEEP": "on",
"PYTHONDONTWRITEBYTECODE": "1",
@@ -277,14 +284,47 @@ def env(hook_env, gateway):
return e
+def _windows_exe(script):
+ """`script` as the bytes of a Windows .exe: Windows starts neither a
+ `#!` file nor, without a shell, a .cmd with multi-line arguments. Built
+ the way pip builds a console script: its launcher stub, then the
+ interpreter to run, then a zip holding the script as __main__.py."""
+ distlib = pytest.importorskip("pip._vendor.distlib")
+ stub = "t%s%s.exe" % ("64" if struct.calcsize("P") == 8 else "32",
+ "-arm" if sysconfig.get_platform() == "win-arm64" else "")
+ stub = os.path.join(os.path.dirname(distlib.__file__), stub)
+ if not os.path.isfile(stub):
+ pytest.skip(f"pip has no script launcher {os.path.basename(stub)}")
+ with open(stub, "rb") as f:
+ launcher = f.read()
+ python = f'"{sys.executable}"' if " " in sys.executable else sys.executable
+ archive = io.BytesIO()
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("__main__.py", script)
+ return launcher + f"#!{python}\n".encode("utf-8") + archive.getvalue()
+
+
+def write_cli(tmp_path, name, script):
+ """A stand-in for `claude` in `tmp_path` that runs the Python `script`;
+ returns its path."""
+ if os.name == "nt":
+ cli = tmp_path / f"{name}.exe"
+ cli.write_bytes(_windows_exe(script))
+ else:
+ cli = tmp_path / name
+ cli.write_text(f"#!{sys.executable}\n{script}")
+ cli.chmod(0o755)
+ return cli
+
+
@pytest.fixture
def failing_inner_cli(tmp_path):
"""An inner CLI that prints a warning on stderr and exits 1; the review
then falls back to a single-shot call."""
- cli = tmp_path / "claude"
- cli.write_text("#!/bin/sh\necho 'claude.ai connectors are disabled' >&2\nexit 1\n")
- cli.chmod(0o755)
- return str(cli)
+ return str(write_cli(tmp_path, "claude", (
+ "import sys\n"
+ "sys.stderr.write('claude.ai connectors are disabled\\n')\n"
+ "sys.exit(1)\n")))
@pytest.fixture
diff --git a/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py b/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py
new file mode 100644
index 00000000..2325cd9b
--- /dev/null
+++ b/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py
@@ -0,0 +1,75 @@
+"""The SDK bootstrap's Python subprocesses must not import from the repository.
+
+`python -c` and `python -m` put the working directory first on the import
+path, and hooks run in the user's repository, so every interpreter the
+bootstrap starts runs from a directory the plugin owns.
+"""
+import ast
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+import ensure_agent_sdk
+
+from conftest import HOOKS_DIR, make_repo
+
+
+def _spawns(tree):
+ for node in ast.walk(tree):
+ if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
+ and node.func.attr in ("run", "Popen", "call", "check_call", "check_output")
+ and isinstance(node.func.value, ast.Name) and node.func.value.id == "subprocess"):
+ yield node
+
+
+def test_every_spawn_sets_a_plugin_owned_cwd():
+ tree = ast.parse((HOOKS_DIR / "ensure_agent_sdk.py").read_text())
+ calls = list(_spawns(tree))
+ assert len(calls) >= 6
+ for call in calls:
+ cwd = [k for k in call.keywords if k.arg == "cwd"]
+ assert cwd, f"subprocess call on line {call.lineno} inherits the hook's working directory"
+ assert ast.unparse(cwd[0].value) == "_spawn_cwd()", call.lineno
+
+
+def test_spawn_cwd_is_the_state_dir(tmp_path, monkeypatch):
+ state = tmp_path / "state"
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(state))
+ assert ensure_agent_sdk._spawn_cwd() == str(state)
+ assert state.is_dir()
+
+
+def test_relative_state_dir_is_made_absolute(tmp_path, monkeypatch):
+ # Children run in the state dir, so a relative one would be resolved twice.
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", "rel")
+ assert ensure_agent_sdk._spawn_cwd() == str(tmp_path / "rel")
+
+
+@pytest.mark.skipif(sys.platform == "win32", reason="symlinked interpreter")
+@pytest.mark.skipif(sys.version_info < (3, 10), reason="bootstrap stops before the probe")
+def test_health_check_ignores_module_in_repo(tmp_path, monkeypatch):
+ repo = tmp_path / "repo"
+ make_repo(repo)
+ marker = tmp_path / "imported-from-repo"
+ (repo / "claude_agent_sdk.py").write_text(
+ f"open({str(marker)!r}, 'w').write('x')\n")
+
+ state = tmp_path / "state"
+ venv_bin = state / "agent-sdk-venv" / ("Scripts" if sys.platform == "win32" else "bin")
+ venv_bin.mkdir(parents=True)
+ venv_py = venv_bin / ("python.exe" if sys.platform == "win32" else "python")
+ os.symlink(sys.executable, venv_py)
+
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(state))
+ monkeypatch.chdir(repo)
+ monkeypatch.setattr(ensure_agent_sdk, "_sdk_on_syspath", lambda: False)
+ # No rebuild if the probe fails: this test only covers the probe.
+ ensure_agent_sdk._write_cooldown(state)
+
+ outcome, _, _ = ensure_agent_sdk.main()
+
+ assert outcome in (ensure_agent_sdk.NOOP_VENV, ensure_agent_sdk.SKIP_COOLDOWN)
+ assert not marker.exists()
diff --git a/plugins/security-guidance/tests/test_gateway_sign_in.py b/plugins/security-guidance/tests/test_gateway_sign_in.py
new file mode 100644
index 00000000..7b6e9fc4
--- /dev/null
+++ b/plugins/security-guidance/tests/test_gateway_sign_in.py
@@ -0,0 +1,396 @@
+"""Reviews in a session signed in to a Claude apps gateway with /login, where
+Claude Code gives hooks no credential."""
+import asyncio
+import json
+import os
+import sys
+import types
+
+import pytest
+
+from conftest import (
+ VULN_PY, bash_payload, commit_file, edit_payload, git, metrics_of, run_hook,
+ stop_payload, ups_payload, write_cli,
+)
+
+import _base
+import llm
+
+SIGNED_IN = json.dumps({"loggedIn": True, "authMethod": "third_party", "apiProvider": "gateway"})
+NOT_SIGNED_IN = json.dumps({"loggedIn": False, "authMethod": "none", "apiProvider": "gateway"})
+
+
+def make_cli(tmp_path, auth_status, *, name="claude", hang=False, linger=False):
+ """A fake `claude` that logs each call to <name>.calls as its arguments, the
+ SECURITY_GUIDANCE_DISABLE it got and its working directory, prints
+ `auth_status` for `auth status --json`, and fails anything else. `hang`
+ waits 5 s before answering; `linger` leaves a process running that holds
+ stdout open after the CLI exits."""
+ calls = tmp_path / f"{name}.calls"
+ script = f"""import os, subprocess, sys, time
+with open({str(calls)!r}, "a", encoding="utf-8") as f:
+ f.write(" ".join(sys.argv[1:]) + " | SGD=" + os.environ.get("SECURITY_GUIDANCE_DISABLE", "")
+ + " | CWD=" + os.getcwd() + "\\n")
+if sys.argv[1:3] != ["auth", "status"]:
+ sys.stderr.write("review refused\\n")
+ sys.exit(1)
+if {hang!r}:
+ time.sleep(5)
+sys.stdout.write({auth_status!r})
+sys.stdout.flush()
+if {linger!r}:
+ subprocess.Popen([sys.executable, "-c", "import time; time.sleep(5)"])
+"""
+ return write_cli(tmp_path, name, script), calls
+
+
+def calls_of(calls):
+ return calls.read_text(encoding="utf-8").splitlines() if calls.exists() else []
+
+
+def review_calls(calls):
+ return [c for c in calls_of(calls) if "--input-format stream-json" in c]
+
+
+def model_of(call):
+ args = call.split(" | ")[0].split()
+ return args[args.index("--model") + 1]
+
+
+@pytest.fixture
+def no_credential(monkeypatch, tmp_path):
+ # CLAUDE_CODE_REMOTE_SESSION_ID makes every session share one state file.
+ for var in ("SECURITY_REVIEW_MODEL", "CLAUDE_CODE_EXECPATH", "CLAUDE_CODE_REMOTE_SESSION_ID",
+ *llm._PROVIDER_ENV_VARS):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(tmp_path / "no-claude"))
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state"))
+ monkeypatch.setattr(_base, "DEBUG_LOG_FILE", str(tmp_path / "log.txt"))
+ monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", False)
+ new_hook_process(monkeypatch)
+
+
+def new_hook_process(monkeypatch):
+ monkeypatch.setattr(llm, "_gateway_cli", None)
+ monkeypatch.setattr(llm, "_gateway_check_unanswered", False)
+ monkeypatch.setattr(llm, "_gateway_review_timed_out", False)
+
+
+class TestGatewaySignInCheck:
+ @pytest.mark.parametrize("auth_status, signed_in", [
+ pytest.param(SIGNED_IN, True, id="signed-in"),
+ pytest.param(NOT_SIGNED_IN, False, id="gateway-named-but-not-signed-in"),
+ pytest.param(json.dumps({"loggedIn": True, "apiProvider": "firstParty"}), False,
+ id="first-party"),
+ pytest.param(json.dumps({"loggedIn": "true", "apiProvider": "gateway"}), False,
+ id="logged-in-not-a-boolean"),
+ pytest.param("Logged in via gateway", False, id="not-json"),
+ pytest.param("[]", False, id="not-an-object"),
+ pytest.param("[" * 60000, False, id="too-deeply-nested"),
+ ])
+ def test_reviews_only_for_a_signed_in_gateway_session(
+ self, no_credential, monkeypatch, tmp_path, auth_status, signed_in):
+ cli, calls = make_cli(tmp_path, auth_status)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli))
+ assert llm.can_review("s1") is signed_in
+ assert [c.split(" | ")[0] for c in calls_of(calls)] == ["auth status --json"]
+
+ def test_cli_that_cannot_start_means_no_review(self, no_credential):
+ assert llm.can_review("s1") is False
+
+ def test_no_cli_found_means_no_review(self, no_credential, monkeypatch):
+ monkeypatch.setattr(llm, "_user_cli_path", lambda: None)
+ assert llm.can_review("s1") is False
+
+ def test_relative_cli_path_is_not_run(self, no_credential, monkeypatch, tmp_path):
+ cli, calls = make_cli(tmp_path, SIGNED_IN)
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", f"./{cli.name}")
+ assert llm.can_review("s1") is False
+ assert calls_of(calls) == []
+
+ def test_asked_from_the_home_directory(self, no_credential, monkeypatch, tmp_path):
+ cli, calls = make_cli(tmp_path, SIGNED_IN)
+ home, repo = tmp_path / "home", tmp_path / "repo"
+ home.mkdir()
+ repo.mkdir()
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("USERPROFILE", str(home)) # "~" on Windows
+ monkeypatch.chdir(repo)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli))
+ assert llm.can_review("s1")
+ assert calls_of(calls)[0].endswith(f"CWD={home}")
+
+ def test_hung_cli_means_no_review(self, no_credential, monkeypatch, tmp_path):
+ cli, _ = make_cli(tmp_path, SIGNED_IN, hang=True)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli))
+ monkeypatch.setattr(llm, "_GATEWAY_CHECK_TIMEOUT_S", 1)
+ assert llm.can_review("s1") is False
+
+ def test_answer_is_read_while_a_process_it_started_holds_stdout(
+ self, no_credential, monkeypatch, tmp_path):
+ cli, _ = make_cli(tmp_path, SIGNED_IN, linger=True)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli))
+ monkeypatch.setattr(llm, "_GATEWAY_CHECK_TIMEOUT_S", 3)
+ assert llm.can_review("s1") is True
+
+ def test_asked_once_per_session(self, no_credential, monkeypatch, tmp_path):
+ cli, calls = make_cli(tmp_path, SIGNED_IN)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli))
+ assert llm.can_review("s1")
+ new_hook_process(monkeypatch)
+ assert llm.can_review("s1")
+ assert len(calls_of(calls)) == 1
+ new_hook_process(monkeypatch)
+ assert llm.can_review("s2")
+ assert len(calls_of(calls)) == 2
+
+ def test_no_answer_is_asked_again(self, no_credential, monkeypatch, tmp_path):
+ cli, calls = make_cli(tmp_path, "")
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli))
+ assert llm.can_review("s1") is False
+ make_cli(tmp_path, SIGNED_IN)
+ new_hook_process(monkeypatch)
+ assert llm.can_review("s1") is True
+ assert len(calls_of(calls)) == 2
+
+ def test_a_different_cli_is_asked_again(self, no_credential, monkeypatch, tmp_path):
+ first, _ = make_cli(tmp_path, SIGNED_IN, name="first")
+ second, second_calls = make_cli(tmp_path, NOT_SIGNED_IN, name="second")
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(first))
+ assert llm.can_review("s1")
+ new_hook_process(monkeypatch)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(second))
+ assert llm.can_review("s1") is False
+ assert len(calls_of(second_calls)) == 1
+
+ def test_credential_in_env_never_asks_the_cli(self, no_credential, monkeypatch, tmp_path):
+ cli, calls = make_cli(tmp_path, SIGNED_IN)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli))
+ monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True)
+ assert llm.can_review("s1")
+ assert calls_of(calls) == []
+
+ def test_telemetry_names_the_route(self, no_credential, monkeypatch, tmp_path):
+ monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)
+ monkeypatch.delenv("ANTHROPIC_CUSTOM_HEADERS", raising=False)
+ cli, _ = make_cli(tmp_path, SIGNED_IN)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli))
+ assert llm.gateway_cfg() == 0
+ assert llm.can_review("s1")
+ assert llm.gateway_cfg() == 4
+
+ def test_essential_traffic_only_still_reviews(self, no_credential, monkeypatch, tmp_path):
+ cli, _ = make_cli(tmp_path, SIGNED_IN)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli))
+ monkeypatch.setenv("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1")
+ assert llm.can_review("s1")
+
+
+class FakeChild:
+ """Stands in for the child CLI's review; `reply` is what each call returns."""
+
+ def __init__(self):
+ self.prompts = []
+ self.reply = {"hasVulnerabilities": False, "vulnerabilities": []}
+
+ def __call__(self, prompt, schema, *, max_tokens=16000, model=None, cli_path=None):
+ self.prompts.append(prompt)
+ if self.reply is None:
+ llm._last_call_claude_http_error = -1
+ return self.reply
+
+
+class TestGatewayReviewOutcome:
+ @pytest.fixture
+ def child(self, no_credential, monkeypatch, tmp_path):
+ cli, _ = make_cli(tmp_path, SIGNED_IN)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli))
+ fake = FakeChild()
+ monkeypatch.setattr(llm, "_call_claude_via_sdk", fake)
+ return fake
+
+ def test_review_is_sent_to_the_child(self, child):
+ assert llm.can_review("s1")
+ assert llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True) == (None, [])
+ assert not llm.last_review_failed()
+ assert "+x = 1" in child.prompts[0]
+ assert child.prompts[0].startswith(llm._CODE_REVIEW_RUBRIC)
+
+ @pytest.mark.parametrize("reply", [
+ pytest.param(None, id="child-failed"),
+ pytest.param({"findings": []}, id="no-verdict"),
+ ])
+ def test_child_without_a_verdict_is_a_failed_review(self, child, reply):
+ child.reply = reply
+ assert llm.can_review("s1")
+ assert llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True) == (None, [])
+ assert llm.last_review_failed()
+
+ def test_failed_review_is_tried_on_sonnet_unless_it_timed_out(self, child, monkeypatch):
+ child.reply = None
+ assert llm.can_review("s1")
+ llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True)
+ assert len(child.prompts) == 2
+ monkeypatch.setattr(llm, "_gateway_review_timed_out", True)
+ llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True)
+ assert len(child.prompts) == 3 and llm.last_review_failed()
+
+ def test_not_signed_in_sends_nothing(self, child, monkeypatch, tmp_path):
+ cli, _ = make_cli(tmp_path, NOT_SIGNED_IN, name="signed-out")
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", str(cli))
+ assert not llm.can_review("s1")
+ assert llm.analyze_code_security([("a.py", "+x = 1\n")], is_diff=True) == (None, [])
+ assert not llm.last_review_failed()
+ assert child.prompts == []
+
+
+def test_timed_out_review_logs_what_the_cli_retried(no_credential, monkeypatch, tmp_path):
+ """The CLI retries a refused sign-in by itself until the plugin's time
+ limit; the retries are in its output, not on stderr."""
+ class Retry:
+ subtype, data = "api_retry", {"error_status": 401}
+
+ async def query(prompt, options):
+ yield Retry()
+ raise asyncio.TimeoutError()
+
+ mod = types.ModuleType("claude_agent_sdk")
+ mod.query = query
+ mod.ClaudeAgentOptions = lambda **kwargs: kwargs
+ mod.AssistantMessage = type("AssistantMessage", (), {})
+ mod.ResultMessage = type("ResultMessage", (), {})
+ monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod)
+ cli, _ = make_cli(tmp_path, SIGNED_IN)
+ schema = {"type": "object", "properties": {}}
+ assert llm._call_claude_via_sdk("review this", schema, cli_path=str(cli)) is None
+ assert llm._gateway_review_timed_out is True
+ assert ("gateway sdk-single-turn: timeout after 120s; the CLI's API requests were "
+ "retried after status 401") in (tmp_path / "log.txt").read_text()
+ # Not for the cloud-provider route, where the model can be the reason.
+ monkeypatch.setattr(llm, "_gateway_review_timed_out", False)
+ assert llm._call_claude_via_sdk("review this", schema) is None
+ assert llm._gateway_review_timed_out is False
+
+
+def without_credential(hook_env):
+ return {k: v for k, v in hook_env.items()
+ if k not in ("ANTHROPIC_API_KEY", "SECURITY_REVIEW_MODEL",
+ "CLAUDE_CODE_REMOTE_SESSION_ID", *llm._PROVIDER_ENV_VARS)}
+
+
+class TestHooksInASignedInSession:
+ """The hooks with the real Agent SDK and a fake CLI that signs in but
+ refuses every review."""
+
+ @pytest.fixture
+ def session(self, hook_env, tmp_path):
+ pytest.importorskip("claude_agent_sdk")
+ env = without_credential(hook_env)
+ cli, calls = make_cli(tmp_path, SIGNED_IN)
+ env["SG_AGENTIC_CLI_PATH"] = str(cli)
+ return env, calls
+
+ def test_commit_review_goes_through_the_cli_and_fails_loudly(self, session, workspace):
+ env, calls = session
+ _, repo = workspace
+ sha, out = commit_file(repo, "app.py", VULN_PY)
+ rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out), env)
+ assert rc == 2
+ assert metrics_of(so)["review_failed"] is True
+ assert ("did not complete: the review through Claude Code on the Claude apps "
+ "gateway returned no result.") in se
+ reviewed = repo / ".git" / "sg-reviewed-shas"
+ assert not reviewed.exists() or sha not in reviewed.read_text()
+ made = calls_of(calls)
+ assert made[0].startswith("auth status --json")
+ reviews = review_calls(calls)
+ assert [model_of(r) for r in reviews] == ["opus", "sonnet"]
+ # Every claude process the plugin starts (the sign-in check and the
+ # reviews) has this plugin switched off. The Agent SDK's own
+ # `claude -v` version check starts no session, so it is not checked.
+ assert " | SGD=1 | " in made[0]
+ assert all(" | SGD=1 | " in r for r in reviews)
+ # The single-shot review gets no tools, as on Bedrock and Vertex.
+ assert all(" --tools --strict-mcp-config" in r for r in reviews)
+ assert metrics_of(so)["gateway_cfg"] & 4
+
+ def test_pinned_model_is_sent_as_given(self, session, workspace):
+ env, calls = session
+ env["SECURITY_REVIEW_MODEL"] = "claude-sonnet-5-5"
+ _, repo = workspace
+ _, out = commit_file(repo, "app.py", VULN_PY)
+ rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out), env)
+ assert rc == 2
+ assert [model_of(r) for r in review_calls(calls)] == ["claude-sonnet-5-5"]
+ assert "SECURITY_REVIEW_MODEL (claude-sonnet-5-5) may also name a model" in se
+
+ def test_agentic_commit_review_runs(self, session, workspace):
+ env, calls = session
+ env["SG_AGENTIC_COMMIT_REVIEW"] = "1"
+ env["SG_AGENTIC_MAX_TURNS"] = "7"
+ _, repo = workspace
+ _, out = commit_file(repo, "app.py", VULN_PY)
+ rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out), env)
+ assert rc == 2 and metrics_of(so)["review_failed"] is True
+ reviews = review_calls(calls)
+ assert any("--max-turns 7" in r for r in reviews)
+ # The agentic reviewer gets the file-reading tools and nothing else.
+ assert any(" --tools Read,Grep,Glob --strict-mcp-config" in r for r in reviews)
+
+ def test_stop_review_goes_through_the_cli(self, session, workspace):
+ env, calls = session
+ ws, repo = workspace
+ assert run_hook(ups_payload(repo), env)[0] == 0
+ (repo / "app.py").write_text(VULN_PY)
+ run_hook(edit_payload(repo, repo / "app.py", VULN_PY), env)
+ rc, so, se = run_hook(stop_payload(repo), env)
+ assert metrics_of(so)["review_failed"] is True
+ assert review_calls(calls)
+
+ def test_push_review_goes_through_the_cli(self, session, workspace, tmp_path):
+ env, calls = session
+ ws, repo = workspace
+ remote = tmp_path / "remote.git"
+ git(ws, "init", "-q", "--bare", str(remote))
+ git(repo, "remote", "add", "origin", str(remote))
+ git(repo, "push", "-q", "-u", "origin", "main")
+ base = git(repo, "rev-parse", "HEAD").strip()
+ sha, _ = commit_file(repo, "app.py", VULN_PY)
+ git(repo, "push", "-q", "origin", "main")
+ push_stdout = f"To {remote}\n {base[:7]}..{sha[:7]} main -> main\n"
+ rc, so, se = run_hook(bash_payload(repo, "git push origin main", push_stdout), env)
+ m = metrics_of(so)
+ assert rc == 2 and m["push_sweep"] is True and m["review_failed"] is True, m
+ assert review_calls(calls)
+
+ def test_not_signed_in_skips_and_asks_once(self, hook_env, tmp_path, workspace):
+ env = without_credential(hook_env)
+ cli, calls = make_cli(tmp_path, NOT_SIGNED_IN)
+ env["SG_AGENTIC_CLI_PATH"] = str(cli)
+ _, repo = workspace
+ for n in range(2):
+ _, out = commit_file(repo, "app.py", VULN_PY + f"# {n}\n")
+ rc, so, se = run_hook(bash_payload(repo, "git commit -m change", out), env)
+ assert rc == 0 and metrics_of(so)["skip_reason"] == 22
+ assert len(calls_of(calls)) == 1
+
+ def test_unanswered_sign_in_check_keeps_the_turn_for_the_next_stop(
+ self, hook_env, tmp_path, workspace):
+ pytest.importorskip("claude_agent_sdk")
+ env = without_credential(hook_env)
+ cli, calls = make_cli(tmp_path, "")
+ env["SG_AGENTIC_CLI_PATH"] = str(cli)
+ _, repo = workspace
+ assert run_hook(ups_payload(repo), env)[0] == 0
+ (repo / "app.py").write_text(VULN_PY)
+ run_hook(edit_payload(repo, repo / "app.py", VULN_PY), env)
+ rc, so, _ = run_hook(stop_payload(repo), env)
+ assert metrics_of(so)["skip_reason"] == 3 and not review_calls(calls)
+ # The CLI answers in the next turn: the first turn's edit is reviewed.
+ make_cli(tmp_path, SIGNED_IN)
+ assert run_hook(ups_payload(repo), env)[0] == 0
+ rc, so, _ = run_hook(stop_payload(repo), env)
+ assert metrics_of(so)["review_failed"] is True
+ assert review_calls(calls)
diff --git a/plugins/security-guidance/tests/test_launcher_newer_python.py b/plugins/security-guidance/tests/test_launcher_newer_python.py
new file mode 100644
index 00000000..fc152b73
--- /dev/null
+++ b/plugins/security-guidance/tests/test_launcher_newer_python.py
@@ -0,0 +1,55 @@
+"""sg-python.sh finds Python releases newer than its versioned list.
+
+The versioned names it prefers stop at python3.13. A machine whose `python3`
+is below 3.10 (stock macOS: 3.9) and whose only newer interpreter is
+python3.14 used to end up on 3.9, which cannot load the agent SDK, so the
+commit reviewer was off without a word. See #4907, #5024.
+
+Interpreters are emulated with shell scripts, so these tests need a POSIX
+shell.
+"""
+import sys
+
+import pytest
+
+from test_launcher_process_count import PYTHON, _add, _run, _starts, box # noqa: F401
+
+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers")
+
+
+def test_newer_release_beats_a_python3_below_3_10(box):
+ _add(box, "python3", PYTHON, version="3.9")
+ _add(box, "python3.14", PYTHON, version="3.14")
+ r = _run(box, "hook.py")
+ assert "ran:python3.14" in r.stdout, r.stdout + r.stderr
+ assert _starts(box) == ["python3 probe", "python3.14 probe", "python3.14 hook.py"]
+
+
+def test_newer_release_is_found_when_it_is_the_only_python(box):
+ _add(box, "python3.15", PYTHON, version="3.15")
+ r = _run(box, "hook.py")
+ assert "ran:python3.15" in r.stdout, r.stdout + r.stderr
+ assert _starts(box) == ["python3.15 probe", "python3.15 hook.py"]
+
+
+@pytest.mark.parametrize("working", ["python3.12", "python3", "python"])
+def test_an_interpreter_that_already_works_is_kept(box, working):
+ _add(box, working, PYTHON, version="3.12")
+ _add(box, "python3.14", PYTHON, version="3.14")
+ r = _run(box, "hook.py")
+ assert f"ran:{working}" in r.stdout, r.stdout + r.stderr
+ assert "python3.14 probe" not in _starts(box)
+
+
+def test_oldest_of_the_newer_releases_is_tried_first(box):
+ _add(box, "python3.16", PYTHON, version="3.16")
+ _add(box, "python3.14", PYTHON, version="3.14")
+ r = _run(box, "hook.py")
+ assert "ran:python3.14" in r.stdout, r.stdout + r.stderr
+
+
+def test_no_python_at_all_still_starts_nothing(box):
+ r = _run(box, "hook.py")
+ assert r.returncode == 1
+ assert "python3.14" in r.stderr
+ assert _starts(box) == []
diff --git a/plugins/security-guidance/tests/test_nested_repos.py b/plugins/security-guidance/tests/test_nested_repos.py
new file mode 100644
index 00000000..cb010018
--- /dev/null
+++ b/plugins/security-guidance/tests/test_nested_repos.py
@@ -0,0 +1,162 @@
+import os
+import subprocess
+import tempfile
+
+import pytest
+
+from conftest import (
+ GIT_ENV, STUB_VULN, VULN_PY, git, make_repo, metrics_of, run_hook,
+ stop_payload, ups_payload,
+)
+
+import gitutil
+
+
+def _add_nested_repo(parent, rel, marker):
+ """A directory with its own `.git` whose config names a filter command,
+ the way an unpacked archive or a vendored checkout can. The command leaves
+ a line in `marker` each time git runs it."""
+ nested = make_repo(parent / rel, {
+ "lib.py": "print('one')\n",
+ ".gitattributes": "* filter=probe\n",
+ })
+ git(nested, "config", "filter.probe.clean",
+ f"sh -c 'echo ran >> \"{marker.as_posix()}\"; cat'")
+ # Same size, so git has to read the file to tell whether it changed.
+ (nested / "lib.py").write_text("print('two')\n")
+ old = os.stat(nested / ".git" / "index").st_mtime - 3600
+ os.utime(nested / ".git" / "index", (old, old))
+ return nested
+
+
+@pytest.fixture
+def outer(tmp_path):
+ return make_repo(tmp_path / "outer", {"app.py": "print('hi')\n"})
+
+
+@pytest.fixture
+def marker(tmp_path):
+ return tmp_path / "filter-ran"
+
+
+def _turn(repo, hook_env, stub_api, during):
+ stub_api.vulns = [STUB_VULN]
+ assert run_hook(ups_payload(repo), hook_env)[0] == 0
+ during()
+ return run_hook(stop_payload(repo), hook_env)
+
+
+def test_untracked_nested_repo_filter_not_run(outer, marker, hook_env, stub_api):
+ def during():
+ _add_nested_repo(outer, "vendor/pkg", marker)
+ (outer / "app.py").write_text(VULN_PY)
+
+ rc, out, err = _turn(outer, hook_env, stub_api, during)
+
+ assert not marker.exists(), marker.read_text()
+ # The turn's own edit is still reviewed.
+ assert stub_api.calls, (rc, out, err)
+ assert "app.py" in out + err
+
+
+def test_untracked_nested_repo_alone_is_not_reviewed(outer, marker, hook_env, stub_api):
+ rc, out, err = _turn(
+ outer, hook_env, stub_api,
+ lambda: _add_nested_repo(outer, "vendor/pkg", marker))
+
+ assert not marker.exists(), marker.read_text()
+ assert not stub_api.calls
+ assert (metrics_of(out) or {}).get("skipped") is True
+
+
+@pytest.fixture
+def git_env(tmp_path, monkeypatch):
+ """For calling gitutil in this process: a temp dir of our own, and the
+ environment restored afterwards."""
+ d = tmp_path / "tmproot"
+ d.mkdir()
+ monkeypatch.setattr(tempfile, "tempdir", str(d))
+ saved = dict(os.environ)
+ os.environ.update(GIT_ENV)
+ yield
+ os.environ.clear()
+ os.environ.update(saved)
+
+
+def _record_nested_repo(outer, marker, gitmodules=None):
+ nested = _add_nested_repo(outer, "vendor/pkg", marker)
+ if gitmodules:
+ (outer / ".gitmodules").write_text(gitmodules)
+ git(outer, "add", "-A")
+ git(outer, "commit", "-q", "-m", "add vendor/pkg")
+ if marker.exists():
+ marker.unlink()
+ return nested
+
+
+def test_untracked_nested_repo_is_not_a_changed_file(outer, marker, git_env):
+ _add_nested_repo(outer, "vendor/pkg", marker)
+ (outer / "new.py").write_text("x = 1\n")
+
+ tracked, untracked = gitutil._git_status_porcelain(str(outer))
+
+ assert (tracked, untracked) == (set(), {"new.py"})
+
+
+def test_intent_to_add_skips_nested_repos(outer, marker, git_env):
+ _add_nested_repo(outer, "vendor/pkg", marker)
+ (outer / "new.py").write_text("x = 1\n")
+
+ with gitutil._temp_index(str(outer), ["new.py", "vendor/pkg/"]) as env:
+ assert env is not None
+ listed = subprocess.run(
+ ["git", "ls-files", "-s"], cwd=outer, capture_output=True,
+ text=True, env=env,
+ ).stdout
+
+ assert "new.py" in listed
+ assert "160000" not in listed
+ assert not marker.exists()
+
+
+# A repository can ask for one submodule to be checked whatever the default.
+GITMODULES_IGNORE_NONE = (
+ '[submodule "pkg"]\n\tpath = vendor/pkg\n\turl = ./vendor/pkg\n\tignore = none\n'
+)
+
+
+@pytest.mark.parametrize("gitmodules", [None, GITMODULES_IGNORE_NONE])
+def test_status_and_diff_leave_out_recorded_nested_repo(outer, marker, git_env, gitmodules):
+ nested = _record_nested_repo(outer, marker, gitmodules)
+ (nested / "lib.py").write_text("print('abc')\n")
+ (outer / "app.py").write_text(VULN_PY)
+
+ tracked, untracked = gitutil._git_status_porcelain(str(outer))
+ diff = gitutil.get_git_diff(str(outer), "HEAD", untracked_paths=[])
+ names = gitutil._git_name_only(str(outer), "HEAD")
+
+ assert tracked == {"app.py"}
+ assert names == {"app.py"}
+ assert "app.py" in diff and "vendor/pkg" not in diff
+ assert not marker.exists()
+
+
+def test_commit_range_diff_does_not_enter_nested_repo(outer, marker, git_env, tmp_path):
+ nested = _record_nested_repo(outer, marker, GITMODULES_IGNORE_NONE)
+ ext_marker = tmp_path / "ext-diff-ran"
+ git(nested, "config", "diff.external",
+ f"sh -c 'echo ran >> \"{ext_marker.as_posix()}\"'")
+ base = git(outer, "rev-parse", "HEAD").strip()
+ git(nested, "commit", "-q", "-am", "two")
+ git(outer, "commit", "-q", "-am", "move vendor/pkg")
+ for m in (marker, ext_marker):
+ if m.exists():
+ m.unlink()
+ # The user's own setting asks for a submodule's changes inline.
+ os.environ.update({"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "diff.submodule",
+ "GIT_CONFIG_VALUE_0": "diff"})
+
+ out = gitutil._git_diff_range(str(outer), base, "HEAD")
+
+ assert not ext_marker.exists() and not marker.exists()
+ assert "lib.py" not in (out or "")
diff --git a/plugins/security-guidance/tests/test_no_credentials_notice.py b/plugins/security-guidance/tests/test_no_credentials_notice.py
new file mode 100644
index 00000000..a828e2ed
--- /dev/null
+++ b/plugins/security-guidance/tests/test_no_credentials_notice.py
@@ -0,0 +1,215 @@
+"""Without credentials the LLM reviews are skipped; the user is told."""
+import json
+import os
+import time
+
+import pytest
+
+from conftest import (
+ bash_payload, commit_file, edit_payload, git, metrics_of, run_hook,
+ stop_payload, ups_payload, VULN_PY,
+)
+from test_gateway_sign_in import NOT_SIGNED_IN, SIGNED_IN, calls_of, make_cli
+
+# Anything in the developer's shell that changes whether a review would run.
+_AMBIENT = (
+ "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN",
+ # Makes every session share one state file.
+ "CLAUDE_CODE_REMOTE_SESSION_ID",
+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "DISABLE_TELEMETRY", "DO_NOT_TRACK",
+ "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY",
+ "CLAUDE_CODE_USE_MANTLE", "CLAUDE_CODE_USE_ANTHROPIC_AWS",
+ "SECURITY_GUIDANCE_DISABLE", "ENABLE_SECURITY_REMINDER",
+ "ENABLE_CODE_SECURITY_REVIEW", "ENABLE_STOP_REVIEW", "ENABLE_COMMIT_REVIEW",
+ "ENABLE_PATTERN_RULES",
+)
+
+
+def _env(hook_env, creds=False, **extra):
+ env = {k: v for k, v in hook_env.items() if k not in _AMBIENT}
+ if creds:
+ env["ANTHROPIC_API_KEY"] = "test-key"
+ env.update(extra)
+ return env
+
+
+def _edit_output(repo, env, name="app.py", content=VULN_PY, session_id="s1"):
+ (repo / name).write_text(content)
+ rc, out, _ = run_hook(
+ edit_payload(repo, repo / name, new_string=content, session_id=session_id), env)
+ assert rc == 0
+ lines = [l for l in out.splitlines() if l.startswith("{")]
+ assert len(lines) <= 1
+ return json.loads(lines[0]) if lines else {}
+
+
+def _notice(repo, env, **kw):
+ return _edit_output(repo, env, **kw).get("systemMessage")
+
+
+def _marker(env):
+ return os.path.join(env["SECURITY_WARNINGS_STATE_DIR"], ".no_credentials_notice")
+
+
+def test_edit_without_credentials_tells_the_user_once(workspace, hook_env):
+ _, repo = workspace
+ env = _env(hook_env)
+ notice = _notice(repo, env)
+ assert "is not running" in notice
+ assert "No Anthropic credentials were passed" in notice
+ assert "only the pattern warnings on edits are active" in notice
+ assert "ENABLE_CODE_SECURITY_REVIEW=0" in notice
+ assert _notice(repo, env) is None
+ assert _notice(repo, env, session_id="s2") is None
+
+
+def test_notice_comes_back_after_a_week(workspace, hook_env):
+ _, repo = workspace
+ env = _env(hook_env)
+ assert _notice(repo, env)
+ six_days, eight_days = time.time() - 6 * 86400, time.time() - 8 * 86400
+ os.utime(_marker(env), (six_days, six_days))
+ assert _notice(repo, env) is None
+ os.utime(_marker(env), (eight_days, eight_days))
+ assert _notice(repo, env)
+ assert _notice(repo, env) is None
+
+
+def test_notice_names_every_setting_that_withholds_credentials(workspace, hook_env):
+ _, repo = workspace
+ notice = _notice(repo, _env(hook_env, DISABLE_TELEMETRY="1", DO_NOT_TRACK="true"))
+ assert "while DISABLE_TELEMETRY or DO_NOT_TRACK is set" in notice
+
+
+@pytest.mark.parametrize("var", ["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "DO_NOT_TRACK"])
+def test_notice_names_the_setting(workspace, hook_env, var):
+ _, repo = workspace
+ assert f"while {var} is set" in _notice(repo, _env(hook_env, **{var: "1"}))
+
+
+def test_do_not_track_off_is_not_blamed(workspace, hook_env):
+ _, repo = workspace
+ notice = _notice(repo, _env(hook_env, DO_NOT_TRACK="0"))
+ assert "DO_NOT_TRACK" not in notice and "No Anthropic credentials" in notice
+
+
+def test_notice_does_not_promise_pattern_warnings_that_are_off(workspace, hook_env):
+ _, repo = workspace
+ notice = _notice(repo, _env(hook_env, ENABLE_PATTERN_RULES="0"))
+ assert "is not running" in notice and "pattern warnings" not in notice
+
+
+def test_notice_rides_along_with_a_pattern_warning(workspace, hook_env):
+ _, repo = workspace
+ risky = "import os\nos.system('ls ' + name)\n"
+ with_creds = _edit_output(
+ repo, _env(hook_env, creds=True), name="a.py", content=risky)
+ assert with_creds["metrics"]["pattern_hits"] == 1
+ assert "systemMessage" not in with_creds
+ out = _edit_output(repo, _env(hook_env), name="b.py", content=risky)
+ assert "is not running" in out["systemMessage"]
+ assert out["metrics"] == with_creds["metrics"]
+ assert (out["hookSpecificOutput"]["additionalContext"]
+ == with_creds["hookSpecificOutput"]["additionalContext"])
+
+
+def test_no_notice_with_credentials(workspace, hook_env):
+ _, repo = workspace
+ assert _notice(repo, _env(hook_env, creds=True)) is None
+ assert _notice(repo, _env(hook_env, ANTHROPIC_AUTH_TOKEN="t")) is None
+ assert _notice(repo, _env(hook_env, CLAUDE_CODE_USE_BEDROCK="1")) is None
+ assert not os.path.exists(_marker(hook_env))
+
+
+def test_no_notice_when_the_reviews_are_turned_off(workspace, hook_env):
+ _, repo = workspace
+ assert _notice(repo, _env(hook_env, ENABLE_CODE_SECURITY_REVIEW="0")) is None
+ assert _notice(repo, _env(hook_env, SECURITY_GUIDANCE_DISABLE="1")) is None
+ assert _notice(repo, _env(
+ hook_env, ENABLE_STOP_REVIEW="0", SECURITY_GUIDANCE_COMMIT_REVIEW="off",
+ SG_PUSH_SWEEP="off")) is None
+ assert not os.path.exists(_marker(hook_env))
+ assert _notice(repo, _env(hook_env, ENABLE_STOP_REVIEW="0"))
+
+
+def test_no_notice_outside_a_git_repo(workspace, hook_env, tmp_path):
+ _, repo = workspace
+ plain = tmp_path / "plain"
+ plain.mkdir()
+ env = _env(hook_env)
+ assert _notice(plain, env, name="notes.py") is None
+ assert not os.path.exists(_marker(env))
+ assert _notice(repo, env)
+
+
+def test_no_notice_when_the_state_dir_is_unwritable(workspace, hook_env, tmp_path):
+ _, repo = workspace
+ blocker = tmp_path / "not-a-dir"
+ blocker.write_text("")
+ env = _env(hook_env, SECURITY_WARNINGS_STATE_DIR=str(blocker / "state"))
+ assert _notice(repo, env) is None
+ assert _notice(repo, env) is None
+
+
+def test_skipped_reviews_report_the_missing_credentials(workspace, hook_env, stub_api):
+ _, repo = workspace
+ env = _env(hook_env)
+ run_hook(ups_payload(repo), env)
+ _edit_output(repo, env)
+ rc, out, _ = run_hook(stop_payload(repo), env)
+ m = metrics_of(out)
+ assert rc == 0 and m["skip_reason"] == 3 and m["no_creds"] is True
+
+ _, commit_out = commit_file(repo, "app.py", VULN_PY + "# again\n")
+ rc, out, _ = run_hook(
+ bash_payload(repo, "git commit -m change", stdout=commit_out), env)
+ m = metrics_of(out)
+ assert rc == 0 and m["skip_reason"] == 22 and m["no_creds"] is True
+
+ rc, out, _ = run_hook(bash_payload(repo, "git push origin main"), env)
+ m = metrics_of(out)
+ assert rc == 0 and m["push_sweep"] and m["skip_reason"] == 22 and m["no_creds"] is True
+ assert stub_api.calls == []
+
+ off = _env(hook_env, ENABLE_CODE_SECURITY_REVIEW="0")
+ for payload in (stop_payload(repo, session_id="s3"),
+ bash_payload(repo, "git push origin main", session_id="s3")):
+ rc, out, _ = run_hook(payload, off)
+ assert "no_creds" not in metrics_of(out)
+
+
+def test_no_notice_in_a_signed_in_gateway_session(workspace, hook_env, tmp_path):
+ # Claude Code passes no credential there, but the reviews run through
+ # the user's claude, so they are running.
+ _, repo = workspace
+ cli, calls = make_cli(tmp_path, SIGNED_IN)
+ env = _env(hook_env, SG_AGENTIC_CLI_PATH=str(cli))
+ assert _notice(repo, env) is None
+ # The check counts as this week's: a new session's edit does not ask.
+ assert _notice(repo, env, session_id="s2") is None
+ assert os.path.exists(_marker(env))
+ assert [c.split(" | ")[0] for c in calls_of(calls)] == ["auth status --json"]
+ # A week later the edit asks again.
+ eight_days = time.time() - 8 * 86400
+ os.utime(_marker(env), (eight_days, eight_days))
+ assert _notice(repo, env, session_id="s3") is None
+ assert len(calls_of(calls)) == 2
+
+
+def test_edit_outside_a_git_repo_does_not_ask_claude(workspace, hook_env, tmp_path):
+ cli, calls = make_cli(tmp_path, SIGNED_IN)
+ plain = tmp_path / "plain"
+ plain.mkdir()
+ env = _env(hook_env, SG_AGENTIC_CLI_PATH=str(cli))
+ assert _notice(plain, env, name="notes.py") is None
+ assert calls_of(calls) == []
+
+
+def test_notice_when_the_gateway_session_is_not_signed_in(workspace, hook_env, tmp_path):
+ _, repo = workspace
+ cli, calls = make_cli(tmp_path, NOT_SIGNED_IN)
+ env = _env(hook_env, SG_AGENTIC_CLI_PATH=str(cli))
+ assert "is not running" in _notice(repo, env)
+ # Within the week no notice is due, so claude is not asked again.
+ assert _notice(repo, env, session_id="s2") is None
+ assert len(calls_of(calls)) == 1
diff --git a/plugins/security-guidance/tests/test_notebook_edit_patterns.py b/plugins/security-guidance/tests/test_notebook_edit_patterns.py
new file mode 100644
index 00000000..df4d37a9
--- /dev/null
+++ b/plugins/security-guidance/tests/test_notebook_edit_patterns.py
@@ -0,0 +1,193 @@
+"""NotebookEdit cell sources go through the same pattern checks as file edits."""
+import json
+import subprocess
+import sys
+
+import pytest
+
+import extensibility
+import security_reminder_hook as hook
+
+from conftest import HOOKS_DIR, metrics_of, run_hook
+
+CELL = (
+ "import pickle, os\n"
+ "data = pickle.loads(open('model.pkl', 'rb').read())\n"
+ "os.system(f'convert {user_input}')\n"
+)
+CELL_RULES = ["os_system_injection", "pickle_deserialization"]
+
+
+@pytest.fixture
+def env(hook_env, tmp_path):
+ # Keep the developer's own security-patterns files out of the counts.
+ home = tmp_path / "home"
+ home.mkdir()
+ hook_env.update(HOME=str(home), USERPROFILE=str(home))
+ hook_env.pop("CLAUDE_CONFIG_DIR", None)
+ return hook_env
+
+
+def notebook_payload(cwd, notebook, new_source=CELL, tool_response=None, **tool_input):
+ return {
+ "session_id": "s1",
+ "hook_event_name": "PostToolUse",
+ "tool_name": "NotebookEdit",
+ "tool_input": {"notebook_path": str(notebook), "new_source": new_source, **tool_input},
+ "tool_response": tool_response if tool_response is not None else {},
+ "cwd": str(cwd),
+ }
+
+
+def warning_of(stdout):
+ for line in stdout.splitlines():
+ if line.strip().startswith("{"):
+ out = json.loads(line).get("hookSpecificOutput")
+ if out:
+ return out["additionalContext"]
+ return ""
+
+
+@pytest.mark.parametrize("tool_input", [
+ {"cell_id": "c1"},
+ {"cell_id": "c1", "edit_mode": "replace", "cell_type": "code"},
+ {"cell_id": "c1", "edit_mode": "insert", "cell_type": "code"},
+ {"edit_mode": "insert", "cell_type": "code"},
+ {"cell_id": "c1", "cell_type": "markdown"},
+])
+def test_cell_source_is_checked(tmp_path, env, tool_input):
+ rc, out, _ = run_hook(
+ notebook_payload(tmp_path, tmp_path / "analysis.ipynb", **tool_input), env)
+ assert rc == 0
+ warning = warning_of(out)
+ assert "pickle" in warning
+ assert "os.system" in warning
+ assert metrics_of(out)["pattern_hits"] == 2
+
+
+def test_same_cell_matches_a_python_file_edit(tmp_path, env):
+ _, nb_out, _ = run_hook(
+ notebook_payload(tmp_path, tmp_path / "analysis.ipynb", cell_id="c1"), env)
+ py = notebook_payload(tmp_path, tmp_path / "analysis.py")
+ py.update(tool_name="Edit", tool_input={
+ "file_path": str(tmp_path / "analysis.py"), "old_string": "", "new_string": CELL})
+ _, py_out, _ = run_hook(py, env)
+ assert metrics_of(nb_out)["rule_mask"] == metrics_of(py_out)["rule_mask"]
+
+
+@pytest.mark.parametrize("tool_input, tool_response", [
+ ({"cell_id": "c1", "edit_mode": "delete"}, {}),
+ ({"cell_id": "c1", "edit_mode": "delete", "cell_type": "code"}, {"error": ""}),
+ ({"cell_id": "c1"}, {"error": "File has been modified since read"}),
+ ({"cell_id": "c1"}, {"new_source": CELL, "error": "Edit rejected"}),
+])
+def test_deleted_cell_and_failed_edit_are_not_checked(tmp_path, env, tool_input, tool_response):
+ rc, out, _ = run_hook(
+ notebook_payload(tmp_path, tmp_path / "analysis.ipynb",
+ tool_response=tool_response, **tool_input), env)
+ assert rc == 0
+ assert metrics_of(out) is None
+ assert warning_of(out) == ""
+
+
+def test_successful_edit_with_an_empty_error_is_checked(tmp_path, env):
+ # What Claude Code sends for an edit that worked.
+ _, out, _ = run_hook(
+ notebook_payload(tmp_path, tmp_path / "analysis.ipynb", cell_id="c1",
+ tool_response={"error": "", "cell_type": "code", "old_source": CELL}),
+ env)
+ assert metrics_of(out)["pattern_hits"] == 2
+
+
+@pytest.mark.parametrize("tool_input, tool_response", [
+ ({"cell_id": "c1", "new_source": None}, {}),
+ ({"cell_id": "c1", "new_source": ["import pickle"]}, {}),
+ ({"cell_id": None}, {}),
+ ({"cell_id": "c1"}, "Updated cell c1"),
+ ({"cell_id": "c1"}, None),
+])
+def test_unexpected_shapes_do_not_break_the_hook(tmp_path, env, tool_input, tool_response):
+ payload = notebook_payload(tmp_path, tmp_path / "analysis.ipynb", **tool_input)
+ payload["tool_response"] = tool_response
+ rc, _, err = run_hook(payload, env)
+ assert rc == 0
+ assert "Traceback" not in err
+
+
+def test_clean_cell_is_quiet(tmp_path, env):
+ rc, out, _ = run_hook(
+ notebook_payload(tmp_path, tmp_path / "analysis.ipynb",
+ new_source="import json\ndata = json.load(open('m.json'))\n",
+ cell_id="c1"), env)
+ assert rc == 0
+ assert metrics_of(out) is None
+
+
+def saved_notebook(code, bom=""):
+ # NotebookEdit saves a cell's source as one string; Jupyter saves a list of lines.
+ return bom + json.dumps({
+ "cells": [
+ {"cell_type": "markdown", "id": "m", "metadata": {}, "source": "# Notes\n"},
+ {"cell_type": "code", "id": "c", "metadata": {}, "source": code, "outputs": []},
+ ],
+ "metadata": {}, "nbformat": 4, "nbformat_minor": 5,
+ }, indent=1)
+
+
+@pytest.fixture
+def rules(monkeypatch):
+ monkeypatch.setattr(extensibility, "_user_patterns", [])
+ return lambda path, content: sorted(r for r, _ in hook.check_patterns(str(path), content))
+
+
+@pytest.mark.parametrize("bom", ["", ""])
+def test_saved_notebook_is_checked_by_its_cells_as_written(rules, bom):
+ saved = saved_notebook(CELL, bom)
+ assert "\\nos.system(" in saved
+ assert rules("analysis.ipynb", saved) == CELL_RULES
+ assert rules("analysis.ipynb", saved_notebook(CELL.splitlines(True), bom)) == CELL_RULES
+ assert rules("analysis.ipynb", saved_notebook("x = 1\n", bom)) == []
+
+
+def test_saved_notebook_outputs_are_not_checked(rules):
+ saved = json.loads(saved_notebook("x = 1\n"))
+ saved["cells"][1]["outputs"] = [{"output_type": "stream", "name": "stdout", "text": [CELL]}]
+ assert rules("analysis.ipynb", json.dumps(saved)) == []
+ saved["cells"][0]["source"] = CELL.splitlines(True)
+ assert rules("analysis.ipynb", json.dumps(saved)) == CELL_RULES
+
+
+@pytest.mark.parametrize("content", [
+ "{not json", "{}", '{"cells": 5}', '{"cells": [5]}', '{"cells": [{"source": 5}]}', "[]",
+])
+def test_content_that_is_not_a_saved_notebook_is_checked_as_is(rules, content):
+ assert rules("analysis.ipynb", content) == []
+ assert rules("analysis.ipynb", content + "\nimport os\nos.system(cmd)\n") == ["os_system_injection"]
+
+
+def test_other_files_are_not_read_as_notebooks(rules):
+ assert rules("analysis.py", saved_notebook("import os\nos.system(cmd)\n")) == []
+
+
+SWEEP = (
+ "import sys, json; sys.path.insert(0, sys.argv[1]);"
+ "import security_reminder_hook as h;"
+ "print(json.dumps(h.sweep_pending_warnings('s1')[:2]))"
+)
+
+
+def sweep(env):
+ r = subprocess.run([sys.executable, "-c", SWEEP, str(HOOKS_DIR)],
+ capture_output=True, text=True, env=env)
+ return json.loads(r.stdout.strip().splitlines()[-1])
+
+
+def test_notebook_warning_is_tallied_from_the_saved_cells(tmp_path, env):
+ nb = tmp_path / "analysis.ipynb"
+ nb.write_text(saved_notebook(CELL))
+ run_hook(notebook_payload(tmp_path, nb, cell_id="c"), env)
+ assert sweep(env) == [0, 2]
+
+ run_hook(notebook_payload(tmp_path, nb, cell_id="c"), env)
+ nb.write_text(saved_notebook("x = 1\n"))
+ assert sweep(env) == [2, 0]
diff --git a/plugins/security-guidance/tests/test_reviewer_tools.py b/plugins/security-guidance/tests/test_reviewer_tools.py
index 3e2aa86c..3b9521ff 100644
--- a/plugins/security-guidance/tests/test_reviewer_tools.py
+++ b/plugins/security-guidance/tests/test_reviewer_tools.py
@@ -1,6 +1,8 @@
"""The inner Claude Code the plugin starts for a review gets only the tools
the review needs."""
+import json
import sys
+import threading
import types
import pytest
@@ -9,11 +11,22 @@ import llm
READ_ONLY = {"tools": "Read,Grep,Glob", "strict-mcp-config": None}
NO_TOOLS = {"tools": "", "strict-mcp-config": None}
+# Once an inner CLI has refused --strict-mcp-config.
+READ_ONLY_NO_MCP = {"tools": "Read,Grep,Glob", "disallowedTools": "mcp__*"}
+NO_TOOLS_NO_MCP = {"tools": "", "disallowedTools": "mcp__*"}
+
+
+@pytest.fixture(autouse=True)
+def strict_mcp_flag_sent(monkeypatch):
+ monkeypatch.setattr(llm, "_send_strict_mcp", True)
def test_tool_flags():
assert llm._only_tools_args(("Read", "Grep", "Glob")) == READ_ONLY
assert llm._only_tools_args() == NO_TOOLS
+ llm._send_strict_mcp = False
+ assert llm._only_tools_args(("Read", "Grep", "Glob")) == READ_ONLY_NO_MCP
+ assert llm._only_tools_args() == NO_TOOLS_NO_MCP
def test_flags_reach_the_command_line_of_the_installed_sdk():
@@ -26,6 +39,16 @@ def test_flags_reach_the_command_line_of_the_installed_sdk():
cmd = transport.SubprocessCLITransport(prompt="x", options=opts)._build_command()
assert cmd[cmd.index("--tools") + 1] == "Read,Grep,Glob"
assert cmd.count("--tools") == 1 and "--strict-mcp-config" in cmd
+ assert "--disallowedTools" not in cmd
+
+ llm._send_strict_mcp = False
+ opts = sdk.ClaudeAgentOptions(
+ cli_path="claude", allowed_tools=["Read", "Grep", "Glob"],
+ extra_args=llm._only_tools_args(llm._REVIEWER_TOOLS))
+ cmd = transport.SubprocessCLITransport(prompt="x", options=opts)._build_command()
+ assert cmd[cmd.index("--tools") + 1] == "Read,Grep,Glob"
+ assert cmd[cmd.index("--disallowedTools") + 1] == "mcp__*"
+ assert cmd.count("--disallowedTools") == 1 and "--strict-mcp-config" not in cmd
@pytest.fixture
@@ -82,3 +105,103 @@ def test_single_turn_sdk_review_gets_no_tools(sdk):
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"] == []
+
+
+# What Claude Code prints, before exiting 1, on a machine whose administrator
+# delivers the MCP servers.
+REFUSAL = "You cannot use --strict-mcp-config when an enterprise MCP config is present"
+
+
+@pytest.fixture
+def managed_mcp(sdk, monkeypatch):
+ """The stand-in SDK's inner CLI now refuses --strict-mcp-config. Gives
+ the options of the refused starts and of the ones that ran."""
+ answer = sys.modules["claude_agent_sdk"].query
+ refused = []
+
+ async def query(prompt, options):
+ if "strict-mcp-config" in options.kwargs["extra_args"]:
+ refused.append(options.kwargs)
+ options.kwargs["stderr"](REFUSAL)
+ raise RuntimeError("Command failed with exit code 1")
+ async for msg in answer(prompt, options):
+ yield msg
+
+ monkeypatch.setattr(sys.modules["claude_agent_sdk"], "query", query)
+ return refused, sdk
+
+
+def test_agentic_review_runs_where_the_strict_mcp_flag_is_refused(managed_mcp, tmp_path):
+ _, vulns, metrics = llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"])
+ assert len(vulns) == 1
+ # The refused start's line is not what child_stderr is there to count.
+ assert "agentic_fallback" not in metrics and "child_stderr" not in metrics
+ refused, ran = managed_mcp
+ assert [o["extra_args"] for o in refused] == [READ_ONLY]
+ # investigate, second investigate pass, refute
+ assert [o["extra_args"] for o in ran] == [READ_ONLY_NO_MCP] * 3
+ for opts in ran:
+ assert opts["allowed_tools"] == ["Read", "Grep", "Glob"]
+
+
+def test_single_turn_sdk_review_runs_where_the_strict_mcp_flag_is_refused(managed_mcp):
+ schema = {"type": "object", "properties": {}}
+ assert llm._call_claude_via_sdk("review this", schema) is not None
+ refused, ran = managed_mcp
+ assert [o["extra_args"] for o in refused] == [NO_TOOLS]
+ assert [o["extra_args"] for o in ran] == [NO_TOOLS_NO_MCP]
+ # The refusal is remembered for the rest of the hook process.
+ assert llm._call_claude_via_sdk("review this", schema) is not None
+ assert len(refused) == 1 and ran[-1]["extra_args"] == NO_TOOLS_NO_MCP
+
+
+def test_other_start_failures_are_not_retried(sdk, monkeypatch, tmp_path):
+ async def query(prompt, options):
+ sdk.append(options.kwargs)
+ options.kwargs["stderr"]("Fallback model cannot be the same as the main model")
+ raise RuntimeError("Command failed with exit code 1")
+ yield
+
+ monkeypatch.setattr(sys.modules["claude_agent_sdk"], "query", query)
+ guidance, vulns, metrics = llm.agentic_review(str(tmp_path), [("a.py", "+x = 1\n")], ["a.py"])
+ assert guidance is None and vulns == []
+ assert metrics["agentic_fallback"] == "investigate:RuntimeError"
+ assert llm._call_claude_via_sdk("review this", {"type": "object", "properties": {}}) is None
+ assert [o["extra_args"] for o in sdk] == [READ_ONLY, NO_TOOLS]
+
+
+def test_reviews_started_together_are_each_started_again(managed_mcp):
+ refused, ran = managed_mcp
+ both_refused = threading.Barrier(2, timeout=10)
+ refuse = sys.modules["claude_agent_sdk"].query
+
+ async def query(prompt, options):
+ if "strict-mcp-config" in options.kwargs["extra_args"]:
+ both_refused.wait()
+ async for msg in refuse(prompt, options):
+ yield msg
+
+ sys.modules["claude_agent_sdk"].query = query
+ schema = {"type": "object", "properties": {}}
+ results = []
+ threads = [threading.Thread(
+ target=lambda: results.append(llm._call_claude_via_sdk("review this", schema)))
+ for _ in range(2)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(20)
+ assert len(results) == 2 and None not in results
+ assert len(refused) == 2 and [o["extra_args"] for o in ran] == [NO_TOOLS_NO_MCP] * 2
+
+
+def test_review_rows_say_when_the_flag_was_left_out(managed_mcp, capsys):
+ import security_reminder_hook as hook
+
+ def row():
+ hook.emit_metrics({"vulns_found": 0, "review_ms": 10})
+ return json.loads(capsys.readouterr().out)["metrics"]
+
+ assert "strict_mcp_off" not in row()
+ assert llm._call_claude_via_sdk("review this", {"type": "object", "properties": {}}) is not None
+ assert row()["strict_mcp_off"] == 1
diff --git a/plugins/security-guidance/tests/test_secret_shaped_paths.py b/plugins/security-guidance/tests/test_secret_shaped_paths.py
index bfd5180d..b20beef3 100644
--- a/plugins/security-guidance/tests/test_secret_shaped_paths.py
+++ b/plugins/security-guidance/tests/test_secret_shaped_paths.py
@@ -25,6 +25,11 @@ import gitutil
"private_dot_netrc",
"dot_aws/credentials",
"Deploy_RSA",
+ ".credentials.json",
+ ".claude/.credentials.json",
+ "private_dot_claude/private_dot_credentials.json",
+ ".claude.json",
+ "dot_claude.json",
])
def test_secret_shaped_names_are_not_reviewable(path):
assert gitutil._is_secret_shaped(path)
@@ -44,6 +49,8 @@ def test_secret_shaped_names_are_not_reviewable(path):
"bin/deploy",
"Dockerfile.dev",
"executable_backup.sh",
+ "config/credentials.json",
+ "src/claude.json",
])
def test_ordinary_source_stays_reviewable(path):
assert not gitutil._is_secret_shaped(path)
@@ -93,3 +100,16 @@ def test_stop_hook_reports_how_many_files_it_left_out(tmp_path, hook_env, stub_a
_rc, stdout, _err = run_hook(stop_payload(repo), hook_env)
assert metrics_of(stdout).get("secret_shaped_skipped") == 2
assert stub_api.calls == []
+
+
+@pytest.mark.parametrize("name", [".credentials.json", ".claude.json"])
+def test_claude_code_files_rewritten_during_the_turn_are_not_sent(tmp_path, hook_env, stub_api, name):
+ repo = make_repo(tmp_path / "repo")
+ (repo / name).write_text('{"accessToken": "old"}\n')
+ run_hook(ups_payload(repo), hook_env)
+ (repo / name).write_text('{"accessToken": "new-and-longer"}\n')
+ later = (repo / name).stat().st_mtime + 5
+ os.utime(repo / name, (later, later))
+ _rc, stdout, _err = run_hook(stop_payload(repo), hook_env)
+ assert metrics_of(stdout).get("secret_shaped_skipped") == 1
+ assert stub_api.calls == []
diff --git a/plugins/security-guidance/tests/test_stop_baseline_checkout.py b/plugins/security-guidance/tests/test_stop_baseline_checkout.py
new file mode 100644
index 00000000..97c20ab3
--- /dev/null
+++ b/plugins/security-guidance/tests/test_stop_baseline_checkout.py
@@ -0,0 +1,282 @@
+"""The turn baseline belongs to the checkout the prompt hook captured it in.
+A Stop review in another checkout (the session entered a worktree, or edited
+another repo) does not use it: commits count from that checkout's own HEAD at
+the time of the prompt, files are diffed against HEAD, and uncommitted files
+last written before the prompt are left out. Stop rows carry `bl_origin`,
+saying which case the row was."""
+import json
+import os
+import shutil
+import time
+
+import pytest
+
+from conftest import (
+ STUB_VULN, VULN_PY, edit_payload, git, make_repo, metrics_of, run_hook,
+ stop_payload, ups_payload,
+)
+
+
+@pytest.fixture
+def checkouts(tmp_path, monkeypatch):
+ """a: a repo's primary checkout. b: a linked worktree of it whose branch
+ already holds a committed file that a's branch lacks. Both were last
+ committed to an hour ago."""
+ monkeypatch.setenv("GIT_COMMITTER_DATE", f"@{int(time.time()) - 3600} +0000")
+ a = make_repo(tmp_path / "ws" / "a", {"app.py": "print('hi')\n"})
+ b = tmp_path / "ws" / "b"
+ git(a, "worktree", "add", "-q", "-b", "feature", str(b))
+ (b / "old.py").write_text(VULN_PY)
+ git(b, "add", "-A")
+ git(b, "commit", "-q", "-m", "earlier work")
+ monkeypatch.delenv("GIT_COMMITTER_DATE")
+ return a, b
+
+
+def _stop(cwd, hook_env):
+ return metrics_of(run_hook(stop_payload(cwd), hook_env)[1])
+
+
+def _state(hook_env):
+ d = hook_env["SECURITY_WARNINGS_STATE_DIR"]
+ for e in os.scandir(d):
+ if e.name.endswith(".json"):
+ with open(e.path) as f:
+ state = json.load(f)
+ if "baseline_sha" in state:
+ return state
+ raise AssertionError(os.listdir(d))
+
+
+def test_baseline_from_the_reviewed_checkout(hook_env, checkouts):
+ a, _ = checkouts
+ run_hook(ups_payload(a), hook_env)
+ (a / "app.py").write_text(VULN_PY)
+ m = _stop(a, hook_env)
+ assert m["files_reviewed"] == 1 and m["bl_origin"] == 0
+
+
+def test_sent_on_a_skipped_review_too(hook_env, checkouts):
+ a, _ = checkouts
+ run_hook(ups_payload(a), hook_env)
+ m = _stop(a, hook_env)
+ assert m["skipped"] is True and m["bl_origin"] == 0
+
+
+def test_prompt_in_a_subdirectory_is_the_same_checkout(hook_env, checkouts):
+ a, _ = checkouts
+ (a / "pkg").mkdir()
+ run_hook(ups_payload(a / "pkg"), hook_env)
+ (a / "app.py").write_text(VULN_PY)
+ assert _stop(a, hook_env)["bl_origin"] == 0
+
+
+def test_turn_that_only_enters_another_worktree_reviews_nothing(
+ hook_env, checkouts, stub_api):
+ a, b = checkouts
+ run_hook(ups_payload(a), hook_env)
+ m = _stop(b, hook_env)
+ # b's earlier commit is not a commit made this turn.
+ assert m["skipped"] is True and m["bl_origin"] == 1
+ assert not stub_api.calls
+
+
+def test_edit_after_entering_another_worktree_is_reviewed(
+ hook_env, checkouts, stub_api):
+ a, b = checkouts
+ run_hook(ups_payload(a), hook_env)
+ (b / "new.py").write_text(VULN_PY)
+ run_hook(edit_payload(b, b / "new.py"), hook_env)
+ m = _stop(b, hook_env)
+ assert m["files_reviewed"] == 1 and m["bl_origin"] == 1
+ assert stub_api.calls.count("/v1/messages") == 1
+
+
+def test_commit_made_after_entering_another_worktree_is_reviewed(
+ hook_env, checkouts):
+ a, b = checkouts
+ run_hook(ups_payload(a), hook_env)
+ (b / "new.py").write_text(VULN_PY)
+ git(b, "add", "-A")
+ git(b, "commit", "-q", "-m", "this turn")
+ m = _stop(b, hook_env)
+ # new.py, not old.py from the earlier commit.
+ assert m["files_reviewed"] == 1 and m["bl_origin"] == 1
+
+
+def test_commit_in_a_worktree_created_this_turn_is_reviewed(hook_env, checkouts):
+ a, _ = checkouts
+ run_hook(ups_payload(a), hook_env)
+ c = a.parent / "c"
+ git(a, "worktree", "add", "-q", "-b", "fresh", str(c))
+ (c / "new.py").write_text(VULN_PY)
+ git(c, "add", "-A")
+ git(c, "commit", "-q", "-m", "this turn")
+ (c / "more.py").write_text(VULN_PY)
+ m = _stop(c, hook_env)
+ assert m["files_reviewed"] == 2 and m["bl_origin"] == 1
+
+
+def test_uncommitted_work_already_in_the_other_worktree_is_left_out(
+ hook_env, checkouts, stub_api):
+ a, b = checkouts
+ (b / "scratch.py").write_text(VULN_PY) # untracked
+ (b / "old.py").write_text(VULN_PY + "# todo\n") # tracked, edited
+ time.sleep(2.2) # past the slack allowed around the prompt time
+ run_hook(ups_payload(a), hook_env)
+ m = _stop(b, hook_env)
+ assert m["skipped"] is True and m["bl_origin"] == 1
+ assert not stub_api.calls
+ # Both are reviewed once the turn writes to them.
+ (b / "scratch.py").write_text(VULN_PY + "x = 1\n")
+ (b / "old.py").write_text(VULN_PY + "# done\n")
+ m = _stop(b, hook_env)
+ assert m["files_reviewed"] == 2 and m["bl_origin"] == 1
+
+
+def test_baseline_kept_from_an_interrupted_turn_in_another_worktree(
+ hook_env, checkouts, stub_api):
+ a, b = checkouts
+ run_hook(ups_payload(a), hook_env)
+ run_hook(edit_payload(a, a / "app.py"), hook_env)
+ run_hook(ups_payload(b), hook_env)
+ m = _stop(b, hook_env)
+ assert m["skipped"] is True and m["bl_origin"] == 21
+ assert not stub_api.calls
+
+
+def test_baseline_kept_from_an_interrupted_turn_in_the_same_checkout(hook_env, checkouts):
+ a, _ = checkouts
+ run_hook(ups_payload(a), hook_env)
+ run_hook(edit_payload(a, a / "app.py"), hook_env)
+ run_hook(ups_payload(a), hook_env)
+ (a / "app.py").write_text(VULN_PY)
+ assert _stop(a, hook_env)["bl_origin"] == 20
+
+
+def test_interrupted_turn_then_a_prompt_that_cannot_capture(hook_env, checkouts):
+ a, _ = checkouts
+ run_hook(ups_payload(a), hook_env)
+ run_hook(edit_payload(a, a / "app.py"), hook_env)
+ run_hook(ups_payload(a), hook_env)
+ run_hook(ups_payload(a.parent), hook_env)
+ (a / "app.py").write_text(VULN_PY)
+ assert _stop(a, hook_env)["bl_origin"] == 10
+
+
+def test_baseline_from_another_repository(hook_env, checkouts, tmp_path):
+ a, _ = checkouts
+ other = make_repo(tmp_path / "ws" / "other", {"lib.py": "x = 1\n"})
+ run_hook(ups_payload(a), hook_env)
+ (other / "lib.py").write_text(VULN_PY)
+ m = _stop(other, hook_env)
+ assert m["files_reviewed"] == 1 and m["bl_origin"] == 2
+
+
+def test_baseline_from_a_checkout_that_is_gone(hook_env, checkouts):
+ a, b = checkouts
+ run_hook(ups_payload(b), hook_env)
+ git(a, "worktree", "remove", "--force", str(b))
+ shutil.rmtree(b, ignore_errors=True)
+ (a / "app.py").write_text(VULN_PY)
+ m = _stop(a, hook_env)
+ assert m["files_reviewed"] == 1 and m["bl_origin"] == 3
+
+
+def test_prompt_in_a_folder_that_is_not_a_repo_keeps_the_untracked_snapshot(
+ hook_env, checkouts):
+ a, _ = checkouts
+ ws = a.parent
+ (a / "notes.py").write_text("n = 0\n") # untracked since before the session
+ run_hook(ups_payload(a), hook_env)
+ (a / "first.py").write_text("x = 1\n")
+ assert _stop(a, hook_env)["bl_origin"] == 0
+ run_hook(ups_payload(ws), hook_env)
+ (a / "second.py").write_text("y = 2\n")
+ run_hook(edit_payload(ws, a / "second.py"), hook_env)
+ m = _stop(ws, hook_env)
+ # The earlier baseline is kept, so the first turn's file is reviewed
+ # again. notes.py is not: the snapshot that goes with it is kept too.
+ assert m["files_reviewed"] == 2 and m["bl_origin"] == 10
+ # The next prompt in the repo captures a fresh baseline there.
+ run_hook(ups_payload(a), hook_env)
+ (a / "third.py").write_text("z = 3\n")
+ m = _stop(a, hook_env)
+ assert m["files_reviewed"] == 1 and m["bl_origin"] == 0
+
+
+def test_baseline_taken_after_a_finding_belongs_to_the_reviewed_checkout(
+ hook_env, checkouts, stub_api):
+ a, b = checkouts
+ run_hook(ups_payload(a), hook_env)
+ (b / "new.py").write_text(VULN_PY)
+ stub_api.vulns = [dict(STUB_VULN, filePath="new.py")]
+ assert _stop(b, hook_env)["bl_origin"] == 1
+ st = _state(hook_env)
+ assert os.path.samefile(st["baseline_root"], b)
+ # b's HEAD at the prompt, not a's.
+ assert st["head_at_capture"] == git(b, "rev-parse", "HEAD").strip()
+ # Same turn, next Stop: only what changed since the finding.
+ stub_api.vulns = []
+ (b / "newer.py").write_text("v = 1\n")
+ m = _stop(b, hook_env)
+ assert m["files_reviewed"] == 1 and m["bl_origin"] == 0
+
+
+def test_baseline_taken_after_a_finding_keeps_the_turns_first_commit(
+ hook_env, checkouts, stub_api):
+ a, _ = checkouts
+ head = git(a, "rev-parse", "HEAD").strip()
+ run_hook(ups_payload(a), hook_env)
+ (a / "app.py").write_text(VULN_PY)
+ git(a, "commit", "-q", "-am", "this turn")
+ stub_api.vulns = [dict(STUB_VULN, filePath="app.py")]
+ assert _stop(a, hook_env)["bl_origin"] == 0
+ assert _state(hook_env)["head_at_capture"] == head
+ # A fix folded into the commit is still inside the turn's range.
+ (a / "app.py").write_text(VULN_PY + "x = 1\n")
+ git(a, "commit", "-q", "-a", "--amend", "-m", "this turn")
+ assert _stop(a, hook_env)["files_reviewed"] == 1
+
+
+def test_first_baseline_taken_after_a_finding_records_its_checkout(
+ hook_env, checkouts, stub_api):
+ a, b = checkouts
+ ws = a.parent
+ run_hook(ups_payload(ws), hook_env)
+ (a / "new.py").write_text(VULN_PY)
+ run_hook(edit_payload(ws, a / "new.py"), hook_env)
+ stub_api.vulns = [dict(STUB_VULN, filePath="new.py")]
+ assert _stop(ws, hook_env)["bl_origin"] == 4
+ assert os.path.samefile(_state(hook_env)["baseline_root"], a)
+ stub_api.vulns = []
+ assert _stop(b, hook_env)["bl_origin"] == 1
+
+
+def test_no_baseline_at_all(hook_env, checkouts):
+ a, _ = checkouts
+ ws = a.parent
+ run_hook(ups_payload(ws), hook_env)
+ (a / "new.py").write_text("v = 1\n")
+ run_hook(edit_payload(ws, a / "new.py"), hook_env)
+ m = _stop(ws, hook_env)
+ assert m["files_reviewed"] == 1 and m["bl_origin"] == 4
+
+
+def test_prompt_subdirectory_removed_during_the_turn(hook_env, checkouts):
+ a, _ = checkouts
+ (a / "pkg").mkdir()
+ run_hook(ups_payload(a / "pkg"), hook_env)
+ (a / "pkg").rmdir()
+ (a / "app.py").write_text(VULN_PY)
+ assert _stop(a, hook_env)["bl_origin"] == 0
+
+
+def test_nested_worktree_removed_during_the_turn(hook_env, checkouts):
+ a, _ = checkouts
+ nested = a / ".claude" / "worktrees" / "wt"
+ git(a, "worktree", "add", "-q", "-b", "nested", str(nested))
+ run_hook(ups_payload(nested), hook_env)
+ git(a, "worktree", "remove", "--force", str(nested))
+ (a / "app.py").write_text(VULN_PY)
+ assert _stop(a, hook_env)["bl_origin"] == 3