summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-10-20 14:58:54 -0700
committerGitHub <noreply@github.com>2026-10-20 14:58:54 -0700
commitb2aa574dae5a7020bfb7cde1fbabea271114892c (patch)
treecd2c333d642a351313c7568bade355001b425cb8
parentc1785e2e56643aec21c99b3d879e9aef39e37d33 (diff)
parentc5bfe80e88f7ae781597b1368eb9dc90f0933d38 (diff)
Merge pull request #6608 from anthropics/mhegazy/sg-sdk-bootstrap-switches
security-guidance: do not install the agent SDK for reviews that are off; rebuild an emptied install
-rw-r--r--plugins/security-guidance/hooks/_base.py42
-rw-r--r--plugins/security-guidance/hooks/ensure_agent_sdk.py106
-rw-r--r--plugins/security-guidance/hooks/llm.py21
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py6
-rw-r--r--plugins/security-guidance/tests/test_sdk_bootstrap_switches.py183
-rw-r--r--plugins/security-guidance/tests/test_sdk_emptied_install.py101
6 files changed, 443 insertions, 16 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py
index eecae8b5..59e8e569 100644
--- a/plugins/security-guidance/hooks/_base.py
+++ b/plugins/security-guidance/hooks/_base.py
@@ -5,6 +5,7 @@ This module exists so that ``patterns``/``session_state``/``gitutil`` can use
``debug_log`` without importing ``security_reminder_hook`` (which would be a
circular import). It must stay free of any other intra-plugin imports.
"""
+import glob
import json
import os
import re
@@ -41,6 +42,47 @@ def state_dir():
return os.path.abspath(os.path.expanduser(d))
+def llm_reviews_switched_off():
+ """True when the environment turns off every review that calls a model:
+ the kill switch (SECURITY_GUIDANCE_DISABLE=1 / ENABLE_SECURITY_REMINDER=0),
+ ENABLE_CODE_SECURITY_REVIEW=0, or ENABLE_STOP_REVIEW=0 together with
+ ENABLE_COMMIT_REVIEW=0. Nothing loads the agent SDK then, so nothing
+ should install it. Same reading of each variable as
+ security_reminder_hook.py."""
+ env = os.environ.get
+ if env("SECURITY_GUIDANCE_DISABLE", "").strip().lower() in ("1", "true", "yes", "on"):
+ return True
+ if env("ENABLE_SECURITY_REMINDER", "1") == "0":
+ return True
+ if env("ENABLE_CODE_SECURITY_REVIEW", "1") == "0":
+ return True
+ return env("ENABLE_STOP_REVIEW", "1") == "0" and env("ENABLE_COMMIT_REVIEW", "1") == "0"
+
+
+def agent_sdk_site_dirs(state_dir):
+ """Directories under the state dir that ensure_agent_sdk.py installs the
+ agent SDK into and llm.py adds to sys.path: the venv's site-packages
+ (POSIX `lib/pythonX.Y/site-packages`, Windows `Lib/site-packages`) and
+ the flat `pip install --target` fallback."""
+ venv_root = os.path.join(state_dir, "agent-sdk-venv")
+ return (
+ glob.glob(os.path.join(venv_root, "lib", "python*", "site-packages"))
+ + glob.glob(os.path.join(venv_root, "Lib", "site-packages"))
+ + [os.path.join(state_dir, "agent-sdk-libs")]
+ )
+
+
+def agent_sdk_installed(state_dir):
+ """True iff one of those directories holds a finished install of the SDK:
+ its package and the metadata pip writes once the package is unpacked. A
+ file check only, no import."""
+ return any(
+ os.path.isfile(os.path.join(d, "claude_agent_sdk", "__init__.py"))
+ and glob.glob(os.path.join(d, "claude_agent_sdk-*.dist-info"))
+ for d in agent_sdk_site_dirs(state_dir)
+ )
+
+
# Debug log file. Lives under the plugin state dir (default ~/.claude/security/)
# rather than /tmp because /tmp is world-writable on multi-user hosts (TOCTOU /
# symlink-attack surface, cross-user log leakage). Overridable per-process via
diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py
index c1d59ba7..fadeae00 100644
--- a/plugins/security-guidance/hooks/ensure_agent_sdk.py
+++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py
@@ -28,6 +28,7 @@ from pathlib import Path
# here to match the existing local name (state_dir was already a local var in
# main() and _maybe_emit_user_notice).
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:
@@ -73,6 +74,9 @@ SKIP_COOLDOWN = 9 # a recent build was signal-killed (memory pressure) — no
# repro confirmed the dominant Linux BUILD_FAILED is a
# SIGKILL/SIGSEGV of the memory-heavy venv+pip subprocess
# (rc<0, empty streams). See #2154 follow-up.
+SKIP_REVIEWS_OFF = 10 # the environment turns off every review that would
+ # load the SDK (kill switch included), so nothing is
+ # installed. See #5331.
# How long to skip rebuilds after a signal kill. Retries at most once per
# window so a machine whose memory frees up still recovers (just not every
@@ -410,6 +414,20 @@ def _pip_err_from_stderr(stderr_b):
return f"other:{tail}" if tail else "other"
+# A package directory that has lost its files still imports, as a namespace
+# package, so a bare `import claude_agent_sdk` calls an emptied install
+# healthy and it is never rebuilt. A real install has a __file__; the probe
+# exits with _PROBE_EMPTIED when there is none. See #6612.
+_PROBE_EMPTIED = 3
+_SDK_IMPORT_PROBE = (
+ "import sys, claude_agent_sdk; "
+ f"sys.exit(0 if getattr(claude_agent_sdk, '__file__', None) else {_PROBE_EMPTIED})"
+)
+
+# Set by main() when the venv's probe exited with _PROBE_EMPTIED.
+_venv_was_emptied = False
+
+
def _target_dir(state_dir) -> Path:
return Path(state_dir) / "agent-sdk-libs"
@@ -425,7 +443,7 @@ def _target_sdk_importable(state_dir) -> bool:
try:
r = subprocess.run(
[sys.executable, "-c",
- "import sys; sys.path.insert(0, sys.argv[1]); import claude_agent_sdk",
+ "import sys; sys.path.insert(0, sys.argv[1]); " + _SDK_IMPORT_PROBE,
str(target)],
capture_output=True, timeout=10, cwd=_spawn_cwd(),
)
@@ -471,6 +489,79 @@ def _build_via_target(state_dir) -> tuple[int, str, str]:
return BUILD_FAILED, "pip_target", f"exc:{type(e).__name__}"
+def _near_git_repo() -> bool:
+ """Whether the session's directory is in a git work tree (a `.git` entry
+ here or above) or directly holds one (a workspace of repositories). The
+ reviews the SDK serves only run on a repository."""
+ try:
+ top = d = os.path.abspath(os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd())
+ while True:
+ if os.path.exists(os.path.join(d, ".git")):
+ return True
+ parent = os.path.dirname(d)
+ if parent == d:
+ break
+ d = parent
+ with os.scandir(top) as entries:
+ for i, entry in enumerate(entries):
+ if i >= 500:
+ return True # too large to say; not counted
+ if entry.is_dir() and os.path.exists(os.path.join(entry.path, ".git")):
+ return True
+ return False
+ except OSError:
+ return True
+
+
+def _venv_python_version(venv) -> int:
+ """The Python the venv was built with, as major*100+minor (312), read
+ from its pyvenv.cfg; 0 if unknown."""
+ try:
+ for line in (Path(venv) / "pyvenv.cfg").read_text(errors="replace").splitlines():
+ key, _, value = line.partition("=")
+ if key.strip() in ("version", "version_info"):
+ major, minor = value.strip().split(".")[:2]
+ return int(major) * 100 + int(minor)
+ except (OSError, ValueError):
+ pass
+ return 0
+
+
+def _install_context_metrics(outcome, state_dir) -> dict:
+ """Counts that size open questions about the private SDK install; no
+ behaviour depends on them. Only when set, and the first three only on
+ rows where the install exists.
+
+ sdk_no_creds / sdk_no_git: the session holds the install while the
+ reviews it serves cannot run, for lack of model credentials or of a git
+ repository. Should the build wait for those? See #5331.
+
+ sdk_venv_py: the venv was built by another Python version than the one
+ running the hooks, which is the one that loads it; its compiled
+ dependencies do not load there. See #5706.
+
+ sdk_venv_emptied: the venv's SDK package directory had lost its files
+ and this run went on to rebuild it, whatever the outcome. See #6612."""
+ out = {}
+ if _venv_was_emptied:
+ out["sdk_venv_emptied"] = 1
+ if outcome not in (NOOP_VENV, BUILT, BUILT_TARGET, NOOP_TARGET):
+ return out
+ try:
+ import llm
+ if not llm.HAS_API_CREDENTIALS:
+ out["sdk_no_creds"] = 1
+ except Exception:
+ pass
+ if not _near_git_repo():
+ out["sdk_no_git"] = 1
+ if outcome == NOOP_VENV:
+ built_by = _venv_python_version(Path(state_dir) / "agent-sdk-venv")
+ if built_by and built_by != sys.version_info[0] * 100 + sys.version_info[1]:
+ out["sdk_venv_py"] = built_by
+ return out
+
+
def _sdk_on_syspath() -> bool:
# find_spec is ~10ms; actually importing the SDK pulls in
# transitive deps and costs ~800ms — too heavy for a
@@ -499,6 +590,15 @@ def main() -> tuple[int, str, str]:
err_phase / err_kind are non-empty only on BUILD_FAILED — they let
telemetry split bootstrap failures by root cause.
"""
+ global _venv_was_emptied
+ _venv_was_emptied = False
+ # The SDK only serves the LLM reviews. With those switched off, or the
+ # whole plugin (SECURITY_GUIDANCE_DISABLE=1), a venv of a few hundred MB
+ # would be built for code that never runs, and the notice below would
+ # advertise a reviewer the user turned off. See #5331.
+ if llm_reviews_switched_off():
+ return SKIP_REVIEWS_OFF, "", ""
+
# Honesty check (fixes the misleading NOOP_VENV in #2071): the SDK
# requires Python >=3.10 and uses 3.10+ syntax (match statements,
# PEP 604 unions). On a 3.9 hook interpreter we CANNOT import it no
@@ -551,11 +651,12 @@ def main() -> tuple[int, str, str]:
if venv_py.exists():
try:
r = subprocess.run(
- [str(venv_py), "-c", "import claude_agent_sdk"],
+ [str(venv_py), "-c", _SDK_IMPORT_PROBE],
capture_output=True, timeout=10, cwd=_spawn_cwd(),
)
if r.returncode == 0:
return NOOP_VENV, "", ""
+ _venv_was_emptied = r.returncode == _PROBE_EMPTIED
except Exception:
pass # broken venv; rebuild below
@@ -864,6 +965,7 @@ if __name__ == "__main__":
# HOOK_PY_INCOMPATIBLE (whose "py_3.9" err_kind otherwise collapses to
# err=99, losing the version). Cheap — no subprocess, just sys.version_info.
metrics["sdk_hook_py"] = sys.version_info[0] * 100 + sys.version_info[1]
+ metrics.update(_install_context_metrics(outcome, _resolve_state_dir()))
pv = _plugin_version_int()
if pv:
metrics["pv"] = pv
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index c2c9cdd1..76d04c54 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -17,7 +17,6 @@ Two reassignable globals here are read by handlers in
``_last_review_truncated_bytes``. Handlers reference them as ``llm.X`` (not via
``from``-import) so they observe reassignment.
"""
-import glob
import hashlib
import json
import logging
@@ -35,7 +34,7 @@ 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 # noqa: F401
+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 load_state, with_locked_state
from gitutil import git_config_env, SAFE_GIT_CONFIG
@@ -60,17 +59,13 @@ def _inject_agent_sdk_venv_into_syspath(state_dir):
fails with `ModuleNotFoundError: pywintypes` and the agentic reviewer
falls back to single-shot silently. Replicate what site.py would do.
"""
- venv_root = os.path.join(state_dir, "agent-sdk-venv")
- candidates = (
- glob.glob(os.path.join(venv_root, "lib", "python*", "site-packages"))
- + glob.glob(os.path.join(venv_root, "Lib", "site-packages"))
- # `pip install --target` fallback (ensure_agent_sdk BUILT_TARGET, used
- # when venv can't bootstrap pip): a FLAT layout — packages sit directly
- # in agent-sdk-libs/, not under a site-packages subdir. See #2154
- # follow-up. The pywin32 .pth bootstrap below applies here too (target
- # installs don't process .pth at runtime, same as a manual venv insert).
- + [os.path.join(state_dir, "agent-sdk-libs")]
- )
+ # `agent-sdk-libs` is the `pip install --target` fallback
+ # (ensure_agent_sdk BUILT_TARGET, used when venv can't bootstrap pip): a
+ # FLAT layout, packages sit directly in it, not under a site-packages
+ # subdir. See #2154 follow-up. The pywin32 .pth bootstrap below applies
+ # there too (target installs don't process .pth at runtime, same as a
+ # manual venv insert).
+ candidates = agent_sdk_site_dirs(state_dir)
added = False
for sp in candidates:
if not os.path.isdir(sp) or sp in sys.path:
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 71ac3769..99b00ce0 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -88,6 +88,7 @@ from _base import ( # noqa: E402,F401
_USAGE_CONTEXT, _log_usage,
state_dir as _resolve_state_dir,
write_hook_output as _write_hook_output,
+ llm_reviews_switched_off, agent_sdk_installed,
)
import extensibility # noqa: E402
from patterns import ( # noqa: E402,F401
@@ -2726,12 +2727,15 @@ def _maybe_bootstrap_agent_sdk_async():
is idempotent and O_EXCL-locked, so concurrent/repeat spawns are safe;
the throttle file only avoids spawning dozens of subprocesses during
the build window. No-ops in ~10ms on local installs (SDK already
- importable).
+ importable, or already installed under the state dir, which is not on
+ sys.path here) and when the environment turns the LLM reviews off.
"""
try:
import importlib.util
if importlib.util.find_spec("claude_agent_sdk") is not None:
return
+ if llm_reviews_switched_off() or agent_sdk_installed(_resolve_state_dir()):
+ return
import time as _t
try:
if _t.time() - os.path.getmtime(_SDK_BOOTSTRAP_THROTTLE) < 300:
diff --git a/plugins/security-guidance/tests/test_sdk_bootstrap_switches.py b/plugins/security-guidance/tests/test_sdk_bootstrap_switches.py
new file mode 100644
index 00000000..36f2742b
--- /dev/null
+++ b/plugins/security-guidance/tests/test_sdk_bootstrap_switches.py
@@ -0,0 +1,183 @@
+"""The agent SDK is not installed for reviews that are switched off.
+
+ensure_agent_sdk.py (SessionStart) and the PostToolUse rescue spawn built a
+venv of a few hundred MB whatever the environment said, including under
+SECURITY_GUIDANCE_DISABLE=1, and the rescue started ensure_agent_sdk.py again
+every five minutes on machines whose SDK lives in that venv. See #5331.
+"""
+import importlib.util
+import subprocess
+import sys
+
+import pytest
+
+from conftest import HOOKS_DIR
+import _base
+import ensure_agent_sdk as boot
+import llm
+import security_reminder_hook as hook
+
+OFF = [
+ {"SECURITY_GUIDANCE_DISABLE": "1"},
+ {"SECURITY_GUIDANCE_DISABLE": "true"},
+ {"ENABLE_SECURITY_REMINDER": "0"},
+ {"ENABLE_CODE_SECURITY_REVIEW": "0"},
+ {"ENABLE_STOP_REVIEW": "0", "ENABLE_COMMIT_REVIEW": "0"},
+]
+STILL_ON = [{}, {"ENABLE_STOP_REVIEW": "0"}, {"ENABLE_COMMIT_REVIEW": "0"},
+ {"SECURITY_GUIDANCE_DISABLE": "0"}]
+SWITCHES = ("SECURITY_GUIDANCE_DISABLE", "ENABLE_SECURITY_REMINDER",
+ "ENABLE_CODE_SECURITY_REVIEW", "ENABLE_STOP_REVIEW", "ENABLE_COMMIT_REVIEW")
+
+
+@pytest.fixture
+def state(tmp_path, monkeypatch):
+ """Empty state dir, no SDK in the interpreter, switches unset."""
+ for name in SWITCHES:
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state"))
+ monkeypatch.setattr(boot, "_sdk_on_syspath", lambda: False)
+ return tmp_path / "state"
+
+
+@pytest.fixture
+def builds(monkeypatch):
+ """Records the venv / pip commands instead of running them."""
+ calls = []
+
+ def run(cmd, **kwargs):
+ calls.append([str(c) for c in cmd])
+ return subprocess.CompletedProcess(cmd, 0, b"", b"")
+ monkeypatch.setattr(boot.subprocess, "run", run)
+ return calls
+
+
+@pytest.fixture
+def spawns(state, monkeypatch):
+ """Records the rescue's detached starts of ensure_agent_sdk.py."""
+ calls = []
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ monkeypatch.setattr(hook, "_SDK_BOOTSTRAP_THROTTLE", str(state / ".sdk_bootstrap_spawned"))
+ monkeypatch.setattr(hook.subprocess, "Popen", lambda cmd, **kw: calls.append(cmd))
+ return calls
+
+
+def _install(root, finished=True):
+ pkg = root / "claude_agent_sdk"
+ pkg.mkdir(parents=True)
+ (pkg / "__init__.py").write_text("")
+ if finished:
+ (root / "claude_agent_sdk-0.2.0.dist-info").mkdir()
+
+
+@pytest.mark.parametrize("env", OFF)
+def test_session_start_builds_nothing_when_reviews_are_off(state, builds, monkeypatch, env):
+ for k, v in env.items():
+ monkeypatch.setenv(k, v)
+ assert boot.main() == (boot.SKIP_REVIEWS_OFF, "", "")
+ assert builds == [] and not state.exists()
+
+
+@pytest.mark.parametrize("env", STILL_ON)
+def test_session_start_still_builds_when_a_review_can_run(state, builds, monkeypatch, env):
+ for k, v in env.items():
+ monkeypatch.setenv(k, v)
+ assert boot.main()[0] == boot.BUILT
+ assert [c[1:3] for c in builds] == [["-m", "venv"], ["-m", "pip"]]
+
+
+@pytest.mark.parametrize("env", OFF[2:])
+def test_rescue_does_not_start_the_bootstrap_when_reviews_are_off(spawns, monkeypatch, env):
+ for k, v in env.items():
+ monkeypatch.setenv(k, v)
+ hook._maybe_bootstrap_agent_sdk_async()
+ assert spawns == []
+
+
+def test_rescue_starts_the_bootstrap_once_when_nothing_is_installed(spawns):
+ hook._maybe_bootstrap_agent_sdk_async()
+ hook._maybe_bootstrap_agent_sdk_async()
+ assert len(spawns) == 1 and spawns[0][1].endswith("ensure_agent_sdk.py")
+
+
+@pytest.mark.parametrize("where", [
+ "agent-sdk-venv/lib/python3.12/site-packages",
+ "agent-sdk-venv/Lib/site-packages",
+ "agent-sdk-libs",
+])
+def test_rescue_leaves_an_existing_install_alone(spawns, state, where):
+ _install(state / where)
+ hook._maybe_bootstrap_agent_sdk_async()
+ assert spawns == [] and not (state / ".sdk_bootstrap_spawned").exists()
+
+
+def test_rescue_still_runs_for_an_install_that_was_cut_short(spawns, state):
+ _install(state / "agent-sdk-venv/lib/python3.12/site-packages", finished=False)
+ hook._maybe_bootstrap_agent_sdk_async()
+ assert len(spawns) == 1
+
+
+def test_reviewer_and_bootstrap_agree_on_where_the_sdk_is_installed(state, monkeypatch):
+ for where in ("agent-sdk-venv/lib/python3.12/site-packages", "agent-sdk-libs"):
+ _install(state / where)
+ monkeypatch.setattr(sys, "path", list(sys.path))
+ assert llm._inject_agent_sdk_venv_into_syspath(str(state))
+ assert {str(state / "agent-sdk-venv/lib/python3.12/site-packages"),
+ str(state / "agent-sdk-libs")} <= set(sys.path)
+
+
+def test_switches_are_read_the_same_way_as_the_hook_reads_them(monkeypatch):
+ for env in OFF + STILL_ON:
+ for name in SWITCHES:
+ monkeypatch.delenv(name, raising=False)
+ for k, v in env.items():
+ monkeypatch.setenv(k, v)
+ out = subprocess.run(
+ [sys.executable, "-c",
+ "import security_reminder_hook as h; "
+ "print(h.SECURITY_GUIDANCE_DISABLED or not h.ENABLE_CODE_SECURITY_REVIEW"
+ " or not (h.ENABLE_STOP_REVIEW or h.ENABLE_COMMIT_REVIEW))"],
+ cwd=HOOKS_DIR, capture_output=True, text=True).stdout.strip()
+ assert out == str(_base.llm_reviews_switched_off()), env
+
+
+def test_disabled_plugin_says_nothing_on_a_python_below_3_10(state, builds, monkeypatch):
+ monkeypatch.setenv("SECURITY_GUIDANCE_DISABLE", "1")
+ monkeypatch.setattr(boot.sys, "version_info", (3, 9, 6, "final", 0))
+ assert boot.main()[0] == boot.SKIP_REVIEWS_OFF
+
+
+def test_install_the_session_cannot_use_is_counted(state, tmp_path, monkeypatch):
+ monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", False)
+ monkeypatch.setattr(boot, "_near_git_repo", lambda: False)
+ assert boot._install_context_metrics(boot.BUILT, state) == {"sdk_no_creds": 1, "sdk_no_git": 1}
+ assert boot._install_context_metrics(boot.BUILD_FAILED, state) == {}
+ monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True)
+ monkeypatch.setattr(boot, "_near_git_repo", lambda: True)
+ assert boot._install_context_metrics(boot.NOOP_VENV, state) == {}
+
+
+def test_session_directory_in_or_holding_a_repository(tmp_path, monkeypatch):
+ monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(tmp_path))
+ if boot._near_git_repo():
+ pytest.skip("the temp dir is itself inside a git work tree")
+ (tmp_path / "ws" / "repo" / ".git").mkdir(parents=True)
+ (tmp_path / "ws" / "repo" / "src").mkdir()
+ for inside in ("ws", "ws/repo", "ws/repo/src"):
+ monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(tmp_path / inside))
+ assert boot._near_git_repo(), inside
+
+
+@pytest.mark.parametrize("cfg, counted", [
+ ("home = /usr/bin\nversion = 3.99.1\n", {"sdk_venv_py": 399}),
+ ("home = /usr/bin\nversion_info = 3.99.1.final.0\n", {"sdk_venv_py": 399}),
+ (f"version = {sys.version_info[0]}.{sys.version_info[1]}.0\n", {}),
+ ("home = /usr/bin\n", {}),
+])
+def test_venv_built_by_another_python_is_counted(state, monkeypatch, cfg, counted):
+ monkeypatch.setattr(boot, "_near_git_repo", lambda: True)
+ monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True)
+ (state / "agent-sdk-venv").mkdir(parents=True)
+ (state / "agent-sdk-venv" / "pyvenv.cfg").write_text(cfg)
+ assert boot._install_context_metrics(boot.NOOP_VENV, state) == counted
+ assert boot._install_context_metrics(boot.BUILT, state) == {}
diff --git a/plugins/security-guidance/tests/test_sdk_emptied_install.py b/plugins/security-guidance/tests/test_sdk_emptied_install.py
new file mode 100644
index 00000000..415e8d99
--- /dev/null
+++ b/plugins/security-guidance/tests/test_sdk_emptied_install.py
@@ -0,0 +1,101 @@
+"""An SDK install whose package directory lost its files is rebuilt.
+
+`import claude_agent_sdk` succeeds on an empty directory (Python imports it
+as a namespace package), so the bootstrap reported a healthy venv, the
+reviewer's `from claude_agent_sdk import ...` failed on every commit, and
+nothing repaired it until the venv was deleted by hand. See #6612.
+"""
+import importlib.util
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+import _base
+import ensure_agent_sdk as boot
+from test_sdk_bootstrap_switches import SWITCHES
+
+
+def _fill(pkg):
+ pkg.mkdir(parents=True, exist_ok=True)
+ (pkg / "__init__.py").write_text("AssistantMessage = object\n")
+ (pkg / "__pycache__").mkdir(exist_ok=True)
+
+
+def _empty(pkg):
+ for f in pkg.rglob("*"):
+ if f.is_file():
+ f.unlink()
+
+
+@pytest.fixture
+def venv(tmp_path, monkeypatch):
+ """A real venv (no pip, so it is quick) holding a stand-in SDK package;
+ the build commands are recorded instead of run, the probes run for real."""
+ for name in SWITCHES + ("PYTHONPATH",):
+ monkeypatch.delenv(name, raising=False)
+ state = tmp_path / "state"
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(state))
+ monkeypatch.setattr(boot, "_sdk_on_syspath", lambda: False)
+ monkeypatch.setattr(boot, "_near_git_repo", lambda: True)
+ subprocess.run([sys.executable, "-m", "venv", "--without-pip",
+ str(state / "agent-sdk-venv")], check=True)
+ pkg = Path(_base.agent_sdk_site_dirs(str(state))[0]) / "claude_agent_sdk"
+ _fill(pkg)
+ real_run = subprocess.run
+ builds = []
+
+ def run(cmd, **kwargs):
+ cmd = [str(c) for c in cmd]
+ if "-m" in cmd:
+ builds.append(cmd)
+ return subprocess.CompletedProcess(cmd, 0, b"", b"")
+ return real_run(cmd, **kwargs)
+ monkeypatch.setattr(boot.subprocess, "run", run)
+ return state, pkg, builds
+
+
+def test_complete_install_is_left_alone(venv):
+ state, _, builds = venv
+ outcome = boot.main()[0]
+ assert outcome == boot.NOOP_VENV and builds == []
+ assert "sdk_venv_emptied" not in boot._install_context_metrics(outcome, state)
+
+
+def test_emptied_install_is_rebuilt_and_counted(venv):
+ state, pkg, builds = venv
+ _empty(pkg)
+ outcome = boot.main()[0]
+ assert outcome == boot.BUILT
+ assert builds[0][1:4] == ["-m", "venv", "--clear"]
+ assert any("pip" in c and "claude-agent-sdk" in c for c in builds)
+ assert boot._install_context_metrics(outcome, state)["sdk_venv_emptied"] == 1
+ # The count belongs to the run that found it, not to later ones.
+ _fill(pkg)
+ outcome = boot.main()[0]
+ assert outcome == boot.NOOP_VENV
+ assert "sdk_venv_emptied" not in boot._install_context_metrics(outcome, state)
+
+
+def test_venv_that_never_held_the_sdk_is_not_counted_as_emptied(venv):
+ state, pkg, builds = venv
+ _empty(pkg)
+ (pkg / "__pycache__").rmdir()
+ pkg.rmdir()
+ outcome = boot.main()[0]
+ assert outcome == boot.BUILT and builds
+ assert "sdk_venv_emptied" not in boot._install_context_metrics(outcome, state)
+
+
+# An SDK installed for the interpreter running the tests is found behind the
+# emptied directory, which hides what this test looks at.
+@pytest.mark.skipif(importlib.util.find_spec("claude_agent_sdk") is not None,
+ reason="claude_agent_sdk is installed for this interpreter")
+def test_emptied_fallback_install_is_not_reused(tmp_path, monkeypatch):
+ monkeypatch.delenv("PYTHONPATH", raising=False)
+ pkg = boot._target_dir(tmp_path) / "claude_agent_sdk"
+ _fill(pkg)
+ assert boot._target_sdk_importable(tmp_path) is True
+ _empty(pkg)
+ assert boot._target_sdk_importable(tmp_path) is False