Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .claude/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -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/**)",
Expand Down
55 changes: 49 additions & 6 deletions docs/setup/sandbox-troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<uid>` 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-<uid>` 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)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@
for installs that do not carry the framework source (see `isolated.py`).
"""

FRAMEWORK_FINGERPRINT = "sha256:39f20ccc594c1b65"
FRAMEWORK_FINGERPRINT = "sha256:15d19373a4432cbb"
2 changes: 1 addition & 1 deletion tools/agent-isolation/git-hook-dispatcher.sh
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ fi
# SANDBOX_RUNTIME only makes its own hook manager fail to write the host home.
# Entries: <home var>=<host dir under ~/.local/share>
# 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
Expand Down
1 change: 1 addition & 0 deletions tools/agent-isolation/hook-manager-shim.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
106 changes: 104 additions & 2 deletions tools/agent-isolation/sandbox-add-project-root.sh
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,91 @@

set -euo pipefail

# --- hook managers whose home cannot spell `~` ------------------------------
#
# Most hook managers keep their environments under `~/.cache/<tool>` 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 <repo-root> prints one line per adapter:
# set<TAB>VAR<TAB>absolute home the repository uses that manager
# unset<TAB>VAR<TAB>absolute 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
Expand Down Expand Up @@ -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
Expand Down
32 changes: 26 additions & 6 deletions tools/agent-isolation/tests/test_git_hook_dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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-<unset>}}" > {seen}\n'
f'#!/bin/sh\nprintf "%s" "${{{home_var}-<unset>}}" > {seen}\n'
f'printf "%s" "${{XDG_CACHE_HOME-<unset>}}" > {seen}.xdg\n'
)
local.chmod(0o755)
Expand All @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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'
Expand Down
35 changes: 29 additions & 6 deletions tools/agent-isolation/tests/test_hook_manager_shim.py
Original file line number Diff line number Diff line change
Expand Up @@ -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-<unset>}}" > {record}\n'
f'printf "%s\\n" "$@" >> {record}\n'
Expand All @@ -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")
Expand Down Expand Up @@ -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=<unset>",
"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"
Expand Down
Loading