fix(codex): make unwrap codex remove headroom init routing (#3920)

## Description

`headroom init -g codex` writes a block into `~/.codex/config.toml` that
points Codex at the local proxy:

```toml
# --- Headroom init provider ---
model_provider = "headroom"
openai_base_url = "http://127.0.0.1:8787/v1"
...
# --- end Headroom init provider ---
```

There was no command to take it out again. `headroom unwrap codex` only
recognises the markers that `headroom wrap codex` writes, so on an
init-written config it prints "Nothing to undo" and then "✓ Codex is no
longer routed through the Headroom proxy." The routing is still there.

This matters most on Windows. `init` relies on Codex session hooks to
start the proxy, and those hooks are disabled upstream on Windows (init
already prints a warning about that). So after a reboot or a proxy
crash, Codex keeps calling `127.0.0.1:8787`, nothing restarts the proxy,
and the obvious undo command claims it worked. That matches the symptom
in #3749: Codex stuck on a dead local proxy until the override was
deleted by hand.

This PR makes `unwrap codex` remove the init block. It also makes the
Windows warning say what it means for the user, and documents how to
remove init routing.

Refs #3749. It doesn't close the issue, which also asks wider questions
about the Windows lifecycle; I'll answer those on the issue.

## 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

- `headroom/cli/wrap.py` (`_restore_codex_provider_config`): if the
config contains the `# --- Headroom init provider ---` marker, strip it
with the existing (already tested) `init._strip_codex_init_block` before
the usual wrap cleanup. The existing `cleaned` / `removed` / thread
re-tag flow then runs unchanged. `_codex_config_has_headroom_markers` is
deliberately not changed, because wrap's pre-wrap backup logic also uses
it.
- `headroom/cli/wrap.py` (`_restore_codex_provider_config`, backup
branch): a pre-wrap snapshot taken *after* `headroom init codex` carries
init's block, so restoring it verbatim left Codex pinned to the proxy
while unwrap printed "Restored". The snapshot is now passed through
`_strip_codex_init_block` too (and the config removed if nothing else is
left). The snapshot is read first and deleted only after the config has
been written, so a failed write leaves it in place for a retry instead
of losing it. Review findings from @JerrettDavis / Devin.
- `headroom/cli/init.py` (new `_strip_codex_root_routing_orphans`): the
orphan-key safety net (`model_provider = "headroom"`, loopback
`openai_base_url`) in both `_strip_codex_init_block` and wrap's
`_strip_codex_headroom_blocks` used to match anywhere in the file, so a
newly-reachable unwrap would delete user-owned `[profiles.*]` overrides.
It now only touches the document root, using the same first-table split
`_ensure_codex_provider` already uses. Neither writer ever puts these
keys inside a table. Review finding from @JerrettDavis / Devin.
- `headroom/cli/init.py` (`_init_codex`): on Windows, after the existing
hook warning, add one message. It says nothing starts the proxy there,
and points to `headroom install apply` for a supervised proxy and to
`headroom unwrap codex` (or deleting the project block) to remove the
routing.
- `docs/content/docs/proxy.mdx`: the "routing is persistent until you
remove it" sentence now says how to remove it, that unwrap leaves init's
Codex `SessionStart` hook in `hooks.json` (routing only), plus the
Windows caveat.
- Tests: five new `unwrap codex` cases: init block plus user content
(user content preserved), init-only file (file removed), init → `wrap
codex --prepare-only` → unwrap (snapshot restored without init routing),
the same sequence with the first unwrap's config write failing (snapshot
kept, a second unwrap restores it cleanly), and init → unwrap with a
`[profiles.work]` that sets `model_provider = "headroom"` + a loopback
`openai_base_url` (profile survives). One assertion added to the
existing Windows init warning test.
`TestSubscriptionRouting::test_strip_cleans_orphaned_openai_base_url`
used a key inside `[profiles.default]` as its "orphan"; it now puts the
orphan at the root and asserts a profile-level key survives.

## Testing

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

### Test Output

Both new tests fail on `main`; the failure reproduces the bug:

```text
tests/test_cli/test_wrap_codex.py FF
E   AssertionError: assert 'Nothing to undo' not in '...'
E         Nothing to undo: ...\.codex\config.toml has no Headroom wrap markers.
E       ✓ Codex is no longer routed through the Headroom proxy.
FAILED tests/test_cli/test_wrap_codex.py::test_unwrap_codex_removes_init_provider_routing
FAILED tests/test_cli/test_wrap_codex.py::test_unwrap_codex_removes_init_only_config_file
```

