fix(plugins): keep the hook launcher's Python fallback off the project dir (#4842)

## Description

`plugins/headroom-agent-hooks/bin/headroom-hook.sh` looks for a
`headroom` executable and, if none is found, falls back to `"$python" -c
'import headroom'` followed by `exec "$python" -m headroom.cli init hook
ensure`. Both forms put the current directory first on `sys.path`, and
the hook runs with the opened project as its working directory, so a
`headroom/` directory in that project was imported instead of the
installed package.

Both calls now pass `-P` (Python 3.11+: do not prepend the cwd/script
dir to `sys.path`). `-P` was chosen over `-I` so `PYTHONPATH` and user
site-packages installs keep working. Interpreters older than 3.11 reject
`-P`, so the import check fails and they are skipped; `headroom-ai`
requires 3.11+ so they could not have a real install anyway.

The same fallback pattern in the OpenClaw plugin
(`plugins/openclaw/src/proxy-manager.ts`) is fixed in a separate PR
because that plugin has its own test suite.

Follow-up from review: the processes Headroom itself relaunches with
`python -m headroom.cli` (`resolve_headroom_command()` for the detached
agent and MCP registration, `build_runtime_command()` for the
python-runtime proxy, and the macOS malloc re-exec in
`headroom/cli/proxy.py`) now also pass `-P`. Registered MCP server args
therefore become `-P -m headroom.cli mcp serve` when no `headroom`
executable is on PATH.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- `plugins/headroom-agent-hooks/bin/headroom-hook.sh`: `-P` on the
import check and on `-m headroom.cli`.
- `tests/test_plugin_hook_launcher.py`: updated the fallback receipt;
new test running a real interpreter (site-packages disabled) from a
project dir that contains a `headroom/` package and asserting it is
never imported.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`) (no package code changed)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
# new/updated tests on origin/main (fix stashed)
$ pytest -q tests/test_plugin_hook_launcher.py
FAILED tests/test_plugin_hook_launcher.py::test_launcher_uses_importable_python_module
FAILED tests/test_plugin_hook_launcher.py::test_launcher_python_fallback_does_not_import_from_the_working_directory
E   AssertionError: assert not True   (marker written by the project's headroom/__init__.py)
========================= 2 failed, 9 passed in 2.19s ==========================

# with the fix
$ pytest -q tests/test_plugin_manifests.py tests/test_plugin_hook_launcher.py
============================== 21 passed in 2.08s ==============================

$ ruff check / ruff format --check (0.17.3) tests/test_plugin_hook_launcher.py
All checks passed!
1 file already formatted
```

## Real Behavior Proof

