summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-12 19:42:43 +0000
committerClaude <noreply@anthropic.com>2026-10-15 22:39:39 +0000
commitcae27dda6824b4861e305c3a145e22379fd837ed (patch)
tree37a9aa21f8b655b0ad3e54a00b731281083024e7 /plugins
parent5a1d326c862f33d05a9e65f30e50a71a4e71d4a5 (diff)
security-guidance: start fewer processes in the hook launcher
sg-python.sh runs on every hook, and under Git Bash each command substitution is a new Windows process, whether or not the interpreter it probes exists (#6470). On a machine with only `python` it started 13 processes before the hook; it now starts 1. - Skip interpreter names that are not on PATH (a builtin lookup) before probing them. - The probe execs the interpreter in its subshell instead of forking again from it. - Remember the first Python below 3.10 seen in pass 2 instead of probing the same names a second time in pass 3. - Convert drive paths (/c/Users/...) to Windows form in-shell under Git Bash / MSYS2; mount points and Cygwin still go through cygpath. Interpreter order and the choice made are unchanged.
Diffstat (limited to 'plugins')
-rwxr-xr-xplugins/security-guidance/hooks/sg-python.sh61
-rw-r--r--plugins/security-guidance/tests/test_launcher_process_count.py158
2 files changed, 203 insertions, 16 deletions
diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh
index 7160baa2..f1b9d68c 100755
--- a/plugins/security-guidance/hooks/sg-python.sh
+++ b/plugins/security-guidance/hooks/sg-python.sh
@@ -45,14 +45,30 @@ unset SG_LAUNCHER_FALLBACK
# fails with ENOENT, and every Edit/Write/MultiEdit tool use blocks until the
# session restarts. See anthropics/claude-plugins-official#2043.
#
-# Fix: convert absolute path args to native Windows form via `cygpath -w`
-# before exec. `cygpath` is a Git Bash builtin; it's absent on macOS/Linux,
-# where the `command -v` guard makes this a no-op. `cygpath -w` is idempotent
-# for already-Windows paths so the rare mixed-form case is safe.
+# Fix: convert absolute path args to native Windows form before exec.
+# `cygpath` ships with Git Bash; it's absent on macOS/Linux, where the
+# `command -v` guard makes this a no-op. `cygpath -w` is idempotent for
+# already-Windows paths so the rare mixed-form case is safe.
+#
+# Under Git Bash every $(...) is a new Windows process, and this shim runs on
+# every hook, so drive paths (`/c/Users/...`, where the plugin lives) are
+# converted in-shell. Git Bash and MSYS2 (OSTYPE=msys) mount drives at
+# /<letter>; anything else (`/tmp`, `/usr`, Cygwin's /cygdrive) needs cygpath
+# to resolve. See #6470.
if command -v cygpath >/dev/null 2>&1; then
+ sg_drive_mounts=""
+ case "${OSTYPE:-}" in msys*) sg_drive_mounts=1 ;; esac
converted=()
for a in "$@"; do
case "$a" in
+ /[A-Za-z]/*)
+ if [ -n "$sg_drive_mounts" ]; then
+ drive="${a:1:1}"
+ rest="${a:3}"
+ converted+=("${drive^^}:\\${rest//\//\\}")
+ else
+ converted+=("$(cygpath -w "$a")")
+ fi ;;
/*) converted+=("$(cygpath -w "$a")") ;;
*) converted+=("$a") ;;
esac
@@ -83,7 +99,11 @@ probe() {
# [Errno 2]" and exit code 2 -- and exit 2 from an asyncRewake hook wakes
# the model, whose reply runs the Stop hook again: an endless loop that
# never reviewed anything. See #6251, #5781.
- "$@" -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
+ #
+ # 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
}
# Use as `v=$(probe ...) || { note_unreadable "<name>"; continue; }`.
@@ -92,6 +112,13 @@ note_unreadable() {
return 0
}
+# True iff the command's executable is on PATH ($1 of a possibly multi-word
+# command like `py -3`). A builtin lookup: `$(probe ...)` costs a process even
+# when the interpreter does not exist, so missing names are skipped first.
+on_path() {
+ command -v "$1" >/dev/null 2>&1
+}
+
# True iff arg is a "M.m" version string >= 3.10. claude_agent_sdk requires
# Python >= 3.10; below that, pip install fails ("No matching distribution")
# and the LLM-powered review (Stop / commit / push) silently no-ops while
@@ -110,7 +137,9 @@ is_sdk_compatible() {
# so picking one here always upgrades over the system `python3`. Highest
# available wins; the user doesn't have to PATH-prefer it.
for cmd in "python3.13" "python3.12" "python3.11" "python3.10"; do
+ on_path "$cmd" || continue
v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; }
+ v=${v%$'\r'}
if is_sdk_compatible "$v"; then
exec "$cmd" "$@"
fi
@@ -119,13 +148,21 @@ done
# Pass 2 — bare interpreters, but only if SDK-compatible. Covers Linux distros
# that ship 3.10+ as the default `python3`, and Windows where `python` /
# `py -3` resolves to the user's python.org install.
+sg_older="" # first of these that is a readable Python 3 below 3.10
for cmd in "python3" "python" "py -3"; do
# shellcheck disable=SC2086
+ on_path $cmd || continue
+ # shellcheck disable=SC2086
v=$(probe $cmd) || { note_unreadable "$cmd"; continue; }
+ v=${v%$'\r'}
if is_sdk_compatible "$v"; then
# shellcheck disable=SC2086
exec $cmd "$@"
fi
+ # Anything that successfully reported a "M.m" string.
+ case "$v" in
+ [0-9]*.[0-9]*) [ -n "$sg_older" ] || sg_older="$cmd" ;;
+ esac
done
# Pass 3 — fallback to any Python 3, even <3.10. Pattern-based checks
@@ -133,18 +170,10 @@ done
# own; the SDK-dependent paths will detect the version mismatch and degrade
# inside the Python code. Without this fallback, the entire plugin would
# stop working on default macOS, which is a regression vs today.
-for cmd in "python3" "python" "py -3"; do
- case "$sg_unreadable" in *"|$cmd|"*) continue ;; esac
+if [ -n "$sg_older" ]; then
# shellcheck disable=SC2086
- v=$(probe $cmd) || continue
- # Accept anything that successfully reported a "M.m" string.
- case "$v" in
- [0-9]*.[0-9]*)
- # shellcheck disable=SC2086
- exec $cmd "$@"
- ;;
- esac
-done
+ exec $sg_older "$@"
+fi
# Pass 4 — nothing above could run the hook script. If that is because the
# names on PATH resolve to packaged launcher aliases that cannot see the
diff --git a/plugins/security-guidance/tests/test_launcher_process_count.py b/plugins/security-guidance/tests/test_launcher_process_count.py
new file mode 100644
index 00000000..f22fd680
--- /dev/null
+++ b/plugins/security-guidance/tests/test_launcher_process_count.py
@@ -0,0 +1,158 @@
+"""sg-python.sh starts as few processes as it can before it runs the hook.
+
+Under Git Bash every command substitution is a new Windows process, and the
+launcher runs on every hook, so probing interpreters that are not installed,
+probing the same one twice, or calling cygpath for a plain drive path is paid
+on each Edit, prompt and Stop. See #6470.
+
+Interpreters and cygpath are emulated with shell scripts, so these tests need
+a POSIX shell.
+"""
+import shutil
+import subprocess
+import sys
+
+import pytest
+
+from conftest import HOOKS_DIR
+
+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers")
+
+SHIM = HOOKS_DIR / "sg-python.sh"
+BASH = shutil.which("bash") or "/bin/bash"
+
+# Logs each start; answers the probe with a fixed version, else prints its argv.
+PYTHON = """#!{bash}
+if [ "${{1:-}}" = "-c" ] || [ "${{1:-}} ${{2:-}}" = "-3 -c" ]; then
+ echo "${{0##*/}} probe" >> '{log}'; printf '{version}{eol}'; exit 0
+fi
+echo "${{0##*/}} $*" >> '{log}'
+printf 'ran:%s\\n' "${{0##*/}}"; printf 'arg:%s\\n' "$@"
+"""
+# ${x^^} in the launcher's Git Bash branch needs bash 4; stock macOS has 3.2.
+BASH_MAJOR = int(subprocess.run([BASH, "-c", "echo ${BASH_VERSINFO[0]}"], capture_output=True,
+ text=True).stdout.strip() or 0)
+
+# The Microsoft Store placeholder: on PATH, starts, does nothing.
+STUB = """#!{bash}
+echo "${{0##*/}} probe" >> '{log}'
+exit 49
+"""
+CYGPATH = """#!{bash}
+echo "cygpath $*" >> '{log}'
+echo "CYGPATH($2)"
+"""
+
+
+@pytest.fixture
+def box(tmp_path):
+ (tmp_path / "bin").mkdir()
+ (tmp_path / "log").write_text("")
+ return tmp_path
+
+
+def _add(box, name, template, version="", crlf=False):
+ p = box / "bin" / name
+ p.write_text(template.format(bash=BASH, log=box / "log", version=version,
+ eol="\\r\\n" if crlf else "\\n"))
+ p.chmod(0o755)
+
+
+def _run(box, *args, ostype="linux-gnu", trace=False):
+ cmd = [BASH] + (["-x"] if trace else []) + [str(SHIM), *args]
+ return subprocess.run(cmd, input="", capture_output=True, text=True, timeout=60,
+ env={"PATH": str(box / "bin"), "HOME": "/", "OSTYPE": ostype})
+
+
+def _starts(box):
+ return (box / "log").read_text().splitlines()
+
+
+def test_only_installed_interpreters_are_probed(box):
+ _add(box, "python", PYTHON, "3.12")
+ r = _run(box, "hook.py", trace=True)
+ assert r.stdout.splitlines() == ["ran:python", "arg:hook.py"]
+ # xtrace marks what runs in a subshell with "++": only the one probe did.
+ probes = [line for line in r.stderr.splitlines() if line.startswith("++ probe ")]
+ assert probes == ["++ probe python"]
+ assert _starts(box) == ["python probe", "python hook.py"]
+
+
+def test_store_placeholder_still_falls_through_to_python(box):
+ _add(box, "python3", STUB)
+ _add(box, "python", PYTHON, "3.13")
+ r = _run(box, "hook.py")
+ assert r.stdout.splitlines() == ["ran:python", "arg:hook.py"]
+ assert _starts(box) == ["python3 probe", "python probe", "python hook.py"]
+
+
+def test_python_below_3_10_is_probed_once(box):
+ _add(box, "python3", PYTHON, "3.9")
+ r = _run(box, "hook.py")
+ assert r.stdout.splitlines() == ["ran:python3", "arg:hook.py"]
+ assert _starts(box) == ["python3 probe", "python3 hook.py"]
+
+
+def test_first_older_python_wins_when_none_is_3_10(box):
+ _add(box, "python3", PYTHON, "3.8")
+ _add(box, "python", PYTHON, "3.9")
+ r = _run(box, "hook.py")
+ assert r.stdout.splitlines() == ["ran:python3", "arg:hook.py"]
+
+
+def test_newer_python_under_a_later_name_beats_an_older_python3(box):
+ _add(box, "python3", PYTHON, "3.9")
+ _add(box, "python", PYTHON, "3.12")
+ r = _run(box, "hook.py")
+ assert r.stdout.splitlines() == ["ran:python", "arg:hook.py"]
+
+
+def test_py_launcher_is_still_a_candidate(box):
+ _add(box, "py", PYTHON, "3.12")
+ r = _run(box, "hook.py")
+ assert r.stdout.splitlines() == ["ran:py", "arg:-3", "arg:hook.py"]
+ assert _starts(box) == ["py probe", "py -3 hook.py"]
+
+
+def test_crlf_version_output_does_not_cost_further_probes(box):
+ # Native Windows Python may print CRLF; 3.12 must still read as 3.10+.
+ _add(box, "python", PYTHON, "3.12", crlf=True)
+ _add(box, "py", PYTHON, "3.12", crlf=True)
+ r = _run(box, "hook.py")
+ assert r.stdout.splitlines() == ["ran:python", "arg:hook.py"]
+ assert _starts(box) == ["python probe", "python hook.py"]
+
+
+@pytest.mark.skipif(BASH_MAJOR < 4, reason="needs bash 4+, as Git Bash has")
+@pytest.mark.parametrize("posix, native", [
+ ("/c/Users/me/.claude/hooks/hook.py", "C:\\Users\\me\\.claude\\hooks\\hook.py"),
+ ("/d/a b/hook.py", "D:\\a b\\hook.py"),
+ ("/c/", "C:\\"),
+])
+def test_drive_paths_are_converted_without_cygpath(box, posix, native):
+ _add(box, "cygpath", CYGPATH)
+ _add(box, "python", PYTHON, "3.12")
+ rest = ["--flag", "rel/path", "C:\\already\\native", "C:/d/mixed"]
+ r = _run(box, posix, *rest, ostype="msys")
+ assert r.stdout.splitlines() == ["ran:python", "arg:" + native] + ["arg:" + a for a in rest]
+ assert not [s for s in _starts(box) if s.startswith("cygpath")]
+
+
+@pytest.mark.parametrize("ostype, posix", [
+ ("msys", "/tmp/hook.py"), # a mount point, not a drive
+ ("msys", "/usr/bin"),
+ ("msys", "/c"),
+ ("msys", "//server/share/hook.py"),
+ ("cygwin", "/c/Users/me/hook.py"), # drives live under /cygdrive there
+])
+def test_other_absolute_paths_still_go_through_cygpath(box, ostype, posix):
+ _add(box, "cygpath", CYGPATH)
+ _add(box, "python", PYTHON, "3.12")
+ r = _run(box, posix, ostype=ostype)
+ assert r.stdout.splitlines() == ["ran:python", "arg:CYGPATH(%s)" % posix]
+
+
+def test_paths_are_left_alone_without_cygpath(box):
+ _add(box, "python3", PYTHON, "3.12")
+ r = _run(box, "/c/Users/me/hook.py", ostype="msys")
+ assert r.stdout.splitlines() == ["ran:python3", "arg:/c/Users/me/hook.py"]