With this branch:

```text
$ pytest tests/test_cli/test_wrap_codex.py tests/test_cli/test_init_cli.py tests/test_cli/test_wrap_opencode.py -q -n 4
228 passed in 7.50s

$ ruff check .
All checks passed!
$ ruff format --check headroom/cli/wrap.py headroom/cli/init.py tests/test_cli/test_wrap_codex.py tests/test_cli/test_init_cli.py
4 files already formatted
$ mypy headroom --ignore-missing-imports --no-site-packages
headroom\fileperms.py:71: error: Module has no attribute "fchmod"  [attr-defined]
Found 1 error in 1 file (checked 554 source files)
```

The mypy error is the Windows-only `os.fchmod` false positive in an
untouched file; it passes on Linux CI.

The full `tests/test_cli` suite on Windows: 907 passed, 12 failed. Five
of those also fail on a clean `upstream/main` worktree with the same
environment (`test_recover_codex` ×2, `test_wrap_stale_marker`,
`test_unwrap_claude` ×2), so they're pre-existing Windows issues. The
other seven (`test_wrap_persistent`,
`test_install_apply_announces_windows_service_fallback`) only failed
under `-n 6` and pass when run serially on this branch (63 passed).

### Review round (rebased on `upstream/main` 1b7977ce)

The two new regression tests fail without the fix:

```text
E   AssertionError: assert {'model': 'gp... {'work': {}}} == {'model': 'gp....1:9999/v1'}}}
FAILED tests/test_cli/test_wrap_codex.py::test_unwrap_codex_after_init_then_wrap_removes_init_routing
FAILED tests/test_cli/test_wrap_codex.py::test_unwrap_codex_init_cleanup_keeps_profile_overrides
====================== 2 failed, 103 deselected in 1.21s ======================
```

With the fix (serial, Windows):

```text
$ pytest tests/test_cli tests/test_install/test_providers.py -q
FAILED tests/test_cli/test_install_cli.py::test_install_apply_restores_previous_deployment_after_failed_update
FAILED tests/test_cli/test_recover_codex.py::test_discover_dangling_homes_only_returns_codex_homes
FAILED tests/test_cli/test_recover_codex.py::test_recovery_never_writes_through_target_symlinks
FAILED tests/test_cli/test_unwrap_claude.py::test_unwrap_claude_removes_mcp_purges_retired_hook_and_stops_proxy
FAILED tests/test_cli/test_unwrap_claude.py::test_unwrap_claude_stops_claude_owned_persistent_deployment
FAILED tests/test_cli/test_wrap_stale_marker.py::test_signal_handler_unwinds_so_the_restore_can_run
====== 6 failed, 1026 passed, 6 skipped, 17 warnings in 90.47s (0:01:30) ======

$ ruff check headroom/cli/init.py headroom/cli/wrap.py tests/test_cli/test_wrap_codex.py tests/test_cli/test_init_cli.py
All checks passed!
$ ruff format --check (same files)
4 files already formatted
```

All six failures reproduce identically on a clean `upstream/main`
worktree in the same environment (`6 failed, 46 passed, 2 skipped` for
those files), so none come from this branch.

### Review round 2 (rebased on `upstream/main` 0d7d61d5)

`test_unwrap_codex_keeps_snapshot_when_init_cleanup_write_fails` fails
on the previous head (the snapshot was already deleted when the write
raised):

```text
E    +    where exists = WindowsPath('.../.codex/config.toml.headroom-backup').exists
FAILED tests/test_cli/test_wrap_codex.py::test_unwrap_codex_keeps_snapshot_when_init_cleanup_write_fails
====================== 1 failed, 105 deselected in 0.94s ======================
```

With the fix:

```text
$ pytest tests/test_cli/test_wrap_codex.py tests/test_cli/test_init_cli.py -q
188 passed in 9.21s
$ ruff check headroom/cli/wrap.py tests/test_cli/test_wrap_codex.py
All checks passed!
$ ruff format --check headroom/cli/wrap.py tests/test_cli/test_wrap_codex.py
2 files already formatted
$ mypy headroom --ignore-missing-imports --no-site-packages
headroomileperms.py:92: error: Module has no attribute "fchmod"; maybe "chmod"?  [attr-defined]
Found 1 error in 1 file (checked 561 source files)
```

Same Windows-only `os.fchmod` false positive as above.

## Real Behavior Proof