- Environment: macOS, `/bin/sh`, a Python 3.12 venv with headroom-ai
installed, `PATH=/usr/bin:/bin` (no `headroom` executable), clean
`HOME`.
- Exact command / steps: in a directory containing
`headroom/__init__.py` and `headroom/cli.py` that each print a line, run
`env -i HOME=... PATH=/usr/bin:/bin HEADROOM_PYTHON=<venv python> sh
plugins/headroom-agent-hooks/bin/headroom-hook.sh`.
- Observed result: on main the project-dir `headroom` package executes;
on this branch the installed `headroom init hook ensure` runs instead.
Per branch:
- main: `planted __init__ module ran` / `planted cli module ran` (the
project's package executed).
- this branch: the installed `headroom init hook ensure` ran (its normal
output), nothing from the project dir.
- Not tested: Windows Git Bash.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: the Python fallback only uses an
installed headroom; a source checkout reachable only via the cwd is no
longer picked up (set `HEADROOM_BIN` or `PYTHONPATH` for that).
- Kill switch / disable path: `HEADROOM_BIN` / a `headroom` executable
on PATH bypass the fallback entirely.
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this PR

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`

## Additional Notes

No docs change needed. Fix adapted from a proposal by HetCreep (this
version uses `-P` instead of `-I` to keep `PYTHONPATH`/user-site
installs working).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Reported by @JoaoMarcos44. Thank you for your contribution! 🩵

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
Tejas Chopra
2026-11-21 16:37:02 -08:00
committed by GitHub
co-authored by Claude Opus 5.5 JerrettDavis
parent b0a8c000ca
commit c5d8f13360
9 changed files with 64 additions and 12 deletions
+1 -1
View File
@@ -69,7 +69,7 @@ def _expected_headroom_mcp_calls(proxy_url: str) -> list[list[str]]:
]
variants = [
[*prefix, *resolve_headroom_command(), "mcp", "serve"],
[*prefix, sys.executable, "-m", "headroom.cli", "mcp", "serve"],
[*prefix, sys.executable, "-P", "-m", "headroom.cli", "mcp", "serve"],
]
deduped: list[list[str]] = []
for variant in variants:
+2 -1
View File
@@ -175,7 +175,8 @@ def _reexec_with_malloc_tuning() -> None:
if not missing:
return
os.environ.update(missing)
os.execv(sys.executable, [sys.executable, "-m", "headroom.cli", *sys.argv[1:]])
# -P keeps the working directory off sys.path in the replacement process.
os.execv(sys.executable, [sys.executable, "-P", "-m", "headroom.cli", *sys.argv[1:]])
def _get_env_int_optional(name: str) -> int | None:
+3 -2
View File
@@ -107,7 +107,8 @@ def resolve_headroom_command() -> list[str]:
headroom_bin = shutil.which("headroom")
if headroom_bin:
return [headroom_bin]
return [sys.executable, "-m", "headroom.cli"]
# -P: never import a `headroom/` folder from the caller's working directory.
return [sys.executable, "-P", "-m", "headroom.cli"]
def _runtime_env(manifest: DeploymentManifest) -> dict[str, str]:
@@ -139,7 +140,7 @@ def build_runtime_command(manifest: DeploymentManifest) -> list[str]:
"""Build the raw foreground command that runs the proxy."""
if manifest.runtime_kind == RuntimeKind.PYTHON.value:
return [sys.executable, "-m", "headroom.cli", "proxy", *manifest.proxy_args]
return [sys.executable, "-P", "-m", "headroom.cli", "proxy", *manifest.proxy_args]
_ensure_host_dirs()
home = str(Path.home())
@@ -33,8 +33,11 @@ try_python() {
elif [ ! -x "$candidate" ]; then
return
fi
if "$candidate" -c 'import headroom' >/dev/null 2>&1; then
exec "$candidate" -m headroom.cli init hook ensure
# -P keeps the current directory (the user's project) off sys.path, so only
# an installed headroom is imported. Interpreters older than 3.11 reject -P
# and are skipped; headroom-ai needs 3.11+ anyway.
if "$candidate" -P -c 'import headroom' >/dev/null 2>&1; then
exec "$candidate" -P -m headroom.cli init hook ensure
fi
}
+1 -1
View File
@@ -98,6 +98,6 @@ def test_reexec_still_execs_for_a_real_cli_launch(monkeypatch: pytest.MonkeyPatc
assert len(calls) == 1
_executable, argv = calls[0]
assert argv[1:] == ["-m", "headroom.cli", "proxy", "--port", "8787"]
assert argv[1:] == ["-P", "-m", "headroom.cli", "proxy", "--port", "8787"]
for key, value in proxy_cli._MALLOC_TUNING.items():
assert proxy_cli.os.environ[key] == value
+2 -1
View File
@@ -408,7 +408,7 @@ def test_resolve_headroom_command_prefers_headroom_binary(monkeypatch) -> None:
def test_resolve_headroom_command_falls_back_to_python_module(monkeypatch) -> None:
monkeypatch.setattr("shutil.which", lambda name: None)
monkeypatch.setattr("headroom.install.runtime.sys.executable", "/usr/bin/python")
assert resolve_headroom_command() == ["/usr/bin/python", "-m", "headroom.cli"]
assert resolve_headroom_command() == ["/usr/bin/python", "-P", "-m", "headroom.cli"]
def test_runtime_env_and_mount_source(monkeypatch) -> None:
@@ -461,6 +461,7 @@ def test_build_runtime_command_python_and_docker_user(monkeypatch, tmp_path: Pat
)
assert build_runtime_command(manifest) == [
"/usr/bin/python",
"-P",
"-m",
"headroom.cli",
"proxy",
+9 -1
View File
@@ -95,7 +95,15 @@ def test_reexec_sets_vars_and_execs_once(monkeypatch):
assert proxy_cli.os.environ["_HEADROOM_MALLOC_TUNED"] == "1"
# Re-exec normalizes to `python -m headroom.cli <args>`, preserving the PID.
assert rec["path"] == "/usr/bin/python3"
assert rec["argv"] == ["/usr/bin/python3", "-m", "headroom.cli", "proxy", "--port", "8787"]
assert rec["argv"] == [
"/usr/bin/python3",
"-P",
"-m",
"headroom.cli",
"proxy",
"--port",
"8787",
]
# --------------------------------------------------------------------------- #
+1 -1
View File
@@ -80,7 +80,7 @@ def test_build_spec_falls_back_to_python_module_when_no_binary(monkeypatch) -> N
spec = build_headroom_spec()
assert spec.command == "/usr/bin/python"
assert spec.args == ("-m", "headroom.cli", "mcp", "serve")
assert spec.args == ("-P", "-m", "headroom.cli", "mcp", "serve")
assert spec.env == {}
+40 -2
View File
@@ -5,6 +5,7 @@ import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
import pytest
@@ -185,7 +186,7 @@ def test_launcher_uses_importable_python_module(tmp_path: Path) -> None:
interpreter = tmp_path / "python-fallback"
interpreter.write_text(
"#!/bin/sh\n"
'if [ "$1" = "-c" ]; then exit 0; fi\n'
'if [ "$2" = "-c" ]; then exit 0; fi\n'
'printf \'%s\\n\' "$*" >"$HEADROOM_RECEIPT"\n',
encoding="utf-8",
)
@@ -194,7 +195,44 @@ def test_launcher_uses_importable_python_module(tmp_path: Path) -> None:
result = _run_launcher(tmp_path, HEADROOM_PYTHON=_posix(interpreter))
assert result.returncode == 0
assert _receipt(tmp_path) == ["-m headroom.cli init hook ensure"]
assert _receipt(tmp_path) == ["-P -m headroom.cli init hook ensure"]
def test_launcher_python_fallback_does_not_import_from_the_working_directory(
tmp_path: Path,
) -> None:
# A real interpreter with site-packages disabled, so the only `headroom`
# it could import is the package sitting in the project directory.
interpreter = tmp_path / "python-no-site"
interpreter.write_text(
f'#!/bin/sh\nexec "{_posix(Path(sys.executable))}" -S "$@"\n', encoding="utf-8"
)
interpreter.chmod(0o755)
project = tmp_path / "project"
(project / "headroom").mkdir(parents=True)
marker = tmp_path / "marker"
for module in ("__init__.py", "cli.py"):
(project / "headroom" / module).write_text(
f"open({_posix(marker)!r}, 'a').write({module!r})\n", encoding="utf-8"
)
result = subprocess.run(
[SHELL, _posix(LAUNCHER)],
cwd=project,
env={
"HOME": _posix(tmp_path / "home"),
"PATH": "/no-such-bin",
"HEADROOM_PYTHON": _posix(interpreter),
},
capture_output=True,
text=True,
timeout=30,
check=False,
)
assert result.returncode == 0
assert not marker.exists()
assert "CLI not found" in result.stderr
def test_launcher_missing_cli_is_nonblocking(tmp_path: Path) -> None: