Files
headroom/tests/test_cli/test_wrap_claude_finally_unbound.py
07b4511537 [codex] Make Claude project settings injection opt in (#1600)
## Description

Closes #1599

`headroom wrap claude` now applies routing in the child environment by
default, leaving project-local settings untouched. `--project-settings`
or `HEADROOM_CLAUDE_PROJECT_SETTINGS=1` explicitly enables project-local
routing writes. This prevents ordinary wraps from leaving routing state
that affects daemon-spawned workers or later direct Claude sessions.
Existing opt-in ownership, selected-port routing, Foundry/Vertex
behavior, and cleanup are retained.

Opted-in cleanup ownership is recorded immediately after the base-URL
write. If self-heal hook installation fails afterward, the original base
URL and user settings are restored and the session marker cleared. The
runtime settings lock file is removed from version control and ignored.

## Validation

### Test Output

```text
132 focused tests passed
63 related lifecycle/Foundry tests passed; 1 SIGHUP-only case excluded on Windows
Ruff lint/format and whitespace: pass
Linux-target mypy: Success: no issues found in 566 source files
REAL CLI opt_in=False: child process used proxy URL; user base URL restored; session marker absent.
REAL CLI opt_in=True: child process used proxy URL; user base URL restored; session marker absent.
```

The exception regression performs real settings-file writes. The runtime
smoke launches a real local fake-Claude child process; default mode
preserves settings byte-for-byte, and opt-in restores the user base URL.
Fresh hosted CI and review remain pending at
`b6999e0b566093e767474cd44d3143c8da506e91`.

## Runtime Rollout Safety

Project writes require explicit opt-in. Default mode scopes routing to
the launched child and preserves project state. Opted-in writes retain
ownership-aware restoration, including the hook-install failure path,
with Vertex and Foundry routing covered by regressions.


### Current validation (2026-10-08, 1a97aeae9)

Default wraps recover the project URL recorded by an older crashed wrap
before launch, but only when the current URL still belongs to that
writer. A manually repaired URL remains byte-for-byte unchanged;
recovery retires only the stale marker. Recovery and opted-in settings
writers share the same settings lock, preventing retirement of a newer
session marker. Windows lock initialization checks file-size metadata
instead of reading a byte locked by another writer.

Four process-level smoke cases use the actual Headroom CLI and a
separate local child executable reading its environment and on-disk
settings: fresh default, opt-in with restoration, default with a stale
marker, and default with a manually repaired URL. All pass on this head.
This proves CLI/environment/settings lifecycle and does not claim
authenticated Claude API traffic. The smoke checks the real marker path;
a synchronization lock may remain after recovery of existing stale
state, while fresh default creates no wrap artifacts.

99 lifecycle tests and 82 concurrency/lock-helper tests pass; one
pre-existing Windows unwrap-hook test remains excluded after reproducing
the same failure on unchanged b6999e0b5. Ruff lint/format, whitespace,
and Linux-target mypy (566 files) pass. Approval is held for
current-head hosted CI and review.

---------

Co-authored-by: JD Davis <jd@jds-macbook-air.tail2a279.ts.net>
Co-authored-by: Jerrett Davis <mxjerrett@gmail.com>
2026-10-08 11:12:35 -05:00

70 lines
2.4 KiB
Python

"""Regression: `wrap claude`'s finally must not raise UnboundLocalError when the
proxy fails to start before `_wrap_settings_path` is assigned inside the try."""
from __future__ import annotations
import pytest
from click.testing import CliRunner
from headroom.cli import wrap as wrap_mod
from headroom.cli.main import main
@pytest.fixture
def runner() -> CliRunner:
return CliRunner()
def test_finally_survives_early_proxy_start_failure(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch
) -> None:
state = {"restore_called": False, "cleanup_called": False}
for key in (
"ANTHROPIC_BASE_URL",
"ANTHROPIC_VERTEX_BASE_URL",
"ANTHROPIC_FOUNDRY_BASE_URL",
"ANTHROPIC_FOUNDRY_RESOURCE",
"HEADROOM_CLAUDE_PROJECT_SETTINGS",
"CLAUDE_CODE_USE_VERTEX",
"CLAUDE_CODE_USE_FOUNDRY",
"VERTEX_TARGET_API_URL",
):
monkeypatch.delenv(key, raising=False)
monkeypatch.setattr(wrap_mod.shutil, "which", lambda _name: "/usr/bin/claude")
monkeypatch.setattr(wrap_mod, "_register_proxy_client", lambda _port, session_token=None: None)
monkeypatch.setattr(wrap_mod.signal, "signal", lambda *_a, **_k: None)
monkeypatch.setattr(wrap_mod, "_push_runtime_env", lambda *_a, **_k: None)
monkeypatch.setattr(wrap_mod, "_setup_coding_compressor", lambda *_a, **_k: None)
monkeypatch.setattr(wrap_mod, "_print_telemetry_notice", lambda: None)
monkeypatch.setattr(wrap_mod, "_write_claude_wrap_base_url", lambda *_a, **_k: None)
def _fake_make_cleanup(_holder, _port):
def _cleanup() -> None:
state["cleanup_called"] = True
return _cleanup
monkeypatch.setattr(wrap_mod, "_make_cleanup", _fake_make_cleanup)
def _fake_restore(*_a, **_k) -> None:
state["restore_called"] = True
monkeypatch.setattr(wrap_mod, "_restore_claude_wrap_base_url", _fake_restore)
def _boom(*_a, **_k):
raise RuntimeError("proxy failed to start")
monkeypatch.setattr(wrap_mod, "_ensure_proxy", _boom)
result = runner.invoke(
main,
["wrap", "claude", "--no-mcp", "--no-tokensave", "--no-serena"],
)
# The finally must complete without masking the real failure, skip restoring settings that this run never wrote, and still clean up.
assert not isinstance(result.exception, UnboundLocalError), result.output
assert state["restore_called"] is False
assert state["cleanup_called"] is True