- Environment: Windows 11, Python 3.13, this branch vs. `upstream/main`
d5318ac2, isolated `HOME`/`USERPROFILE`/`CODEX_HOME` in a temp dir.
- Exact command / steps: wrote `model = "gpt-5"` to `config.toml`, added
the init block with `init._ensure_codex_provider(cfg, 8787)` (the same
writer `headroom init -g codex` uses), then ran the real `headroom
unwrap codex --no-stop-proxy` Click command and printed the file.
- Observed result: on `main`, unwrap prints "Nothing to undo ... has no
Headroom wrap markers." and "✓ Codex is no longer routed through the
Headroom proxy.", and the file still has `openai_base_url =
"http://127.0.0.1:8787/v1"`. On this branch it prints "Removed Headroom
block from ...\.codex\config.toml; other content preserved." and the
file is just `model = "gpt-5"`. Review round, same isolated setup with a
`[profiles.work]` table that sets `model_provider = "headroom"` and
`openai_base_url = "http://127.0.0.1:9999/v1"`: (a) `init` → `headroom
wrap codex --prepare-only --port 8787` → `headroom unwrap codex`: before
the fix the restored file still began with the full `# --- Headroom init
provider ---` block (`openai_base_url = "http://127.0.0.1:8787/v1"`);
after it, it prints "Restored prior ... from pre-wrap backup." and the
file is `model = "gpt-5"` plus the untouched profile. (b) `init` →
`unwrap`: before the fix `[profiles.work]` came back empty; after it
both profile keys survive.
- Not tested: running the full `headroom init -g codex` command end to
end (it also writes hooks and a deployment manifest, so I wrote the
block with the same function directly); a real Codex Desktop session;
project-scope `.codex/config.toml` init blocks, which `unwrap codex`
doesn't target (the docs now say to delete that block by hand).

## Runtime Rollout Safety

- Rollout-managed feature(s): none; CLI-only change to `headroom unwrap
codex` and an extra `headroom init codex` message on Windows
- Minimum rollout channel: stable
- Stable/default behavior changed: yes, narrowly. `unwrap codex` now
also removes the `# --- Headroom init provider ---` block from the
active Codex config; previously it left it in place and reported
success. The orphan-key safety net shared with `wrap codex` re-injection
is narrowed to the document root, so it no longer deletes matching keys
inside `[profiles.*]`
- Kill switch / disable path: not needed; the only new action runs when
the user explicitly runs `headroom unwrap codex`
- Unsafe override required: no
- Qualification impact: none; no proxy, compression or request-path code
changed
- Rollback path: revert this commit; `headroom init -g codex` re-adds
the routing if a user wants it back

## 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)

## Additional Notes

