diff options
| author | mhegazy <mhegazy@users.noreply.github.com> | 2026-10-27 20:11:58 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-27 20:11:58 +0000 |
| commit | 70ef2c2ed7001343cc954bb6ea8060d9475639bb (patch) | |
| tree | 514ebc9e3681418fec3b6dbc1c959a8fbbd29f95 /plugins | |
| parent | f8c5e7a1dcb71b10cb74586224b5401f3de5db28 (diff) | |
security-guidance: stop starting the packaged Python alias on every hookmhegazy/sg-launcher-alias-real-path
On Windows with the Python Install Manager, python, python3 and py are
packaged aliases under ...\Microsoft\WindowsApps, and each start of one
makes Windows run an App Installer update check for the package. The
launcher started the chosen alias twice per hook (probe, then the hook),
on every Edit, prompt and Stop. See anthropics/claude-code#98929.
When the name that answers is such an alias and its interpreter is a
regular python*.exe elsewhere, the launcher now checks that interpreter
once (same version, reads the hook script when started by itself), runs
the hook with it, and keeps its path in the state folder for a day.
Later hooks start it directly: one process, none through the alias.
The remembered path is used only while PATH and the hook folder are
unchanged and the file is still there. A hook that fails on it empties
the entry so the next hook searches again. Not used while VIRTUAL_ENV is
set. Other systems, regular installs and Microsoft Store Python are
unchanged.
Hooks report launcher_direct (1 remembered, 2 just checked) as the last
metric key on rows they already send.
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/_base.py | 10 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/ensure_agent_sdk.py | 3 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 6 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/sg-python.sh | 155 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_launcher_alias_own_path.py | 372 |
5 files changed, 542 insertions, 4 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py index 28b189a4..c265b959 100644 --- a/plugins/security-guidance/hooks/_base.py +++ b/plugins/security-guidance/hooks/_base.py @@ -378,6 +378,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 {} + + def _usage_metrics(): """Snapshot the accumulator as metric keys. Returns {} when no API calls AND no HTTP errors were made so skip-path emits don't burn key budget. diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py index d3aaf96b..738266c0 100644 --- a/plugins/security-guidance/hooks/ensure_agent_sdk.py +++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py @@ -28,7 +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 ( - launcher_probe_metrics, portable_output, state_dir as _resolve_state_dir, + launcher_direct_metric, launcher_probe_metrics, portable_output, state_dir as _resolve_state_dir, write_hook_output, ) from _base import llm_reviews_switched_off @@ -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()) response: dict[str, object] = {"metrics": metrics} # One-time user-visible notice when the agentic reviewer is dead on # arrival. Uses hookSpecificOutput.additionalContext (SessionStart's diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 3efe344e..38ae3b8a 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -86,7 +86,7 @@ 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, ) @@ -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: 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_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() == {} |
