summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/hooks
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-10-20 20:29:41 +0000
committerClaude <noreply@anthropic.com>2026-10-20 20:35:31 +0000
commitf15240feee15b8fe020d38fd46ab5becc97c80a0 (patch)
tree750e7516e8ca33fb39c959f54e4414acac15edd5 /plugins/security-guidance/hooks
parent8680640bffd91d9a7fc33ad1ede46a031d36abef (diff)
parentf61e6d15fc03feb474d6df219e37b46f9c14565b (diff)
Merge branch 'main' into mhegazy/sg-gateway-loginmhegazy/sg-gateway-login
Diffstat (limited to 'plugins/security-guidance/hooks')
-rw-r--r--plugins/security-guidance/hooks/_base.py11
-rw-r--r--plugins/security-guidance/hooks/diffstate.py67
-rw-r--r--plugins/security-guidance/hooks/ensure_agent_sdk.py30
-rw-r--r--plugins/security-guidance/hooks/gitutil.py72
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py79
-rwxr-xr-xplugins/security-guidance/hooks/sg-python.sh21
6 files changed, 256 insertions, 24 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py
index 1daa6642..eecae8b5 100644
--- a/plugins/security-guidance/hooks/_base.py
+++ b/plugins/security-guidance/hooks/_base.py
@@ -33,11 +33,12 @@ def state_dir():
"""
explicit = os.environ.get("SECURITY_WARNINGS_STATE_DIR")
if explicit:
- return os.path.expanduser(explicit)
- cc_config = os.environ.get("CLAUDE_CONFIG_DIR")
- if cc_config:
- return os.path.expanduser(os.path.join(cc_config, "security"))
- return os.path.expanduser("~/.claude/security")
+ d = explicit
+ elif os.environ.get("CLAUDE_CONFIG_DIR"):
+ d = os.path.join(os.environ["CLAUDE_CONFIG_DIR"], "security")
+ else:
+ d = "~/.claude/security"
+ return os.path.abspath(os.path.expanduser(d))
# Debug log file. Lives under the plugin state dir (default ~/.claude/security/)
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index f2d9dbe4..02b073e8 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -17,6 +17,7 @@ from gitutil import (
_git_rev_parse_head, _is_ancestor, _git_name_only, _temp_index,
)
from session_state import with_locked_state
+from extensibility import _same_dir
# =====================================================================
@@ -96,6 +97,10 @@ def consume_stop_state(session_id, clear=True):
"touched_paths": list(state.get("touched_paths", [])),
"baseline_sha": state.get("baseline_sha"),
"head_at_capture": state.get("head_at_capture"),
+ # Where and when the prompt hook captured it; see baseline_origin.
+ "baseline_root": state.get("baseline_root"),
+ "prompt_at": state.get("prompt_at"),
+ "baseline_kept": state.get("baseline_kept") or 0,
"untracked_at_baseline": (
dict(state["untracked_at_baseline"])
if isinstance(state.get("untracked_at_baseline"), dict) else {}
@@ -117,7 +122,8 @@ def consume_stop_state(session_id, clear=True):
return with_locked_state(session_id, _snap) or {
"touched_paths": [], "baseline_sha": None, "head_at_capture": None,
- "untracked_at_baseline": {},
+ "untracked_at_baseline": {}, "baseline_root": None, "prompt_at": None,
+ "baseline_kept": 0,
"fire_count": 0, "fire_count_expired": False, "previous_findings": [],
"reviewed_diff_hash": None, "state_resets": 0, "state_overwrites": 0,
}
@@ -153,6 +159,48 @@ def restore_unreviewed_stop_state(session_id, paths, baseline_sha):
with_locked_state(session_id, _restore)
+# state["baseline_kept"]: why a prompt left an earlier turn's baseline in
+# place. Only telemetry reads it.
+KEPT_NO_CAPTURE = 1 # it could not capture one (not a repo, or git failed)
+KEPT_UNREVIEWED = 2 # the previous turn's edits were never reviewed
+
+# baseline_origin() values that mean "captured in another checkout".
+FOREIGN_ORIGINS = (1, 2, 3)
+
+
+def baseline_origin(repo_root, baseline_sha, baseline_root):
+ """Where the session's baseline was captured, relative to the checkout a
+ Stop review is about to read (`repo_root`):
+
+ 0 that checkout (or the origin was not recorded)
+ 1 another worktree of the same repository
+ 2 another repository
+ 3 another folder, which is gone or cannot be read as a checkout
+ 4 there is no baseline
+
+ `baseline_root` is the repo root the prompt hook stored beside the SHA."""
+ if not baseline_sha:
+ return 4
+ if not baseline_root or not isinstance(baseline_root, str):
+ return 0
+ if _same_dir(baseline_root, repo_root):
+ return 0
+ if not os.path.isdir(baseline_root):
+ return 3
+ here, there = _git_dir(repo_root), _git_dir(baseline_root)
+ if not here or not there:
+ return 3
+ return 1 if _same_dir(here, there) else 2
+
+
+def baseline_origin_metric(origin, kept):
+ """The `bl_origin` number on Stop rows: baseline_origin, plus 10 or 20
+ (KEPT_*) when the baseline is an earlier turn's."""
+ if origin == 4 or kept not in (KEPT_NO_CAPTURE, KEPT_UNREVIEWED):
+ return origin
+ return origin + 10 * kept
+
+
def get_baseline_file_content(session_id, file_path, cwd):
"""Get the content of a file at the baseline SHA. Returns None if unavailable.
@@ -605,7 +653,8 @@ def _list_untracked(cwd):
debug_log(f"_list_untracked error: {e}")
return {}
-def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_baseline=None):
+def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_baseline=None,
+ since_ns=None):
"""v2 diff strategy: derive the review set from git state alone.
review_set = (files dirty vs current HEAD, plus files committed this turn
@@ -620,6 +669,10 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel
A file is excluded only if it was untracked at baseline AND its mtime is
unchanged — an in-place edit during the turn is still reviewed.
+ since_ns: for a checkout the prompt hook took no baseline or snapshot of
+ (the turn moved into it), the time the turn began. A dirty or untracked
+ file last written before then was already that way and is left out.
+
Known limitation: a Bash-only turn that's interrupted before Stop fires
leaves touched_paths empty, so the next UPS re-baselines past those edits.
v1 never reviews Bash-only turns at all, so v2 is no worse there.
@@ -662,6 +715,16 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel
return max(st.st_mtime_ns, st.st_ctime_ns) < capped_at_ns - _CAPPED_BASELINE_SLACK_NS
preexisting_unchanged = {p for p in untracked if _unchanged_since_baseline(p)}
+ if since_ns:
+ def _written_before_turn(p):
+ try:
+ st = os.stat(os.path.join(repo, p))
+ except OSError:
+ return False
+ return max(st.st_mtime_ns, st.st_ctime_ns) < since_ns - _CAPPED_BASELINE_SLACK_NS
+
+ preexisting_unchanged |= {p for p in untracked if _written_before_turn(p)}
+ tracked_dirty = {p for p in tracked_dirty if not _written_before_turn(p)}
new_untracked = untracked - preexisting_unchanged
dirty_now = tracked_dirty | new_untracked
diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py
index 059f3825..c1d59ba7 100644
--- a/plugins/security-guidance/hooks/ensure_agent_sdk.py
+++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py
@@ -29,6 +29,24 @@ from pathlib import Path
# main() and _maybe_emit_user_notice).
from _base import portable_output, state_dir as _resolve_state_dir, write_hook_output
+
+def _spawn_cwd() -> str:
+ """Working directory for every Python this file starts.
+
+ `python -c` and `python -m` put the working directory first on the import
+ path, and hooks run in the user's repository, so a repository file named
+ `claude_agent_sdk.py`, `venv.py` or `pip.py` would be imported in place
+ of the real module. The state dir is the plugin's own (the venv is built
+ there, so the interpreter can reach it); the plugin folder is the
+ fallback when it can't be created.
+ """
+ d = _resolve_state_dir()
+ try:
+ os.makedirs(d, exist_ok=True)
+ return d
+ except OSError:
+ return str(Path(__file__).resolve().parent.parent)
+
# Outcome codes for the sdk_bootstrap metric. Values are stable for telemetry.
NOOP_SYSTEM = 0 # claude_agent_sdk already importable in system python
NOOP_VENV = 1 # venv already built and SDK imports from it
@@ -311,7 +329,7 @@ def _probe_has_pip() -> bool:
try:
r = subprocess.run(
[sys.executable, "-m", "pip", "--version"],
- capture_output=True, timeout=10,
+ capture_output=True, timeout=10, cwd=_spawn_cwd(),
)
return r.returncode == 0
except Exception:
@@ -409,7 +427,7 @@ def _target_sdk_importable(state_dir) -> bool:
[sys.executable, "-c",
"import sys; sys.path.insert(0, sys.argv[1]); import claude_agent_sdk",
str(target)],
- capture_output=True, timeout=10,
+ capture_output=True, timeout=10, cwd=_spawn_cwd(),
)
return r.returncode == 0
except Exception:
@@ -434,7 +452,7 @@ def _build_via_target(state_dir) -> tuple[int, str, str]:
"--target", str(target), "--upgrade",
"--disable-pip-version-check", "--prefer-binary", "--no-cache-dir",
"claude-agent-sdk"],
- capture_output=True, timeout=120, check=True,
+ capture_output=True, timeout=120, check=True, cwd=_spawn_cwd(),
)
return BUILT_TARGET, "", ""
except subprocess.CalledProcessError as e:
@@ -534,7 +552,7 @@ def main() -> tuple[int, str, str]:
try:
r = subprocess.run(
[str(venv_py), "-c", "import claude_agent_sdk"],
- capture_output=True, timeout=10,
+ capture_output=True, timeout=10, cwd=_spawn_cwd(),
)
if r.returncode == 0:
return NOOP_VENV, "", ""
@@ -570,7 +588,7 @@ def main() -> tuple[int, str, str]:
err_phase = "venv"
subprocess.run(
[sys.executable, "-m", "venv", "--clear", str(venv)],
- capture_output=True, timeout=60, check=True,
+ capture_output=True, timeout=60, check=True, cwd=_spawn_cwd(),
)
# Some machines route pip through a private registry; we
# don't pass --index-url here so we inherit that default. Outside
@@ -594,7 +612,7 @@ def main() -> tuple[int, str, str]:
[str(venv_py), "-m", "pip", "install", "--quiet",
"--disable-pip-version-check", "--prefer-binary", "--no-cache-dir",
"claude-agent-sdk"],
- capture_output=True, timeout=120, check=True,
+ capture_output=True, timeout=120, check=True, cwd=_spawn_cwd(),
)
return BUILT, "", ""
except subprocess.CalledProcessError as e:
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index bc4d753b..8702e4da 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -48,11 +48,27 @@ GIT_CMD = [
"-c", "diff.noprefix=false",
"-c", "diff.srcPrefix=a/",
"-c", "diff.dstPrefix=b/",
+ # A directory with its own `.git` inside the work tree (a submodule, a
+ # vendored checkout, an unpacked archive) is another repository with its
+ # own config. To report it as modified, or to show its changes inline
+ # (diff.submodule=diff), git starts a second git inside it, which reads
+ # that config and runs the commands it names. The hook stays out of it:
+ # such a directory is left out of the review set, and a commit that moves
+ # one shows as the two commit ids.
+ "-c", "diff.ignoreSubmodules=all",
+ "-c", "diff.submodule=short",
]
+# diff.ignoreSubmodules is a default that the repository's own settings for
+# one submodule (.gitmodules, submodule.<name>.ignore) override. The option
+# cannot be overridden. Pass it to every `git status` and work-tree `git diff`.
+IGNORE_SUBMODULES = "--ignore-submodules=all"
+
SAFE_GIT_CONFIG = (
("core.fsmonitor", "false"),
("core.hooksPath", "/dev/null"),
+ ("diff.ignoreSubmodules", "all"),
+ ("diff.submodule", "short"),
)
# The hook's git runs in the background beside the session's own git. Without
@@ -448,8 +464,11 @@ def _copied_index(cwd, real_index, tmpdir, untracked_paths):
# `git status` and here would silently drop ALL untracked files
# from the diff. --ignore-missing only works with --dry-run, so
# filter to surviving paths (lexists so dangling symlinks count).
+ # A nested repository (`dir/`) would be added as a submodule
+ # entry; see diff.ignoreSubmodules in GIT_CMD.
surviving = [p for p in untracked_paths
- if os.path.lexists(os.path.join(cwd, p))]
+ if not p.endswith("/")
+ and os.path.lexists(os.path.join(cwd, p))]
add_args = ["--"] + surviving if surviving else None
else:
add_args = None
@@ -487,6 +506,41 @@ def _git_toplevel(cwd):
return None
+def _git_toplevel_and_head(cwd):
+ """(repo root, HEAD SHA) for `cwd` from one git call, or (None, None)
+ when git cannot give both (not a work tree, no commits)."""
+ try:
+ r = subprocess.run(
+ [*GIT_CMD, "rev-parse", "--show-toplevel", "HEAD"],
+ cwd=cwd, capture_output=True, timeout=5,
+ )
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
+ return None, None
+ if r.returncode != 0:
+ return None, None
+ # See #2099: the first line is a PATH, so decode the bytes manually.
+ top, _, head = r.stdout.decode("utf-8", errors="replace").strip().rpartition("\n")
+ return (top.strip() or None), (head.strip() or None)
+
+
+def _git_head_at(cwd, epoch):
+ """The SHA this checkout's HEAD pointed at just before `epoch` (seconds),
+ read from its own reflog. A checkout created after `epoch` answers with
+ the commit it was created at. None when git cannot say (no reflog)."""
+ try:
+ # Reflog times are whole seconds: ask for the second before, so a
+ # commit made in the same second as `epoch` counts as after it.
+ r = subprocess.run(
+ [*GIT_CMD, "rev-parse", "--verify", "-q", f"HEAD@{{@{int(epoch) - 1}}}"],
+ cwd=cwd, capture_output=True, timeout=5,
+ )
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError,
+ TypeError, ValueError, OverflowError):
+ return None
+ sha = r.stdout.decode("utf-8", errors="replace").strip()
+ return sha if r.returncode == 0 and sha else None
+
+
def _git_dir(repo_root):
"""Absolute shared `.git` directory for repo_root.
@@ -673,7 +727,7 @@ def _git_name_only(cwd, base, include_untracked=False):
def _run(env):
# core.quotePath=false comes from GIT_CMD globally (see definition).
result = subprocess.run(
- [*GIT_CMD, "diff", "--name-only", "-z", base],
+ [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--name-only", "-z", base],
cwd=cwd, capture_output=True, timeout=30,
env=env,
)
@@ -714,7 +768,7 @@ def _git_status_porcelain(cwd):
try:
# core.quotePath=false comes from GIT_CMD globally (see definition).
r = subprocess.run(
- [*GIT_CMD, "status", "--porcelain=v1", "-uall", "-z"],
+ [*GIT_CMD, "status", IGNORE_SUBMODULES, "--porcelain=v1", "-uall", "-z"],
cwd=cwd, capture_output=True, timeout=30,
)
if r.returncode != 0:
@@ -732,7 +786,10 @@ def _git_status_porcelain(cwd):
continue
xy, path = e[:2], e[3:]
if xy == "??":
- untracked.add(path)
+ # With -uall only a nested repository is listed as `dir/`.
+ # It is not a file to review; see diff.ignoreSubmodules.
+ if not path.endswith("/"):
+ untracked.add(path)
else:
tracked.add(path)
# Rename/copy entries are XY old\0new\0 — second NUL field is
@@ -791,7 +848,7 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa
return ""
# core.quotePath=false comes from GIT_CMD globally (see definition).
- cmd = [*GIT_CMD, "diff", "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec
+ cmd = [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec
try:
if untracked_paths is not None and not untracked_paths:
# Nothing to `add -N`, and the diff only reads the index.
@@ -874,9 +931,12 @@ _SSH_PRIVATE_KEY_BASENAMES = frozenset((
'id_ed25519_sk', 'id_xmss',
))
_PRIVATE_KEY_NAME_SUFFIXES = ('_rsa', '_dsa', '_ecdsa', '_ed25519')
+# `.credentials.json` and `.claude.json` are Claude Code's own files: sign-in
+# tokens, a saved API key, MCP server secrets. Claude Code rewrites them as it
+# runs, so they show up as changed when its config directory is a git repo.
_CREDENTIAL_BASENAMES = frozenset((
'credentials', '.netrc', '.pgpass', '.npmrc', '.pypirc',
- '.git-credentials', '.dockercfg',
+ '.git-credentials', '.dockercfg', '.credentials.json', '.claude.json',
))
# chezmoi encodes a target file's attributes as stacked name prefixes
# (`private_dot_netrc`, `encrypted_private_token`); `dot_` stands for a
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index ad13ecdf..eb132c50 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -104,6 +104,7 @@ from gitutil import ( # noqa: E402,F401
GIT_CMD, apply_safe_git_env, remove_copies_on_termination,
_git_rev_parse_head, _find_git_index, _diff_pathspec, _temp_index,
_git_toplevel, _git_dir, _git_rev_list_range, _git_diff_range,
+ _git_toplevel_and_head, _git_head_at,
_detect_main_branch, _git_reflog_recent_commits, _git_name_only,
_git_status_porcelain, _is_ancestor, get_git_diff,
SOURCE_CODE_EXTENSIONS, SOURCE_CODE_BASENAMES,
@@ -123,6 +124,8 @@ from diffstate import ( # noqa: E402,F401
_reviewed_shas_path, _load_reviewed_shas, _append_reviewed_shas,
_full_shas, _mark_inflight, _load_inflight_shas, _reviewed_after_inflight,
UNTRACKED_BASELINE_CAP, _list_untracked, compute_v2_review_set,
+ baseline_origin, baseline_origin_metric, FOREIGN_ORIGINS,
+ KEPT_NO_CAPTURE, KEPT_UNREVIEWED,
)
from reporesolve import ( # noqa: E402,F401
RES_NONE, RES_CWD, RES_COMMAND, RES_SHA_SCAN, RES_TOUCHED_PATHS, RES_HINT,
@@ -684,14 +687,24 @@ def handle_user_prompt_submit(input_data):
# something tracked is dirtied.
return _f_sha.result(), _f_ut.result() or {}
+ import time as _time
+ captured_at = _time.time()
sha, untracked_now = _capture(cwd)
+ # No repo here and none remembered: the listing above failed, it did not
+ # come back empty.
+ no_repo = False
if not sha and not _git_toplevel(cwd):
hint = load_repo_hint(session_id)
if hint:
debug_log(f"UPS: cwd is not a git repo; using repo hint {hint!r}")
cwd = hint
sha, untracked_now = _capture(cwd)
- head = _git_rev_parse_head(cwd)
+ else:
+ no_repo = True
+ # The repo root rides on the same git call as HEAD.
+ root, head = (None, None) if no_repo else _git_toplevel_and_head(cwd)
+ if sha and not head:
+ head = _git_rev_parse_head(cwd)
# If the previous turn's Stop hook never ran (user interrupt, follow-up
# during work, tool-reject, model crash, maxTurns, PostToolUse block…),
@@ -714,10 +727,25 @@ def handle_user_prompt_submit(input_data):
# untracked file in the tree as written this turn.
if untracked_now is not None and "untracked_at_baseline" not in state:
state["untracked_at_baseline"] = untracked_now
+ # Once a prompt failed to capture, the baseline is old whatever
+ # later prompts did.
+ state["baseline_kept"] = (
+ KEPT_NO_CAPTURE
+ if not sha or state.get("baseline_kept") == KEPT_NO_CAPTURE
+ else KEPT_UNREVIEWED)
return
if sha:
state["baseline_sha"] = sha
state["head_at_capture"] = head
+ # A Stop review that ends up in another checkout does not use
+ # this baseline.
+ state["baseline_root"] = root
+ state.pop("baseline_kept", None)
+ elif state.get("baseline_sha"):
+ state["baseline_kept"] = KEPT_NO_CAPTURE
+ # When the turn began: what a Stop review in another checkout has
+ # to go on.
+ state["prompt_at"] = captured_at
# untracked_at_baseline is independent of whether the stash produced
# a SHA, so compute_v2_review_set's preexisting-untracked exclusion
# works in untracked-only trees. None means no snapshot was taken
@@ -725,7 +753,10 @@ def handle_user_prompt_submit(input_data):
# baseline.
if untracked_now is None:
state.pop("untracked_at_baseline", None)
- else:
+ elif not no_repo:
+ # no_repo: the earlier baseline stays (above), and so does the
+ # snapshot that belongs to it. An empty one in its place would
+ # make every untracked file in that repo look new.
state["untracked_at_baseline"] = untracked_now
with_locked_state(session_id, _save)
@@ -2379,9 +2410,40 @@ def handle_stop_hook(input_data):
save_repo_hint(session_id, repo_cwd)
cwd = repo_cwd
+ # The baseline belongs to the checkout the prompt hook captured it in.
+ # When the turn ends in another one (the session entered a worktree, or
+ # the edits were in a different repo), it says nothing about what changed
+ # here: this checkout's older commits would look like commits made this
+ # turn, and its files would be diffed against the other checkout's. Use
+ # what this checkout can say for itself instead: its own HEAD when the
+ # turn began (from its reflog) for commits, HEAD for file contents, and
+ # file times for which uncommitted files were already there.
+ origin = None
+ if repo_cwd:
+ try:
+ origin = baseline_origin(repo_cwd, snap_baseline, snap["baseline_root"])
+ except Exception as e:
+ debug_log(f"Stop hook: baseline origin check failed: {e}")
+ foreign_baseline = origin in FOREIGN_ORIGINS
+ since_ns = None
+ if foreign_baseline:
+ at = snap["prompt_at"]
+ at = at if isinstance(at, (int, float)) and 0 < at < 1e11 else None
+ baseline_sha = None
+ head_at_capture = _git_head_at(repo_cwd, at) if at else None
+ untracked_at_baseline = {}
+ since_ns = int(at * 1e9) if at else None
+ debug_log(f"Stop hook: baseline {str(snap_baseline)[:12]} is from another "
+ f"checkout (origin {origin}); this one was at "
+ f"{str(head_at_capture)[:12]} when the turn began")
+
review_paths, diff_base, repo_root, untracked, v2_metrics = compute_v2_review_set(
- cwd, baseline_sha, head_at_capture, untracked_at_baseline
+ cwd, baseline_sha, head_at_capture, untracked_at_baseline, since_ns=since_ns
)
+ # Sent even when 0, once git status has worked.
+ if origin is not None and v2_metrics.get("dirty_now_count", -1) >= 0:
+ _TAIL_METRICS["bl_origin"] = baseline_origin_metric(origin, snap["baseline_kept"])
+
v2_metrics = {**res_metrics, **v2_metrics}
if not review_paths:
debug_log("Stop hook: empty review set")
@@ -2488,6 +2550,10 @@ def handle_stop_hook(input_data):
# Update baseline so next stop hook iteration only sees new changes
new_sha = None if is_subagent else capture_git_baseline(cwd)
new_untracked_baseline = _list_untracked(cwd) if new_sha else None
+ # After a baseline from another checkout, the rest of it is replaced
+ # too, below.
+ new_head = (_git_rev_parse_head(cwd)
+ if new_sha and foreign_baseline and not head_at_capture else None)
def _record_fire(state):
if is_subagent:
@@ -2512,6 +2578,13 @@ def handle_stop_hook(input_data):
if new_sha:
state["baseline_sha"] = new_sha
state["untracked_at_baseline"] = new_untracked_baseline
+ state["baseline_root"] = repo_root
+ state.pop("baseline_kept", None)
+ if foreign_baseline:
+ # The stored HEAD is the other checkout's. Keep the one
+ # this review used, so a later Stop this turn still sees
+ # commits made (or amended) here since the prompt.
+ state["head_at_capture"] = head_at_capture or new_head
with_locked_state(session_id, _record_fire)
if new_sha:
diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh
index f1b9d68c..a02c7d6c 100755
--- a/plugins/security-guidance/hooks/sg-python.sh
+++ b/plugins/security-guidance/hooks/sg-python.sh
@@ -135,7 +135,8 @@ is_sdk_compatible() {
# Pass 1 — try minor-versioned binaries in descending order. These are only
# present if the user explicitly installed them (Homebrew / python.org / pyenv),
# so picking one here always upgrades over the system `python3`. Highest
-# available wins; the user doesn't have to PATH-prefer it.
+# of these wins; the user doesn't have to PATH-prefer it. Releases newer
+# than this list are pass 2b.
for cmd in "python3.13" "python3.12" "python3.11" "python3.10"; do
on_path "$cmd" || continue
v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; }
@@ -165,6 +166,22 @@ for cmd in "python3" "python" "py -3"; do
esac
done
+# Pass 2b — minor versions newer than the pass 1 list, so a machine whose
+# only SDK-compatible Python is a recent release (system `python3` 3.9 next to
+# Homebrew's python3.14) is not left on pass 3. Tried only when nothing
+# above is compatible: an interpreter that already works is never traded for
+# a newer one, which may not have the SDK or wheels for its dependencies yet.
+# Oldest first for the same reason. Missing names cost no process (on_path).
+# See #4907, #5024.
+for cmd in "python3.14" "python3.15" "python3.16" "python3.17" "python3.18" "python3.19"; do
+ on_path "$cmd" || continue
+ v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; }
+ v=${v%$'\r'}
+ if is_sdk_compatible "$v"; then
+ exec "$cmd" "$@"
+ fi
+done
+
# Pass 3 — fallback to any Python 3, even <3.10. Pattern-based checks
# (PostToolUse regex on Edit/Write) only need 3.6+ and are useful on their
# own; the SDK-dependent paths will detect the version mismatch and degrade
@@ -237,7 +254,7 @@ if [ -n "$sg_unreadable" ]; then
exit 1
fi
echo "security-guidance: no working Python 3 interpreter found." >&2
-echo " tried: python3.13, python3.12, python3.11, python3.10, python3, python, py -3" >&2
+echo " tried: python3.13 to python3.10, python3, python, py -3, python3.14 to python3.19" >&2
echo " on Windows, install Python from https://python.org (NOT the Microsoft Store)" >&2
echo " on macOS, install Python 3.10+ via Homebrew (\`brew install python\`)" >&2
exit 1