headroom/tests/test_cli/test_unwrap_claude.py
JD Davis ddd2a259ec
fix(install): consolidate Windows fallback and cleanup safety (#2980)
## Description

Consolidates two fully reviewed installation-safety fixes whose original
PRs can no longer merge under current branch protection: Windows
persistent-service deployments need a supported Task Scheduler fallback,
and legacy context-tool cleanup must never delete user-owned
RTK/lean-ctx artifacts.

Closes #2552
Closes #2817

Supersedes #2600 and #2828 while preserving their authors' commits and
review-driven corrections.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- Convert Windows `persistent-service` plans to the supported
`persistent-task` supervisor and make the fallback explicit in CLI
output.
- Restrict context-tool cleanup to artifacts proven to live under
Headroom's managed directory.
- Recognize wrapped, relative, and platform-specific managed commands
without accepting prefixed/path-boundary lookalikes.
- Scope cleanup completion state correctly across projects and alternate
agent homes.
- Stamp cleanup complete only after all managed remnants are settled.
- Preserve the original focused regression suites and behavior-proof
artifact.

## Testing

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

### Test Output

```text
$ uv run pytest -q tests/test_install/test_planner.py tests/test_install/test_supervisors.py tests/test_cli/test_install_cli.py tests/test_context_tool_cleanup.py tests/test_cli/test_unwrap_claude.py
135 passed in 0.45s

$ uv run ruff check <changed Python and test files>
All checks passed!

$ uv run ruff format --check <changed Python and test files>
8 files already formatted
```

## Real Behavior Proof

- Environment: macOS arm64 for consolidated current-main validation; the
Windows fallback source PR was independently validated on Windows and
includes its captured verification artifact.
- Exact command / steps: run the planner, supervisor, install CLI,
cleanup provenance, and unwrap suites on the rebased combined branch.
- Observed result: 135/135 focused tests pass. Windows service requests
resolve to `persistent-task`; cleanup rejects user-owned and path-prefix
lookalikes while removing managed artifacts.
- Not tested: a fresh privileged Windows host deployment in this local
pass; #2600's accepted review contains the Windows-specific proof.

## Runtime Rollout Safety

- Rollout-managed feature(s): Install supervisor selection and one-time
legacy cleanup.
- Minimum rollout channel: Stable/default; both prevent currently
destructive or nonfunctional install paths.
- Stable/default behavior changed: Windows service requests use Task
Scheduler; cleanup requires managed provenance.
- Kill switch / disable path: Select `persistent-task` explicitly;
cleanup remains bounded by its completion stamp and provenance checks.
- Unsafe override required: No.
- Qualification impact: Windows native install and wrap/unwrap cleanup
suites.
- Rollback path: Revert this PR, restoring the two pre-fix behaviors.

## 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
- [x] 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` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

The Windows verification artifact from #2600 is retained at
`.github/pr-images/issue-2552-windows-fallback-verification.png`.

## Additional Notes

This is intentionally an installation-safety batch rather than two
replacement PRs. Original commit authorship is preserved, and the
combined diff was applied cleanly to current `main` after #2832 and
#1628 landed.

---------

Co-authored-by: Inference1 <68734681+Inference1@users.noreply.github.com>
Co-authored-by: Dennis Alexis Valin Dittrich <dd+github@dr-dittrich.de>
2026-08-13 15:05:45 -05:00

472 lines
16 KiB
Python

from __future__ import annotations
import json
from pathlib import Path
from unittest.mock import patch
import pytest
from click.testing import CliRunner
from headroom import paths
from headroom.cli import wrap as wrap_cli
from headroom.cli.main import main
@pytest.fixture
def runner() -> CliRunner:
return CliRunner()
@pytest.fixture(autouse=True)
def _no_persistent_manifest(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(wrap_cli, "_find_persistent_manifest", lambda _port: None)
def test_remove_claude_managed_hooks_preserves_unrelated_hooks(tmp_path: Path) -> None:
settings = tmp_path / "settings.json"
settings.write_text(
json.dumps(
{
"model": "opus",
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": (
"headroom init hook ensure --marker headroom-init-claude"
),
},
{"type": "command", "command": "echo keep"},
],
}
],
"SessionStart": [
{"matcher": "startup", "hooks": [{"type": "command", "command": "keep"}]}
],
},
}
)
+ "\n",
encoding="utf-8",
)
assert wrap_cli._remove_claude_managed_hooks(settings) is True
payload = json.loads(settings.read_text(encoding="utf-8"))
pre_tool_hooks = payload["hooks"]["PreToolUse"][0]["hooks"]
assert pre_tool_hooks == [{"type": "command", "command": "echo keep"}]
assert payload["hooks"]["SessionStart"][0]["hooks"][0]["command"] == "keep"
def test_unwrap_claude_removes_mcp_purges_retired_hook_and_stops_proxy(
runner: CliRunner,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
home = str(tmp_path)
monkeypatch.setenv("HOME", home)
monkeypatch.setenv("USERPROFILE", home)
monkeypatch.delenv("HEADROOM_WORKSPACE_DIR", raising=False)
bin_dir = paths.bin_dir()
claude_dir = tmp_path / ".claude"
claude_dir.mkdir()
hooks_dir = claude_dir / "hooks"
hooks_dir.mkdir()
hook_script = hooks_dir / "rtk-rewrite.sh"
hook_script.write_text(f'#!/bin/sh\nexec {bin_dir / "rtk"} "$@"\n', encoding="utf-8")
settings = claude_dir / "settings.json"
settings.write_text(
json.dumps(
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [{"type": "command", "command": str(hook_script)}],
}
]
}
}
)
+ "\n",
encoding="utf-8",
)
stopped: list[int] = []
unregistered: list[str] = []
class Registrar:
name = "claude"
def detect(self) -> bool:
return True
def unregister_server(self, server_name: str) -> bool:
unregistered.append(server_name)
return True
def get_server(self, server_name: str):
return None
with (
patch("headroom.mcp_registry.ClaudeRegistrar", return_value=Registrar()),
patch(
"headroom.cli.wrap._stop_local_proxy_for_unwrap",
side_effect=lambda port: stopped.append(port) or "stopped",
),
):
result = runner.invoke(main, ["unwrap", "claude", "--port", "9999"])
assert result.exit_code == 0, result.output
assert unregistered == ["headroom", "codebase-memory-mcp"]
assert stopped == [9999]
assert "Stopped local Headroom proxy on port 9999" in result.output
# The leftover retired context-tool hook is purged end-to-end by unwrap
# (via purge_context_tool_artifacts), leaving no hooks behind.
assert "hooks" not in json.loads(settings.read_text(encoding="utf-8"))
def test_unwrap_claude_preserves_user_managed_serena(
runner: CliRunner,
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path / ".headroom"))
unregistered: list[str] = []
class Registrar:
name = "claude"
def detect(self) -> bool:
return True
def unregister_server(self, server_name: str) -> bool:
unregistered.append(server_name)
return True
def get_server(self, server_name: str):
if server_name == "serena":
from headroom.mcp_registry.base import ServerSpec
return ServerSpec(name="serena", command="/usr/local/bin/custom-serena")
return None
with (
patch("headroom.mcp_registry.ClaudeRegistrar", return_value=Registrar()),
patch("headroom.cli.wrap._remove_claude_managed_hooks", return_value=False),
patch("headroom.cli.wrap._stop_local_proxy_for_unwrap"),
):
result = runner.invoke(main, ["unwrap", "claude"])
assert result.exit_code == 0, result.output
assert unregistered == ["headroom", "codebase-memory-mcp"]
def test_unwrap_claude_removes_headroom_installed_serena(
runner: CliRunner,
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path / ".headroom"))
from headroom.mcp_registry import build_serena_spec
from headroom.mcp_registry.ledger import record_install
serena_spec = build_serena_spec("claude-code")
record_install("claude", serena_spec)
unregistered: list[str] = []
class Registrar:
name = "claude"
def detect(self) -> bool:
return True
def unregister_server(self, server_name: str) -> bool:
unregistered.append(server_name)
return True
def get_server(self, server_name: str):
if server_name == "serena":
return serena_spec
return None
with (
patch("headroom.mcp_registry.ClaudeRegistrar", return_value=Registrar()),
patch("headroom.cli.wrap._remove_claude_managed_hooks", return_value=False),
patch("headroom.cli.wrap._stop_local_proxy_for_unwrap"),
):
result = runner.invoke(main, ["unwrap", "claude"])
assert result.exit_code == 0, result.output
assert unregistered == ["headroom", "codebase-memory-mcp", "serena"]
assert "Removed Headroom-installed Serena MCP server" in result.output
def test_unwrap_claude_keep_flags_skip_cleanup(
runner: CliRunner,
) -> None:
with (
patch("headroom.mcp_registry.ClaudeRegistrar") as registrar,
patch("headroom.cli.wrap._remove_claude_managed_hooks", return_value=False),
patch("headroom.cli.wrap._stop_local_proxy_for_unwrap") as stop_proxy,
):
result = runner.invoke(
main,
["unwrap", "claude", "--keep-mcp", "--no-stop-proxy"],
)
assert result.exit_code == 0, result.output
registrar.assert_not_called()
stop_proxy.assert_not_called()
def test_unwrap_claude_restores_all_base_url_modes(runner: CliRunner) -> None:
restore_calls: list[dict[str, object]] = []
def restore_base_url(previous: str | None, **kwargs: object) -> None:
restore_calls.append({"previous": previous, **kwargs})
with patch("headroom.cli.wrap._restore_claude_wrap_base_url", side_effect=restore_base_url):
result = runner.invoke(
main,
["unwrap", "claude", "--keep-mcp", "--no-stop-proxy"],
)
assert result.exit_code == 0, result.output
settings_path = Path.cwd() / ".claude" / "settings.local.json"
assert restore_calls == [
{
"previous": None,
"foundry_mode": False,
"vertex_mode": False,
"settings_path": settings_path,
},
{
"previous": None,
"foundry_mode": True,
"vertex_mode": False,
"settings_path": settings_path,
},
{
"previous": None,
"foundry_mode": False,
"vertex_mode": True,
"settings_path": settings_path,
},
]
def test_unwrap_claude_stops_claude_owned_persistent_deployment(
runner: CliRunner,
monkeypatch: pytest.MonkeyPatch,
) -> None:
class Manifest:
profile = "unwrap-2340"
targets = ["claude"]
tool_envs = {"claude": {"ANTHROPIC_BASE_URL": "http://127.0.0.1:8787"}}
mutations: list[object] = []
supervisor_kind = "service"
stopped: list[str] = []
deactivated: list[str] = []
monkeypatch.setattr(wrap_cli, "_find_persistent_manifest", lambda port: Manifest())
monkeypatch.setattr(
"headroom.cli.install._deactivate_deployment_mutations",
lambda manifest: deactivated.append(manifest.profile),
)
monkeypatch.setattr(
"headroom.cli.install._stop_deployment",
lambda manifest: stopped.append(manifest.profile),
)
with (
patch("headroom.cli.wrap._stop_local_proxy_for_unwrap") as stop_local,
):
result = runner.invoke(
main,
["unwrap", "claude", "--keep-mcp", "--port", "8787"],
)
assert result.exit_code == 0, result.output
stop_local.assert_not_called()
assert deactivated == ["unwrap-2340"]
assert stopped == ["unwrap-2340"]
assert "Stopped Claude-owned persistent deployment 'unwrap-2340' on port 8787." in result.output
assert "Claude is no longer durably wrapped by Headroom." in result.output
def test_unwrap_claude_reports_ambiguous_same_port_persistent_deployment(
runner: CliRunner,
monkeypatch: pytest.MonkeyPatch,
) -> None:
class Manifest:
profile = "shared-proxy"
targets = ["codex"]
tool_envs = {"codex": {"OPENAI_BASE_URL": "http://127.0.0.1:8787"}}
mutations: list[object] = []
supervisor_kind = "service"
monkeypatch.setattr(wrap_cli, "_find_persistent_manifest", lambda port: Manifest())
with patch("headroom.cli.wrap._stop_local_proxy_for_unwrap") as stop_local:
result = runner.invoke(
main,
["unwrap", "claude", "--keep-mcp", "--port", "8787"],
)
assert result.exit_code == 0, result.output
stop_local.assert_not_called()
assert "same-port persistent deployment 'shared-proxy' still owns port 8787" in result.output
assert "headroom install stop --profile shared-proxy" in result.output
assert "Claude is no longer durably wrapped by Headroom." not in result.output
def test_unwrap_claude_warns_about_same_port_inherited_env(
runner: CliRunner,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("ANTHROPIC_BASE_URL", "http://127.0.0.1:8787")
with patch("headroom.cli.wrap._stop_local_proxy_for_unwrap", return_value="stopped"):
result = runner.invoke(
main,
["unwrap", "claude", "--keep-mcp", "--port", "8787"],
)
assert result.exit_code == 0, result.output
assert "current shell still exports ANTHROPIC_BASE_URL for port 8787" in result.output
assert "Claude is no longer durably wrapped by Headroom." not in result.output
def test_unwrap_claude_ignores_malformed_inherited_env_port(
runner: CliRunner,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("ANTHROPIC_BASE_URL", "http://127.0.0.1:notaport")
with patch("headroom.cli.wrap._stop_local_proxy_for_unwrap", return_value="stopped"):
result = runner.invoke(
main,
["unwrap", "claude", "--keep-mcp", "--port", "8787"],
)
assert result.exit_code == 0, result.output
assert "current shell still exports ANTHROPIC_BASE_URL" not in result.output
assert "Claude is no longer durably wrapped by Headroom." in result.output
def test_remove_claude_managed_hooks_removes_init_hooks_and_env(tmp_path: Path) -> None:
settings = tmp_path / "settings.json"
settings.write_text(
json.dumps(
{
"model": "opus",
"env": {"ANTHROPIC_BASE_URL": "http://127.0.0.1:8787", "FOO": "bar"},
"hooks": {
"SessionStart": [
{
"matcher": "startup|resume",
"hooks": [
{
"type": "command",
"command": (
"/home/u/.local/bin/headroom init hook ensure "
"--profile init-user --marker headroom-init-claude"
),
"timeout": 15,
}
],
}
],
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "headroom init hook ensure --marker headroom-init-claude",
},
{"type": "command", "command": "echo keep-me"},
],
}
],
},
}
)
+ "\n",
encoding="utf-8",
)
assert wrap_cli._remove_claude_managed_hooks(settings) is True
payload = json.loads(settings.read_text(encoding="utf-8"))
# ANTHROPIC_BASE_URL stripped; unrelated env var preserved
assert payload.get("env") == {"FOO": "bar"}
# SessionStart removed entirely (its only hook was the init marker)
assert "SessionStart" not in payload.get("hooks", {})
# PreToolUse: init-marker hook gone, unrelated hook kept
assert payload["hooks"]["PreToolUse"][0]["hooks"] == [
{"type": "command", "command": "echo keep-me"}
]
assert payload["model"] == "opus"
def test_remove_claude_managed_hooks_strips_env_without_hooks(tmp_path: Path) -> None:
# Regression: unwrap previously returned early when no hooks existed,
# leaving init's ANTHROPIC_BASE_URL behind in settings.json.
settings = tmp_path / "settings.json"
settings.write_text(
json.dumps({"env": {"ANTHROPIC_BASE_URL": "http://127.0.0.1:8787"}}) + "\n",
encoding="utf-8",
)
assert wrap_cli._remove_claude_managed_hooks(settings) is True
payload = json.loads(settings.read_text(encoding="utf-8"))
assert "env" not in payload # emptied env dict is dropped
def test_remove_claude_managed_hooks_noop_when_nothing_managed(tmp_path: Path) -> None:
settings = tmp_path / "settings.json"
original = {
"model": "opus",
"env": {"FOO": "bar"},
"hooks": {
"PreToolUse": [
{"matcher": "Bash", "hooks": [{"type": "command", "command": "echo hi"}]}
]
},
}
settings.write_text(json.dumps(original) + "\n", encoding="utf-8")
assert wrap_cli._remove_claude_managed_hooks(settings) is False
# nothing managed -> file untouched
assert json.loads(settings.read_text(encoding="utf-8")) == original
def test_remove_claude_managed_hooks_strips_enable_tool_search(tmp_path: Path) -> None:
# unwrap must remove BOTH env vars init writes (ANTHROPIC_BASE_URL +
# ENABLE_TOOL_SEARCH, GH #746), leaving user-set vars intact.
settings = tmp_path / "settings.json"
settings.write_text(
json.dumps(
{
"env": {
"ANTHROPIC_BASE_URL": "http://127.0.0.1:8787",
"ENABLE_TOOL_SEARCH": "true",
"KEEP": "1",
}
}
)
+ "\n",
encoding="utf-8",
)
assert wrap_cli._remove_claude_managed_hooks(settings) is True
payload = json.loads(settings.read_text(encoding="utf-8"))
assert payload["env"] == {"KEEP": "1"}