- Open PR #3355 also edits `_restore_codex_provider_config` (auth-helper
cleanup). The changes don't overlap logically, but whichever lands
second may need a small rebase.
- Open PR #749 (consolidated `headroom uninstall`) detects Codex only
through wrap markers, so it has the same blind spot for init routing; it
would get this for free by calling `unwrap codex`.
- Not in scope, and a maintainer call: whether `init codex` on Windows
should refuse to write routing, or should set up a supervisor, given
that nothing starts the proxy there.
- Deferred (Devin "existing Codex provider settings lost"): `init codex`
already deletes a user's prior root `model_provider` / `openai_base_url`
when it writes its block, and saves them nowhere. That is pre-existing
`init` behaviour on `main`, which this PR neither introduces nor
worsens, and there is no stored value for unwrap to restore. A clean fix
belongs in `init` (stash the replaced values inside its block, restore
them on unwrap), so I'd rather do it as a follow-up than widen this PR.

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

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3920"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
Parideboy
2026-10-07 20:59:10 -05:00
committed by GitHub
co-authored by Claude Opus 5.5 JerrettDavis
parent 70b21c12c4
commit 326079517b
5 changed files with 209 additions and 23 deletions
+7 -1
View File
@@ -912,7 +912,13 @@ headroom init -g codex # ~/.codex/config.toml, for every project
```
That routing is persistent: it applies to every Codex session in that scope
until you remove it.
until you remove it. `headroom unwrap codex` removes the `-g` routing; for a
project, delete the `# --- Headroom init provider ---` block from
`.codex/config.toml`. Unwrap removes only the routing: the Headroom
`SessionStart` hook that `init` adds to Codex's `hooks.json` stays, and still
starts a proxy when a Codex session begins until you delete it. On Windows,
nothing starts the proxy for this routing, so Codex cannot connect while the
proxy is down; use `headroom install apply` if you need a supervised proxy.
Cursor reads model endpoints from its settings UI, so `headroom wrap cursor`
does not rewrite Cursor configuration or launch the app. After it starts the
+28 -6
View File
@@ -319,6 +319,27 @@ def _remove_marker_block(content: str, marker_start: str, marker_end: str) -> st
return content[:start].rstrip() + "\n\n" + content[end:].lstrip()
def _strip_codex_root_routing_orphans(content: str) -> str:
"""Drop Headroom loopback routing keys left at the document root.
Only the root (everything before the first table header) is Headroom's to
clean: the same keys inside ``[profiles.*]`` tables are user-owned
per-profile overrides, even when they point at Headroom.
"""
import re
first_table = re.search(r"(?m)^[ \t]*\[", content)
split = first_table.start() if first_table else len(content)
root, rest = content[:split], content[split:]
root = re.sub(r'(?m)^[ \t]*model_provider[ \t]*=[ \t]*"headroom"[ \t]*\r?\n', "", root)
root = re.sub(
r'(?m)^[ \t]*openai_base_url[ \t]*=[ \t]*"http://127\.0\.0\.1:\d+/v1"[ \t]*\r?\n',
"",
root,
)
return root + rest
def _strip_codex_init_block(content: str) -> str:
"""Remove all Headroom init-managed blocks and orphan keys from a Codex config.toml string."""
import re
@@ -338,12 +359,7 @@ def _strip_codex_init_block(content: str) -> str:
# Strip any orphan top-level keys that a crashed or partial write may have
# left outside the marker block.
content = re.sub(r'(?m)^[ \t]*model_provider[ \t]*=[ \t]*"headroom"[ \t]*\r?\n', "", content)
content = re.sub(
r'(?m)^[ \t]*openai_base_url[ \t]*=[ \t]*"http://127\.0\.0\.1:\d+/v1"[ \t]*\r?\n',
"",
content,
)
content = _strip_codex_root_routing_orphans(content)
# Strip any orphaned [model_providers.headroom] table that is recognisably ours.
orphan_headroom_table = re.compile(
@@ -921,6 +937,12 @@ def _init_codex(*, global_scope: bool, profile: str, port: int) -> None:
click.echo(
"Codex hooks are currently disabled upstream on Windows; provider routing was still installed."
)
click.echo(
"Nothing starts the Headroom proxy for Codex on Windows, so Codex cannot connect "
"while it is down. Use `headroom install apply` for a supervised proxy. To remove "
"this routing, run `headroom unwrap codex` (user scope) or delete the Headroom init "
"provider block from the project's .codex/config.toml."
)
click.echo("Restart Codex to activate Headroom configuration.")
+31 -13
View File
@@ -3109,13 +3109,11 @@ def _strip_codex_headroom_blocks(
content = _remove_marker_span(content, _MEMORY_MCP_MARKER, _MEMORY_MCP_END)
# Strip any leftover top-level keys that older (or crashed) versions of
# `wrap codex` may have written outside the marker block.
content = re.sub(r'(?m)^[ \t]*model_provider[ \t]*=[ \t]*"headroom"[ \t]*\r?\n', "", content)
content = re.sub(
r'(?m)^[ \t]*openai_base_url[ \t]*=[ \t]*"http://127\.0\.0\.1:\d+/v1"[ \t]*\r?\n',
"",
content,
)
# `wrap codex` may have written outside the marker block. Root only:
# [profiles.*] overrides are the user's.
from headroom.cli.init import _strip_codex_root_routing_orphans
content = _strip_codex_root_routing_orphans(content)
# Remove an orphaned local-proxy provider structurally. Text-level table
# matching cannot safely distinguish comments, multiline strings, and
@@ -3634,7 +3632,8 @@ def _inject_codex_provider_config(port: int) -> str | None:
def _restore_codex_provider_config() -> tuple[str, Path]:
"""Undo ``_inject_codex_provider_config`` for the active Codex config file.
"""Undo ``_inject_codex_provider_config`` (and ``headroom init codex``
routing) for the active Codex config file.
Returns a tuple of ``(status, config_file)`` where status is one of:
@@ -3643,21 +3642,37 @@ def _restore_codex_provider_config() -> tuple[str, Path]:
* ``"cleaned"`` — no backup existed, but the Headroom-managed block was
found and stripped out (preserving surrounding user content).
* ``"removed"`` — the config file only contained Headroom-managed
content (created by wrap) and has been deleted.
content (created by wrap or init) and has been deleted.
* ``"noop"`` — nothing to undo; no Headroom marker and no backup.
"""
from headroom.cli.init import _CODEX_PROVIDER_MARKER_START, _strip_codex_init_block
config_file, backup_file = _codex_config_paths()
# Case 1: pre-wrap snapshot exists — restore it exactly.
if backup_file.exists():
shutil.copy2(backup_file, config_file)
# A snapshot taken after `headroom init codex` still carries init's
# routing block; restoring it verbatim would leave Codex pinned to the
# proxy while unwrap reports success (#3749). The snapshot is deleted
# only once the config is written, so a failed write can be retried.
snapshot = _read_text(backup_file)
if _CODEX_PROVIDER_MARKER_START in snapshot:
cleaned = _strip_codex_init_block(snapshot)
if not cleaned.strip():
config_file.unlink(missing_ok=True)
backup_file.unlink()
return "removed", config_file
_write_text(config_file, cleaned)
else:
shutil.copy2(backup_file, config_file)
backup_file.unlink()
return "restored", config_file
# Case 2: no backup, but config file exists and has markers — strip them.
if config_file.exists():
original = _read_text(config_file)
if _codex_config_has_headroom_markers(original):
has_init_block = _CODEX_PROVIDER_MARKER_START in original
if has_init_block or _codex_config_has_headroom_markers(original):
# Without a backup, only remove named MCP blocks when this file
# also carries wrap-owned provider markers from a full wrap.
remove_named_mcp = any(
@@ -3669,8 +3684,11 @@ def _restore_codex_provider_config() -> tuple[str, Path]:
_CODEX_MCP_END,
)
)
# `headroom init codex` writes its own routing block, and nothing else
# removes it (#3749). Strip it first so its markers go with its keys.
content = _strip_codex_init_block(original) if has_init_block else original
cleaned = _strip_codex_headroom_blocks(
original,
content,
remove_mcp=True,
remove_named_mcp=remove_named_mcp,
)
@@ -8785,7 +8803,7 @@ def unwrap_grok_build(port: int, no_stop_proxy: bool) -> None:
)
@click.option("--no-stop-proxy", is_flag=True, help="Do not stop the local Headroom proxy")
def unwrap_codex(port: int, no_stop_proxy: bool) -> None:
"""Undo ``headroom wrap codex`` edits to the active Codex config file.
"""Undo ``headroom wrap codex`` and ``headroom init codex`` routing in the Codex config.
Behaviour:
+2
View File
@@ -1368,6 +1368,8 @@ def test_init_codex_windows_warns_about_upstream_hook_limitation(monkeypatch) ->
init_cli._init_codex(global_scope=True, profile="init-user", port=9000)
assert any("disabled upstream on Windows" in message for message in messages)
# Routing to a proxy nothing restarts must come with a way out (#3749).
assert any("headroom unwrap codex" in message for message in messages)
def test_init_openclaw_propagates_nonzero_exit(monkeypatch) -> None:
+141 -3
View File
@@ -802,12 +802,18 @@ class TestSubscriptionRouting:
assert config_file.read_text(encoding="utf-8") == original
def test_strip_cleans_orphaned_openai_base_url(self) -> None:
"""Safety net: orphaned openai_base_url lines are cleaned up."""
"""Safety net: orphaned root openai_base_url lines are cleaned up.
Wrap only ever writes these keys at the document root; the same key
inside a [profiles.*] table is a user override and stays.
"""
content = (
'[profiles.default]\nmodel = "gpt-4o"\nopenai_base_url = "http://127.0.0.1:8787/v1"\n'
'openai_base_url = "http://127.0.0.1:8787/v1"\n\n'
'[profiles.default]\nmodel = "gpt-4o"\nopenai_base_url = "http://127.0.0.1:9999/v1"\n'
)
cleaned = wrap_mod._strip_codex_headroom_blocks(content)
assert "openai_base_url" not in cleaned
assert "127.0.0.1:8787" not in cleaned
assert 'openai_base_url = "http://127.0.0.1:9999/v1"' in cleaned
assert 'model = "gpt-4o"' in cleaned
def test_no_env_key_in_injected_provider(
@@ -2137,6 +2143,138 @@ def test_unwrap_codex_preserves_unrelated_sections(
assert restored == original
def test_unwrap_codex_removes_init_provider_routing(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""`headroom init -g codex` routing must be removable with `unwrap codex` (#3749).
Without this, unwrap reported "no longer routed" while Codex stayed pinned
to a local proxy that nothing restarts on Windows.
"""
from headroom.cli import init as init_cli
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
original = 'model = "gpt-5"\n\n[mcp_servers.local_thing]\ncommand = "thing"\n'
config_file.write_text(original, encoding="utf-8")
init_cli._ensure_codex_provider(config_file, 8787)
assert 'openai_base_url = "http://127.0.0.1:8787/v1"' in config_file.read_text(encoding="utf-8")
result = runner.invoke(main, ["unwrap", "codex", "--no-stop-proxy"])
assert result.exit_code == 0, result.output
assert "Nothing to undo" not in result.output
cleaned = config_file.read_text(encoding="utf-8")
assert "Headroom init provider" not in cleaned
assert "openai_base_url" not in cleaned
assert "model_providers.headroom" not in cleaned
assert tomllib.loads(cleaned) == tomllib.loads(original)
def test_unwrap_codex_removes_init_only_config_file(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
from headroom.cli import init as init_cli
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
init_cli._ensure_codex_provider(config_file, 8787)
result = runner.invoke(main, ["unwrap", "codex", "--no-stop-proxy"])
assert result.exit_code == 0, result.output
assert not config_file.exists()
def test_unwrap_codex_after_init_then_wrap_removes_init_routing(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""init -> persistent wrap -> unwrap: the pre-wrap snapshot holds init's
routing, so restoring it verbatim left Codex pinned to the proxy."""
from headroom.cli import init as init_cli
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
original = 'model = "gpt-5"\n\n[mcp_servers.local_thing]\ncommand = "thing"\n'
config_file.write_text(original, encoding="utf-8")
init_cli._ensure_codex_provider(config_file, 8787)
runner.invoke(main, ["wrap", "codex", "--prepare-only", "--port", "8787"])
assert wrap_mod._codex_config_paths()[1].exists()
result = runner.invoke(main, ["unwrap", "codex", "--no-stop-proxy"])
assert result.exit_code == 0, result.output
assert "Restored prior" in result.output
restored = config_file.read_text(encoding="utf-8")
assert "Headroom init provider" not in restored
assert "127.0.0.1:8787" not in restored
assert tomllib.loads(restored) == tomllib.loads(original)
def test_unwrap_codex_keeps_snapshot_when_init_cleanup_write_fails(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""A failed write of the init-cleaned snapshot must not consume the
snapshot, or a retry has nothing left to restore."""
from headroom.cli import init as init_cli
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
original = 'model = "gpt-5"\n\n[mcp_servers.local_thing]\ncommand = "thing"\n'
config_file.write_text(original, encoding="utf-8")
init_cli._ensure_codex_provider(config_file, 8787)
runner.invoke(main, ["wrap", "codex", "--prepare-only", "--port", "8787"])
backup_file = wrap_mod._codex_config_paths()[1]
assert backup_file.exists()
def failing_write(path: Path, content: str) -> None:
raise OSError("disk full")
with monkeypatch.context() as m:
m.setattr(wrap_mod, "_write_text", failing_write)
failed = runner.invoke(main, ["unwrap", "codex", "--no-stop-proxy"])
assert failed.exit_code != 0
assert backup_file.exists()
result = runner.invoke(main, ["unwrap", "codex", "--no-stop-proxy"])
assert result.exit_code == 0, result.output
assert "Restored prior" in result.output
restored = config_file.read_text(encoding="utf-8")
assert "127.0.0.1:8787" not in restored
assert tomllib.loads(restored) == tomllib.loads(original)
def test_unwrap_codex_init_cleanup_keeps_profile_overrides(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Orphan cleanup is root-only: [profiles.*] routing keys are user-owned,
even when they point at a Headroom proxy."""
from headroom.cli import init as init_cli
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
original = (
'model = "gpt-5"\n\n'
"[profiles.work]\n"
'model_provider = "headroom"\n'
'openai_base_url = "http://127.0.0.1:9999/v1"\n'
)
config_file.write_text(original, encoding="utf-8")
init_cli._ensure_codex_provider(config_file, 8787)
result = runner.invoke(main, ["unwrap", "codex", "--no-stop-proxy"])
assert result.exit_code == 0, result.output
assert tomllib.loads(config_file.read_text(encoding="utf-8")) == tomllib.loads(original)
assert tomllib.loads(wrap_mod._strip_codex_headroom_blocks(original)) == tomllib.loads(original)
# ---------------------------------------------------------------------------
# Per-project savings: env_http_headers in the injected provider block
# ---------------------------------------------------------------------------