summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authormhegazy <mhegazy@users.noreply.github.com>2026-11-05 22:30:42 +0000
committerClaude <noreply@anthropic.com>2026-11-05 22:30:42 +0000
commit6ba0afbdce92bdafd4b3c7323ba57328455257f4 (patch)
tree0298cecc8b3ec7dd4c4aaa1fb90cb0fe6d15e55c /plugins
parenta6e9f5b1f95d3b997cf496e58541fd80b0f2f934 (diff)
parent81a14a7f0ab55316795a8eab350393e852d47384 (diff)
Merge main into mhegazy/sg-interp-reparse-telemetry
Both sides add a metric after the launcher probe timings on the SessionStart row; keep launcher_direct, then interp_reparse as the last key.
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/README.md4
-rw-r--r--plugins/security-guidance/hooks/_base.py37
-rw-r--r--plugins/security-guidance/hooks/ensure_agent_sdk.py15
-rw-r--r--plugins/security-guidance/hooks/extensibility.py29
-rw-r--r--plugins/security-guidance/hooks/gitutil.py38
-rw-r--r--plugins/security-guidance/hooks/llm.py84
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py12
-rw-r--r--plugins/security-guidance/hooks/session_state.py21
-rwxr-xr-xplugins/security-guidance/hooks/sg-python.sh155
-rw-r--r--plugins/security-guidance/tests/test_git_program.py115
-rw-r--r--plugins/security-guidance/tests/test_launcher_alias_own_path.py372
-rw-r--r--plugins/security-guidance/tests/test_nested_repos.py48
-rw-r--r--plugins/security-guidance/tests/test_project_config_files.py117
-rw-r--r--plugins/security-guidance/tests/test_state_dir_mode.py107
-rw-r--r--plugins/security-guidance/tests/test_windows_cli_lookup.py279
15 files changed, 1397 insertions, 36 deletions
diff --git a/plugins/security-guidance/README.md b/plugins/security-guidance/README.md
index caef1866..bae789b4 100644
--- a/plugins/security-guidance/README.md
+++ b/plugins/security-guidance/README.md
@@ -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 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.
+- 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. On Windows the agentic commit reviewer runs through the bundled copy too, unless `SG_AGENTIC_CLI_PATH` is set. Where the Agent SDK has no bundled copy for Windows, those reviews run through `~\.local\bin\claude.exe`, or else a `claude.exe` on `PATH`; if there is neither, set `SG_AGENTIC_CLI_PATH`. 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:
@@ -93,6 +93,8 @@ Drop a `claude-security-guidance.md` in any of:
- `<project>/.claude/claude-security-guidance.md` — project rules, intended to be committed
- `<project>/.claude/claude-security-guidance.local.md` — local overrides, intended to be `.gitignore`'d
+Project files must be regular files: a link there, or a `.claude` folder that is a link, is skipped.
+
All three are loaded and concatenated into the LLM diff review's prompt in the order user → project → project-local. If the combined size exceeds the 8 KB prompt budget, the tail is truncated, so user-wide rules are kept and project-local rules are dropped first. The agentic commit reviewer (layer 3) does not currently read this file. Example:
```markdown
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py
index de25e4c9..523049c1 100644
--- a/plugins/security-guidance/hooks/_base.py
+++ b/plugins/security-guidance/hooks/_base.py
@@ -9,10 +9,17 @@ import glob
import json
import os
import re
+import stat
import sys
import threading
from datetime import datetime
+if os.name == "nt":
+ # Unless this variable exists, Windows looks for a program that is started
+ # by name in the working directory before PATH.
+ os.environ.setdefault("NoDefaultCurrentDirectoryInExePath", "1")
+
+
def state_dir():
"""Return the absolute path of the plugin's state directory.
@@ -43,6 +50,26 @@ def state_dir():
return os.path.abspath(os.path.expanduser(d))
+def make_state_dir(d=None):
+ """Create the state dir (or `d`) with access for its user alone, and
+ narrow the default one to that if it is already there, so a umask such as
+ 002 does not leave the reviewer's venv, logs and session state open to the
+ rest of a shared group. A folder named by SECURITY_WARNINGS_STATE_DIR
+ that already exists is the user's to set. Raises OSError like os.makedirs."""
+ if d is None:
+ d = state_dir()
+ os.makedirs(d, mode=0o700, exist_ok=True)
+ if (os.name != "nt" and not os.environ.get("SECURITY_WARNINGS_STATE_DIR", "").strip()
+ and os.path.abspath(d) == state_dir()):
+ try:
+ st = os.lstat(d)
+ if stat.S_ISDIR(st.st_mode) and st.st_uid == os.getuid() and st.st_mode & 0o077:
+ os.chmod(d, 0o700)
+ except OSError:
+ pass
+ return 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),
@@ -379,6 +406,16 @@ def launcher_probe_metrics():
return {"launcher_probe_ms": min(total, cap), "launcher_probe_max_ms": min(slowest, cap)}
+def launcher_direct_metric():
+ """`launcher_direct` when sg-python.sh ran this hook with the interpreter
+ behind a packaged Windows alias instead of the alias: 1 from the path it
+ remembered (one process for the hook), 2 when it had just worked that
+ path out. Read once, like the probe timings.
+ """
+ how = os.environ.pop("SG_LAUNCHER_DIRECT", "")
+ return {"launcher_direct": int(how)} if how in ("1", "2") else {}
+
+
# Reparse tags that redirect every open below them: symbolic links and
# junctions. App execution aliases (the entries under WindowsApps) carry
# another tag and are not counted.
diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py
index 9304aba4..17e61e12 100644
--- a/plugins/security-guidance/hooks/ensure_agent_sdk.py
+++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py
@@ -28,10 +28,11 @@ 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 (
- interp_reparse_metric, launcher_probe_metrics, portable_output, state_dir as _resolve_state_dir,
+ interp_reparse_metric, launcher_direct_metric, launcher_probe_metrics, portable_output,
+ state_dir as _resolve_state_dir,
write_hook_output,
)
-from _base import llm_reviews_switched_off
+from _base import llm_reviews_switched_off, make_state_dir
def _spawn_cwd() -> str:
@@ -46,8 +47,7 @@ def _spawn_cwd() -> str:
"""
d = _resolve_state_dir()
try:
- os.makedirs(d, exist_ok=True)
- return d
+ return make_state_dir(d)
except OSError:
return str(Path(__file__).resolve().parent.parent)
@@ -256,7 +256,7 @@ def _write_cooldown(state_dir) -> None:
"""Start/refresh the signal-kill cooldown so we stop re-attempting a build
that keeps getting killed every session. Best-effort."""
try:
- Path(state_dir).mkdir(parents=True, exist_ok=True)
+ make_state_dir(str(state_dir))
(Path(state_dir) / "agent-sdk-venv.cooldown").write_text(
time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
except OSError:
@@ -681,7 +681,7 @@ def main() -> tuple[int, str, str]:
err_kind = ""
we_own_sentinel = False
try:
- state_dir.mkdir(parents=True, exist_ok=True)
+ make_state_dir(str(state_dir))
# O_EXCL makes the sentinel an atomic lock — if two SessionStarts
# race past the exists() check above, only one creates it.
try:
@@ -857,7 +857,7 @@ def _maybe_emit_user_notice(outcome: int, pv: int) -> str | None:
marker = state_dir / f".agentic_unavailable_notice_v{pv or 0}"
if marker.exists():
return None
- state_dir.mkdir(parents=True, exist_ok=True)
+ make_state_dir(str(state_dir))
# Write timestamp + Python version so the marker is self-documenting
# if a user goes looking. O_EXCL would be racier with no real win
# (two concurrent SessionStarts both showing the notice once is fine).
@@ -977,6 +977,7 @@ if __name__ == "__main__":
if os.environ.get("SG_LAUNCHER_FALLBACK") == "1":
metrics["launcher_fallback"] = 1
metrics.update(launcher_probe_metrics())
+ metrics.update(launcher_direct_metric())
# Last, so it is the first key a row over Claude Code's key cap (20, 10
# in older versions) loses.
metrics.update(interp_reparse_metric())
diff --git a/plugins/security-guidance/hooks/extensibility.py b/plugins/security-guidance/hooks/extensibility.py
index ed332c99..d27e9173 100644
--- a/plugins/security-guidance/hooks/extensibility.py
+++ b/plugins/security-guidance/hooks/extensibility.py
@@ -30,6 +30,9 @@ Trust model:
built-in ones. Reminder length is capped.
- Custom regexes are validated at load for catastrophic-backtracking
structure and skipped (with a debug log) if they look ReDoS-prone.
+ - A project file that is a link, or sits under a ``.claude`` that is one, is
+ skipped (with a debug log). User files may be links, as dotfile managers
+ make them.
- Built-in patterns cannot be disabled. ``ENABLE_PATTERN_RULES=0`` disables
all pattern checks; there is no per-rule kill switch in v1.
"""
@@ -125,13 +128,30 @@ def _config_paths(cwd: Optional[str], basename: str) -> List[Tuple[str, str]]:
return paths
+def _readable_config(path: str, cwd: Optional[str]) -> bool:
+ """Whether a config file may be read. A project file (`cwd` given) must be
+ a regular file at that very place: a link, or a `.claude` that is one,
+ would bring in text from wherever it points."""
+ if cwd is None or not os.path.lexists(path):
+ return True
+ expected = os.path.join(os.path.realpath(cwd), os.path.relpath(path, cwd))
+ real = os.path.realpath(path)
+ if os.path.normcase(real) == os.path.normcase(expected) and os.path.isfile(real):
+ return True
+ debug_log(f"extensibility: skipping {path}: a link, or not a regular file")
+ return False
+
+
def _load_guidance(cwd: Optional[str]) -> str:
parts = []
for label, path in _config_paths(cwd, GUIDANCE_BASENAME):
+ if not _readable_config(path, cwd if label.startswith("Project") else None):
+ continue
try:
with open(path, encoding="utf-8") as f:
txt = f.read().strip()
- except OSError:
+ except (OSError, UnicodeDecodeError) as e:
+ debug_log(f"extensibility: skipping {path}: {type(e).__name__}")
continue
if txt:
parts.append(f"### {label} security guidance\n{txt}")
@@ -148,9 +168,14 @@ def _load_guidance(cwd: Optional[str]) -> str:
return combined
+_GUIDANCE_END_TAG = re.compile(r"<(\s*/\s*project-security-guidance)", re.IGNORECASE)
+
+
def _wrap_guidance(guidance: str) -> str:
if not guidance:
return ""
+ # The block ends at its own closing tag, not at one in the text it holds.
+ guidance = _GUIDANCE_END_TAG.sub(r"&lt;\1", guidance)
return (
"\n\n<project-security-guidance>\n"
"The user has provided project-specific security guidance below. "
@@ -178,6 +203,8 @@ def _load_user_patterns(cwd: Optional[str]) -> List[Dict[str, Any]]:
# One unusable file is skipped on its own, so the rules from the
# other locations still load.
try:
+ if not _readable_config(candidate, cwd if label.startswith("Project") else None):
+ continue
found = _rules_from_file(candidate, label)
except Exception as e:
debug_log(f"extensibility: skipping {candidate}: {type(e).__name__}: {e}")
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index ec51e3c6..75d08298 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -27,8 +27,39 @@ import time
from _base import debug_log
+def _git_program(windows=os.name == "nt"):
+ """How to start git. On Windows a bare name is looked up in the process's
+ working directory before PATH, and the hooks run in the project, so a
+ `git.exe` there would start in place of the installed one. Name the first
+ git.exe on PATH instead, leaving out relative entries, the working
+ directory, and folders inside the project (unless the project holds the
+ home folder, and with it the user's own tools). With none, a path that
+ does not exist: git is reported missing, as it would be anywhere else."""
+ if not windows:
+ return "git"
+ def norm(p):
+ return os.path.normcase(os.path.normpath(p))
+ try:
+ cwd = norm(os.getcwd())
+ except OSError:
+ cwd = ""
+ home = norm(os.path.expanduser("~")) + os.sep
+ roots = [norm(r) for r in (cwd, os.environ.get("CLAUDE_PROJECT_DIR")) if r]
+ roots = [r.rstrip(os.sep) + os.sep for r in roots if not home.startswith(r.rstrip(os.sep) + os.sep)]
+ for d in os.environ.get("PATH", "").split(os.pathsep):
+ d = d.strip().strip('"')
+ if not d or not os.path.isabs(d) or norm(d) == cwd:
+ continue
+ if any((norm(d) + os.sep).startswith(r) for r in roots):
+ continue
+ path = os.path.join(d, "git.exe")
+ if os.path.isfile(path):
+ return path
+ return os.path.join(os.path.dirname(os.path.abspath(__file__)), "git.exe")
+
+
GIT_CMD = [
- "git",
+ _git_program(),
"-c", "core.fsmonitor=false",
"-c", "core.hooksPath=/dev/null",
# core.quotePath=false: emit raw UTF-8 in path-emitting commands instead
@@ -62,6 +93,10 @@ GIT_CMD = [
# _drop_gitlinks for the commands that take no such setting.
"-c", "diff.ignoreSubmodules=all",
"-c", "diff.submodule=short",
+ # `git log` and `git show` print commit metadata for the hooks to parse.
+ # With log.showSignature set they would also verify each signed commit,
+ # adding lines to the output and starting the program gpg.program names.
+ "-c", "log.showSignature=false",
]
# diff.ignoreSubmodules is a default that the repository's own settings for
@@ -74,6 +109,7 @@ SAFE_GIT_CONFIG = (
("core.hooksPath", "/dev/null"),
("diff.ignoreSubmodules", "all"),
("diff.submodule", "short"),
+ ("log.showSignature", "false"),
)
# The hook's git runs in the background beside the session's own git. Without
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index 468d9e6d..aa201235 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -39,7 +39,7 @@ except ImportError: # a Python built without TLS
import extensibility
import review_api
-from _base import debug_log, _record_usage, _record_http_error, _record_net_error, _clear_net_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir, agent_sdk_site_dirs # noqa: F401
+from _base import debug_log, _record_usage, _record_http_error, _record_net_error, _clear_net_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir, agent_sdk_site_dirs, make_state_dir # noqa: F401
from session_state import load_state, with_locked_state
from gitutil import git_config_env, SAFE_GIT_CONFIG
@@ -735,7 +735,7 @@ def _read_review_model_cache(path, endpoint_key, now):
def _write_review_model_cache(path, endpoint_key, model, now):
tmp = None
try:
- os.makedirs(os.path.dirname(path), exist_ok=True)
+ make_state_dir(os.path.dirname(path))
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".review_model.")
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump({"endpoint": endpoint_key, "model": model, "at": now}, f)
@@ -805,11 +805,12 @@ _gateway_check_unanswered = False
# depend on the model, so the Sonnet attempt is not made after it.
_gateway_review_timed_out = False
+_WINDOWS = os.name == "nt"
+
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."""
+ """The user's own `claude`: SG_AGENTIC_CLI_PATH if set ("" names none), 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
@@ -821,18 +822,71 @@ def _user_cli_path() -> Optional[str]:
# 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",
- ):
+ probes = [os.environ.get("CLAUDE_CODE_EXECPATH")]
+ if not _WINDOWS:
+ # Where Claude Code is installed on macOS and Linux.
+ probes += [
+ os.path.expanduser("~/.local/bin/claude"),
+ "/root/.local/bin/claude",
+ # Claude Code Remote container install path.
+ "/opt/claude-code/bin/claude",
+ ]
+ for p in probes:
if p and os.path.isfile(p):
return p
return None
+def _windows_user_cli() -> Optional[str]:
+ """Windows: the full path of the user's claude.exe, from the native
+ installer's folder, else from PATH; None when neither has one. Skips any
+ folder that is not given as a full path, and the working directory and
+ project root, and any folder inside them (unless that root holds the home
+ folder, and with it the user's own tools)."""
+ skipped = [d for d in (os.getcwd(), os.environ.get("CLAUDE_PROJECT_DIR")) if d and os.path.isdir(d)]
+ home = os.path.expanduser("~")
+ real_home = os.path.normcase(os.path.realpath(home)).rstrip(os.sep) + os.sep
+ roots = [r.rstrip(os.sep) + os.sep for r in (os.path.normcase(os.path.realpath(d)) for d in skipped)]
+ roots = [r for r in roots if not real_home.startswith(r)]
+ home_bin = os.path.join(home, ".local", "bin")
+ for folder in [home_bin] + os.environ.get("PATH", "").split(os.pathsep):
+ folder = folder.strip().strip('"')
+ cli = os.path.join(folder, "claude.exe")
+ try:
+ real = os.path.normcase(os.path.realpath(folder))
+ # A full path is one that abspath leaves as it is.
+ if (os.path.normcase(os.path.abspath(folder)) == os.path.normcase(os.path.normpath(folder))
+ and os.path.isfile(cli)
+ and not any(os.path.samefile(folder, d) for d in skipped)
+ and not any(real.startswith(r) for r in roots)):
+ return cli
+ except OSError:
+ pass
+ return None
+
+
+def _cli_for_sdk(cli_path: Optional[str]) -> Optional[str]:
+ """What to pass the Agent SDK as `cli_path`: a given one as it is. With none
+ given, the SDK chooses, except on Windows. There this names the CLI bundled
+ with the SDK, else the user's own, by its full path, and when neither exists
+ the bundled path anyway, so that the start fails."""
+ if cli_path or not _WINDOWS:
+ return cli_path or None
+ # When the SDK module has no file, any full path at which nothing exists will do.
+ sdk_file = getattr(sys.modules.get("claude_agent_sdk"), "__file__", None) or __file__
+ bundled = os.path.join(os.path.dirname(os.path.abspath(sdk_file)), "_bundled", "claude.exe")
+ if os.path.isfile(bundled):
+ return bundled
+ cli_path = _windows_user_cli()
+ if not cli_path:
+ debug_log("no Claude Code for the Agent SDK: none is bundled with it, and there is no claude.exe "
+ "in ~\\.local\\bin or on PATH outside this project (SG_AGENTIC_CLI_PATH can name one)")
+ return bundled
+ debug_log(f"the Agent SDK has no bundled Claude Code; using {cli_path}")
+ _tolerate_unknown_sdk_messages()
+ return cli_path
+
+
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
@@ -980,7 +1034,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None,
if cli_path:
_tolerate_unknown_sdk_messages()
else:
- cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") or None
+ cli_path = _cli_for_sdk(os.environ.get("SG_AGENTIC_CLI_PATH") or None)
default_model = default_review_model()
chosen_model = model or default_model
@@ -2009,7 +2063,7 @@ def _agentic_review(
"the findings list."
)
- # Always prefer the user's installed `claude` over the SDK's bundled CLI.
+ # Prefer the `claude` that _user_cli_path finds over the SDK's bundled CLI.
# The bundled CLI is whatever shipped with the pip-installed SDK version
# and can lag the user's CLI by months — protocol skew between them is a
# top cause of agentic_fallback=2 in production (the SDK reads
@@ -2019,6 +2073,8 @@ def _agentic_review(
cli_path = _gateway_cli or _user_cli_path()
if cli_path:
_tolerate_unknown_sdk_messages()
+ else:
+ cli_path = _cli_for_sdk(cli_path)
# Without a callback the inner CLI writes to this hook's stderr, which
# Claude Code shows Claude as the review notice. Log it instead.
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 3efe344e..8723710d 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -86,9 +86,9 @@ from _base import ( # noqa: E402,F401
_read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK,
_PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics, _net_error_metric,
_USAGE_CONTEXT, _log_usage,
- launcher_probe_metrics, state_dir as _resolve_state_dir,
+ launcher_direct_metric, launcher_probe_metrics, state_dir as _resolve_state_dir,
write_hook_output as _write_hook_output, portable_output,
- llm_reviews_switched_off, agent_sdk_installed,
+ llm_reviews_switched_off, agent_sdk_installed, make_state_dir,
)
import extensibility # noqa: E402
from patterns import ( # noqa: E402,F401
@@ -228,6 +228,8 @@ _LAST_METRIC_KEYS = ("diff_seen",)
# The launcher's slow interpreter probes, if any. After the keys above.
_LAUNCHER_METRICS: Dict[str, Any] = launcher_probe_metrics()
+# Whether the launcher skipped a packaged alias. Only on rows sent anyway.
+_LAUNCHER_DIRECT: Dict[str, Any] = launcher_direct_metric()
# Reviewer context diagnostics from llm.agentic_review, most useful first.
_REVIEWER_CONTEXT_KEYS = ("rv_cwd_gone", "rv_tool_err", "rv_tool_calls")
@@ -357,6 +359,8 @@ def emit_metrics(
tail[k] = tail.pop(k)
tail.update(_LAUNCHER_METRICS)
tail.update(_REVIEWER_EFFORT_METRICS)
+ # Last of all: the first key a full row loses.
+ tail.update(_LAUNCHER_DIRECT)
metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}}
out = {"metrics": metrics}
if rewake_summary:
@@ -422,7 +426,7 @@ def _no_credentials_notice(file_path, session_id):
pass
if not _git_toplevel(os.path.dirname(os.path.abspath(file_path))):
return None
- os.makedirs(os.path.dirname(marker), exist_ok=True)
+ make_state_dir(os.path.dirname(marker))
with open(marker, "w"):
pass
# In a session signed in to a Claude apps gateway the reviews do run,
@@ -2877,7 +2881,7 @@ def _maybe_bootstrap_agent_sdk_async():
return
except OSError:
pass
- os.makedirs(os.path.dirname(_SDK_BOOTSTRAP_THROTTLE), exist_ok=True)
+ make_state_dir(os.path.dirname(_SDK_BOOTSTRAP_THROTTLE))
# Touch the throttle BEFORE spawning so a burst of PostToolUse
# fires in the same second don't each spawn a subprocess.
open(_SDK_BOOTSTRAP_THROTTLE, "w").close()
diff --git a/plugins/security-guidance/hooks/session_state.py b/plugins/security-guidance/hooks/session_state.py
index c8045532..330abd28 100644
--- a/plugins/security-guidance/hooks/session_state.py
+++ b/plugins/security-guidance/hooks/session_state.py
@@ -20,7 +20,7 @@ import re
import tempfile
from datetime import datetime
-from _base import debug_log, state_dir as _state_dir
+from _base import debug_log, make_state_dir, state_dir as _state_dir
def _state_key(session_id):
@@ -139,6 +139,18 @@ def _write_then_rename(state_file, state):
raise
+def _write_in_place(state_file, state):
+ """The fallback (Windows, or a folder that refuses the rename) writes the
+ state file itself. As with the rename, a link there is replaced, not
+ followed, and a new file is the user's only, as the temporary file is."""
+ if os.path.islink(state_file):
+ os.unlink(state_file)
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0)
+ fd = os.open(state_file, flags, 0o600)
+ with os.fdopen(fd, "w") as f:
+ json.dump(state, f)
+
+
def save_state(session_id, state):
"""Save the full state dict to file.
@@ -152,12 +164,11 @@ def save_state(session_id, state):
try:
state_dir = os.path.dirname(state_file)
if state_dir:
- os.makedirs(state_dir, exist_ok=True)
+ make_state_dir(state_dir)
if _RENAME_INTO_PLACE and _write_then_rename(state_file, state):
return
- with open(state_file, "w") as f:
- json.dump(state, f)
+ _write_in_place(state_file, state)
except (IOError, OSError) as e:
debug_log(f"Failed to save state file {state_file}: {e}")
@@ -181,7 +192,7 @@ def with_locked_state(session_id, callback):
state_dir = os.path.dirname(lock_file)
try:
- os.makedirs(state_dir, exist_ok=True)
+ make_state_dir(state_dir)
except OSError:
pass
diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh
index e0c2730e..b1a5d5b9 100755
--- a/plugins/security-guidance/hooks/sg-python.sh
+++ b/plugins/security-guidance/hooks/sg-python.sh
@@ -100,10 +100,12 @@ probe() {
# the model, whose reply runs the Stop hook again: an endless loop that
# never reviewed anything. See #6251, #5781.
#
+ # On Windows a second line carries sys.executable (see sg_own_path).
+ #
# Only for `$(probe ...)`: the `exec` replaces that subshell instead of
# forking a second process from it.
[ "${BASH_SUBSHELL:-0}" -gt 0 ] || return 1
- exec "$@" -c 'import os, sys; t = (sys.argv[1:] or [""])[0]; sys.exit(3) if t and not (os.path.isfile(t) and os.access(t, os.R_OK)) else print(f"{sys.version_info[0]}.{sys.version_info[1]}")' "$SG_TARGET" 2>/dev/null
+ exec "$@" -c 'import os, sys; t = (sys.argv[1:] or [""])[0]; sys.exit(3) if t and not (os.path.isfile(t) and os.access(t, os.R_OK)) else print(f"{sys.version_info[0]}.{sys.version_info[1]}"); sys.platform == "win32" and sys.version_info >= (3, 10) and print(sys.executable)' "$SG_TARGET" 2>/dev/null
}
# Use as `ask ... || { note_unreadable "<name>"; continue; }` (see ask below).
@@ -142,11 +144,17 @@ sg_clock() {
esac
}
ask() {
- # Sets $v; same exit status as probe.
+ # Sets $v and $sg_exe; same exit status as probe.
local rc=0 t0 ms
sg_clock; t0=$sg_now
[ -n "$sg_probe_first" ] || sg_probe_first=$t0
v=$(probe "$@") || rc=$?
+ sg_exe=""
+ case "$v" in
+ *$'\n'*)
+ sg_exe=${v#*$'\n'}; sg_exe=${sg_exe%$'\r'}
+ v=${v%%$'\n'*} ;;
+ esac
sg_clock; ms=$((sg_now - t0))
if [ -n "$sg_coarse" ]; then
[ "$ms" -ge 2000 ] || ms=0
@@ -175,6 +183,145 @@ is_sdk_compatible() {
esac
}
+# Packaged launcher aliases on Windows (python, python3 and py under
+# ...\Microsoft\WindowsApps): starting one starts more than Python. The
+# Python Install Manager's aliases make Windows check the package for an
+# update on each start, and the launcher started the chosen name twice per
+# hook, on every Edit, prompt and Stop. See anthropics/claude-code#98929.
+#
+# So when the name that answers is such an alias and its interpreter is a
+# regular file elsewhere, the hook runs with that file instead, and its path
+# is kept in the plugin's state folder (`launcher-python`) for a day. Later
+# hooks start it directly: one process, and none through the alias. The
+# remembered path is used only while PATH and the hook folder are what they
+# were when it was checked and the file is still there; anything else is the
+# full search below, which writes the entry again. A hook that fails on the
+# remembered path empties the entry, so the next one searches again; deleting
+# the file does the same by hand. One entry: sessions with different PATHs
+# take turns checking, which is still one alias start per hook instead of two.
+#
+# Not while a virtual environment is active: the alias may be answering for
+# that environment's interpreter, which other sessions should not inherit.
+#
+# Builtins only: nothing here starts a process on the remembered route.
+unset SG_LAUNCHER_DIRECT
+sg_args=("$@")
+sg_exe="" # sys.executable from the last `ask` (Windows, Python 3.10+)
+sg_own="" # set by sg_recall and sg_own_path
+sg_memo="" # the entry's file; empty where none of this applies
+sg_target_dir=""
+case "${OSTYPE:-}" in
+ msys*|cygwin*)
+ if [ "${BASH_VERSINFO[0]:-0}" -ge 5 ] && [ -n "$SG_TARGET" ] && [ -z "${VIRTUAL_ENV:-}" ]; then
+ # The folder _base.state_dir() resolves to.
+ sg_home="${USERPROFILE:-${HOME:-}}"
+ sg_memo="${SECURITY_WARNINGS_STATE_DIR:-}"
+ if [ -z "$sg_memo" ] && [ -n "${CLAUDE_CONFIG_DIR:-}" ]; then
+ sg_memo="$CLAUDE_CONFIG_DIR/security"
+ fi
+ [ -n "$sg_memo" ] || sg_memo="~/.claude/security"
+ case "$sg_memo" in
+ "~"|"~"[\\/]*)
+ if [ -n "$sg_home" ]; then sg_memo="$sg_home${sg_memo:1}"; else sg_memo=""; fi ;;
+ esac
+ [ -z "$sg_memo" ] || sg_memo="$sg_memo/launcher-python"
+ sg_target_dir="${SG_TARGET%[\\/]*}"
+ fi ;;
+esac
+
+sg_is_alias_path() {
+ case "${1,,}" in
+ */microsoft/windowsapps/*|*\\microsoft\\windowsapps\\*) return 0 ;;
+ esac
+ return 1
+}
+
+# An interpreter the remembered route may start: python*.exe by absolute
+# path, a regular file, and not an alias itself.
+sg_startable() {
+ local name="${1##*/}"
+ case "$1" in
+ /*) ;;
+ *) return 1 ;;
+ esac
+ case "${name,,}" in
+ python*.exe) ;;
+ *) return 1 ;;
+ esac
+ ! sg_is_alias_path "$1" || return 1
+ [ -f "$1" ] && [ -x "$1" ]
+}
+
+sg_recall() {
+ # Sets $sg_own to the remembered interpreter iff it may run this hook.
+ local tag saved path exe dir end age
+ [ -n "$sg_memo" ] && [ -r "$sg_memo" ] || return 1
+ {
+ IFS= read -r tag && IFS= read -r saved && IFS= read -r path &&
+ IFS= read -r exe && IFS= read -r dir && IFS= read -r end
+ } 2>/dev/null < "$sg_memo" || return 1
+ [ "$tag" = "sg-launcher-python 1" ] && [ "$end" = "end" ] || return 1
+ case "$saved" in
+ ""|*[!0-9]*|????????????*) return 1 ;;
+ esac
+ age=$((EPOCHSECONDS - 10#$saved))
+ [ "$age" -ge 0 ] && [ "$age" -lt 86400 ] || return 1
+ [ "$path" = "$PATH" ] && [ "$dir" = "$sg_target_dir" ] || return 1
+ sg_startable "$exe" && [ -r "$SG_TARGET" ] || return 1
+ sg_own="$exe"
+}
+
+sg_own_path() {
+ # $1: the name that just answered `ask` with version $v. Succeeds, with
+ # $sg_own set, iff that name is a packaged alias whose interpreter is a
+ # regular file elsewhere that reads the hook script when started by
+ # itself and is the same version. Remembers it for the next hooks.
+ local alias="" own="$sg_exe" want="$v" drive
+ [ -n "$sg_memo" ] && [ -n "$own" ] || return 1
+ hash "$1" 2>/dev/null && alias="${BASH_CMDS[$1]:-}"
+ sg_is_alias_path "$alias" || return 1
+ case "$own" in
+ [A-Za-z]:[\\/]*)
+ if [ -n "${sg_drive_mounts:-}" ]; then
+ drive="${own:0:1}"; own="/${drive,,}/${own:3}"; own="${own//\\//}"
+ else
+ own=$(cygpath -u "$own" 2>/dev/null) || return 1
+ fi ;;
+ esac
+ sg_startable "$own" || return 1
+ ask "$own" || { v=$want; return 1; }
+ v=${v%$'\r'}
+ [ "$v" = "$want" ] || { v=$want; return 1; }
+ sg_own="$own"
+ if [ -d "${sg_memo%/*}" ]; then
+ { printf '%s\n' "sg-launcher-python 1" "$EPOCHSECONDS" "$PATH" "$own" "$sg_target_dir" "end"; } \
+ 2>/dev/null > "$sg_memo" || true
+ fi
+ return 0
+}
+
+# Use right before `exec <name> "$@"`: runs the hook with the interpreter
+# behind <name> instead when sg_own_path finds one, else returns.
+sg_direct() {
+ if sg_own_path "$@"; then
+ export SG_LAUNCHER_DIRECT=2
+ exec "$sg_own" "${sg_args[@]}"
+ fi
+ return 0
+}
+
+if sg_recall; then
+ export SG_LAUNCHER_DIRECT=1
+ # Not exec'd, so a failure can empty the entry: no probe checked this
+ # interpreter today, and a broken one must not fail every hook for a day.
+ sg_rc=0
+ "$sg_own" "$@" || sg_rc=$?
+ if [ "$sg_rc" -ne 0 ]; then
+ { : > "$sg_memo"; } 2>/dev/null || true
+ fi
+ exit "$sg_rc"
+fi
+
# 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
@@ -185,6 +332,7 @@ for cmd in "python3.13" "python3.12" "python3.11" "python3.10"; do
ask "$cmd" || { note_unreadable "$cmd"; continue; }
v=${v%$'\r'}
if is_sdk_compatible "$v"; then
+ sg_direct "$cmd"
exec "$cmd" "$@"
fi
done
@@ -201,6 +349,8 @@ for cmd in "python3" "python" "py -3"; do
v=${v%$'\r'}
if is_sdk_compatible "$v"; then
# shellcheck disable=SC2086
+ sg_direct $cmd
+ # shellcheck disable=SC2086
exec $cmd "$@"
fi
# Anything that successfully reported a "M.m" string.
@@ -219,6 +369,7 @@ done
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%%$'\n'*}
v=${v%$'\r'}
if is_sdk_compatible "$v"; then
exec "$cmd" "$@"
diff --git a/plugins/security-guidance/tests/test_git_program.py b/plugins/security-guidance/tests/test_git_program.py
new file mode 100644
index 00000000..9249c6e4
--- /dev/null
+++ b/plugins/security-guidance/tests/test_git_program.py
@@ -0,0 +1,115 @@
+"""On Windows the hooks name git by its full path, found on PATH, so a git.exe
+in the project is not the one that starts."""
+import json
+import os
+import subprocess
+import sys
+
+import pytest
+
+from conftest import HOOK_SCRIPT, make_repo, ups_payload, write_cli
+
+import gitutil
+
+windows_only = pytest.mark.skipif(os.name != "nt", reason="Windows program lookup")
+
+
+def _git_in(d):
+ d.mkdir(parents=True, exist_ok=True)
+ (d / "git.exe").write_bytes(b"")
+ return str(d / "git.exe")
+
+
+def test_bare_name_outside_windows():
+ assert gitutil._git_program(windows=False) == "git"
+
+
+def test_first_git_on_path(tmp_path, monkeypatch):
+ first, second = tmp_path / "a", tmp_path / "b"
+ first.mkdir()
+ expected = _git_in(second)
+ _git_in(tmp_path / "c")
+ monkeypatch.setenv("PATH", os.pathsep.join([str(first), str(second), str(tmp_path / "c")]))
+ assert gitutil._git_program(windows=True) == expected
+
+
+def test_working_directory_and_relative_entries_are_left_out(tmp_path, monkeypatch):
+ project = tmp_path / "project"
+ _git_in(project)
+ _git_in(project / "bin")
+ expected = _git_in(tmp_path / "installed")
+ monkeypatch.chdir(project)
+ monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False)
+ monkeypatch.setenv("PATH", os.pathsep.join(
+ ["", ".", "bin", str(project), str(project) + os.sep, str(tmp_path / "installed")]))
+ assert gitutil._git_program(windows=True) == expected
+
+
+def test_folder_inside_the_project_is_left_out(tmp_path, monkeypatch):
+ project = tmp_path / "project"
+ _git_in(project)
+ _git_in(project / ".venv" / "Scripts")
+ (project / "pkg").mkdir()
+ expected = _git_in(tmp_path / "installed")
+ monkeypatch.chdir(project / "pkg")
+ monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(project))
+ monkeypatch.setenv("PATH", os.pathsep.join(
+ [str(project), str(project / ".venv" / "Scripts"), str(tmp_path / "installed")]))
+ assert gitutil._git_program(windows=True) == expected
+
+
+def test_project_above_the_home_folder_keeps_the_users_tools(tmp_path, monkeypatch):
+ home = tmp_path / "me"
+ expected = _git_in(home / "scoop" / "shims")
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("USERPROFILE", str(home))
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False)
+ monkeypatch.setenv("PATH", str(home / "scoop" / "shims"))
+ assert gitutil._git_program(windows=True) == expected
+
+
+def test_similar_folder_name_stays(tmp_path, monkeypatch):
+ project = tmp_path / "project"
+ project.mkdir()
+ expected = _git_in(tmp_path / "project-tools")
+ monkeypatch.chdir(project)
+ monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False)
+ monkeypatch.setenv("PATH", str(tmp_path / "project-tools"))
+ assert gitutil._git_program(windows=True) == expected
+
+
+def test_quoted_entry(tmp_path, monkeypatch):
+ expected = _git_in(tmp_path / "installed")
+ monkeypatch.setenv("PATH", f'"{tmp_path / "installed"}"')
+ assert gitutil._git_program(windows=True) == expected
+
+
+def test_no_git_on_path_names_nothing_that_exists(tmp_path, monkeypatch):
+ project = tmp_path / "project"
+ _git_in(project)
+ monkeypatch.chdir(project)
+ monkeypatch.setenv("PATH", str(project))
+ program = gitutil._git_program(windows=True)
+ assert os.path.isabs(program) and not os.path.exists(program)
+
+
+def test_working_directory_that_is_gone(tmp_path, monkeypatch):
+ expected = _git_in(tmp_path / "installed")
+ monkeypatch.setattr(gitutil.os, "getcwd", lambda: (_ for _ in ()).throw(OSError()))
+ monkeypatch.setenv("PATH", str(tmp_path / "installed"))
+ assert gitutil._git_program(windows=True) == expected
+
+
+@windows_only
+def test_git_exe_in_the_project_does_not_start(tmp_path, env):
+ marker = tmp_path / "started"
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ write_cli(repo, "git", f"open({str(marker)!r}, 'a').write('x')\n")
+
+ r = subprocess.run(
+ [sys.executable, str(HOOK_SCRIPT)], input=json.dumps(ups_payload(repo)),
+ capture_output=True, text=True, env=env, cwd=repo, timeout=120)
+
+ assert r.returncode == 0, r.stderr
+ assert not marker.exists()
diff --git a/plugins/security-guidance/tests/test_launcher_alias_own_path.py b/plugins/security-guidance/tests/test_launcher_alias_own_path.py
new file mode 100644
index 00000000..2dd133d0
--- /dev/null
+++ b/plugins/security-guidance/tests/test_launcher_alias_own_path.py
@@ -0,0 +1,372 @@
+"""sg-python.sh stops starting a packaged Windows alias on every hook.
+
+When the name that answers is an alias under ...\\Microsoft\\WindowsApps and
+its interpreter is a regular file elsewhere, the hook runs with that file and
+the path is remembered for a day, so later hooks are one process and none
+through the alias. See anthropics/claude-code#98929.
+
+Aliases and interpreters are shell wrappers, so these tests need a POSIX
+shell; the launcher's Windows branch is switched on with OSTYPE.
+"""
+import os
+import shutil
+import subprocess
+import sys
+import time
+
+import pytest
+
+from conftest import HOOKS_DIR, metrics_of, run_hook, stop_payload
+
+SHIM = HOOKS_DIR / "sg-python.sh"
+BASH = shutil.which("bash") or "/bin/bash"
+REAL = os.path.realpath(sys.executable)
+VERSION = f"{sys.version_info[0]}.{sys.version_info[1]}"
+try:
+ BASH_MAJOR = int(subprocess.run([BASH, "-c", "echo ${BASH_VERSINFO[0]}"], capture_output=True,
+ text=True, timeout=30).stdout.strip() or 0)
+except (OSError, ValueError, subprocess.SubprocessError):
+ BASH_MAJOR = 0
+
+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers")
+
+HOOK = (
+ "import os, sys\n"
+ "print('direct=' + os.environ.get('SG_LAUNCHER_DIRECT', ''))\n"
+ "print('exe=' + os.environ.get('SG_NAME', ''))\n"
+ "print('argv=' + ' '.join(sys.argv[1:]))\n"
+ "print('stdin=' + sys.stdin.read())\n"
+)
+
+# A packaged alias: answers the probe like Windows Python does (version, then
+# sys.executable, CRLF), and runs the hook itself when asked to.
+ALIAS = """#!{bash}
+[ "${{0##*/}}" = "py" ] && [ "${{1:-}}" = "-3" ] && shift
+if [ "${{1:-}}" = "-c" ]; then
+ echo "${{0##*/}} probe" >> '{log}'; printf '{version}\\r\\n{own}\\r\\n'; exit 0
+fi
+echo "${{0##*/}} run" >> '{log}'
+SG_NAME=alias exec '{real}' "$@"
+"""
+# The interpreter behind it: the real one, logging its starts.
+OWN = """#!{bash}
+if [ "${{1:-}}" = "-c" ]; then
+ echo "own probe" >> '{log}'
+ [ {rc} -eq 0 ] || exit {rc}
+else
+ echo "own run" >> '{log}'
+fi
+SG_NAME=own exec '{real}' "$@"
+"""
+
+
+class Box:
+ def __init__(self, tmp_path):
+ self.root = tmp_path
+ self.apps = tmp_path / "AppData" / "Local" / "Microsoft" / "WindowsApps"
+ self.own = tmp_path / "AppData" / "Local" / "Python" / "pythoncore-3-64" / "python.exe"
+ self.state = tmp_path / "state"
+ self.log = tmp_path / "log"
+ self.hooks = tmp_path / "plugin" / "hooks"
+ for d in (self.apps, self.own.parent, self.state, self.hooks):
+ d.mkdir(parents=True)
+ self.log.write_text("")
+ self.script = self.hooks / "hook.py"
+ self.script.write_text(HOOK)
+ self.memo = self.state / "launcher-python"
+
+ def write(self, path, template, **kw):
+ kw = {"version": VERSION, "own": self.own, "rc": 0, **kw}
+ path.write_text(template.format(bash=BASH, log=self.log, real=REAL, **kw))
+ path.chmod(0o755)
+
+ def alias(self, name="py", **kw):
+ self.write(self.apps / name, ALIAS, **kw)
+
+ def interpreter(self, **kw):
+ self.write(self.own, OWN, **kw)
+
+ def launch(self, *args, script=None, ostype="msys", path=None, **extra_env):
+ env = {"PATH": path or str(self.apps), "HOME": str(self.root), "OSTYPE": ostype,
+ "SECURITY_WARNINGS_STATE_DIR": str(self.state)}
+ env.update(extra_env)
+ self.log.write_text("")
+ return subprocess.run([BASH, str(SHIM), str(script or self.script), *args], input="payload",
+ capture_output=True, text=True, timeout=60, env=env)
+
+ def run(self, *args, **kw):
+ r = self.launch(*args, **kw)
+ assert r.returncode == 0 and r.stderr == "", r.stderr
+ out = dict(line.split("=", 1) for line in r.stdout.splitlines())
+ return out, self.starts()
+
+ def starts(self):
+ return self.log.read_text().splitlines()
+
+
+@pytest.fixture
+def box(tmp_path):
+ if BASH_MAJOR < 5:
+ pytest.skip("the remembered route needs bash 5")
+ b = Box(tmp_path)
+ b.alias()
+ b.interpreter()
+ return b
+
+
+def test_first_hook_checks_the_interpreter_and_runs_it(box):
+ out, starts = box.run("extra")
+ assert starts == ["py probe", "own probe", "own run"]
+ assert (out["exe"], out["direct"], out["argv"], out["stdin"]) == ("own", "2", "extra", "payload")
+ assert box.memo.read_text().splitlines()[3] == str(box.own)
+
+
+def test_later_hooks_are_one_process_and_never_the_alias(box):
+ box.run()
+ for _ in range(3):
+ out, starts = box.run("extra")
+ assert starts == ["own run"]
+ assert (out["exe"], out["direct"], out["argv"], out["stdin"]) == ("own", "1", "extra", "payload")
+
+
+def test_state_folder_follows_the_config_dir(box):
+ (box.root / "cfg" / "security").mkdir(parents=True)
+ env = {"SECURITY_WARNINGS_STATE_DIR": "", "CLAUDE_CONFIG_DIR": str(box.root / "cfg")}
+ box.run(**env)
+ assert (box.root / "cfg" / "security" / "launcher-python").exists()
+ assert box.run(**env)[1] == ["own run"]
+ (box.root / ".claude" / "security").mkdir(parents=True)
+ env["CLAUDE_CONFIG_DIR"] = ""
+ box.run(**env)
+ assert (box.root / ".claude" / "security" / "launcher-python").exists()
+ assert not box.memo.exists()
+
+
+def test_changed_path_is_searched_again(box):
+ box.run()
+ other = box.root / "other"
+ other.mkdir()
+ out, starts = box.run(path=f"{box.apps}{os.pathsep}{other}")
+ assert starts == ["py probe", "own probe", "own run"] and out["direct"] == "2"
+
+
+def test_another_hook_folder_is_checked_again(box):
+ box.run()
+ moved = box.root / "plugin-next" / "hooks"
+ moved.mkdir(parents=True)
+ (moved / "hook.py").write_text(HOOK)
+ out, starts = box.run(script=moved / "hook.py")
+ assert starts == ["py probe", "own probe", "own run"]
+ # Same folder, another hook script: still the remembered route.
+ (moved / "other.py").write_text(HOOK)
+ assert box.run(script=moved / "other.py")[1] == ["own run"]
+
+
+@pytest.mark.parametrize("shift", [-86400 - 60, 3600])
+def test_entry_is_trusted_for_a_day(box, shift):
+ box.run()
+ lines = box.memo.read_text().splitlines()
+ lines[1] = str(int(time.time()) + shift)
+ box.memo.write_text("\n".join(lines) + "\n")
+ out, starts = box.run()
+ assert starts == ["py probe", "own probe", "own run"]
+ assert abs(int(box.memo.read_text().splitlines()[1]) - time.time()) < 120
+
+
+@pytest.mark.parametrize("damage", [
+ lambda lines: lines[:4], # cut short while being written
+ lambda lines: ["sg-launcher-python 0"] + lines[1:], # another format
+ lambda lines: lines[:1] + ["soon"] + lines[2:],
+ lambda lines: lines[:1] + ["9" * 30] + lines[2:],
+ lambda lines: lines[:3] + ["/bin/sh"] + lines[4:], # not an interpreter
+ lambda lines: lines[:3] + ["tools/python.exe"] + lines[4:], # not absolute
+ lambda lines: lines[:3] + [lines[4] + "/python.exe"] + lines[4:], # a folder (made below)
+ lambda lines: lines[:5] + ["more"],
+ lambda lines: [],
+])
+def test_damaged_entry_is_ignored_and_replaced(box, damage):
+ box.run()
+ (box.hooks / "python.exe").mkdir()
+ good = box.memo.read_text()
+ box.memo.write_text("".join(line + "\n" for line in damage(good.splitlines())))
+ out, starts = box.run()
+ assert starts == ["py probe", "own probe", "own run"] and out["stdin"] == "payload"
+ assert box.memo.read_text().splitlines()[2:] == good.splitlines()[2:]
+
+
+def test_remembered_alias_path_is_never_started(box):
+ box.run()
+ lines = box.memo.read_text().splitlines()
+ inner = box.apps / "python.exe"
+ box.write(inner, OWN)
+ lines[3] = str(inner)
+ box.memo.write_text("\n".join(lines) + "\n")
+ assert box.run()[1] == ["py probe", "own probe", "own run"]
+
+
+def test_removed_interpreter_falls_back_to_the_alias(box):
+ box.run()
+ box.own.unlink()
+ out, starts = box.run()
+ assert starts == ["py probe", "py run"]
+ assert (out["exe"], out["direct"], out["stdin"]) == ("alias", "", "payload")
+
+
+def test_missing_hook_script_is_not_run_from_memory(box):
+ box.run()
+ box.script.unlink()
+ box.launch()
+ # The full search ran: the remembered interpreter was not started first.
+ assert box.starts()[0] == "py probe"
+
+
+@pytest.mark.parametrize("code", [1, 2])
+def test_failed_hook_on_the_remembered_path_empties_the_entry(box, code):
+ box.run()
+ failing = box.hooks / "fails.py"
+ failing.write_text(f"import sys\nsys.stderr.write('findings')\nsys.exit({code})\n")
+ r = box.launch(script=failing)
+ # Its exit code and output pass through unchanged, once.
+ assert (r.returncode, r.stderr, box.starts()) == (code, "findings", ["own run"])
+ assert box.memo.read_text() == ""
+ out, starts = box.run()
+ assert starts == ["py probe", "own probe", "own run"] and out["direct"] == "2"
+ assert box.run()[1] == ["own run"]
+
+
+def test_virtual_environment_keeps_the_alias(box):
+ box.run()
+ out, starts = box.run(VIRTUAL_ENV=str(box.root / "venv"))
+ assert starts == ["py probe", "py run"] and (out["exe"], out["direct"]) == ("alias", "")
+
+
+def test_tilde_and_userprofile_resolve_like_the_hooks_do(box):
+ profile = box.root / "profile"
+ (profile / "st").mkdir(parents=True)
+ env = {"SECURITY_WARNINGS_STATE_DIR": "~/st", "USERPROFILE": str(profile)}
+ box.run(**env)
+ assert (profile / "st" / "launcher-python").exists()
+ assert box.run(**env)[1] == ["own run"]
+ (profile / ".claude" / "security").mkdir(parents=True)
+ env["SECURITY_WARNINGS_STATE_DIR"] = ""
+ box.run(**env)
+ assert (profile / ".claude" / "security" / "launcher-python").exists()
+
+
+def test_unwritable_entry_is_silent(box):
+ box.memo.mkdir()
+ for _ in range(2):
+ out, starts = box.run() # run() asserts an empty stderr
+ assert starts == ["py probe", "own probe", "own run"]
+
+
+def test_windows_form_path_goes_through_cygpath(box):
+ # OSTYPE=cygwin has no /<drive> mounts: the answer is converted by cygpath.
+ box.write(box.apps / "cygpath", """#!{bash}
+echo "cygpath $1" >> '{log}'
+[ "$1" = "-u" ] && [ "$2" = 'C:\\Py\\python.exe' ] && {{ echo '{own}'; exit 0; }}
+echo "$2"
+""")
+ box.alias(own="C:\\\\Py\\\\python.exe")
+ out, starts = box.run(ostype="cygwin")
+ assert [s for s in starts if not s.startswith("cygpath -w")] == [
+ "py probe", "cygpath -u", "own probe", "own run"]
+ assert (out["exe"], out["direct"]) == ("own", "2")
+ assert box.memo.read_text().splitlines()[3] == str(box.own)
+ assert [s for s in box.run(ostype="cygwin")[1] if not s.startswith("cygpath -w")] == ["own run"]
+
+
+@pytest.mark.parametrize("name", ["pypy3.exe", "python"])
+def test_interpreter_by_another_name_is_neither_checked_nor_remembered(box, name):
+ other = box.own.parent / name
+ box.write(other, OWN)
+ box.alias(own=other)
+ out, starts = box.run()
+ assert starts == ["py probe", "py run"] and not box.memo.exists()
+
+
+def test_interpreter_that_cannot_read_the_script_is_not_used(box):
+ box.interpreter(rc=3)
+ out, starts = box.run()
+ assert starts == ["py probe", "own probe", "py run"]
+ assert (out["exe"], out["direct"]) == ("alias", "") and not box.memo.exists()
+
+
+def test_other_version_behind_the_alias_is_not_used(box):
+ box.alias(version="3.10" if VERSION != "3.10" else "3.11")
+ out, starts = box.run()
+ assert starts == ["py probe", "own probe", "py run"]
+ assert (out["exe"], out["direct"]) == ("alias", "") and not box.memo.exists()
+
+
+def test_interpreter_inside_the_alias_folder_is_left_alone(box):
+ # Microsoft Store Python: sys.executable is itself under WindowsApps.
+ inner = box.apps / "PythonSoftwareFoundation.Python.3" / "python.exe"
+ inner.parent.mkdir()
+ box.write(inner, OWN)
+ box.alias(own=inner)
+ out, starts = box.run()
+ assert starts == ["py probe", "py run"] and out["direct"] == "" and not box.memo.exists()
+
+
+def test_regular_install_is_left_alone(box):
+ regular = box.root / "Python312"
+ regular.mkdir()
+ box.write(regular / "python", ALIAS)
+ out, starts = box.run(path=str(regular))
+ assert starts == ["python probe", "python run"] and out["direct"] == "" and not box.memo.exists()
+
+
+@pytest.mark.parametrize("ostype", ["linux-gnu", "darwin23", ""])
+def test_other_systems_are_left_alone(box, ostype):
+ box.run()
+ out, starts = box.run(ostype=ostype)
+ assert starts == ["py probe", "py run"] and out["direct"] == ""
+
+
+def test_missing_state_folder_is_not_created(box):
+ gone = box.root / "nowhere"
+ out, starts = box.run(SECURITY_WARNINGS_STATE_DIR=str(gone))
+ assert starts == ["py probe", "own probe", "own run"] and out["exe"] == "own"
+ assert not gone.exists()
+
+
+def test_versioned_alias_is_remembered_too(box):
+ (box.apps / "py").unlink()
+ box.alias("python3.12", version="3.12")
+ box.write(box.own, ALIAS.replace("SG_NAME=alias", "SG_NAME=own").replace("${{0##*/}}", "own"),
+ version="3.12")
+ out, starts = box.run()
+ assert starts == ["python3.12 probe", "own probe", "own run"] and out["direct"] == "2"
+ assert box.run()[1] == ["own run"]
+
+
+def test_newer_python_answering_with_two_lines_is_still_chosen(box):
+ # Pass 2b reads the probe without `ask`.
+ (box.apps / "py").unlink()
+ box.alias("python3.14", version="3.14")
+ out, starts = box.run()
+ assert starts == ["python3.14 probe", "python3.14 run"] and out["exe"] == "alias"
+
+
+@pytest.mark.parametrize("value,expected", [("1", 1), ("2", 2), ("", None), ("3", None), ("yes", None)])
+def test_stop_hook_reports_the_direct_route(hook_env, workspace, value, expected):
+ _, repo = workspace
+ rc, out, err = run_hook(stop_payload(repo), {**hook_env, "SG_LAUNCHER_DIRECT": value})
+ m = metrics_of(out)
+ assert m is not None, err
+ assert m.get("launcher_direct") == expected
+
+
+def test_direct_route_key_is_the_last_one(hook_env, workspace):
+ """Claude Code keeps the first 20 keys, so this one never displaces another."""
+ _, repo = workspace
+ rc, out, err = run_hook(stop_payload(repo), {**hook_env, "SG_LAUNCHER_DIRECT": "1"})
+ assert list(metrics_of(out))[-1] == "launcher_direct"
+
+
+def test_value_is_read_once(monkeypatch):
+ import _base
+ monkeypatch.setenv("SG_LAUNCHER_DIRECT", "1")
+ assert _base.launcher_direct_metric() == {"launcher_direct": 1}
+ assert "SG_LAUNCHER_DIRECT" not in os.environ and _base.launcher_direct_metric() == {}
diff --git a/plugins/security-guidance/tests/test_nested_repos.py b/plugins/security-guidance/tests/test_nested_repos.py
index 3c93a580..8357abf1 100644
--- a/plugins/security-guidance/tests/test_nested_repos.py
+++ b/plugins/security-guidance/tests/test_nested_repos.py
@@ -6,7 +6,7 @@ import pytest
from conftest import (
GIT_ENV, STUB_VULN, VULN_PY, git, make_repo, metrics_of, run_hook,
- stop_payload, ups_payload,
+ stop_payload, ups_payload, write_cli,
)
import diffstate
@@ -425,3 +425,49 @@ def test_gitlink_found_in_every_index_format(outer, marker, git_env, monkeypatch
assert seen and "160000" not in copy and "later.py" in copy
assert baseline != git(outer, "rev-parse", "HEAD").strip()
assert not marker.exists()
+
+
+def _signed_head(repo, tmp_path, marker):
+ """Make HEAD a commit that carries a signature, with log.showSignature on
+ and gpg.program naming a stand-in that leaves a line in `marker`."""
+ program = write_cli(tmp_path, "signature-check", (
+ "import sys\n"
+ f"open({str(marker)!r}, 'a').write('ran\\n')\n"
+ "sys.exit(1)\n"))
+ head = git(repo, "rev-parse", "HEAD").strip()
+ tree = git(repo, "rev-parse", "HEAD^{tree}").strip()
+ who = "t <t@example.com> 1800000000 +0000"
+ commit = (
+ f"tree {tree}\nparent {head}\nauthor {who}\ncommitter {who}\n"
+ "gpgsig -----BEGIN PGP SIGNATURE-----\n \n xx\n"
+ " -----END PGP SIGNATURE-----\n\nsigned\n")
+ sha = subprocess.run(
+ ["git", "hash-object", "-t", "commit", "-w", "--stdin"], cwd=repo,
+ input=commit.encode(), capture_output=True, check=True,
+ ).stdout.decode().strip()
+ git(repo, "update-ref", "--create-reflog", "-m", "commit: signed", "HEAD", sha)
+ git(repo, "config", "log.showSignature", "true")
+ git(repo, "config", "gpg.program", str(program))
+ return sha
+
+
+def test_reading_the_reflog_does_not_check_signatures(outer, marker, tmp_path, git_env):
+ sha = _signed_head(outer, tmp_path, marker)
+ # The stand-in does run for a plain `git log` in this repository.
+ git(outer, "log", "-1")
+ assert marker.exists()
+ marker.unlink()
+
+ fresh, _stale = gitutil._git_reflog_recent_commits(str(outer), max_age_s=10**10)
+
+ assert sha in fresh
+ assert not marker.exists(), marker.read_text()
+
+
+def test_reviewer_environment_turns_signature_display_off(outer, marker, tmp_path, git_env):
+ _signed_head(outer, tmp_path, marker)
+
+ gitutil.apply_safe_git_env()
+ git(outer, "log", "-1")
+
+ assert not marker.exists(), marker.read_text()
diff --git a/plugins/security-guidance/tests/test_project_config_files.py b/plugins/security-guidance/tests/test_project_config_files.py
new file mode 100644
index 00000000..5cef98c0
--- /dev/null
+++ b/plugins/security-guidance/tests/test_project_config_files.py
@@ -0,0 +1,117 @@
+"""Project guidance and pattern files are read only as real files in the
+project, and the guidance block ends where the plugin ends it."""
+import os
+import re
+import sys
+
+import pytest
+
+import extensibility
+
+
+GUIDANCE = extensibility.GUIDANCE_BASENAME
+RULE = '{"patterns": [{"rule_name": "r", "reminder": "from the file", "substrings": ["zz"]}]}'
+
+
+@pytest.fixture
+def project(tmp_path, monkeypatch):
+ monkeypatch.setenv("HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path / "home"))
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+ monkeypatch.setattr(extensibility, "_guidance_block", "")
+ monkeypatch.setattr(extensibility, "_user_patterns", [])
+ repo = tmp_path / "repo"
+ (repo / ".claude").mkdir(parents=True)
+ return repo
+
+
+def _link(link, target, is_dir=False):
+ try:
+ os.symlink(target, link, target_is_directory=is_dir)
+ except (OSError, NotImplementedError) as e:
+ pytest.skip(f"cannot make a link here: {e}")
+
+
+def _guidance(cwd):
+ extensibility.load_for_session(str(cwd))
+ return extensibility.guidance_block()
+
+
+def test_guidance_file_in_the_project_is_read(project):
+ (project / ".claude" / GUIDANCE).write_text("use the vault\n")
+ assert "use the vault" in _guidance(project)
+
+
+def test_guidance_link_inside_the_repository_is_skipped(project):
+ (project / ".env").write_text("TOKEN=abc\n")
+ _link(project / ".claude" / GUIDANCE, project / ".env")
+ assert _guidance(project) == ""
+
+
+def test_guidance_link_outside_is_skipped(project, tmp_path):
+ (tmp_path / "outside.md").write_text("outside text\n")
+ _link(project / ".claude" / GUIDANCE, tmp_path / "outside.md")
+ assert _guidance(project) == ""
+
+
+def test_config_folder_link_is_skipped(project, tmp_path):
+ other = tmp_path / "other"
+ other.mkdir()
+ (other / GUIDANCE).write_text("outside text\n")
+ (project / ".claude").rmdir()
+ _link(project / ".claude", other, is_dir=True)
+ assert _guidance(project) == ""
+
+
+def test_patterns_link_is_skipped(project, tmp_path):
+ (tmp_path / "rules.json").write_text(RULE)
+ _link(project / ".claude" / "security-patterns.json", tmp_path / "rules.json")
+ extensibility.load_for_session(str(project))
+ assert extensibility.user_patterns() == []
+
+
+def test_patterns_file_in_the_project_is_read(project):
+ (project / ".claude" / "security-patterns.json").write_text(RULE)
+ extensibility.load_for_session(str(project))
+ assert [r["ruleName"] for r in extensibility.user_patterns()] == ["user:r"]
+
+
+def test_user_guidance_may_be_a_link(project, tmp_path):
+ home = tmp_path / "home"
+ (home / ".claude").mkdir(parents=True)
+ (tmp_path / "dotfiles.md").write_text("my own rules\n")
+ _link(home / ".claude" / GUIDANCE, tmp_path / "dotfiles.md")
+ assert "my own rules" in _guidance(project)
+
+
+@pytest.mark.skipif(sys.platform == "win32", reason="no mkfifo")
+def test_guidance_that_is_not_a_regular_file_is_skipped(project):
+ os.mkfifo(project / ".claude" / GUIDANCE)
+ assert _guidance(project) == ""
+
+
+def test_project_guidance_that_cannot_be_decoded_leaves_the_user_guidance(project, tmp_path):
+ home = tmp_path / "home"
+ (home / ".claude").mkdir(parents=True)
+ (home / ".claude" / GUIDANCE).write_text("my own rules\n")
+ (project / ".claude" / GUIDANCE).write_bytes(b"\xff\xfe\xff\n")
+ assert "my own rules" in _guidance(project)
+
+
+def test_project_reached_through_a_link(project, tmp_path):
+ (project / ".claude" / GUIDANCE).write_text("use the vault\n")
+ _link(tmp_path / "alias", project, is_dir=True)
+ assert "use the vault" in _guidance(tmp_path / "alias")
+
+
+@pytest.mark.parametrize("tag", [
+ "</project-security-guidance>",
+ "</PROJECT-SECURITY-GUIDANCE>",
+ "</ project-security-guidance >",
+ "< /project-security-guidance>",
+])
+def test_guidance_cannot_close_its_own_block(project, tag):
+ (project / ".claude" / GUIDANCE).write_text(f"one\n{tag}\ntwo\n")
+ block = _guidance(project)
+ assert len(re.findall(r"<\s*/\s*project-security-guidance", block, re.I)) == 1
+ assert block.endswith("two\n</project-security-guidance>")
diff --git a/plugins/security-guidance/tests/test_state_dir_mode.py b/plugins/security-guidance/tests/test_state_dir_mode.py
new file mode 100644
index 00000000..d55afaf9
--- /dev/null
+++ b/plugins/security-guidance/tests/test_state_dir_mode.py
@@ -0,0 +1,107 @@
+"""The state dir holds the reviewer's venv, review logs and session state. It
+is created, and kept, with access for its user alone, whatever the umask."""
+import os
+import stat
+import sys
+
+import pytest
+
+import _base
+import session_state
+
+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX modes")
+
+
+@pytest.fixture
+def loose_umask():
+ old = os.umask(0o002)
+ yield
+ os.umask(old)
+
+
+def _mode(p):
+ return stat.S_IMODE(os.stat(p).st_mode)
+
+
+def test_new_state_dir_is_owner_only(tmp_path, monkeypatch, loose_umask):
+ d = tmp_path / "state"
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(d))
+ session_state.save_state("s1", {"k": 1})
+ assert _mode(d) == 0o700
+
+
+def test_existing_default_state_dir_is_narrowed(tmp_path, monkeypatch, loose_umask):
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.delenv("SECURITY_WARNINGS_STATE_DIR", raising=False)
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+ d = tmp_path / ".claude" / "security"
+ d.mkdir(parents=True)
+ os.chmod(d, 0o775)
+ _base.make_state_dir()
+ assert _mode(d) == 0o700
+
+
+def test_existing_folder_named_by_the_user_is_left_alone(tmp_path, monkeypatch):
+ d = tmp_path / "team"
+ d.mkdir()
+ os.chmod(d, 0o2775)
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(d))
+ _base.make_state_dir()
+ assert _mode(d) == 0o2775
+
+
+def test_a_link_at_the_default_state_dir_is_left_alone(tmp_path, monkeypatch):
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.delenv("SECURITY_WARNINGS_STATE_DIR", raising=False)
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+ shared = tmp_path / "shared"
+ shared.mkdir()
+ os.chmod(shared, 0o775)
+ (tmp_path / ".claude").mkdir()
+ os.symlink(shared, tmp_path / ".claude" / "security")
+ _base.make_state_dir()
+ assert _mode(shared) == 0o775
+
+
+def test_other_folders_are_left_alone(tmp_path, monkeypatch):
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.delenv("SECURITY_WARNINGS_STATE_DIR", raising=False)
+ logs = tmp_path / "logs"
+ logs.mkdir()
+ os.chmod(logs, 0o755)
+ _base.make_state_dir(str(logs))
+ assert _mode(logs) == 0o755
+
+
+def test_debug_log_in_the_working_directory_leaves_the_state_dir_alone(tmp_path, monkeypatch):
+ d = tmp_path / "state"
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(d))
+ with pytest.raises(OSError):
+ _base.make_state_dir("")
+ assert not d.exists()
+
+
+@pytest.mark.parametrize("nofollow", [True, False])
+def test_in_place_save_replaces_a_symlink(tmp_path, monkeypatch, nofollow):
+ d = tmp_path / "state"
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(d))
+ monkeypatch.setattr(session_state, "_RENAME_INTO_PLACE", False)
+ if not nofollow: # the Windows path: no O_NOFOLLOW
+ monkeypatch.delattr(os, "O_NOFOLLOW")
+ _base.make_state_dir()
+ target = tmp_path / "elsewhere.txt"
+ target.write_text("keep\n")
+ state_file = session_state.get_state_file("s1")
+ os.symlink(target, state_file)
+ session_state.save_state("s1", {"k": 1})
+ assert target.read_text() == "keep\n"
+ assert not os.path.islink(state_file)
+ assert session_state.load_state("s1").get("k") == 1
+
+
+def test_in_place_save_creates_an_owner_only_file(tmp_path, monkeypatch, loose_umask):
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state"))
+ monkeypatch.setattr(session_state, "_RENAME_INTO_PLACE", False)
+ session_state.save_state("s1", {"k": 1})
+ assert _mode(session_state.get_state_file("s1")) == 0o600
+ assert session_state.load_state("s1").get("k") == 1
diff --git a/plugins/security-guidance/tests/test_windows_cli_lookup.py b/plugins/security-guidance/tests/test_windows_cli_lookup.py
new file mode 100644
index 00000000..3afea8e5
--- /dev/null
+++ b/plugins/security-guidance/tests/test_windows_cli_lookup.py
@@ -0,0 +1,279 @@
+"""Which Claude Code the Agent SDK is told to start on Windows."""
+import os
+import subprocess
+import sys
+import types
+
+import pytest
+
+from conftest import HOOKS_DIR
+
+import _base
+import llm
+
+VAR = "NoDefaultCurrentDirectoryInExePath"
+windows_only = pytest.mark.skipif(os.name != "nt", reason="needs Windows path rules")
+
+
+def put(folder, name="claude.exe"):
+ folder.mkdir(parents=True, exist_ok=True)
+ (folder / name).write_text("")
+ return str(folder / name)
+
+
+def set_path(monkeypatch, *entries):
+ monkeypatch.setenv("PATH", os.pathsep.join(str(e) for e in entries))
+
+
+@pytest.fixture
+def win(monkeypatch, tmp_path):
+ """llm as on Windows: an empty home and PATH, no CLI named in the
+ environment, and a working directory that has a claude.exe of its own."""
+ ns = types.SimpleNamespace(home=tmp_path / "home", repo=tmp_path / "repo", tools=tmp_path / "tools")
+ for d in (ns.home, ns.repo, ns.tools):
+ d.mkdir()
+ put(ns.repo)
+ monkeypatch.setattr(llm, "_WINDOWS", True)
+ monkeypatch.setattr(llm, "_gateway_cli", None)
+ monkeypatch.setattr(_base, "DEBUG_LOG_FILE", str(tmp_path / "log.txt"))
+ monkeypatch.setenv("HOME", str(ns.home))
+ monkeypatch.setenv("USERPROFILE", str(ns.home)) # "~" on Windows
+ for var in ("SG_AGENTIC_CLI_PATH", "CLAUDE_CODE_EXECPATH", "CLAUDE_PROJECT_DIR"):
+ monkeypatch.delenv(var, raising=False)
+ set_path(monkeypatch)
+ monkeypatch.chdir(ns.repo)
+ return ns
+
+
+class TestUsersOwnCli:
+ def test_native_installers_folder_comes_first(self, win, monkeypatch):
+ put(win.tools)
+ set_path(monkeypatch, win.tools)
+ native = put(win.home / ".local" / "bin")
+ assert llm._windows_user_cli() == native
+
+ @pytest.mark.parametrize("spelling", [
+ pytest.param("{}", id="plain"),
+ pytest.param('"{}"', id="quoted"),
+ pytest.param("{}" + os.sep, id="trailing-separator"),
+ ])
+ def test_found_on_path(self, win, monkeypatch, spelling):
+ put(win.tools)
+ set_path(monkeypatch, win.tools / "empty", spelling.format(win.tools))
+ assert os.path.samefile(llm._windows_user_cli(), win.tools / "claude.exe")
+
+ def test_batch_file_is_not_used(self, win, monkeypatch):
+ put(win.tools, "claude.cmd")
+ set_path(monkeypatch, win.tools)
+ assert llm._windows_user_cli() is None
+
+ @pytest.mark.parametrize("entry", [
+ pytest.param("", id="empty"),
+ pytest.param(".", id="dot"),
+ pytest.param("{repo}", id="full-path"),
+ pytest.param("{repo}" + os.sep, id="trailing-separator"),
+ pytest.param(os.path.join("..", "repo"), id="relative"),
+ ])
+ def test_working_directory_is_not_searched(self, win, monkeypatch, entry):
+ set_path(monkeypatch, entry.format(repo=win.repo))
+ assert llm._windows_user_cli() is None
+
+ def test_search_continues_past_the_working_directory(self, win, monkeypatch):
+ exe = put(win.tools)
+ set_path(monkeypatch, ".", win.repo, win.tools)
+ assert llm._windows_user_cli() == exe
+
+ def test_relative_entry_is_skipped(self, win, monkeypatch):
+ put(win.tools)
+ set_path(monkeypatch, os.path.join("..", "tools"))
+ assert llm._windows_user_cli() is None
+
+ @pytest.mark.parametrize("home", ["~", "", "home"])
+ def test_home_that_is_not_a_full_path_is_skipped(self, win, monkeypatch, home):
+ put(win.repo / home / ".local" / "bin")
+ monkeypatch.setattr(llm.os.path, "expanduser", lambda p: home)
+ assert llm._windows_user_cli() is None
+
+ def test_project_root_is_not_searched_from_a_subfolder(self, win, monkeypatch):
+ (win.repo / "sub").mkdir()
+ monkeypatch.chdir(win.repo / "sub")
+ monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(win.repo).replace(os.sep, "/"))
+ set_path(monkeypatch, win.repo)
+ assert llm._windows_user_cli() is None
+
+ def test_link_to_the_working_directory_is_not_searched(self, win, monkeypatch, tmp_path):
+ try:
+ if os.name == "nt":
+ import _winapi
+ _winapi.CreateJunction(str(win.repo), str(tmp_path / "link"))
+ else:
+ os.symlink(win.repo, tmp_path / "link", target_is_directory=True)
+ except OSError:
+ pytest.skip("cannot make a link here")
+ set_path(monkeypatch, tmp_path / "link")
+ assert llm._windows_user_cli() is None
+
+ @pytest.mark.parametrize("project", [False, True])
+ def test_folder_inside_the_project_is_not_searched(self, win, monkeypatch, project):
+ put(win.repo / ".venv" / "Scripts")
+ if project:
+ (win.repo / "sub").mkdir()
+ monkeypatch.chdir(win.repo / "sub")
+ monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(win.repo))
+ set_path(monkeypatch, win.repo / ".venv" / "Scripts")
+ assert llm._windows_user_cli() is None
+
+ def test_folder_that_only_shares_a_prefix_is_found(self, win, monkeypatch, tmp_path):
+ exe = put(tmp_path / "repo-tools")
+ set_path(monkeypatch, tmp_path / "repo-tools")
+ assert llm._windows_user_cli() == exe
+
+ def test_session_above_the_home_folder_still_finds_the_native_install(self, win, monkeypatch):
+ native = put(win.home / ".local" / "bin")
+ monkeypatch.chdir(win.home.parent)
+ monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(win.home.parent))
+ assert llm._windows_user_cli() == native
+
+ def test_tools_under_the_home_folder_are_found(self, win, monkeypatch):
+ exe = put(win.home / "AppData" / "tool")
+ monkeypatch.chdir(win.home)
+ set_path(monkeypatch, win.home / "AppData" / "tool")
+ assert llm._windows_user_cli() == exe
+
+ @windows_only
+ def test_entries_without_a_drive_or_a_root_are_skipped(self, win, monkeypatch):
+ put(win.tools)
+ drive, rest = os.path.splitdrive(str(win.tools))
+ set_path(monkeypatch, rest, rest.replace("\\", "/"), drive + os.path.relpath(str(win.tools)))
+ assert llm._windows_user_cli() is None
+
+ @windows_only
+ def test_other_spellings_of_the_working_directory_are_skipped(self, win, monkeypatch):
+ import ctypes
+ short = ctypes.create_unicode_buffer(1024)
+ ctypes.windll.kernel32.GetShortPathNameW(str(win.repo), short, 1024)
+ repo = str(win.repo)
+ set_path(monkeypatch, repo.upper(), repo.replace("\\", "/"), "\\\\?\\" + repo, short.value or repo)
+ assert llm._windows_user_cli() is None
+
+
+class TestFixedPaths:
+ @pytest.fixture
+ def installed_as_on_linux(self, win, monkeypatch):
+ monkeypatch.setattr(llm.os.path, "isfile", lambda p: p.endswith("/bin/claude"))
+
+ def test_not_used_on_windows(self, installed_as_on_linux):
+ assert llm._user_cli_path() is None
+
+ def test_used_elsewhere(self, installed_as_on_linux, monkeypatch):
+ monkeypatch.setattr(llm, "_WINDOWS", False)
+ assert llm._user_cli_path().endswith("/.local/bin/claude")
+
+
+@pytest.fixture
+def sdk(monkeypatch, tmp_path):
+ """Stand-in for claude_agent_sdk, installed in tmp_path, that records the
+ options of each spawn in .spawned."""
+ class ResultMessage:
+ subtype, usage, total_cost_usd = "success", {}, 0.0
+ structured_output = {"findings": []}
+
+ async def query(prompt, options):
+ yield ResultMessage()
+
+ mod = types.ModuleType("claude_agent_sdk")
+ mod.spawned = []
+ mod.ClaudeAgentOptions = lambda **kwargs: mod.spawned.append(kwargs)
+ mod.AssistantMessage = type("AssistantMessage", (), {})
+ mod.ResultMessage, mod.query = ResultMessage, query
+ mod.__file__ = str(tmp_path / "site" / "claude_agent_sdk" / "__init__.py")
+ mod.bundled = str(tmp_path / "site" / "claude_agent_sdk" / "_bundled" / "claude.exe")
+ monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod)
+ monkeypatch.setenv("SECURITY_REVIEW_MODEL", "opus")
+ return mod
+
+
+def bundle(tmp_path):
+ return put(tmp_path / "site" / "claude_agent_sdk" / "_bundled")
+
+
+REVIEWS = [
+ pytest.param(lambda: llm.agentic_review(os.getcwd(), [("a.py", "+x = 1\n")], ["a.py"]), id="agentic"),
+ pytest.param(lambda: llm._call_claude_via_sdk("review this", {"type": "object"}), id="cloud-provider"),
+]
+
+
+@pytest.mark.parametrize("review", REVIEWS)
+class TestWhatTheSdkIsTold:
+ @staticmethod
+ def told(sdk):
+ assert sdk.spawned
+ return {o["cli_path"] for o in sdk.spawned}
+
+ def test_bundled_cli_before_the_users(self, win, sdk, tmp_path, review):
+ put(win.home / ".local" / "bin")
+ bundle(tmp_path)
+ review()
+ assert self.told(sdk) == {sdk.bundled}
+
+ def test_users_cli_when_nothing_is_bundled(self, win, sdk, monkeypatch, review):
+ tolerant = []
+ monkeypatch.setattr(llm, "_tolerate_unknown_sdk_messages", lambda: tolerant.append(1))
+ set_path(monkeypatch, ".", win.tools)
+ cli = put(win.tools)
+ review()
+ assert self.told(sdk) == {cli} and tolerant
+
+ def test_full_path_is_named_when_no_cli_exists(self, win, sdk, review):
+ review()
+ assert self.told(sdk) == {sdk.bundled}
+
+ def test_named_cli_is_used_as_named(self, win, sdk, tmp_path, monkeypatch, review):
+ bundle(tmp_path)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "X:\\my\\claude.exe")
+ review()
+ assert self.told(sdk) == {"X:\\my\\claude.exe"}
+
+ def test_empty_name_is_no_name(self, win, sdk, tmp_path, monkeypatch, review):
+ put(win.home / ".local" / "bin")
+ bundle(tmp_path)
+ monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "")
+ review()
+ assert self.told(sdk) == {sdk.bundled}
+
+ def test_sdk_chooses_off_windows(self, win, sdk, tmp_path, monkeypatch, review):
+ monkeypatch.setattr(llm, "_WINDOWS", False)
+ monkeypatch.setattr(llm, "_user_cli_path", lambda: None)
+ bundle(tmp_path)
+ review()
+ assert self.told(sdk) == {None}
+
+
+def test_empty_name_is_no_name_off_windows(monkeypatch):
+ monkeypatch.setattr(llm, "_WINDOWS", False)
+ assert llm._cli_for_sdk("") is None
+
+
+def test_sdk_module_without_a_file_still_gets_a_full_path(win, sdk):
+ del sdk.__file__
+ assert os.path.isabs(llm._cli_for_sdk(None))
+
+
+class TestSearchOrderVariable:
+ @staticmethod
+ def after_import(os_name, **env):
+ code = (f"import os; os.name = {os_name!r}; import _base; "
+ f"print(os.environ.get({VAR!r}))")
+ base = {k: v for k, v in os.environ.items() if k.upper() != VAR.upper()}
+ return subprocess.run([sys.executable, "-c", code], cwd=HOOKS_DIR, env={**base, **env},
+ capture_output=True, text=True, check=True).stdout.strip()
+
+ def test_set_on_windows_when_absent(self):
+ assert self.after_import("nt") == "1"
+
+ def test_existing_value_is_kept(self):
+ assert self.after_import("nt", **{VAR: "0"}) == "0"
+
+ @pytest.mark.skipif(os.name == "nt", reason="checks that the variable is not set off Windows")
+ def test_not_set_elsewhere(self):
+ assert self.after_import(os.name) == "None"