diff --git a/.claude/settings.json b/.claude/settings.json index f82930694..3f30eebdd 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -116,6 +116,7 @@ "Edit(~/.claude/plugins/cache/apache-magpie/magpie-vetted-ops/**)", "Edit(~/.claude/magpie/**)", "Edit(~/.config/uv/**)", + "Edit(~/.cache/pre-commit/**)", "Edit(~/.cache/prek/**)", "Edit(~/.cache/pnpm/**)", "Edit(~/.cache/ponymail-attachments/**)", diff --git a/docs/setup/sandbox-troubleshooting.md b/docs/setup/sandbox-troubleshooting.md index 3dc6864dd..c15334f3f 100644 --- a/docs/setup/sandbox-troubleshooting.md +++ b/docs/setup/sandbox-troubleshooting.md @@ -72,29 +72,34 @@ - [Root cause](#root-cause-12) - [Fix](#fix-12) - [Notes](#notes-12) - - [CaptainHook's Composer plugin replaced the shared hook directory](#captainhooks-composer-plugin-replaced-the-shared-hook-directory) + - [`pre-commit install` refuses with "Cowardly refusing to install hooks with core.hooksPath set"](#pre-commit-install-refuses-with-cowardly-refusing-to-install-hooks-with-corehookspath-set) - [Symptom](#symptom-13) - [Root cause](#root-cause-13) - [Fix](#fix-13) - [Notes](#notes-13) - - [Reads of `~/.claude/magpie` or `/tmp/claude-` ask for approval every time](#reads-of-claudemagpie-or-tmpclaude-uid-ask-for-approval-every-time) + - [CaptainHook's Composer plugin replaced the shared hook directory](#captainhooks-composer-plugin-replaced-the-shared-hook-directory) - [Symptom](#symptom-14) - [Root cause](#root-cause-14) - [Fix](#fix-14) - [Notes](#notes-14) - - [Every Bash call fails with `bwrap: Can't create file … Read-only file system`](#every-bash-call-fails-with-bwrap-cant-create-file--read-only-file-system) + - [Reads of `~/.claude/magpie` or `/tmp/claude-` ask for approval every time](#reads-of-claudemagpie-or-tmpclaude-uid-ask-for-approval-every-time) - [Symptom](#symptom-15) - [Root cause](#root-cause-15) - [Fix](#fix-15) - - [`git status` shows files you never created, such as `.mcp.json` or `.bash_profile`](#git-status-shows-files-you-never-created-such-as-mcpjson-or-bash_profile) + - [Notes](#notes-15) + - [Every Bash call fails with `bwrap: Can't create file … Read-only file system`](#every-bash-call-fails-with-bwrap-cant-create-file--read-only-file-system) - [Symptom](#symptom-16) - [Root cause](#root-cause-16) - [Fix](#fix-16) - - [Writes to a `tools/vetted-ops` policy directory fail anywhere on disk](#writes-to-a-toolsvetted-ops-policy-directory-fail-anywhere-on-disk) + - [`git status` shows files you never created, such as `.mcp.json` or `.bash_profile`](#git-status-shows-files-you-never-created-such-as-mcpjson-or-bash_profile) - [Symptom](#symptom-17) - [Root cause](#root-cause-17) - [Fix](#fix-17) - - [Notes](#notes-15) + - [Writes to a `tools/vetted-ops` policy directory fail anywhere on disk](#writes-to-a-toolsvetted-ops-policy-directory-fail-anywhere-on-disk) + - [Symptom](#symptom-18) + - [Root cause](#root-cause-18) + - [Fix](#fix-18) + - [Notes](#notes-16) - [Adding a new entry](#adding-a-new-entry) @@ -1410,6 +1415,44 @@ The setup installs the shim only for a repository that uses lefthook: a root `le --- +## `pre-commit install` refuses with "Cowardly refusing to install hooks with core.hooksPath set" + +### Symptom + +A repository that uses pre-commit has no working hooks, and `pre-commit install` fails: + +```console +$ pre-commit install +Cowardly refusing to install hooks with `core.hooksPath` set. +hint: `git config --unset-all core.hooksPath` +``` + +### Root cause + +Whole-user scope sets a global `core.hooksPath`, and pre-commit refuses to install while `git config core.hooksPath` returns anything, with no flag to name another target. +Unsetting it would take the whole-user dispatcher away from every repository on the host. + +### Fix + +Run the install through the framework shim, which hides the global config from that check and leaves the hook in the repository's own `$(git rev-parse --git-common-dir)/hooks/`: + +```bash +~/.claude/bin/pre-commit install +``` + +With `~/.claude/bin` ahead of the real binary on PATH, plain `pre-commit install` does that already. +The setup installs the shim only for a repository that uses pre-commit: a root `.pre-commit-config.yaml` or `.pre-commit-config.yml`, or an installed hook mentioning `pre-commit.com` (the URL pre-commit writes into its generated hook; a `prek` hook does not carry it). + +### Notes + +- Do not use `pre-commit init-templatedir` as a workaround: it forces `overwrite=True`, moves a foreign hook to `.legacy` and then deletes it, which removes the dispatcher. +- Do not override `core.hooksPath` through `GIT_CONFIG_COUNT`: pre-commit refuses any non-empty value, and git treats an empty one as set — hooks then resolve against the filesystem root. +- pre-commit keeps `~` literal in `PRE_COMMIT_HOME` (it calls `os.path.realpath`), so a sandboxed run cannot take its environment home from the committed settings. + `sandbox-add-project-root.sh` writes the absolute home into the project-local `.claude/settings.local.json` when the repository uses pre-commit, and removes that value again from a repository that does not; a value you set there yourself is left alone. +- `~/.claude/bin/pre-commit install --force` still gets the override, so `--force` cannot reach the shared directory through the shim either; run the real binary to do that. + +--- + ## CaptainHook's Composer plugin replaced the shared hook directory ### Symptom diff --git a/plugins/magpie-setup/skills/setup/setup_preflight/isolated_fingerprint.py b/plugins/magpie-setup/skills/setup/setup_preflight/isolated_fingerprint.py index 61858d388..c3ecff56f 100644 --- a/plugins/magpie-setup/skills/setup/setup_preflight/isolated_fingerprint.py +++ b/plugins/magpie-setup/skills/setup/setup_preflight/isolated_fingerprint.py @@ -21,4 +21,4 @@ for installs that do not carry the framework source (see `isolated.py`). """ -FRAMEWORK_FINGERPRINT = "sha256:39f20ccc594c1b65" +FRAMEWORK_FINGERPRINT = "sha256:15d19373a4432cbb" diff --git a/tools/agent-isolation/git-hook-dispatcher.sh b/tools/agent-isolation/git-hook-dispatcher.sh index f3f6d2dc3..3562cc792 100755 --- a/tools/agent-isolation/git-hook-dispatcher.sh +++ b/tools/agent-isolation/git-hook-dispatcher.sh @@ -129,7 +129,7 @@ fi # SANDBOX_RUNTIME only makes its own hook manager fail to write the host home. # Entries: = # BEGIN generated by tools/dev/sync-hook-managers.py; do not edit -hook_manager_homes="PREK_HOME=prek-host" +hook_manager_homes="PRE_COMMIT_HOME=pre-commit-host PREK_HOME=prek-host" hook_manager_runtime_envs="overcommit:overcommit" # END generated by tools/dev/sync-hook-managers.py if [ -z "${SANDBOX_RUNTIME:-}" ]; then diff --git a/tools/agent-isolation/hook-manager-shim.sh b/tools/agent-isolation/hook-manager-shim.sh index 53c8d8c8c..55334229e 100755 --- a/tools/agent-isolation/hook-manager-shim.sh +++ b/tools/agent-isolation/hook-manager-shim.sh @@ -94,6 +94,7 @@ adapter() { captainhook) install_subcommand=install; install_strategy=hooks-path-env; install_match=prefix; install_vendor_bin=1 ;; lefthook) install_subcommand=install; install_strategy=hide-global-config ;; overcommit) install_subcommand=--install; install_strategy=hooks-path-env; install_aliases='--install -i' ;; + pre-commit) install_subcommand=install; install_strategy=hide-global-config ;; prek) install_subcommand=install; install_strategy=git-dir-flag; install_flag=--git-dir ;; *) return 1 ;; esac diff --git a/tools/agent-isolation/sandbox-add-project-root.sh b/tools/agent-isolation/sandbox-add-project-root.sh index e2e9bf393..3f13a7790 100755 --- a/tools/agent-isolation/sandbox-add-project-root.sh +++ b/tools/agent-isolation/sandbox-add-project-root.sh @@ -159,6 +159,91 @@ set -euo pipefail +# --- hook managers whose home cannot spell `~` ------------------------------ +# +# Most hook managers keep their environments under `~/.cache/` and take +# the location from an environment variable they expand themselves, so the +# committed `.claude/settings.json` can name the sandbox home with `~`. +# A manager that does not expand it (pre-commit runs `os.path.realpath` on +# `PRE_COMMIT_HOME`, leaving a literal `~`) cannot be told that way: the value +# would resolve under the session's working directory. +# For those managers this helper writes the absolute sandbox home into the +# project-local `.claude/settings.local.json`, which only this machine reads, +# and removes it again from a project that does not use the manager — a sandbox +# home the repository never reaches is harmless, but a stale absolute path in a +# shared checkout is noise the operator cannot explain. A value already in the +# file is the operator's: it is left alone both while the repository uses the +# manager and when the helper removes its own value after the repository stops +# using it. +# +# Detection follows tools/hook-manager/README.md#detection: a config file at +# the repository root, a tracked nested config for a manager with workspaces, +# or an installed hook that names the manager. +# +# BEGIN generated by tools/dev/sync-hook-managers.py; do not edit +absolute_home_adapters="pre-commit" +absolute_home_adapter() { + case "$1" in + pre-commit) printf '%s\n' 'PRE_COMMIT_HOME .cache/pre-commit-sandbox .pre-commit-config.yaml,.pre-commit-config.yml pre-commit.com root' ;; + *) return 1 ;; + esac +} +# END generated by tools/dev/sync-hook-managers.py + +# absolute_home_lines prints one line per adapter: +# setVARabsolute home the repository uses that manager +# unsetVARabsolute home it does not; drop that value if present, +# and leave any other value of VAR alone +absolute_home_lines() { + local root="$1" tool entry var rel configs marker scope cfg hook_dir hook used + local hook_git="env -u GIT_DIR -u GIT_WORK_TREE -u GIT_INDEX_FILE" + for tool in $absolute_home_adapters; do + entry=$(absolute_home_adapter "$tool") || continue + set -- $entry + var=$1 + rel=$2 + configs=$3 + marker=$4 + scope=$5 + used=0 + if [ -n "$root" ]; then + for cfg in $(printf '%s' "$configs" | tr ',' ' '); do + if [ -f "$root/$cfg" ]; then + used=1 + break + fi + done + if [ "$used" -eq 0 ] && [ "$scope" = "nested" ]; then + for cfg in $(printf '%s' "$configs" | tr ',' ' '); do + if [ -n "$($hook_git git -C "$root" ls-files -z -- ":(glob)**/$cfg" 2>/dev/null | tr -d '\0')" ]; then + used=1 + break + fi + done + fi + if [ "$used" -eq 0 ]; then + hook_dir=$($hook_git git -C "$root" rev-parse --path-format=absolute --git-common-dir 2>/dev/null) || hook_dir="" + if [ -n "$hook_dir" ] && [ -d "$hook_dir/hooks" ]; then + for hook in "$hook_dir"/hooks/*; do + [ -f "$hook" ] || continue + case "$hook" in *.sample) continue ;; esac + if grep -qF -- "$marker" "$hook" 2>/dev/null; then + used=1 + break + fi + done + fi + fi + fi + if [ "$used" -eq 1 ] && [ -n "${HOME:-}" ]; then + printf 'set\t%s\t%s\n' "$var" "$HOME/$rel" + elif [ -n "${HOME:-}" ]; then + printf 'unset\t%s\t%s\n' "$var" "$HOME/$rel" + fi + done +} + + # --- option parsing --------------------------------------------------------- all_worktrees=0 @@ -435,19 +520,36 @@ update_settings() { | if (.permissions.additionalDirectories | type) == "array" then .permissions.additionalDirectories |= map(select(. as $d | $stale | index([$d]) | not)) else . end + | if ($envs | length) > 0 then .env = ($envs + (.env // {})) else . end + | if (.env | type) == "object" then + (.env |= with_entries(select($stale_vars[.key] != .value))) + | (if (.env | length) == 0 then del(.env) else . end) + else . end ' + local home_envs='{}' home_stale='{}' action key value + while IFS=$'\t' read -r action key value; do + case "$action" in + set) + home_envs=$(jq -cn --argjson o "$home_envs" --arg k "$key" --arg v "$value" '$o + {($k): $v}') + ;; + unset) + home_stale=$(jq -cn --argjson a "$home_stale" --arg k "$key" --arg v "$value" '$a + {($k): $v}') + ;; + esac + done < <(absolute_home_lines "${root:-}") + local tmp tmp=$(mktemp "${file}.XXXXXX") if [ "$input" = "/dev/null" ]; then - if ! printf '{}\n' | jq --arg p "$path" --argjson reads "$tool_reads" --argjson writes "$tool_writes" --argjson dirs "$work_dirs" --argjson stale "$stale_dirs" --argjson stale_writes "$stale_writes" --argjson parent "$parent" --argjson unsafe "$unsafe" "$jq_prog" > "$tmp"; then + if ! printf '{}\n' | jq --arg p "$path" --argjson reads "$tool_reads" --argjson writes "$tool_writes" --argjson dirs "$work_dirs" --argjson stale "$stale_dirs" --argjson stale_writes "$stale_writes" --argjson parent "$parent" --argjson unsafe "$unsafe" --argjson envs "$home_envs" --argjson stale_vars "$home_stale" "$jq_prog" > "$tmp"; then rm -f "$tmp" warn "jq update of $file failed — leaving file untouched." return 0 fi else - if ! jq --arg p "$path" --argjson reads "$tool_reads" --argjson writes "$tool_writes" --argjson dirs "$work_dirs" --argjson stale "$stale_dirs" --argjson stale_writes "$stale_writes" --argjson parent "$parent" --argjson unsafe "$unsafe" "$jq_prog" "$file" > "$tmp"; then + if ! jq --arg p "$path" --argjson reads "$tool_reads" --argjson writes "$tool_writes" --argjson dirs "$work_dirs" --argjson stale "$stale_dirs" --argjson stale_writes "$stale_writes" --argjson parent "$parent" --argjson unsafe "$unsafe" --argjson envs "$home_envs" --argjson stale_vars "$home_stale" "$jq_prog" "$file" > "$tmp"; then rm -f "$tmp" warn "jq update of $file failed — leaving file untouched." return 0 diff --git a/tools/agent-isolation/tests/test_git_hook_dispatcher.py b/tools/agent-isolation/tests/test_git_hook_dispatcher.py index 3420e3004..2682f9cb9 100644 --- a/tools/agent-isolation/tests/test_git_hook_dispatcher.py +++ b/tools/agent-isolation/tests/test_git_hook_dispatcher.py @@ -29,9 +29,11 @@ def _repo_with_local_hook( - tmp_path: Path, config: str | None = ".pre-commit-config.yaml" + tmp_path: Path, + config: str | None = ".pre-commit-config.yaml", + home_var: str = "PREK_HOME", ) -> tuple[Path, Path, Path]: - """A repository whose own pre-commit records the PREK_HOME it was given. + """A repository whose own pre-commit records the home variable it was given. `config` is the hook-manager config at its root, or None for a repository that has none. @@ -43,7 +45,7 @@ def _repo_with_local_hook( seen = tmp_path / "seen" local = repo / ".git" / "hooks" / "pre-commit" local.write_text( - f'#!/bin/sh\nprintf "%s" "${{PREK_HOME-}}" > {seen}\n' + f'#!/bin/sh\nprintf "%s" "${{{home_var}-}}" > {seen}\n' f'printf "%s" "${{XDG_CACHE_HOME-}}" > {seen}.xdg\n' ) local.chmod(0o755) @@ -65,11 +67,11 @@ def _common_dir(repo: Path) -> str: def _run(repo: Path, hook: Path, env_extra: dict[str, str]) -> None: + dropped = ("PREK_HOME", "PRE_COMMIT_HOME", "SANDBOX_RUNTIME", "XDG_CACHE_HOME") env = { k: v for k, v in os.environ.items() - if k not in ("PREK_HOME", "SANDBOX_RUNTIME", "XDG_CACHE_HOME") - and not k.startswith("GIT_CONFIG_") + if k not in dropped and not k.startswith("GIT_CONFIG_") } env.update(env_extra) subprocess.run(["bash", str(hook)], cwd=repo, env=env, check=True) @@ -91,6 +93,24 @@ def test_outside_the_sandbox_prek_gets_the_host_home( assert seen.read_text() == HOST_HOME.format(home=home) +PRE_COMMIT_HOST_HOME = "{home}/.local/share/pre-commit-host" + + +def test_outside_the_sandbox_pre_commit_gets_the_host_home(tmp_path: Path) -> None: + """pre-commit's environments run outside the sandbox from a home nothing sandboxed writes.""" + repo, hook, seen = _repo_with_local_hook(tmp_path, home_var="PRE_COMMIT_HOME") + home = os.environ["HOME"] + _run(repo, hook, {}) + assert seen.read_text() == PRE_COMMIT_HOST_HOME.format(home=home) + + +def test_inside_the_sandbox_pre_commit_keeps_its_absolute_home(tmp_path: Path) -> None: + repo, hook, seen = _repo_with_local_hook(tmp_path, home_var="PRE_COMMIT_HOME") + sandbox_home = str(tmp_path / "home" / ".cache" / "pre-commit-sandbox") + _run(repo, hook, {"SANDBOX_RUNTIME": "1", "PRE_COMMIT_HOME": sandbox_home}) + assert seen.read_text() == sandbox_home + + @pytest.mark.parametrize("given", [None, "~/.cache/prek"]) def test_inside_the_sandbox_prek_keeps_its_home( tmp_path: Path, given: str | None @@ -122,7 +142,7 @@ def test_an_overcommit_hook_preserves_existing_git_config(tmp_path: Path) -> Non repo, hook, seen = _repo_with_local_hook(tmp_path, config=".overcommit.yml") local = repo / ".git" / "hooks" / "pre-commit" local.write_text( - '#!/bin/sh\n# overcommit\n' + "#!/bin/sh\n# overcommit\n" 'printf "%s\\n" "${GIT_CONFIG_COUNT-}" "${GIT_CONFIG_KEY_0-}" ' '"${GIT_CONFIG_VALUE_0-}" "${GIT_CONFIG_KEY_1-}" ' f'"${{GIT_CONFIG_VALUE_1-}}" > {seen}\n' diff --git a/tools/agent-isolation/tests/test_hook_manager_shim.py b/tools/agent-isolation/tests/test_hook_manager_shim.py index 2e3b91160..9961260a8 100644 --- a/tools/agent-isolation/tests/test_hook_manager_shim.py +++ b/tools/agent-isolation/tests/test_hook_manager_shim.py @@ -59,17 +59,19 @@ def _setup(tmp_path: Path, name: str = "prek") -> tuple[dict[str, str], Path]: return env, argv -def _setup_lefthook(tmp_path: Path) -> tuple[dict[str, str], Path, Path]: - """A fake lefthook that refuses while a global core.hooksPath is visible. +def _setup_lefthook( + tmp_path: Path, name: str = "lefthook" +) -> tuple[dict[str, str], Path, Path]: + """A fake manager that refuses while a global core.hooksPath is visible. It records the global config it was given, then installs a hook where - `git rev-parse --git-path hooks` resolves, as lefthook does. + `git rev-parse --git-path hooks` resolves, as lefthook and pre-commit do. """ real = tmp_path / "real" real.mkdir() record = tmp_path / "record" shared = tmp_path / "shared-hooks" - (real / "lefthook").write_text( + (real / name).write_text( "#!/bin/sh\n" f'printf "GIT_CONFIG_GLOBAL=%s\\n" "${{GIT_CONFIG_GLOBAL-}}" > {record}\n' f'printf "%s\\n" "$@" >> {record}\n' @@ -86,10 +88,10 @@ def _setup_lefthook(tmp_path: Path) -> tuple[dict[str, str], Path, Path]: ' mkdir -p "$hooks" && printf "#!/bin/sh\\n" > "$hooks/pre-commit"\n' "fi\n" ) - (real / "lefthook").chmod(0o755) + (real / name).chmod(0o755) shims = tmp_path / "shims" shims.mkdir() - (shims / "lefthook").symlink_to(SHIM) + (shims / name).symlink_to(SHIM) home = tmp_path / "home" home.mkdir() (home / ".gitconfig").write_text(f"[core]\n\thooksPath = {shared}\n") @@ -367,6 +369,27 @@ def test_lefthook_install_hides_the_global_hooks_path(tmp_path: Path) -> None: assert not (shared / "pre-commit").exists() +def test_pre_commit_install_hides_the_global_hooks_path(tmp_path: Path) -> None: + """pre-commit refuses to install with any global core.hooksPath; the shim hides it.""" + env, record, shared = _setup_lefthook(tmp_path, name="pre-commit") + repo = _repo(tmp_path) + assert _run(env, repo, "install", name="pre-commit").returncode == 0 + assert record.read_text().splitlines() == ["GIT_CONFIG_GLOBAL=/dev/null", "install"] + assert (repo / ".git" / "hooks" / "pre-commit").is_file() + assert not (shared / "pre-commit").exists() + + +def test_pre_commit_passes_other_invocations_through(tmp_path: Path) -> None: + env, record, _shared = _setup_lefthook(tmp_path, name="pre-commit") + repo = _repo(tmp_path) + assert _run(env, repo, "run", "--all-files", name="pre-commit").returncode == 0 + assert record.read_text().splitlines() == [ + "GIT_CONFIG_GLOBAL=", + "run", + "--all-files", + ] + + def test_lefthook_install_hides_a_custom_global_hooks_path(tmp_path: Path) -> None: env, record, _shared = _setup_lefthook(tmp_path) other = tmp_path / "other-hooks" diff --git a/tools/agent-isolation/tests/test_sandbox_add_project_root.py b/tools/agent-isolation/tests/test_sandbox_add_project_root.py index 959c3a67a..6ae2c18da 100644 --- a/tools/agent-isolation/tests/test_sandbox_add_project_root.py +++ b/tools/agent-isolation/tests/test_sandbox_add_project_root.py @@ -104,6 +104,107 @@ def test_output_is_valid_json(self, tmp_path: Path) -> None: assert isinstance(parsed, dict) +# --------------------------------------------------------------------------- +# hook managers whose home cannot spell `~` +# --------------------------------------------------------------------------- + + +class TestHookManagerHomes: + """pre-commit keeps `~` literal, so its sandbox home is an absolute path.""" + + def test_absolute_home_for_a_repository_that_uses_pre_commit( + self, tmp_path: Path + ) -> None: + repo = _make_git_repo(tmp_path) + (repo / ".pre-commit-config.yaml").write_text("repos: []\n") + home = tmp_path / "home" + assert _run(repo, extra_env={"HOME": str(home)}).returncode == 0 + data = _load(repo / ".claude" / "settings.local.json") + assert data["env"]["PRE_COMMIT_HOME"] == str( + home / ".cache" / "pre-commit-sandbox" + ) + + def test_no_home_for_a_repository_without_the_manager(self, tmp_path: Path) -> None: + repo = _make_git_repo(tmp_path) + home = tmp_path / "home" + assert _run(repo, extra_env={"HOME": str(home)}).returncode == 0 + data = _load(repo / ".claude" / "settings.local.json") + assert "env" not in data + + def test_an_installed_hook_that_names_the_manager_counts( + self, tmp_path: Path + ) -> None: + repo = _make_git_repo(tmp_path) + hook = repo / ".git" / "hooks" / "pre-push" + hook.write_text( + "#!/usr/bin/env bash\n" + "# File generated by pre-commit: https://pre-commit.com\n" + 'exec pre-commit hook-impl --config=ci/hooks.yaml "$@"\n' + ) + home = tmp_path / "home" + assert _run(repo, extra_env={"HOME": str(home)}).returncode == 0 + data = _load(repo / ".claude" / "settings.local.json") + assert data["env"]["PRE_COMMIT_HOME"] == str( + home / ".cache" / "pre-commit-sandbox" + ) + + def test_a_hook_of_another_manager_does_not_count(self, tmp_path: Path) -> None: + """A prek hook mentions `--hook-type=pre-commit`, not the marker.""" + repo = _make_git_repo(tmp_path) + hook = repo / ".git" / "hooks" / "pre-commit" + hook.write_text( + "#!/bin/sh\n" + "# File generated by prek: https://github.com/j178/prek\n" + 'exec prek hook-impl --hook-dir "$(dirname "$0")" --hook-type=pre-commit -- "$@"\n' + ) + home = tmp_path / "home" + assert _run(repo, extra_env={"HOME": str(home)}).returncode == 0 + data = _load(repo / ".claude" / "settings.local.json") + assert "env" not in data + + def test_the_value_the_helper_wrote_is_removed(self, tmp_path: Path) -> None: + repo = _make_git_repo(tmp_path) + (repo / ".claude").mkdir() + settings_file = repo / ".claude" / "settings.local.json" + home = tmp_path / "home" + settings_file.write_text( + json.dumps( + {"env": {"PRE_COMMIT_HOME": str(home / ".cache" / "pre-commit-sandbox")}} + ) + ) + assert _run(repo, extra_env={"HOME": str(home)}).returncode == 0 + data = _load(settings_file) + assert "env" not in data + assert str(repo) in data["sandbox"]["filesystem"]["allowRead"] + + def test_a_value_the_operator_chose_is_kept(self, tmp_path: Path) -> None: + """A project that stops using the manager must not lose a foreign value.""" + repo = _make_git_repo(tmp_path) + (repo / ".claude").mkdir() + settings_file = repo / ".claude" / "settings.local.json" + chosen = str(tmp_path / "elsewhere" / "pre-commit") + settings_file.write_text(json.dumps({"env": {"PRE_COMMIT_HOME": chosen}})) + home = tmp_path / "home" + assert _run(repo, extra_env={"HOME": str(home)}).returncode == 0 + data = _load(settings_file) + assert data["env"]["PRE_COMMIT_HOME"] == chosen + + def test_a_value_the_operator_chose_survives_a_repository_that_uses_it( + self, tmp_path: Path + ) -> None: + """The sandbox home fills a gap; it does not replace a chosen value.""" + repo = _make_git_repo(tmp_path) + (repo / ".pre-commit-config.yaml").write_text("repos: []\n") + (repo / ".claude").mkdir() + settings_file = repo / ".claude" / "settings.local.json" + chosen = str(tmp_path / "elsewhere" / "pre-commit") + settings_file.write_text(json.dumps({"env": {"PRE_COMMIT_HOME": chosen}})) + home = tmp_path / "home" + assert _run(repo, extra_env={"HOME": str(home)}).returncode == 0 + data = _load(settings_file) + assert data["env"]["PRE_COMMIT_HOME"] == chosen + + # --------------------------------------------------------------------------- # idempotence # --------------------------------------------------------------------------- diff --git a/tools/dev/sync-hook-managers.py b/tools/dev/sync-hook-managers.py index 24971ab6e..a21671493 100755 --- a/tools/dev/sync-hook-managers.py +++ b/tools/dev/sync-hook-managers.py @@ -29,6 +29,9 @@ - `tools/agent-isolation/git-hook-dispatcher.sh`: the host-only home and run-time override per tool. - `tools/sandbox-lint/src/sandbox_lint/__init__.py`: the homes the lint checks. +- `tools/agent-isolation/sandbox-add-project-root.sh`: the managers whose + home variable a `~` cannot spell, so the helper writes an absolute path into + the project-local settings instead. It also checks, without writing, that the committed settings and the sandbox-lint baseline deny every manager's default home and give the sandbox @@ -52,6 +55,7 @@ SHIM = Path("tools/agent-isolation/hook-manager-shim.sh") DISPATCHER = Path("tools/agent-isolation/git-hook-dispatcher.sh") SANDBOX_LINT = Path("tools/sandbox-lint/src/sandbox_lint/__init__.py") +ADD_PROJECT_ROOT = Path("tools/agent-isolation/sandbox-add-project-root.sh") SETTINGS = (Path(".claude/settings.json"), Path("tools/sandbox-lint/expected.json")) #: Install strategies the shim implements. A new one lands with its shim branch. @@ -173,10 +177,13 @@ def validate(registry: dict[str, Any]) -> list[str]: continue if not isinstance(home.get("env"), str) or not _ENV.match(home["env"]): errors.append(f"{where}.home.env: the environment variable that relocates the home") - if home.get("expands_tilde") is not True: + if not isinstance(home.get("expands_tilde"), bool): # The committed settings can only spell a per-user path with `~`. + # A tool that does not expand it gets an absolute path written into + # the project-local settings by sandbox-add-project-root.sh. errors.append( - f"{where}.home.expands_tilde: a tool that does not expand ~ needs a per-user sandbox home" + f"{where}.home.expands_tilde: must be true or false; false means the tool does not " + "expand ~ and needs an absolute home in the project-local settings.local.json" ) default, sandbox, host = home.get("default"), home.get("sandbox"), home.get("host") for key, value in (("default", default), ("sandbox", sandbox)): @@ -240,10 +247,30 @@ def render(registry: dict[str, Any]) -> dict[Path, str]: json.dumps(home["default"]), json.dumps(home["sandbox"]), ] - fields += [files, str(detect["nested"]), json.dumps(detect["hook_marker"])] + fields += [ + files, + str(detect["nested"]), + json.dumps(detect["hook_marker"]), + str(home["expands_tilde"]), + ] lint += " (\n" + "".join(f" {f},\n" for f in fields) + " ),\n" lint += ")\n" - return {SHIM: shim, DISPATCHER: dispatcher, SANDBOX_LINT: lint} + # A home the tool expands from `~` is written into the committed settings. + # One it does not expand gets an absolute path from the helper instead, so + # the helper needs the same facts in shell form. + absolute = [(n, a) for n, a in homes if not a["home"]["expands_tilde"]] + add_project_root = ( + 'absolute_home_adapters="' + " ".join(n for n, _ in absolute) + '"\n' + 'absolute_home_adapter() {\n case "$1" in\n' + + "".join( + f" {n}) printf '%s\\n' '{a['home']['env']} {a['home']['sandbox'][2:]} " + f"{','.join(a['detect']['config_files'])} {a['detect']['hook_marker']} " + f"{'nested' if a['detect']['nested'] else 'root'}' ;;\n" + for n, a in absolute + ) + + " *) return 1 ;;\n esac\n}\n" + ) + return {SHIM: shim, DISPATCHER: dispatcher, SANDBOX_LINT: lint, ADD_PROJECT_ROOT: add_project_root} def check_settings(registry: dict[str, Any], root: Path) -> list[str]: @@ -263,7 +290,15 @@ def check_settings(registry: dict[str, Any], root: Path) -> list[str]: if not home: continue used = any((root / f).is_file() for f in adapter["detect"]["config_files"]) - if used and env.get(home["env"]) != home["sandbox"]: + if not home["expands_tilde"]: + # An absolute path is not portable, so this one belongs in the + # project-local settings the helper writes, not here. + if env.get(home["env"]) is not None: + errors.append( + f"{rel}: env.{home['env']} must not be set: {name} does not expand ~, so " + "sandbox-add-project-root.sh writes the absolute home per project" + ) + elif used and env.get(home["env"]) != home["sandbox"]: errors.append(f"{rel}: env.{home['env']} must be {home['sandbox']!r} ({name})") if f"Edit({home['default']}/**)" not in deny: errors.append(f"{rel}: permissions.deny must carry Edit({home['default']}/**) ({name})") diff --git a/tools/dev/tests/test_sync_hook_managers.py b/tools/dev/tests/test_sync_hook_managers.py index 6d24e05c7..341eb3e9a 100644 --- a/tools/dev/tests/test_sync_hook_managers.py +++ b/tools/dev/tests/test_sync_hook_managers.py @@ -57,7 +57,14 @@ def registry() -> dict[str, Any]: @pytest.fixture def tree(tmp_path: Path) -> Path: """A copy of every file the script reads or writes.""" - for rel in (mod.REGISTRY, mod.SHIM, mod.DISPATCHER, mod.SANDBOX_LINT, *mod.SETTINGS): + for rel in ( + mod.REGISTRY, + mod.SHIM, + mod.DISPATCHER, + mod.SANDBOX_LINT, + mod.ADD_PROJECT_ROOT, + *mod.SETTINGS, + ): (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True) shutil.copy(mod.REPO_ROOT / rel, tmp_path / rel) (tmp_path / ".pre-commit-config.yaml").write_text("repos: []\n") # this repository uses prek @@ -88,7 +95,7 @@ def test_the_committed_registry_follows_the_contract(registry: dict[str, Any]) - (("home", "sandbox"), "/tmp/prek", "home.sandbox"), (("home", "host"), "~/.cache/prek-host", "home.host"), (("home", "host"), "~/.local/share/a/b", "home.host"), - (("home", "expands_tilde"), False, "home.expands_tilde"), + (("home", "expands_tilde"), "no", "home.expands_tilde"), (("home", "env"), "prek_home", "home.env"), ], ) @@ -180,11 +187,38 @@ def test_aliases_need_a_flag_style_subcommand(registry: dict[str, Any]) -> None: ) +def test_a_home_that_does_not_expand_tilde_reaches_the_helper(tree: Path, registry: dict[str, Any]) -> None: + """A tool that keeps `~` literal gets its absolute home from the helper.""" + mod.main(["--root", str(tree)]) + helper = (tree / mod.ADD_PROJECT_ROOT).read_text() + assert 'absolute_home_adapters="pre-commit"' in helper + assert ( + "pre-commit) printf '%s\\n' 'PRE_COMMIT_HOME .cache/pre-commit-sandbox " + ".pre-commit-config.yaml,.pre-commit-config.yml pre-commit.com root' ;;" + ) in helper + lint = (tree / mod.SANDBOX_LINT).read_text() + assert ( + '"PRE_COMMIT_HOME",\n "~/.cache/pre-commit",\n "~/.cache/pre-commit-sandbox",' in lint + ) + assert ' False,\n "pre-commit.com",\n False,\n' in lint + + +def test_a_home_that_does_not_expand_tilde_cannot_sit_in_committed_settings( + tree: Path, registry: dict[str, Any] +) -> None: + for rel in mod.SETTINGS: + settings = json.loads((tree / rel).read_text()) + settings["env"]["PRE_COMMIT_HOME"] = "~/.cache/pre-commit-sandbox" + (tree / rel).write_text(json.dumps(settings), encoding="utf-8") + assert mod.main(["--check", "--root", str(tree)]) == 1 + + def test_a_manager_without_a_home_is_allowed(registry: dict[str, Any]) -> None: del registry["adapters"]["prek"]["home"] assert mod.validate(registry) == [] assert mod.render(registry)[mod.DISPATCHER] == ( - 'hook_manager_homes=""\nhook_manager_runtime_envs="overcommit:overcommit"\n' + 'hook_manager_homes="PRE_COMMIT_HOME=pre-commit-host"\n' + 'hook_manager_runtime_envs="overcommit:overcommit"\n' ) @@ -239,7 +273,10 @@ def test_a_new_adapter_reaches_every_block(tree: Path, registry: dict[str, Any]) assert mod.main(["--root", str(tree)]) == 1 # rewrote the blocks; the settings lack the demo deny assert " demo) install_subcommand=install;" in (tree / mod.SHIM).read_text() dispatcher = (tree / mod.DISPATCHER).read_text() - assert 'hook_manager_homes="DEMO_HOME=demo-host PREK_HOME=prek-host"' in dispatcher + assert ( + 'hook_manager_homes="DEMO_HOME=demo-host PRE_COMMIT_HOME=pre-commit-host PREK_HOME=prek-host"' + in dispatcher + ) assert 'hook_manager_runtime_envs="overcommit:overcommit"' in dispatcher lint = (tree / mod.SANDBOX_LINT).read_text() assert ( diff --git a/tools/hook-manager/README.md b/tools/hook-manager/README.md index ac3d5b9c1..6fd188b87 100644 --- a/tools/hook-manager/README.md +++ b/tools/hook-manager/README.md @@ -95,7 +95,11 @@ A manager that keeps environments in a home outside the repository gets three di | `host` (one directory under `~/.local/share/`) | Every hook the whole-user dispatcher runs outside the sandbox (no `SANDBOX_RUNTIME`). | The dispatcher exports `=~/.local/share/` for every registered manager unless the operator chose a value outside `~/.cache`. | `~/.local/share/` is outside every sandbox write grant, so nothing sandboxed can plant code in the host home. -The committed settings can name a per-user directory only with `~`, so the contract requires a manager whose home variable is relative to `~` to expand it (`expands_tilde: true`); one that does not needs the sandbox home written as an absolute path into the per-user `settings.local.json`, which no adapter does yet. +The committed settings can name a per-user directory only with `~`, so a manager whose home variable expands `~` (`expands_tilde: true`) takes its sandbox home from `env.` there. + +A manager that keeps `~` literal (`expands_tilde: false`, pre-commit runs `os.path.realpath` on `PRE_COMMIT_HOME`) cannot be told that way: the value would resolve under the session's working directory. +Its sandbox home is written as an absolute path into the project-local `.claude/settings.local.json` by [`sandbox-add-project-root.sh`](../agent-isolation/sandbox-add-project-root.sh), which reads the adapter table the registry generates and removes the value again from a project that does not use the manager. +That file exists only where the helper ran, so the committed settings never carry the value and `sandbox-lint` validates it only when it is present: an absent value is covered by the default-home deny, because a sandboxed run that finds no home of its own fails rather than writing the one a terminal's commits use. ### Detection @@ -178,7 +182,7 @@ Its operations are carried out by the scripts generated from the registry: | Install rewrite | [`hook-manager-shim.sh`](../agent-isolation/hook-manager-shim.sh), installed as `~/.claude/bin/` | ` [args…]`, e.g. `prek install`, `lefthook install`, `overcommit --install` (also `-i`, or after other options) or `captainhook -n install` (also `inst`) | Applies the adapter's install strategy: `git-dir-flag` runs `prek install --git-dir [args…]`; `hooks-path-env` runs `overcommit --install` or `-i`, or `captainhook install` in any of its spellings, with `core.hooksPath` pointed at `/hooks`, appending to any existing `GIT_CONFIG_*` entries; `hide-global-config` runs the install with `GIT_CONFIG_GLOBAL=/dev/null` when the global config holds a `core.hooksPath`. Left unchanged when `args` already carry the target flag or ask for `-h` / `--help`, or outside a git work tree; a `hide-global-config` install carrying `--force` or `--reset-hooks-path` still gets the override, so neither reaches the shared directory through the shim. Every other subcommand passes through to the real binary, the next `` on `PATH` that is not the shim, or `/vendor/bin/` for an adapter with `install.vendor_bin`. Exits 127 when the name it is installed under has no adapter or no real binary is found. | | Host home and run-time override | [`git-hook-dispatcher.sh`](../agent-isolation/git-hook-dispatcher.sh), from `~/.claude/git-hooks/` | Every hook git runs, before it chains to the repository's own hook | Outside the sandbox (no `SANDBOX_RUNTIME`), exports `=~/.local/share/` for every registered manager unless the operator's value lies outside `~/.cache`, and moves `XDG_CACHE_HOME` to `~/.local/share/prek-host/cache` by the same rule. Sandboxed hooks keep their values. Before chaining to a hook whose marker matches an adapter with `install.runtime_env`, exports the same `core.hooksPath` override the shim used, so the manager's own run-time check accepts the hook. | | Home check | [`sandbox-lint`](../sandbox-lint/) | `uv run --project tools/sandbox-lint sandbox-lint` | Fails a settings file whose `permissions.deny` lacks `Edit(/**)` for any registered manager, and, for a project that uses a manager (see [Detection](#detection)), one whose `env.` is missing or overlaps the default home. | -| Registry sync | [`tools/dev/sync-hook-managers.py`](../dev/sync-hook-managers.py) | `tools/dev/sync-hook-managers.py [--check]`; the `sync-hook-managers` prek hook | Validates `registry.json`, rewrites the generated blocks of the three scripts above, and checks the committed settings and the sandbox-lint baseline. Exits 1 when a block changed (re-stage and commit), or, with `--check`, when one would. | +| Registry sync | [`tools/dev/sync-hook-managers.py`](../dev/sync-hook-managers.py) | `tools/dev/sync-hook-managers.py [--check]`; the `sync-hook-managers` prek hook | Validates `registry.json`, rewrites the generated blocks of the scripts above plus the absolute-home table in [`sandbox-add-project-root.sh`](../agent-isolation/sandbox-add-project-root.sh), and checks the committed settings and the sandbox-lint baseline. Exits 1 when a block changed (re-stage and commit), or, with `--check`, when one would. | ## Configuration @@ -188,7 +192,7 @@ What a repository or an operator configures is where each manager's environments | Setting | Where | Value for prek | Required | |---|---|---|---| | `permissions.deny` entry `Edit(/**)` | `.claude/settings.json` (and `tools/sandbox-lint/expected.json` in this repository) | `Edit(~/.cache/prek/**)` | Always, for every registered manager. | -| `env.` | `.claude/settings.json` | `"PREK_HOME": "~/.cache/prek-sandbox"` | Only when the repository uses the manager; it must not overlap the default home. | +| `env.` | `.claude/settings.json` for an expanding home, `.claude/settings.local.json` for one that does not | `"PREK_HOME": "~/.cache/prek-sandbox"`, or `"/home//.cache/pre-commit-sandbox"` | Only when the repository uses the manager; it must not overlap the default home. An absolute value is per machine, so it is never committed. | | `` in the operator's environment | the shell the operator commits from | unset, or a directory outside `~/.cache` | Optional: a value outside `~/.cache` is kept by the dispatcher; one under it is replaced with the host home. | | `PATH` | the operator's shell profile | `~/.claude/bin` ahead of the real `prek` | Only under whole-user scope, where the shim is installed; removing `~/.claude/bin` from `PATH` restores the stock binary. | @@ -203,6 +207,7 @@ What a repository or an operator configures is where each manager's environments | `git-build-hook` | Java | `none`; detected by `pom.xml` (nested too) or a hook mentioning `git-build-hook` | none (no external home) | shipping (JGit `getGitDir()` targets `/hooks` in linked worktrees; `configure` goal can set repo-local `core.hooksPath`) | | `git-code-format-maven-plugin` | Java | `none`; detected by `pom.xml` (nested too) or a hook mentioning `git-code-format-maven-plugin` | none (no external home) | shipping (JGit `getCommonDirectory()` targets common hooks dir, coexisting cleanly in linked worktrees) | | `lefthook` | Go | `hide-global-config`; detected by `lefthook.yml`, `lefthook.yaml`, `lefthook.json`, `lefthook.jsonc`, `lefthook.toml`, their `.lefthook` and `-local` variants, or a hook mentioning `call_lefthook` | none: remote configs live under `/lefthook-remotes`, inside `.git` | shipping | +| `pre-commit` | Python | `hide-global-config`; detected by `.pre-commit-config.yaml` or `.pre-commit-config.yml`, or a hook mentioning `pre-commit.com` (the URL its generated hook carries; a `prek` hook mentions only `--hook-type=pre-commit`) | `PRE_COMMIT_HOME`: `~/.cache/pre-commit` → sandbox `~/.cache/pre-commit-sandbox`, host `~/.local/share/pre-commit-host`; the sandbox value is absolute (see *Home*) | shipping (verified: v4.7.0 through the shim writes `$(git rev-parse --git-common-dir)/hooks/pre-commit` and leaves the shared directory empty, including from a linked worktree; a bare install refuses) | | `prek` | Rust | `git-dir-flag` (`--git-dir`); detected by `prek.toml`, `.pre-commit-config.yaml` or `.pre-commit-config.yml` (nested too) or a hook mentioning `prek` | `PREK_HOME`: `~/.cache/prek` → sandbox `~/.cache/prek-sandbox`, host `~/.local/share/prek-host` | shipping | | `overcommit` | Ruby | `hooks-path-env` (`--install`, alias `-i`, found anywhere in argv); detected by `.overcommit.yml` or a hook mentioning `overcommit` | none — it keeps its own state in git config and the repository | shipping | | `simple-git-hooks` | JavaScript | `none`; detected by `package.json`, `.simple-git-hooks.{js,cjs,json}`, `simple-git-hooks.{js,cjs,json}` or a hook mentioning `simple-git-hooks` | none (no external home) | shipping | @@ -234,6 +239,12 @@ What a repository or an operator configures is where each manager's environments In a linked worktree the same install lands in the main checkout's `.git/hooks/`. npm's `postinstall` runs `node_modules/.bin/lefthook` ahead of `~/.claude/bin`, so the shim does not cover it: that install refuses, and the repository needs one run through the shim. A fix would be the session-start hook noticing hooks in the shared directory that are not the dispatcher; the shim cannot reach an npm-run child ahead of it on `PATH`. + - `pre-commit` (v4.7.0, verified against the release binary through the shim): + Refuses a bare install while `git config core.hooksPath` returns anything, and has no flag to name another target; `GIT_CONFIG_GLOBAL=/dev/null` hides it, and the install then writes `$(git rev-parse --git-common-dir)/hooks/pre-commit`, leaving the shared directory empty. + An install from a linked worktree lands in the main checkout's `.git/hooks/`. + `PRE_COMMIT_HOME` reaches `os.path.realpath` unexpanded, so its sandbox home has to be an absolute path (see *Home*); `sandbox-add-project-root.sh` writes it per project. + `pre-commit init-templatedir` is not a workaround: it forces `overwrite=True`, which moves a foreign hook to `.legacy` and then deletes it. + The generated hook hardcodes the install-time interpreter with a fallback to `pre-commit` on `PATH`, and passes `--hook-dir "$(dirname "$0")"`, which only locates `.legacy`; the dispatcher execs the hook by its real path, so it works. - **JGit in linked worktrees (Maven):** The linked-worktree limitation applies only to `git-build-hook` (`InstallMojo`), which uses `getGitDir()` and creates hooks under `/worktrees//hooks/`. Because C-git commits read hooks exclusively from `$(git rev-parse --git-common-dir)/hooks/`, hooks installed by `git-build-hook` from within a worktree are ignored by Git. diff --git a/tools/hook-manager/registry.json b/tools/hook-manager/registry.json index 4d296e809..292c4bff7 100644 --- a/tools/hook-manager/registry.json +++ b/tools/hook-manager/registry.json @@ -155,6 +155,29 @@ "install": { "strategy": "none" } + }, + "pre-commit": { + "language": "Python", + "upstream": "https://github.com/pre-commit/pre-commit", + "detect": { + "config_files": [ + ".pre-commit-config.yaml", + ".pre-commit-config.yml" + ], + "nested": false, + "hook_marker": "pre-commit.com" + }, + "install": { + "subcommand": "install", + "strategy": "hide-global-config" + }, + "home": { + "env": "PRE_COMMIT_HOME", + "default": "~/.cache/pre-commit", + "sandbox": "~/.cache/pre-commit-sandbox", + "host": "~/.local/share/pre-commit-host", + "expands_tilde": false + } } } } diff --git a/tools/sandbox-lint/expected.json b/tools/sandbox-lint/expected.json index 015e95ac1..3fad6c12c 100644 --- a/tools/sandbox-lint/expected.json +++ b/tools/sandbox-lint/expected.json @@ -157,6 +157,7 @@ "Edit(~/.claude/plugins/cache/apache-magpie/magpie-vetted-ops/**)", "Edit(~/.claude/magpie/**)", "Edit(~/.config/uv/**)", + "Edit(~/.cache/pre-commit/**)", "Edit(~/.cache/prek/**)", "Edit(~/.cache/pnpm/**)", "Edit(~/.cache/ponymail-attachments/**)", diff --git a/tools/sandbox-lint/src/sandbox_lint/__init__.py b/tools/sandbox-lint/src/sandbox_lint/__init__.py index dd87593f6..5d7111405 100644 --- a/tools/sandbox-lint/src/sandbox_lint/__init__.py +++ b/tools/sandbox-lint/src/sandbox_lint/__init__.py @@ -261,6 +261,16 @@ def registry_errors(floor: dict[str, Any], registry: dict[str, Any]) -> list[str # runs of the manager then fail on the denied default home. # BEGIN generated by tools/dev/sync-hook-managers.py; do not edit HOOK_MANAGER_HOMES = ( + ( + "pre-commit", + "PRE_COMMIT_HOME", + "~/.cache/pre-commit", + "~/.cache/pre-commit-sandbox", + (".pre-commit-config.yaml", ".pre-commit-config.yml"), + False, + "pre-commit.com", + False, + ), ( "prek", "PREK_HOME", @@ -269,6 +279,7 @@ def registry_errors(floor: dict[str, Any], registry: dict[str, Any]) -> list[str ("prek.toml", ".pre-commit-config.yaml", ".pre-commit-config.yml"), True, "prek", + True, ), ) # END generated by tools/dev/sync-hook-managers.py @@ -873,12 +884,30 @@ def check_invariants(settings: dict[str, Any], project_root: Path | None = None) # managers the project uses; the default-home deny is required for every # manager (REQUIRED_PERMISSIONS_DENY). env = settings.get("env") - for tool, var, default, sandbox_home, files, nested, marker in HOOK_MANAGER_HOMES: + for tool, var, default, sandbox_home, files, nested, marker, expands_tilde in HOOK_MANAGER_HOMES: if not uses_hook_manager(project_root, files, nested, marker): continue given = env.get(var) if isinstance(env, dict) else None default_home = os.path.normpath(os.path.expanduser(default)) - expanded_home = _expand(given, project_root) if isinstance(given, str) and given else None + if not expands_tilde: + # The tool keeps `~` literal, so the committed settings cannot name + # its sandbox home: the absolute path is per machine and comes from + # sandbox-add-project-root.sh in the project-local settings. The + # file exists only where the helper ran, so an absent value is not + # an error: a sandboxed run without it fails against the denied + # default home instead of writing the home a terminal's commits use. + if not isinstance(given, str) or not given: + continue + if not os.path.isabs(given): + errors.append( + f"env.{var}: {given!r} must be an absolute path; {tool} does not expand ~, so " + "this value would resolve under the working directory. Run " + "sandbox-add-project-root.sh to write it" + ) + continue + expanded_home: str | None = os.path.normpath(given) + else: + expanded_home = _expand(given, project_root) if isinstance(given, str) and given else None if expanded_home is None: errors.append( f"env.{var}: missing; set it to {sandbox_home} so sandboxed {tool} does not " diff --git a/tools/sandbox-lint/tests/test_validator.py b/tools/sandbox-lint/tests/test_validator.py index 41ee835ad..1eefd1eea 100644 --- a/tools/sandbox-lint/tests/test_validator.py +++ b/tools/sandbox-lint/tests/test_validator.py @@ -1107,6 +1107,54 @@ def test_settings_need_no_prek_home_for_a_project_without_prek( assert any(e.startswith("env.PREK_HOME: missing") for e in errors), errors +PRE_COMMIT_FILES = (".pre-commit-config.yaml", ".pre-commit-config.yml") + + +def _pre_commit_repo(tmp_path: Path) -> Path: + repo = _git_repo(tmp_path / "pre-commit-repo") + (repo / ".pre-commit-config.yaml").write_text("") + return repo + + +def test_the_default_pre_commit_home_is_denied(baseline: dict[str, Any]) -> None: + assert "Edit(~/.cache/pre-commit/**)" in baseline["permissions"]["deny"] + + +def test_a_literal_tilde_is_refused_for_a_home_the_tool_does_not_expand( + baseline: dict[str, Any], tmp_path: Path +) -> None: + """pre-commit runs os.path.realpath, so `~` would resolve under the working directory.""" + settings = copy.deepcopy(baseline) + settings["env"] = {"PRE_COMMIT_HOME": "~/.cache/pre-commit-sandbox"} + errors = check_invariants(settings, project_root=_pre_commit_repo(tmp_path)) + assert any("PRE_COMMIT_HOME" in e and "absolute" in e for e in errors), errors + + +def test_an_absent_pre_commit_home_is_not_an_error(baseline: dict[str, Any], tmp_path: Path) -> None: + """The helper writes it per machine; without it a sandboxed run hits the denied default home.""" + settings = copy.deepcopy(baseline) + settings.pop("env", None) + errors = check_invariants(settings, project_root=_pre_commit_repo(tmp_path)) + assert not [e for e in errors if "PRE_COMMIT_HOME" in e], errors + + +def test_a_pre_commit_home_inside_the_default_home_is_refused( + baseline: dict[str, Any], tmp_path: Path +) -> None: + default_home = Path(os.path.expanduser("~/.cache/pre-commit")) + settings = copy.deepcopy(baseline) + settings["env"] = {"PRE_COMMIT_HOME": str(default_home / "sandbox")} + errors = check_invariants(settings, project_root=_pre_commit_repo(tmp_path)) + assert any(e.startswith("env.PRE_COMMIT_HOME:") for e in errors), errors + + +def test_an_absolute_pre_commit_home_is_accepted(baseline: dict[str, Any], tmp_path: Path) -> None: + settings = copy.deepcopy(baseline) + settings["env"] = {"PRE_COMMIT_HOME": str(tmp_path / "home" / ".cache" / "pre-commit-sandbox")} + errors = check_invariants(settings, project_root=_pre_commit_repo(tmp_path)) + assert not [e for e in errors if "PRE_COMMIT_HOME" in e], errors + + def test_the_default_prek_home_is_denied_even_without_prek(baseline: dict[str, Any], tmp_path: Path) -> None: """The default home is per-user: another project's terminal commits run from it.""" settings = copy.deepcopy(baseline) diff --git a/tools/spec-loop/specs/agent-isolation-sandbox.md b/tools/spec-loop/specs/agent-isolation-sandbox.md index 2a4e81805..3dd8d1457 100644 --- a/tools/spec-loop/specs/agent-isolation-sandbox.md +++ b/tools/spec-loop/specs/agent-isolation-sandbox.md @@ -419,6 +419,21 @@ See `docs/adapters/harnesses/goose.md`. points `PREK_HOME` at `~/.local/share/prek-host` and `XDG_CACHE_HOME` at `~/.local/share/prek-host/cache`, keeping an operator's own value outside `~/.cache`. + pre-commit takes lefthook's `hide-global-config` strategy (#1820) and + has a home the committed settings cannot carry: `PRE_COMMIT_HOME` + reaches `os.path.realpath` unexpanded, so a `~` value would resolve + under the session's working directory. + The settings keep no `env` entry for it (an absolute path is per + machine), `Edit(~/.cache/pre-commit/**)` denies the default home, and + `sandbox-add-project-root.sh` writes the resolved sandbox home + `~/.cache/pre-commit-sandbox` into the project-local + `.claude/settings.local.json` for a repository that uses pre-commit — + filling a gap only, never replacing a value the operator set there — + and removes that value again from a repository that does not. + Detection counts an installed hook only when it carries + `https://pre-commit.com`, the URL pre-commit writes into its generated + hook; a `prek` hook mentions `--hook-type=pre-commit` and would otherwise + match. pnpm gets the same split without being a hook manager: a pnpm project's own settings `env` (never the shared template, since npm warns about unknown `npm_config_*` names) sets `PNPM_HOME` to a @@ -457,7 +472,8 @@ See `docs/adapters/harnesses/goose.md`. `registry.json` registers prek (install strategy `git-dir-flag`), overcommit (`hooks-path-env`, with `install.runtime_env` so the dispatcher exports the same `core.hooksPath` at run time), lefthook - (`hide-global-config`, no home), captainhook (`hooks-path-env`, #1899), + (`hide-global-config`, no home), pre-commit (`hide-global-config`, home + from the helper, #1820), captainhook (`hooks-path-env`, #1899), plus four managers with install strategy `none`, which already write to the repository's own hooks directory whatever the global `core.hooksPath`: