Files
headroom/tests/test_cli/test_wrap_codex.py
2649835a51 feat(wrap): make the Serena code-memory MCP opt-in (#4509)
## What changes

`headroom wrap claude|codex|grok|opencode` no longer registers Serena by
default.

| | Before | After |
|---|---|---|
| Default | Serena registered | No code-memory MCP |
| Opt in | (default) | `--code-memory serena` or
`HEADROOM_CODE_MEMORY=serena` (deprecated `--serena` still works) |
| Opt out | `--code-memory none` / `--no-serena` | Still accepted |
| Upgrading user, Serena installed by Headroom | Kept | Removed on next
wrap, with the message "Serena is now off by default; pass --code-memory
serena to keep it" |
| Upgrading user, Serena added by hand | Kept | Kept, no message (shown
only with `--verbose` or an explicit opt-out) |

OpenCode now accepts `--code-memory` and uses the same setup path as the
other agents. Its `--no-serena` flag is hidden and deprecated.

## Why

Measured on 2026-10-27, Serena started exactly as `wrap` registers it:

- It adds 22 tools, about 5.9K tokens of tool definitions on every
request where tools aren't deferred. Its server instruction tells the
model to call `initial_instructions`, which costs another 2K tokens.
- Each launch takes about 6 s cold via `uvx`, plus a background `serena
project index` that starts language servers. It also writes a `.serena/`
folder into the user's repo.
- Serena was registered in 6 of our own Claude Code sessions and called
0 times. Separately, an offline replay of about 108K tool calls found
that symbol-level reads have little to recover for Claude Code.

## Not in this PR

- `headroom.integrations.strands` still defaults
`enable_serena_mcp=True`. It's public integration API, so it needs a
deprecation step instead of a silent flip.
- The opt-in `--serena-instructions` block in CLAUDE.md/AGENTS.md is
never removed, by unwrap or anything else. Users who opted into it keep
instructions that point at tools no longer registered. This predates
this PR and will be fixed separately.
- For Claude Code, Serena entries are per project, so removal happens
the next time `wrap` or `unwrap` runs in each project. The docs say so.

## Tests

- `pytest tests/test_wrap_code_memory.py tests/test_cli
tests/test_mcp_registry`: 1368 passed. 5 failed, and those 5 fail the
same way on `main` in my local venv:
`test_mcp_reconcile.py::test_ordinary_install_does_not_adopt_serena` and
4 in `test_wrap_persistent.py`, all from an environment/install
mismatch.
- New tests:
- The default wrap removes a Serena entry Headroom installed and prints
how to keep it.
- The default wrap leaves a hand-added Serena alone and prints nothing.
  - `--serena --no-serena` resolves to none.
- `wrap opencode --code-memory serena` registers Serena with the `agent`
context.
- `ruff check`, `ruff format --check` and `mypy` are clean on the
changed files.

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

## Real Behavior Proof

- **Environment:** macOS (Darwin 27.2), Python 3.12.13, Claude Code
2.1.318, real `claude` CLI doing every `claude mcp add`/`remove`. A
temporary `HOME`, so `~/.claude.json` starts empty, and a fresh git repo
per case.
- **Builds:** "before" = `main` at `12864fc8`; "after" = this PR at
`56557dc9`.
- **Command:** `headroom wrap claude --no-proxy [flags] -- --version`.
Wrap does its full MCP setup, then launches Claude Code, which prints
its version and exits, so no model call is made. `state` is read from
`~/.claude.json` (user scope and this project's local scope) and the
project's `.mcp.json` after each run.

```
== 1. Upgrade: Serena installed by Headroom (project/local scope)
    $ headroom wrap claude --no-proxy -- --version    (cwd=projA, build=12864fc8)
    exit=0
    wrap|   Serena MCP: registered (restart Claude Code if it was already running)
    wrap|     scoped to this project — pass --code-memory-scope user to register it for every Claude Code session
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projA): ['serena'] | .mcp.json: -
    $ headroom wrap claude --no-proxy -- --version    (cwd=projA, build=56557dc9)
    exit=0
    wrap|   Removed previously-installed Serena MCP (Serena is now off by default; pass --code-memory serena to keep it)
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projA): - | .mcp.json: -

== 2. Upgrade: Serena added by hand (claude mcp add)
    state| user: ['headroom'] | local(projB): ['serena'] | .mcp.json: -
    $ headroom wrap claude --no-proxy -- --version    (cwd=projB, build=56557dc9)
    exit=0
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projB): ['serena'] | .mcp.json: -
    $ headroom wrap claude --no-proxy --code-memory none -- --version    (cwd=projB, build=56557dc9)
    exit=0
    wrap|   Serena MCP is present but user-managed — leaving it in place (Headroom only removes entries it installed)
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projB): ['serena'] | .mcp.json: -

== 3. Explicit opt-in, then rollback to the default
    $ headroom wrap claude --no-proxy --code-memory serena -- --version    (cwd=projC, build=56557dc9)
    exit=0
    wrap|   Serena MCP: registered (restart Claude Code if it was already running)
    wrap|     scoped to this project — pass --code-memory-scope user to register it for every Claude Code session
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projC): ['serena'] | .mcp.json: -
    $ headroom wrap claude --no-proxy -- --version    (cwd=projC, build=56557dc9)
    exit=0
    wrap|   Removed previously-installed Serena MCP (Serena is now off by default; pass --code-memory serena to keep it)
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projC): - | .mcp.json: -
    $ headroom wrap claude --no-proxy -- --version    (cwd=projC, build=56557dc9)
    exit=0
    wrap|   Serena MCP: registered (restart Claude Code if it was already running)
    wrap|     scoped to this project — pass --code-memory-scope user to register it for every Claude Code session
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projC): ['serena'] | .mcp.json: -
    $ headroom wrap claude --no-proxy --serena -- --version    (cwd=projC, build=56557dc9)
    exit=0
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projC): ['serena'] | .mcp.json: -

== 4. User scope: installed by Headroom with --code-memory-scope user
    $ headroom wrap claude --no-proxy --code-memory-scope user -- --version    (cwd=projD, build=12864fc8)
    exit=0
    wrap|   Serena MCP: registered (restart Claude Code if it was already running)
    wrap|     registered for every Claude Code session on this machine (--code-memory-scope user)
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom', 'serena'] | local(projD): - | .mcp.json: -
    $ headroom wrap claude --no-proxy -- --version    (cwd=projD, build=56557dc9)
    exit=0
    wrap|   Removed previously-installed Serena MCP (Serena is now off by default; pass --code-memory serena to keep it)
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projD): - | .mcp.json: -

== 5. User scope opt-in on the PR build
    $ headroom wrap claude --no-proxy --code-memory serena --code-memory-scope user -- --version    (cwd=projE, build=56557dc9)
    exit=0
    wrap|   Serena MCP: registered (restart Claude Code if it was already running)
    wrap|     registered for every Claude Code session on this machine (--code-memory-scope user)
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom', 'serena'] | local(projE): - | .mcp.json: -
    $ headroom wrap claude --no-proxy -- --version    (cwd=projE, build=56557dc9)
    exit=0
    wrap|   Removed previously-installed Serena MCP (Serena is now off by default; pass --code-memory serena to keep it)
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projE): - | .mcp.json: -
```

What this shows:
1. A Serena entry Headroom installed on `main` is removed on the first
wrap after upgrading, with the "off by default" message. This holds for
both scopes (cases 1 and 4).
2. A hand-added Serena entry is kept, and the default wrap prints
nothing. `--code-memory none` keeps it and says it's user-managed (case
2).
3. Opting in works with `--code-memory serena`,
`HEADROOM_CODE_MEMORY=serena` and the deprecated `--serena`, at project
scope and user scope (cases 3 and 5). Running the default afterwards
rolls it back.
4. Project scope here means Claude Code's `local` scope, which is where
wrap registers. Wrap never writes `.mcp.json`.

Not tested live: `wrap codex|grok|opencode` (unit tests only), Windows,
and an interactive Claude session that calls Serena tools.

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

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4509"
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 -->

## Maintainer post-merge qualification
Published `983b6bb15119a3ecb8f6e20bf014b8bed123e95d` includes upstream
main `e4a60ed72f6ef5b28569f8bfbe2163cfda32c948`. 19 selector/Serena
tests pass,1optional skip; Ruff/format/diff pass. Clean main sync;
contributor selector/ownership code unchanged. Existing real
upgrade/configuration/launch proof requirement remains; jCodeMunch
proposal is unrelated to this source delta. Contributor correctness
logic was not rewritten. Existing Changes Requested decision retained
without duplicate findings. Scoped Windows validation uses the existing
development native extension, not a fresh build. Hosted qualification is
handled by maintainers; nothing merged.


### Maintainer current-main requalification

Exact head `e8e3011187a2ffdfbb6c9932db26b22ec911ab39`, upstream main
`ecbaf86d78cf52d185fbffa306157b9a4cc1b906`.

Mechanically updated from upstream/main
ecbaf86d78 without changing contributor
selector/ownership logic. Reviewed the current discussion and
integration delta. All 29 focused code-memory/Serena-disable/Gemini
tests pass with one optional skip; Ruff0.17.3 lint/format and whitespace
checks pass. Existing Windows HOME/USERPROFILE fixture isolation remains
intact.

The prior upgrade/runtime qualification requirement remains unresolved:
post-patch real configuration/launch evidence must cover an existing
Headroom-owned Serena entry, a hand-managed entry, explicit opt-in, and
Claude project/user scopes, with commands/results and untested-agent
limits. No new author evidence was found to close it. This pass does not
claim those actual launch/upgrade flows were executed; passing unit
tests and the main sync do not establish that deployment behavior. The
hold is not an inherited-main CI defect. Maintainers handle hosted
checks; no contributor CI execution requested. Nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `0b49a79cb192b294dde7ecb1c72b75fffa2733d5`, upstream main
`8d3e9e5ca7cd645eb73084b848edbea5fc796e1a`.

Clean mechanical sync with upstream
main8d3e9e5ca7cd645eb73084b848edbea5fc796e1a without changing
contributor selector/ownership logic. Current source, author discussion
and Devin findings reviewed.29focused code-memory/Serena-disable/Gemini
tests pass with1optional skip; changed Python Ruff0.17.3check/format and
whitespace pass. Windows HOME/USERPROFILE fixture isolation preserved.

Existing real upgrade/runtime qualification remains missing: existing
Headroom-owned Serena versus hand-managed entry, explicit opt-in, and
Claude project/user scopes need observed configuration/launch results
with explicit untested-agent limits. No new evidence found to close it;
these launch/upgrade paths were not executed in this pass. Passing unit
tests and clean main integration do not establish deployment behavior.
No new provider/native-build claim or inherited-main pipeline
attribution. Maintainers handle hosted checks; nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `30dfb386fa7284c9817bf5d7db0648fb10830055`, upstream main
`7592e681459f14a2041eb5f524a658cb6ad1dd92`.

Clean current-main
sync7592e681459f14a2041eb5f524a658cb6ad1dd92,including HNSW re-index and
memory relation-key fixes after917release-recovery merge. Contributor
selector/ownership logic unchanged; fresh discussion
considered.37wrapper/Serena/memory-regression/Gemini tests pass
with1optional skip;whitespace passes. PriorRuff0.17.3validation applies
to unchanged PR files.

Existing real upgrade/launch evidence hold remains: Headroom-owned
versus hand-managed Serena
entries,explicitoptin,andClaudeproject/userscopes need
observedpostpatchresults. No newevidence closesit;actualupgrade/launch
pathsnotrerun. No freshnativebuild/provider claim.
MaintainershandleCI;nothingmerged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `e1778a5368626547ad958926d5570edf153182f6`, upstream main
`2d3ee51846435ef5b320eea4806af14e602b0d8c`.

Clean integration with upstream/main
2d3ee51846 after the external 0.43.1
release merge. Exact headroom/crates/tests comparison against previously
reviewed 30dfb386f shows no changes. Re-reviewed generated metadata; 78
release/version/MCP tests pass on this tree and whitespace passes.
Earlier 37 wrapper/Serena/memory/Gemini passes and one optional skip
remain scoped to unchanged inputs.

Existing actual upgrade/launch proof hold remains: Headroom-owned versus
hand-managed Serena entries, explicit opt-in, and Claude project/user
scopes need observed postpatch results. Those runtime paths were not
rerun and no new evidence closes the hold. No contributor ownership
policy changed, no fresh native-build/provider claim. Maintainers handle
checks; nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `173c5739d7357ca9398faa41b4d1ce3b72d6c550`, upstream main
`7877241d84c93b3ec487e07324245838ddae85cc`.

Cleanly integrated upstream/main7877241d84c93b3ec487e07324245838ddae85cc
and re-reviewed the wrapper overlap with Hermes registration and port
discovery.35 selector/Serena-disable/Hermes provider and wrapper tests
pass,1optional skip; Ruff and whitespace pass. Contributor
ownership/default policy is unchanged. Existing actual
upgrade/configuration/launch proof requirement remains open for
Headroom-owned versus user-managed entries, explicit opt-in, and Claude
project/user scopes. No runtime proof is inferred from mocks or
native-build claim made. Maintainers handle hosted checks; nothing
merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `eb1c3d66669cf71f881f1ba06dc049d36b20da7b`, upstream main
`c01cf07d943d816cfd9d97e6838ed4e38f1ff9a4`.

Final post-Dependabot requalification against upstream/main
c01cf07d94. All six Dependabot updates are
now merged. Relative to this branch's freshly tested prepared tree, the
final main sync changes only the three intended Cargo.lock records;
Python/source/test inputs are unchanged. Re-reviewed the integration and
confirmed complete native source/lock/toolchain objects match the tested
combined build and exact fresh native DLL used for this branch's local
tests.

Focused fresh-native qualification: 35 passed, 1 skipped in 2.93s.
Selected real dependency overlays and native DLL paths are recorded in
final4509-fresh-native-tests.log; the DLL provenance/input hashes are in
final-native-artifact-proof.json. No redundant rerun is implied after
this Cargo-only merge. Whitespace passes. Prior source review and scoped
real-behavior evidence remain applicable to unchanged contributor
inputs.

Existing real upgrade/configuration/launch qualification remains open
for Headroom-owned versus user-managed Serena entries, explicit
opt-in/rollback, and Claude project/user scopes. No new author evidence
closes it; contributor ownership/default policy is unchanged.

Maintainers handle hosted checks; no external-provider claim,
contributor semantic rewrite or non-Dependabot merge.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `43bfea8a164c21ab69793b3905fbf1457fef7bc2`, upstream main
`da6d9736cd82074988c7d0a2360b49d9d8b6c0a0`.

Current-main requalification against
da6d9736cd. All69 integration patches
exactly match c01cf07-to-current-main delta after diff-location
normalization; contributor selector/default/Serena ownership logic
unchanged.162 focused code-memory,Serena disable,Hermes,Windows
supervisor,search-compressor tests pass;3 platform/optional skips. All31
changed Python files pass Ruff lint/format; offline lock and whitespace
pass. Native pr3982 DLL verified against complete tracked native-input
hash proof and artifact checksum; no fresh native-build claim.
Author/Devin discussion checked. Existing real
upgrade/configuration/launch qualification remains open: prior
Headroom-owned Serena entry versus user-managed entry, explicit
opt-in/rollback, Claude project/user scopes. No new author evidence
closes it; this run does not assert actual agent launch or deployment
proof. Maintainers handle hosted checks; no contributor policy rewrite
or merge.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `56557dc91725422257f90c3cb5c5f04a665e6043`, upstream main
`0ddaa56c21cdc01c4774391fdcc69e987ecc4e5c`.

Clean integration with upstream/main
0ddaa56c21. All 19 integration patches
exactly match the prior-reviewed-main da6d9736 to current-main delta
after diff-location normalization; contributor selector/default/Serena
ownership logic is unchanged. Fresh code-memory/Serena
disable/scope/reconciliation/migration, doctor and incoming
Vertex/backend/CLI tests: 330 passed, 12 skipped, 1 warning. Fourteen
changed Python files pass Ruff lint/format; offline lock and whitespace
checks pass.

Author/Devin discussion read. Existing real upgrade/configuration/launch
qualification remains open: prior Headroom-owned entry versus
user-managed entry, explicit opt-in/rollback, Claude project/user
scopes. This run establishes no actual agent launch or deployment proof.
Static source/test scope and security inspection found no new workflow,
dependency or setup path; the inherited flagged workflow-validation job
is excluded by the exact PR's unchanged workflow paths. Native DLL
reused after complete tracked input-set/hash and artifact-checksum
verification; no fresh build claimed. Maintainers handle exact-head
hosted checks; no PR merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-11-09 12:23:08 -06:00

2647 lines
106 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Tests for `headroom wrap codex` and `headroom unwrap codex`.
These exercise the Codex-specific ``config.toml`` injection and restoration
helpers that route Codex through the Headroom proxy. They are deliberately
end-to-end-ish: the unit tests call the helpers directly against a temp
``$HOME``, and the integration tests invoke the real Click commands the same
way a user would from the shell.
"""
from __future__ import annotations
import shutil
import sqlite3
import sys
from pathlib import Path
from unittest.mock import patch
import pytest
from click.testing import CliRunner
if sys.version_info >= (3, 11):
import tomllib
else: # pragma: no cover - exercised in the Python 3.10 test job
import tomli as tomllib
from headroom.cli import wrap as wrap_mod
from headroom.cli.main import main
from headroom.mcp_registry.install import build_headroom_spec
def _set_test_home(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
home = str(tmp_path)
monkeypatch.setenv("HOME", home)
monkeypatch.setenv("USERPROFILE", home)
monkeypatch.delenv("CODEX_HOME", raising=False)
@pytest.fixture
def runner() -> CliRunner:
return CliRunner()
_PROXY_DEP_TESTS = frozenset(
{
"test_wrap_codex_aborts_before_mutating_config_when_proxy_deps_missing",
"test_wrap_codex_skips_proxy_dependency_check_with_no_proxy",
}
)
@pytest.fixture(autouse=True)
def _skip_wrap_proxy_dependency_gate_unless_exercised(
request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Wrap-codex integration tests run in the base CI env without [proxy] extras."""
if request.node.name in _PROXY_DEP_TESTS:
return
monkeypatch.setattr("headroom.cli.wrap.ensure_proxy_dependencies", lambda: None)
# ---------------------------------------------------------------------------
# Unit tests: helpers operating on ~/.codex/config.toml
# ---------------------------------------------------------------------------
class TestStripCodexHeadroomBlocks:
"""Tests for the regex-based cleanup helper."""
def test_empty_content_returns_empty(self) -> None:
assert wrap_mod._strip_codex_headroom_blocks("") == ""
def test_returns_content_unchanged_when_no_markers(self) -> None:
original = '[profiles.default]\nmodel = "gpt-4o"\n'
cleaned = wrap_mod._strip_codex_headroom_blocks(original)
# Trailing whitespace normalization only — semantic content preserved.
assert 'model = "gpt-4o"' in cleaned
assert "[profiles.default]" in cleaned
def test_removes_complete_headroom_block(self) -> None:
wrapped = (
f"{wrap_mod._CODEX_TOP_LEVEL_MARKER}\n"
'model_provider = "headroom"\n'
"\n"
"[model_providers.headroom]\n"
'base_url = "http://127.0.0.1:8787/v1"\n'
f"{wrap_mod._CODEX_END_MARKER}\n"
)
assert wrap_mod._strip_codex_headroom_blocks(wrapped) == ""
def test_preserves_user_content_around_block(self) -> None:
user_pre = '[profiles.default]\nmodel = "gpt-4o"\n'
user_post = '[mcp_servers.foo]\ncommand = "echo"\n'
wrapped = (
f"{wrap_mod._CODEX_TOP_LEVEL_MARKER}\n"
'model_provider = "headroom"\n'
f"{wrap_mod._CODEX_END_MARKER}\n" + user_pre + "\n"
f"{wrap_mod._CODEX_TOP_LEVEL_MARKER}\n"
"[model_providers.headroom]\n"
'base_url = "http://127.0.0.1:8787/v1"\n'
f"{wrap_mod._CODEX_END_MARKER}\n" + user_post
)
cleaned = wrap_mod._strip_codex_headroom_blocks(wrapped)
assert wrap_mod._CODEX_TOP_LEVEL_MARKER not in cleaned
assert wrap_mod._CODEX_END_MARKER not in cleaned
assert 'model = "gpt-4o"' in cleaned
assert "[mcp_servers.foo]" in cleaned
def test_removes_stray_top_level_model_provider_line(self) -> None:
# Old wrap versions left `model_provider = "headroom"` outside markers.
content = 'foo = 1\nmodel_provider = "headroom"\nbar = 2\n'
cleaned = wrap_mod._strip_codex_headroom_blocks(content, remove_mcp=True)
assert 'model_provider = "headroom"' not in cleaned
assert "foo = 1" in cleaned
assert "bar = 2" in cleaned
def test_removes_codex_mcp_blocks(self) -> None:
content = (
'[profiles.default]\nmodel = "gpt-4o"\n\n'
f"{wrap_mod._CODEX_MCP_MARKER}\n"
"[mcp_servers.headroom]\n"
'command = "headroom"\n'
f"{wrap_mod._CODEX_MCP_END}\n\n"
"# --- Headroom MCP server: serena ---\n"
"[mcp_servers.serena]\n"
'command = "uvx"\n'
"# --- end Headroom MCP server: serena ---\n\n"
f"{wrap_mod._MEMORY_MCP_MARKER}\n"
"[mcp_servers.headroom_memory]\n"
'command = "python"\n'
f"{wrap_mod._MEMORY_MCP_END}\n"
)
cleaned = wrap_mod._strip_codex_headroom_blocks(content, remove_mcp=True)
assert "[mcp_servers.headroom]" not in cleaned
assert "[mcp_servers.serena]" not in cleaned
assert "[mcp_servers.headroom_memory]" not in cleaned
assert 'model = "gpt-4o"' in cleaned
def test_preserves_named_mcp_blocks_when_remove_named_mcp_false(self) -> None:
content = (
"# --- Headroom MCP server: serena ---\n"
"[mcp_servers.serena]\n"
'command = "uvx"\n'
"# --- end Headroom MCP server: serena ---\n\n"
f"{wrap_mod._MEMORY_MCP_MARKER}\n"
"[mcp_servers.headroom_memory]\n"
'command = "python"\n'
f"{wrap_mod._MEMORY_MCP_END}\n"
)
cleaned = wrap_mod._strip_codex_headroom_blocks(
content, remove_mcp=True, remove_named_mcp=False
)
assert "[mcp_servers.serena]" in cleaned
assert "[mcp_servers.headroom_memory]" not in cleaned
class TestSnapshotCodexConfig:
"""Tests for ``_snapshot_codex_config_if_unwrapped``."""
def test_creates_backup_on_first_call(self, tmp_path: Path) -> None:
config_file = tmp_path / "config.toml"
backup_file = tmp_path / "config.toml.headroom-backup"
config_file.write_text('model = "gpt-4o"\n', encoding="utf-8")
wrap_mod._snapshot_codex_config_if_unwrapped(config_file, backup_file)
assert backup_file.exists()
assert backup_file.read_text(encoding="utf-8") == 'model = "gpt-4o"\n'
def test_does_not_overwrite_existing_backup(self, tmp_path: Path) -> None:
config_file = tmp_path / "config.toml"
backup_file = tmp_path / "config.toml.headroom-backup"
config_file.write_text("second-wrap content\n", encoding="utf-8")
backup_file.write_text("original-pre-wrap content\n", encoding="utf-8")
wrap_mod._snapshot_codex_config_if_unwrapped(config_file, backup_file)
# Backup must still contain the *original* pre-wrap content.
assert backup_file.read_text(encoding="utf-8") == "original-pre-wrap content\n"
def test_no_backup_when_config_missing(self, tmp_path: Path) -> None:
config_file = tmp_path / "config.toml"
backup_file = tmp_path / "config.toml.headroom-backup"
wrap_mod._snapshot_codex_config_if_unwrapped(config_file, backup_file)
assert not backup_file.exists()
def test_no_backup_when_config_already_wrapped(self, tmp_path: Path) -> None:
config_file = tmp_path / "config.toml"
backup_file = tmp_path / "config.toml.headroom-backup"
config_file.write_text(
f"{wrap_mod._CODEX_TOP_LEVEL_MARKER}\n"
'model_provider = "headroom"\n'
f"{wrap_mod._CODEX_END_MARKER}\n",
encoding="utf-8",
)
wrap_mod._snapshot_codex_config_if_unwrapped(config_file, backup_file)
# Pre-wrap snapshot must never snapshot an already-wrapped file.
assert not backup_file.exists()
def test_no_backup_when_config_already_contains_memory_mcp_block(self, tmp_path: Path) -> None:
config_file = tmp_path / "config.toml"
backup_file = tmp_path / "config.toml.headroom-backup"
config_file.write_text(
f"{wrap_mod._MEMORY_MCP_MARKER}\n"
"[mcp_servers.headroom_memory]\n"
'command = "python"\n'
'args = ["-m", "headroom.memory.mcp_server", "--user", "codex-user"]\n'
f"{wrap_mod._MEMORY_MCP_END}\n"
)
wrap_mod._snapshot_codex_config_if_unwrapped(config_file, backup_file)
assert not backup_file.exists()
def test_backup_when_config_contains_named_mcp_marker(self, tmp_path: Path) -> None:
config_file = tmp_path / "config.toml"
backup_file = tmp_path / "config.toml.headroom-backup"
original = (
"# --- Headroom MCP server: headroom ---\n"
"[mcp_servers.headroom]\n"
'command = "headroom"\n'
"# --- end Headroom MCP server: headroom ---\n"
)
config_file.write_text(original)
wrap_mod._snapshot_codex_config_if_unwrapped(config_file, backup_file)
assert backup_file.exists()
assert backup_file.read_text() == original
class TestCodexMemoryMcpConfig:
"""Tests for the persisted Codex memory MCP block."""
def test_inject_omits_db_and_replaces_existing_memory_block(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
config_file.write_text(
'[profiles.default]\nmodel = "gpt-4o"\n\n'
f"{wrap_mod._MEMORY_MCP_MARKER}\n"
"[mcp_servers.headroom_memory]\n"
'command = "python"\n'
'args = ["-m", "headroom.memory.mcp_server", "--db", "/tmp/project-a/.headroom/memory.db", "--user", "old-user"]\n'
f"{wrap_mod._MEMORY_MCP_END}\n"
)
wrap_mod._inject_memory_mcp_config("codex-user")
content = config_file.read_text()
assert content.count(wrap_mod._MEMORY_MCP_MARKER) == 1
assert "[mcp_servers.headroom_memory]" in content
assert '"--user", "codex-user"' in content
assert "--db" not in content
assert 'model = "gpt-4o"' in content
def test_inject_replaces_unmarked_memory_block(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""A `[mcp_servers.headroom_memory]` table without the injection
markers (e.g. hand-copied from the `mcp_server.py` docstring, or left
over from before this table was marker-guarded) must be replaced in
place, not duplicated alongside a second, marked table.
"""
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
config_file.write_text(
'[profiles.default]\nmodel = "gpt-4o"\n\n'
"[mcp_servers.headroom_memory]\n"
'command = "python"\n'
'args = ["-m", "headroom.memory.mcp_server", "--user", "old-user"]\n'
"startup_timeout_sec = 30\n"
"tool_timeout_sec = 30\n\n"
"[mcp_servers.other]\n"
'command = "other-tool"\n'
)
wrap_mod._inject_memory_mcp_config("codex-user")
content = config_file.read_text()
assert content.count("[mcp_servers.headroom_memory]") == 1
assert content.count(wrap_mod._MEMORY_MCP_MARKER) == 1
assert '"--user", "codex-user"' in content
assert "old-user" not in content
assert 'model = "gpt-4o"' in content
assert "[mcp_servers.other]" in content
assert 'command = "other-tool"' in content
# The result must also be valid, parseable TOML — the original bug
# produced two `[mcp_servers.headroom_memory]` tables, which is
# invalid TOML (duplicate key) and breaks Codex startup.
parsed = tomllib.loads(content)
assert parsed["mcp_servers"]["headroom_memory"]["args"][-1] == "codex-user"
def test_inject_preserves_table_looking_text_in_multiline_string(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""A `[mcp_servers.headroom_memory]`-looking line embedded inside an
unrelated multiline string value must not be mistaken for a real
table and stripped -- doing so previously deleted the string's
closing delimiter and any settings after it, corrupting the file.
"""
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
original = (
'instructions = """\n'
"[mcp_servers.headroom_memory]\n"
"keep this instruction\n"
'"""\n'
'model="gpt-4o"\n'
)
config_file.write_text(original)
wrap_mod._inject_memory_mcp_config("codex-user")
content = config_file.read_text()
# The unrelated multiline string and the setting after it must
# survive untouched.
assert "keep this instruction" in content
assert 'model="gpt-4o"' in content
# The real, marker-wrapped memory MCP block must still be injected.
assert content.count(wrap_mod._MEMORY_MCP_MARKER) == 1
parsed = tomllib.loads(content)
assert parsed["model"] == "gpt-4o"
assert parsed["instructions"] == "[mcp_servers.headroom_memory]\nkeep this instruction\n"
assert parsed["mcp_servers"]["headroom_memory"]["args"][-1] == "codex-user"
def test_inject_replaces_quoted_key_memory_table(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""TOML allows `[mcp_servers."headroom_memory"]` as an equivalent
spelling of `[mcp_servers.headroom_memory]`; an unmarked table using
this spelling must still be replaced in place, not left behind
alongside a second, semantically-duplicate table.
"""
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
config_file.write_text(
'[profiles.default]\nmodel = "gpt-4o"\n\n'
'[mcp_servers."headroom_memory"]\n'
'command = "python"\n'
'args = ["-m", "headroom.memory.mcp_server", "--user", "old-user"]\n\n'
"[mcp_servers.other]\n"
'command = "other-tool"\n'
)
wrap_mod._inject_memory_mcp_config("codex-user")
content = config_file.read_text()
assert content.count(wrap_mod._MEMORY_MCP_MARKER) == 1
assert '"--user", "codex-user"' in content
assert "old-user" not in content
assert 'model = "gpt-4o"' in content
assert "[mcp_servers.other]" in content
assert 'command = "other-tool"' in content
# Must parse as valid TOML with exactly one `mcp_servers.headroom_memory`
# table -- the original bug left the quoted-key table behind, and
# `tomllib.loads` raises `Cannot declare (\'mcp_servers\', \'headroom_memory\')
# twice` once the marker-wrapped table is appended alongside it.
parsed = tomllib.loads(content)
assert parsed["mcp_servers"]["headroom_memory"]["args"][-1] == "codex-user"
assert parsed["mcp_servers"]["other"]["command"] == "other-tool"
def test_inject_preserves_array_table_after_unmarked_memory_table(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Removing an old memory table must stop before an unrelated array table."""
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
config_file.write_text(
"[mcp_servers.headroom_memory]\n"
'command = "old"\n\n'
"[[profiles.custom.entries]]\n"
'name = "preserve"\n'
)
wrap_mod._inject_memory_mcp_config("codex-user")
parsed = tomllib.loads(config_file.read_text())
assert parsed["profiles"]["custom"]["entries"] == [{"name": "preserve"}]
assert parsed["mcp_servers"]["headroom_memory"]["args"][-1] == "codex-user"
def test_inject_ignores_triple_quote_in_comment_before_memory_table(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""A comment delimiter cannot hide the real old memory table from cleanup."""
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
config_file.write_text(
'# Example triple quote: """\n[mcp_servers.headroom_memory]\ncommand = "old"\n'
)
wrap_mod._inject_memory_mcp_config("codex-user")
content = config_file.read_text()
parsed = tomllib.loads(content)
assert content.count("[mcp_servers.headroom_memory]") == 1
assert parsed["mcp_servers"]["headroom_memory"]["args"][-1] == "codex-user"
def test_inject_leaves_file_unchanged_when_candidate_is_invalid(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""An invalid candidate must never overwrite the user's configuration."""
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
original = (
"broken = [\n"
f"{wrap_mod._MEMORY_MCP_MARKER}\n"
"[mcp_servers.headroom_memory]\n"
'command = "old"\n'
f"{wrap_mod._MEMORY_MCP_END}\n"
)
config_file.write_text(original)
wrap_mod._inject_memory_mcp_config("codex-user")
assert config_file.read_text() == original
class TestInjectAndRestoreRoundTrip:
"""End-to-end wrap → unwrap cycle operating directly on a temp $HOME."""
def test_invalid_user_config_is_named_and_left_untouched(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
"""A broken config.toml is reported by path, with the user's own line.
The merged candidate used to be the first thing parsed, so the warning
named a line in Headroom's generated text and no file at all.
"""
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
config_file.write_text("model = [unterminated\n", encoding="utf-8")
assert wrap_mod._inject_codex_provider_config(8787) is None
out = capsys.readouterr().out
assert f"could not update Codex config {config_file}: it is not valid TOML" in out
assert "line 1" in out
assert "Fix or remove the file, then re-run." in out
assert config_file.read_text(encoding="utf-8") == "model = [unterminated\n"
def test_wrap_unwrap_restores_empty_state(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
wrap_mod._inject_codex_provider_config(8787)
assert config_file.exists()
assert 'model_provider = "headroom"' in config_file.read_text(encoding="utf-8")
status, _ = wrap_mod._restore_codex_provider_config()
# No prior config existed → the injected file is fully removed.
assert status == "removed"
assert not config_file.exists()
assert not (tmp_path / ".codex" / "config.toml.headroom-backup").exists()
def test_wrap_unwrap_removes_generated_auth_helper(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
(config_dir / "auth.json").write_text(
'{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8"
)
wrap_mod._inject_codex_provider_config(8787)
helper = wrap_mod.codex_auth_helper_path(config_dir / "auth.json")
assert helper.exists()
config = tomllib.loads((config_dir / "config.toml").read_text(encoding="utf-8"))
assert config["model_providers"]["headroom"]["auth"]["args"] == [str(helper.resolve())]
status, _ = wrap_mod._restore_codex_provider_config()
assert status == "removed"
assert not helper.exists()
def test_wrap_unwrap_preserves_preexisting_unrelated_auth_helper(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
config_file.write_text('model = "gpt-5"\n', encoding="utf-8")
(config_dir / "auth.json").write_text(
'{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8"
)
helper = config_dir / ".headroom-codex-auth.py"
helper.write_text("user content", encoding="utf-8")
wrap_mod._inject_codex_provider_config(8787)
status, _ = wrap_mod._restore_codex_provider_config()
assert status == "restored"
assert helper.read_text(encoding="utf-8") == "user content"
def test_wrap_unwrap_respects_codex_home(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
codex_home = tmp_path / "custom-codex-home"
monkeypatch.setenv("CODEX_HOME", str(codex_home))
config_file = codex_home / "config.toml"
wrap_mod._inject_codex_provider_config(8787)
assert config_file.exists()
assert 'model_provider = "headroom"' in config_file.read_text(encoding="utf-8")
assert not (tmp_path / ".codex" / "config.toml").exists()
status, _ = wrap_mod._restore_codex_provider_config()
assert status == "removed"
assert not config_file.exists()
def test_wrap_helper_collision_aborts_before_backup(self, monkeypatch, tmp_path: Path) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
auth = config_dir / "auth.json"
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
config_file = config_dir / "config.toml"
original = 'model_provider = "openai"\n'
config_file.write_text(original, encoding="utf-8")
helper = wrap_mod.codex_auth_helper_path(auth, config_path=config_file)
helper.write_text("user content", encoding="utf-8")
with pytest.raises(
wrap_mod.click.ClickException, match="Codex provider configuration was not updated"
):
wrap_mod._inject_codex_provider_config(8787)
assert config_file.read_text(encoding="utf-8") == original
assert not (config_dir / "config.toml.headroom-backup").exists()
assert helper.read_text(encoding="utf-8") == "user content"
def test_unwrap_keeps_helper_used_by_restored_custom_provider(
self, monkeypatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
auth = config_dir / "auth.json"
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
original = "[model_providers.custom]\n" + wrap_mod.build_codex_auth_config(auth)
config_file = config_dir / "config.toml"
config_file.write_text(original, encoding="utf-8")
wrap_mod._inject_codex_provider_config(8787)
status, _ = wrap_mod._restore_codex_provider_config()
assert status == "restored"
assert config_file.read_text(encoding="utf-8") == original
assert wrap_mod.codex_auth_helper_path(auth).exists()
def test_wrap_unwrap_restores_prior_model_provider(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
original = (
'model_provider = "openai"\n'
"\n"
"[model_providers.openai]\n"
'name = "OpenAI"\n'
'base_url = "https://api.openai.com/v1"\n'
)
config_file.write_text(original, encoding="utf-8")
wrap_mod._inject_codex_provider_config(8787)
wrapped = config_file.read_text(encoding="utf-8")
assert 'model_provider = "headroom"' in wrapped
assert "[model_providers.headroom]" in wrapped
status, _ = wrap_mod._restore_codex_provider_config()
assert status == "restored"
assert config_file.read_text(encoding="utf-8") == original
assert not (config_dir / "config.toml.headroom-backup").exists()
def test_wrap_is_idempotent(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
original = '[profiles.default]\nmodel = "gpt-4o"\n'
config_file.write_text(original, encoding="utf-8")
wrap_mod._inject_codex_provider_config(8787)
wrap_mod._inject_codex_provider_config(8787)
wrap_mod._inject_codex_provider_config(9999) # port change
content = config_file.read_text(encoding="utf-8")
# Exactly two Headroom blocks — a top-level-key block and the
# provider-table block. Re-wrapping must not duplicate them.
assert content.count(wrap_mod._CODEX_TOP_LEVEL_MARKER) == 2
assert content.count(wrap_mod._CODEX_END_MARKER) == 2
# Latest port is honoured in both keys.
assert 'base_url = "http://127.0.0.1:9999/v1"' in content
assert 'openai_base_url = "http://127.0.0.1:9999/v1"' in content
assert 'base_url = "http://127.0.0.1:8787/v1"' not in content
assert 'openai_base_url = "http://127.0.0.1:8787/v1"' not in content
# User's original content is preserved.
assert 'model = "gpt-4o"' in content
status, _ = wrap_mod._restore_codex_provider_config()
assert status == "restored"
assert config_file.read_text(encoding="utf-8") == original
def test_unwrap_is_noop_when_never_wrapped(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
status, _ = wrap_mod._restore_codex_provider_config()
assert status == "noop"
def test_unwrap_cleans_block_without_backup(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Handles crash-case where wrap injected but backup was wiped."""
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
user_content = '[profiles.default]\nmodel = "gpt-4o"\n'
config_file.write_text(
user_content + f"{wrap_mod._CODEX_TOP_LEVEL_MARKER}\n"
'model_provider = "headroom"\n\n'
"[model_providers.headroom]\n"
'base_url = "http://127.0.0.1:8787/v1"\n'
f"{wrap_mod._CODEX_END_MARKER}\n",
encoding="utf-8",
)
status, _ = wrap_mod._restore_codex_provider_config()
assert status == "cleaned"
cleaned = config_file.read_text(encoding="utf-8")
assert wrap_mod._CODEX_TOP_LEVEL_MARKER not in cleaned
assert wrap_mod._CODEX_END_MARKER not in cleaned
assert 'model_provider = "headroom"' not in cleaned
assert 'model = "gpt-4o"' in cleaned
def test_unwrap_without_backup_removes_provider_and_mcp_blocks(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
config_file.write_text(
'[profiles.default]\nmodel = "gpt-4o"\n\n'
f"{wrap_mod._CODEX_TOP_LEVEL_MARKER}\n"
'model_provider = "headroom"\n'
f"{wrap_mod._CODEX_END_MARKER}\n\n"
f"{wrap_mod._CODEX_MCP_MARKER}\n"
"[mcp_servers.headroom]\n"
'command = "headroom"\n'
f"{wrap_mod._CODEX_MCP_END}\n\n"
f"{wrap_mod._MEMORY_MCP_MARKER}\n"
"[mcp_servers.headroom_memory]\n"
'command = "python"\n'
f"{wrap_mod._MEMORY_MCP_END}\n",
encoding="utf-8",
)
status, _ = wrap_mod._restore_codex_provider_config()
assert status == "cleaned"
cleaned = config_file.read_text(encoding="utf-8")
assert 'model = "gpt-4o"' in cleaned
assert "headroom" not in cleaned
def test_memory_only_wrap_restores_preexisting_named_mcp_block(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
original = (
"# --- Headroom MCP server: headroom ---\n"
"[mcp_servers.headroom]\n"
'command = "headroom"\n'
"# --- end Headroom MCP server: headroom ---\n"
)
config_file.write_text(original)
wrap_mod._inject_memory_mcp_config("codex-user")
status, _ = wrap_mod._restore_codex_provider_config()
assert status == "restored"
assert config_file.read_text() == original
def test_memory_only_wrap_without_backup_preserves_named_mcp_block(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
backup_file = config_dir / "config.toml.headroom-backup"
original = (
"# --- Headroom MCP server: headroom ---\n"
"[mcp_servers.headroom]\n"
'command = "headroom"\n'
"# --- end Headroom MCP server: headroom ---\n"
)
config_file.write_text(original)
wrap_mod._inject_memory_mcp_config("codex-user")
backup_file.unlink()
status, _ = wrap_mod._restore_codex_provider_config()
assert status == "cleaned"
assert config_file.read_text() == original
def test_unwrap_handles_malformed_prior_config(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Unwrap preserves backup content verbatim — TOML validity isn't required."""
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
malformed = 'this is not valid toml ][ "" \x00\n'
config_file.write_text(malformed, encoding="utf-8")
wrap_mod._inject_codex_provider_config(8787)
status, _ = wrap_mod._restore_codex_provider_config()
assert status == "restored"
assert config_file.read_text(encoding="utf-8") == malformed
def test_unwrap_is_safe_when_no_global_agents(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""No Codex AGENTS.md → unwrap is a clean no-op, not a crash."""
_set_test_home(monkeypatch, tmp_path)
wrap_mod.unwrap_codex.callback(port=8787, no_stop_proxy=True)
assert not (tmp_path / ".codex" / "AGENTS.md").exists()
# ---------------------------------------------------------------------------
# Thread retag: wrap pulls native threads into the headroom menu, unwrap hands
# them back, so the Codex history list stays whole across the proxy boundary.
# ---------------------------------------------------------------------------
class TestWrapRetagsThreadProviders:
"""``wrap codex`` retags ``openai`` threads to ``headroom`` and back."""
@staticmethod
def _seed_threads(db: Path, rows: list[tuple[str, str]]) -> None:
db.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(str(db))
try:
conn.execute("CREATE TABLE threads (id TEXT PRIMARY KEY, model_provider TEXT NOT NULL)")
conn.executemany("INSERT INTO threads (id, model_provider) VALUES (?, ?)", rows)
conn.commit()
finally:
conn.close()
@staticmethod
def _count(db: Path, provider: str) -> int:
conn = sqlite3.connect(str(db))
try:
(n,) = conn.execute(
"SELECT COUNT(*) FROM threads WHERE model_provider = ?", (provider,)
).fetchone()
return n
finally:
conn.close()
def test_wrap_unwrap_round_trips_thread_providers(
self, runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
gui_db = tmp_path / ".codex" / "sqlite" / "state_5.sqlite"
cli_db = tmp_path / ".codex" / "state_5.sqlite"
self._seed_threads(gui_db, [("a", "openai"), ("b", "headroom"), ("c", "anthropic")])
self._seed_threads(cli_db, [("d", "openai")])
wrap_result = runner.invoke(main, ["wrap", "codex", "--prepare-only", "--port", "8787"])
assert wrap_result.exit_code == 0, wrap_result.output
# Native threads are now visible under the headroom provider menu;
# third-party providers are left untouched.
assert self._count(gui_db, "headroom") == 2
assert self._count(gui_db, "openai") == 0
assert self._count(gui_db, "anthropic") == 1
assert self._count(cli_db, "headroom") == 1
with patch("headroom.cli.wrap._stop_local_proxy_for_unwrap", return_value="stopped"):
unwrap_result = runner.invoke(main, ["unwrap", "codex", "--port", "8787"])
assert unwrap_result.exit_code == 0, unwrap_result.output
# Back to native so the unproxied Codex menu is whole again.
assert self._count(gui_db, "openai") == 2
assert self._count(gui_db, "headroom") == 0
assert self._count(gui_db, "anthropic") == 1
assert self._count(cli_db, "openai") == 1
# ---------------------------------------------------------------------------
# Subscription routing: openai_base_url intercepts ChatGPT plan traffic
# ---------------------------------------------------------------------------
class TestSubscriptionRouting:
"""Codex subscription (ChatGPT plan) bypasses OPENAI_BASE_URL and the
custom model_provider; it uses the built-in ``openai`` provider whose
base_url defaults to ``https://chatgpt.com/backend-api/codex``.
Setting ``openai_base_url`` overrides that default for all auth modes."""
def test_inject_writes_openai_base_url(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
wrap_mod._inject_codex_provider_config(8787)
content = (tmp_path / ".codex" / "config.toml").read_text(encoding="utf-8")
assert 'openai_base_url = "http://127.0.0.1:8787/v1"' in content
def test_inject_preserves_multiline_inline_profile_overrides(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Keys nested in a multi-line inline profiles table are not root keys."""
from headroom.providers.codex.config_toml import loads_codex_config
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
config_file.write_text(
'profiles = {\n work = {\n model_provider = "company",\n },\n}\n',
encoding="utf-8",
)
wrap_mod._inject_codex_provider_config(8787)
parsed = loads_codex_config(config_file.read_text(encoding="utf-8"))
assert parsed["model_provider"] == "headroom"
assert parsed["openai_base_url"] == "http://127.0.0.1:8787/v1"
assert parsed["profiles"]["work"] == {"model_provider": "company"}
def test_inject_emits_requires_openai_auth_for_chatgpt(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
(config_dir / "auth.json").write_text('{"auth_mode": "chatgpt"}', encoding="utf-8")
wrap_mod._inject_codex_provider_config(8787)
assert "requires_openai_auth = true" in (config_dir / "config.toml").read_text(
encoding="utf-8"
)
def test_inject_omits_requires_openai_auth_for_api_key(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
(config_dir / "auth.json").write_text('{"auth_mode": "apikey"}', encoding="utf-8")
wrap_mod._inject_codex_provider_config(8787)
assert "requires_openai_auth" not in (config_dir / "config.toml").read_text(
encoding="utf-8"
)
def test_openai_base_url_port_updates_on_rewrap(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
wrap_mod._inject_codex_provider_config(8787)
wrap_mod._inject_codex_provider_config(9999)
content = (tmp_path / ".codex" / "config.toml").read_text(encoding="utf-8")
assert 'openai_base_url = "http://127.0.0.1:9999/v1"' in content
assert 'openai_base_url = "http://127.0.0.1:8787/v1"' not in content
def test_openai_base_url_removed_on_unwrap(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
original = '[profiles.default]\nmodel = "gpt-4o"\n'
config_file.write_text(original, encoding="utf-8")
wrap_mod._inject_codex_provider_config(8787)
assert 'openai_base_url = "http://127.0.0.1:8787/v1"' in config_file.read_text(
encoding="utf-8"
)
wrap_mod._restore_codex_provider_config()
assert config_file.read_text(encoding="utf-8") == original
def test_strip_cleans_orphaned_openai_base_url(self) -> None:
"""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 = (
'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 "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(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""env_key must be absent so Codex doesn't require OPENAI_API_KEY.
Codex treats env_key as a hard requirement — if the env var is missing
it throws "Missing environment variable" at startup. Subscription
(ChatGPT Plus) users don't have OPENAI_API_KEY set, so injecting
env_key breaks them (issue #393).
"""
_set_test_home(monkeypatch, tmp_path)
wrap_mod._inject_codex_provider_config(8787)
content = (tmp_path / ".codex" / "config.toml").read_text(encoding="utf-8")
assert "env_key" not in content
# ---------------------------------------------------------------------------
# Custom upstream preservation (#1614): wrap must not silently reroute a
# pre-existing custom [model_providers.*] base_url to api.openai.com.
# ---------------------------------------------------------------------------
class TestDetectCustomCodexUpstreamBaseUrl:
"""Unit tests for the detection helper used by ``_inject_codex_provider_config``."""
def test_no_config_returns_none(self) -> None:
assert wrap_mod._detect_custom_codex_upstream_base_url("") is None
def test_no_custom_provider_returns_none(self) -> None:
content = (
'model_provider = "openai"\n\n'
"[model_providers.openai]\n"
'base_url = "https://api.openai.com/v1"\n'
)
assert wrap_mod._detect_custom_codex_upstream_base_url(content) is None
def test_sole_candidate_used_without_explicit_selection(self) -> None:
"""Matches the #1614 repro: a custom table with no static top-level pin."""
content = (
"[model_providers.freemodel]\n"
'base_url = "https://api.freemodel.dev"\n'
'wire_api = "responses"\n'
)
assert (
wrap_mod._detect_custom_codex_upstream_base_url(content) == "https://api.freemodel.dev"
)
def test_explicit_top_level_selection_wins(self) -> None:
content = (
'model_provider = "freemodel"\n\n'
"[model_providers.freemodel]\n"
'base_url = "https://api.freemodel.dev"\n\n'
"[model_providers.other]\n"
'base_url = "https://api.other.example"\n'
)
assert (
wrap_mod._detect_custom_codex_upstream_base_url(content) == "https://api.freemodel.dev"
)
def test_was_comment_recovers_selection_on_rewrap(self) -> None:
"""After a prior wrap, model_provider reads 'headroom # was: freemodel'."""
content = (
'model_provider = "headroom" # was: freemodel\n\n'
"[model_providers.freemodel]\n"
'base_url = "https://api.freemodel.dev"\n'
)
assert (
wrap_mod._detect_custom_codex_upstream_base_url(content) == "https://api.freemodel.dev"
)
def test_ambiguous_multiple_candidates_returns_none(self) -> None:
content = (
"[model_providers.freemodel]\n"
'base_url = "https://api.freemodel.dev"\n\n'
"[model_providers.other]\n"
'base_url = "https://api.other.example"\n'
)
assert wrap_mod._detect_custom_codex_upstream_base_url(content) is None
def test_builtin_provider_tables_excluded(self) -> None:
content = (
'model_provider = "openai"\n\n'
"[model_providers.openai]\n"
'base_url = "https://api.openai.com/v1"\n\n'
"[model_providers.anthropic]\n"
'base_url = "https://api.anthropic.com/v1"\n'
)
assert wrap_mod._detect_custom_codex_upstream_base_url(content) is None
def test_own_headroom_table_excluded(self) -> None:
content = (
'model_provider = "headroom"\n\n'
"[model_providers.headroom]\n"
'base_url = "http://127.0.0.1:8787/v1"\n'
)
assert wrap_mod._detect_custom_codex_upstream_base_url(content) is None
class TestInjectPreservesCustomUpstreamBaseUrl:
"""``_inject_codex_provider_config`` must preserve a pre-existing custom
provider's ``base_url`` instead of silently rerouting to api.openai.com."""
def test_inject_returns_and_carries_custom_base_url(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
config_file.write_text(
"[model_providers.freemodel]\n"
'base_url = "https://api.freemodel.dev"\n'
'wire_api = "responses"\n',
encoding="utf-8",
)
result = wrap_mod._inject_codex_provider_config(8787)
assert result == "https://api.freemodel.dev"
content = config_file.read_text(encoding="utf-8")
parsed = tomllib.loads(content)
headers = parsed["model_providers"]["headroom"]["env_http_headers"]
assert (
headers[wrap_mod._UPSTREAM_BASE_URL_HEADER_NAME] == wrap_mod._UPSTREAM_BASE_URL_ENV_VAR
)
# The user's own table is left untouched — only headroom's own is managed.
assert parsed["model_providers"]["freemodel"]["base_url"] == "https://api.freemodel.dev"
def test_inject_without_custom_provider_returns_none(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
result = wrap_mod._inject_codex_provider_config(8787)
assert result is None
content = (tmp_path / ".codex" / "config.toml").read_text(encoding="utf-8")
assert wrap_mod._UPSTREAM_BASE_URL_HEADER_NAME not in content
def test_preserved_upstream_survives_rewrap_and_port_change(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
config_file.write_text(
'model_provider = "freemodel"\n\n'
"[model_providers.freemodel]\n"
'base_url = "https://api.freemodel.dev"\n',
encoding="utf-8",
)
first = wrap_mod._inject_codex_provider_config(8787)
second = wrap_mod._inject_codex_provider_config(9999) # port change / re-wrap
assert first == "https://api.freemodel.dev"
assert second == "https://api.freemodel.dev"
content = config_file.read_text(encoding="utf-8")
parsed = tomllib.loads(content)
assert parsed["model_providers"]["headroom"]["base_url"] == "http://127.0.0.1:9999/v1"
headers = parsed["model_providers"]["headroom"]["env_http_headers"]
assert (
headers[wrap_mod._UPSTREAM_BASE_URL_HEADER_NAME] == wrap_mod._UPSTREAM_BASE_URL_ENV_VAR
)
class TestInjectAvoidsDuplicateTopLevelKeys:
"""Wrap must not produce a TOML-validity-breaking duplicate-key error.
Codex's ``config.toml`` is parsed strictly: two top-level
``model_provider = …`` (or two ``openai_base_url = …``) declarations
cause ``codex`` to refuse to start with
``Error loading config.toml: …: …:1: duplicate key``. The injector
used to unconditionally prepend a top-level block, breaking any user
who had already configured their own provider (e.g. ``ccswitch``).
"""
def test_inject_does_not_create_duplicate_model_provider(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
config_file.write_text(
'model_provider = "ccswitch"\n'
'openai_base_url = "http://llm-gateway-proxy/v1"\n'
'model = "azure-gpt-5_5"\n'
"\n"
"[model_providers.ccswitch]\n"
'name = "OpenAI"\n'
'base_url = "http://llm-gateway-proxy/v1"\n'
'wire_api = "responses"\n',
encoding="utf-8",
)
wrap_mod._inject_codex_provider_config(8787)
content = config_file.read_text(encoding="utf-8")
# The wrapped file must be TOML-parseable — duplicate keys were
# the failure mode the user reported.
tomllib.loads(content)
# No duplicate top-level key for either redirectable key.
assert content.count("model_provider =") == 1
assert content.count("openai_base_url =") == 1
# And the rewritten values are the headroom ones.
assert 'model_provider = "headroom"' in content
assert 'openai_base_url = "http://127.0.0.1:8787/v1"' in content
@pytest.mark.parametrize("blank", ["", " ", "\n\t\n"])
def test_redirect_existing_top_level_keys_noop_on_blank(self, blank: str) -> None:
# No redirectable keys to rewrite in blank/whitespace content — the
# helper returns it unchanged so the caller falls back to prepending
# the marker-delimited top-level block.
assert wrap_mod._redirect_existing_top_level_keys(blank, 8787) == blank
@pytest.mark.parametrize("sep", ["
", "\x85"])
def test_redirect_leaves_provider_text_inside_single_line_string(self, sep: str) -> None:
# TOML allows U+2028 and U+0085 inside a single-line string, so the
# text after them is still part of the value, not a root assignment.
content = f"notes = 'hello{sep}model_provider = \"company\"{sep}world'\n"
assert wrap_mod._redirect_existing_top_level_keys(content, 8787) == content
assert not wrap_mod._has_redirectable_top_level_key(content, "model_provider")
def test_inject_preserves_user_value_in_trailing_comment(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
config_file.write_text(
'model_provider = "ccswitch"\nopenai_base_url = "http://llm-gateway-proxy/v1"\n',
encoding="utf-8",
)
wrap_mod._inject_codex_provider_config(8787)
content = config_file.read_text(encoding="utf-8")
# Original value kept in a comment so the user can recover it.
# The comment intentionally drops the surrounding quotes — the
# value is a single TOML string and the comment is human-facing.
assert "was: ccswitch" in content
assert "was: http://llm-gateway-proxy/v1" in content
def test_inject_rewrap_updates_existing_redirected_keys(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Idempotent re-wrap on a config that already has top-level keys."""
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
config_file.write_text('model_provider = "ccswitch"\n', encoding="utf-8")
wrap_mod._inject_codex_provider_config(8787)
wrap_mod._inject_codex_provider_config(9999) # port change
content = config_file.read_text(encoding="utf-8")
tomllib.loads(content)
assert content.count("model_provider =") == 1
assert 'model_provider = "headroom"' in content
# Port updated in the openai_base_url we injected.
assert 'openai_base_url = "http://127.0.0.1:9999/v1"' in content
assert 'openai_base_url = "http://127.0.0.1:8787/v1"' not in content
def test_inject_empty_file_still_uses_marker_block(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""No existing top-level keys → fall back to the marker-delimited block."""
_set_test_home(monkeypatch, tmp_path)
wrap_mod._inject_codex_provider_config(8787)
content = (tmp_path / ".codex" / "config.toml").read_text(encoding="utf-8")
assert wrap_mod._CODEX_TOP_LEVEL_MARKER in content
assert 'model_provider = "headroom"' in content
assert 'openai_base_url = "http://127.0.0.1:8787/v1"' in content
assert "[model_providers.headroom]" in content
def test_inject_replaces_existing_headroom_provider_table(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Existing headroom provider table must not create duplicate TOML keys."""
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
config_file.write_text(
"[model_providers.headroom]\n"
'name = "Existing custom headroom"\n'
'base_url = "http://example.invalid/v1"\n'
"supports_websockets = true\n"
'env_http_headers = { "X-Headroom-Project" = "HEADROOM_PROJECT" }\n'
"\n"
"[profiles.default]\n"
'model = "gpt-5"\n'
)
wrap_mod._inject_codex_provider_config(8787)
content = config_file.read_text()
tomllib.loads(content)
assert content.count("[model_providers.headroom]") == 1
assert content.count("env_http_headers") == 1
assert 'base_url = "http://127.0.0.1:8787/v1"' in content
assert 'env_http_headers = { "X-Headroom-Project" = "HEADROOM_PROJECT" }' in content
assert "[profiles.default]" in content
assert 'model = "gpt-5"' in content
def test_inject_replaces_legacy_nested_subtable_format(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Legacy ``wrap`` output used a nested
``[model_providers.headroom.env_http_headers]`` sub-table instead of
today's inline table. The strip must consume the sub-table as well:
leaving it behind makes the re-injected inline ``env_http_headers``
key a duplicate TOML key and invalidates the whole config (seen in
the wild as ``TOMLDecodeError: Cannot declare ('model_providers',
'headroom') twice``).
"""
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
config_file.write_text(
"[profiles.default]\n"
'model = "gpt-5"\n'
"\n"
"[model_providers.headroom]\n"
'base_url = "http://127.0.0.1:8787/v1"\n'
'name = "OpenAI via Headroom proxy"\n'
"requires_openai_auth = true\n"
"supports_websockets = true\n"
"\n"
"[model_providers.headroom.env_http_headers]\n"
'X-Headroom-Project = "HEADROOM_PROJECT"\n'
"\n"
"[notice]\n"
"hide_rate_limit_model_nudge = true\n"
)
wrap_mod._inject_codex_provider_config(8787)
content = config_file.read_text()
parsed = tomllib.loads(content) # must not raise: the original bug did
assert content.count("[model_providers.headroom]") == 1
assert "[model_providers.headroom.env_http_headers]" not in content
assert content.count("env_http_headers") == 1 # inline form from the injection
assert parsed["model_providers"]["headroom"]["base_url"] == "http://127.0.0.1:8787/v1"
assert parsed["model_providers"]["headroom"]["env_http_headers"] == {
"X-Headroom-Project": "HEADROOM_PROJECT"
}
assert parsed["profiles"]["default"]["model"] == "gpt-5"
assert parsed["notice"] == {"hide_rate_limit_model_nudge": True}
def test_inject_preserves_array_table_after_legacy_provider_table(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Provider cleanup must stop before an unrelated TOML array table."""
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir()
config_file.write_text(
"[model_providers.headroom]\n"
'base_url = "http://127.0.0.1:8787/v1"\n\n'
"[[profiles.custom.entries]]\n"
'name = "preserve"\n'
)
wrap_mod._inject_codex_provider_config(8787)
parsed = tomllib.loads(config_file.read_text())
assert parsed["profiles"]["custom"]["entries"] == [{"name": "preserve"}]
assert parsed["model_providers"]["headroom"]["base_url"] == "http://127.0.0.1:8787/v1"
def test_inject_leaves_invalid_provider_config_unchanged(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Provider injection must not overwrite a config that cannot validate."""
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir()
original = 'broken = [\n[model_providers.headroom]\nbase_url = "http://127.0.0.1:8787/v1"\n'
config_file.write_text(original)
wrap_mod._inject_codex_provider_config(8787)
assert config_file.read_text() == original
def test_unwrap_restores_prior_headroom_provider_table(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Pre-wrap headroom provider table is restored from snapshot."""
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
original = (
"[model_providers.headroom]\n"
'name = "Existing custom headroom"\n'
'base_url = "http://example.invalid/v1"\n'
"supports_websockets = true\n"
'env_http_headers = { "X-Headroom-Project" = "HEADROOM_PROJECT" }\n'
)
config_file.write_text(original)
wrap_mod._inject_codex_provider_config(8787)
status, _ = wrap_mod._restore_codex_provider_config()
assert status == "restored"
assert config_file.read_text() == original
def test_unwrap_restores_prior_model_provider_after_rewrite(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""The snapshot mechanism must still restore the pre-wrap state byte-for-byte."""
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
original = 'model_provider = "ccswitch"\nopenai_base_url = "http://llm-gateway-proxy/v1"\n'
config_file.write_text(original, encoding="utf-8")
wrap_mod._inject_codex_provider_config(8787)
status, _ = wrap_mod._restore_codex_provider_config()
assert status == "restored"
assert config_file.read_text(encoding="utf-8") == original
# ---------------------------------------------------------------------------
# Integration tests: full `headroom wrap codex` / `headroom unwrap codex`
# ---------------------------------------------------------------------------
def test_wrap_codex_prepare_only_creates_backup_and_config(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
original = 'model_provider = "openai"\n'
config_file.write_text(original, encoding="utf-8")
result = runner.invoke(main, ["wrap", "codex", "--prepare-only", "--port", "8787"])
assert result.exit_code == 0, result.output
assert 'model_provider = "headroom"' in config_file.read_text(encoding="utf-8")
backup = tmp_path / ".codex" / "config.toml.headroom-backup"
assert backup.exists()
assert backup.read_text(encoding="utf-8") == original
def test_wrap_codex_aborts_before_mutating_config_when_proxy_deps_missing(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
original = 'model_provider = "openai"\n'
config_file.write_text(original, encoding="utf-8")
with patch("headroom.cli.wrap.ensure_proxy_dependencies", side_effect=SystemExit(1)):
result = runner.invoke(
main,
["wrap", "codex", "--prepare-only", "--no-serena", "--port", "8787"],
)
assert result.exit_code == 1, result.output
assert config_file.read_text(encoding="utf-8") == original
assert "[mcp_servers.headroom]" not in config_file.read_text(encoding="utf-8")
assert not (tmp_path / ".codex" / "config.toml.headroom-backup").exists()
def test_wrap_codex_skips_proxy_dependency_check_with_no_proxy(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
config_file.write_text('model_provider = "openai"\n', encoding="utf-8")
with patch(
"headroom.cli.wrap.ensure_proxy_dependencies",
side_effect=AssertionError("should not run with --no-proxy"),
):
result = runner.invoke(
main,
[
"wrap",
"codex",
"--prepare-only",
"--no-proxy",
"--no-serena",
"--port",
"8787",
],
)
assert result.exit_code == 0, result.output
def test_wrap_codex_registers_mcp_when_codex_home_does_not_exist_yet(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""MCP must register on a machine where Codex was installed but never launched.
``CodexRegistrar.detect()`` is just ``~/.codex`` being a directory, and that
directory used to be created as a side effect of writing the rtk guidance
into ``$CODEX_HOME/AGENTS.md``. Once the CLI context tools were removed,
nothing created it, so detect() said "Codex not detected" and Headroom
silently skipped MCP registration — leaving every compression marker the
proxy emits unresolvable, with no error shown.
Every other codex test pre-creates ``~/.codex``, which is exactly why none of
them caught it; this one deliberately does not.
"""
_set_test_home(monkeypatch, tmp_path)
codex_dir = tmp_path / ".codex"
assert not codex_dir.exists() # the whole point
result = runner.invoke(main, ["wrap", "codex", "--prepare-only", "--port", "8787"])
assert result.exit_code == 0, result.output
config = codex_dir / "config.toml"
assert config.exists(), "wrap codex did not persist config in the durable Codex home"
assert "[mcp_servers.headroom]" in config.read_text(encoding="utf-8")
assert "not detected" not in result.output
def test_wrap_codex_prepare_only_respects_codex_home(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
codex_home = tmp_path / "custom-codex-home"
codex_home.mkdir()
monkeypatch.setenv("CODEX_HOME", str(codex_home))
result = runner.invoke(
main,
["wrap", "codex", "--prepare-only", "--no-serena", "--port", "8787"],
)
assert result.exit_code == 0, result.output
config_file = codex_home / "config.toml"
assert config_file.exists()
content = config_file.read_text(encoding="utf-8")
assert 'model_provider = "headroom"' in content
assert "[mcp_servers.headroom]" in content
assert not (tmp_path / ".codex" / "config.toml").exists()
def test_wrap_codex_launch_uses_durable_codex_home(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
codex_home = tmp_path / "custom-codex-home"
codex_home.mkdir()
monkeypatch.setenv("CODEX_HOME", str(codex_home))
config_file = codex_home / "config.toml"
auth_file = codex_home / "auth.json"
original_config = '[profiles.default]\nmodel = "gpt-4o"\n'
original_auth = '{"auth_mode": "apikey"}'
config_file.write_text(original_config, encoding="utf-8")
auth_file.write_text(original_auth, encoding="utf-8")
launch_env: dict[str, str] = {}
rollout = codex_home / "sessions" / "2026" / "07" / "14" / "rollout-thread.jsonl"
def fake_launch(
*,
binary: str,
args: tuple,
env: dict[str, str],
port: int,
no_proxy: bool,
tool_label: str,
env_vars_display: list[str],
**kwargs: object,
) -> None:
del args, port, no_proxy, tool_label, env_vars_display, kwargs
assert binary == "/fake/codex"
launch_env.update(env)
assert Path(env["CODEX_HOME"]) == codex_home
rollout.parent.mkdir(parents=True)
rollout.write_text('{"type":"session_meta"}\n', encoding="utf-8")
with patch(
"headroom.cli.wrap.shutil.which",
side_effect=lambda cmd: "/fake/codex" if cmd == "codex" else None,
):
with patch("headroom.cli.wrap._launch_tool", side_effect=fake_launch):
result = runner.invoke(
main,
[
"wrap",
"codex",
"--port",
"8787",
"--no-tokensave",
"--no-serena",
],
)
assert result.exit_code == 0, result.output
assert launch_env["CODEX_HOME"] == str(codex_home)
assert launch_env["OPENAI_BASE_URL"] == "http://127.0.0.1:8787/v1"
persisted_config = config_file.read_text(encoding="utf-8")
assert original_config in persisted_config
assert "[mcp_servers.headroom]" in persisted_config
assert 'model_provider = "headroom"' not in persisted_config
assert "[model_providers.headroom]" not in persisted_config
assert auth_file.read_text(encoding="utf-8") == original_auth
assert rollout.read_text(encoding="utf-8") == '{"type":"session_meta"}\n'
def test_codex_session_launch_settings_keep_routing_process_local(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
codex_home = tmp_path / "custom-codex-home"
codex_home.mkdir()
monkeypatch.setenv("CODEX_HOME", str(codex_home))
monkeypatch.setattr(wrap_mod, "_project_name_from_cwd", lambda: None)
config_file = codex_home / "config.toml"
original_config = 'model = "gpt-5"\n'
config_file.write_text(original_config, encoding="utf-8")
args, env, display = wrap_mod._codex_session_launch_settings(
port=9898,
codex_args=("exec", "hello"),
environ={"CODEX_HOME": str(codex_home)},
)
assert args == (
"--config",
'openai_base_url="http://127.0.0.1:9898/v1"',
"exec",
"hello",
)
assert env["CODEX_HOME"] == str(codex_home)
assert env["OPENAI_BASE_URL"] == "http://127.0.0.1:9898/v1"
assert display == [
"OPENAI_BASE_URL=http://127.0.0.1:9898/v1",
wrap_mod._CODEX_EMBEDDED_MODE_NOTE,
]
assert config_file.read_text(encoding="utf-8") == original_config
def test_codex_session_launch_settings_accept_multiline_inline_table(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
# #4378: Codex accepts an inline table split across lines.
_set_test_home(monkeypatch, tmp_path)
codex_home = tmp_path / "custom-codex-home"
codex_home.mkdir()
monkeypatch.setenv("CODEX_HOME", str(codex_home))
monkeypatch.setattr(wrap_mod, "_project_name_from_cwd", lambda: None)
config_file = codex_home / "config.toml"
original_config = (
'model = "gpt-5"\n\n'
"[mcp_servers.dingtalk]\n"
'command = "npx"\n'
"env = {\n"
' DINGTALK_Client_ID = "**********",\n'
" \n"
" }\n"
)
config_file.write_text(original_config, encoding="utf-8")
args, env, _ = wrap_mod._codex_session_launch_settings(
port=9898,
codex_args=("exec", "hello"),
environ={"CODEX_HOME": str(codex_home)},
)
assert args[:2] == ("--config", 'openai_base_url="http://127.0.0.1:9898/v1"')
assert env["OPENAI_BASE_URL"] == "http://127.0.0.1:9898/v1"
assert config_file.read_text(encoding="utf-8") == original_config
def test_codex_session_launch_settings_preserve_custom_provider_identity(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
codex_home = tmp_path / "custom-codex-home"
codex_home.mkdir()
monkeypatch.setenv("CODEX_HOME", str(codex_home))
monkeypatch.setattr(wrap_mod, "_project_name_from_cwd", lambda: None)
config_file = codex_home / "config.toml"
original_config = (
'[profiles.work]\nmodel_provider = "company"\n\n'
'[model_providers.company]\nbase_url = "https://api.example.test/v1"\n'
)
config_file.write_text(original_config, encoding="utf-8")
args, env, display = wrap_mod._codex_session_launch_settings(
port=9898,
codex_args=("--profile", "work"),
environ={"CODEX_HOME": str(codex_home)},
)
assert "model_provider=headroom" not in " ".join(args)
# Bare dotted keys — Codex (0.144.x) silently ignores quoted segments (#2358).
assert 'model_providers.company.base_url="http://127.0.0.1:9898/v1"' in args
assert "model_providers.company.supports_websockets=true" in args
assert (
"model_providers.company.env_http_headers.X-Headroom-Base-Url"
'="HEADROOM_CODEX_UPSTREAM_BASE_URL"'
) in args
assert env[wrap_mod._UPSTREAM_BASE_URL_ENV_VAR] == "https://api.example.test/v1"
# Custom-provider routing also goes through --config, so the note applies (#3888).
assert display[-1] == wrap_mod._CODEX_EMBEDDED_MODE_NOTE
assert config_file.read_text(encoding="utf-8") == original_config
def test_codex_dotted_key_emits_bare_segments_when_safe() -> None:
"""#2358: quoted segments are silently ignored by Codex's --config parser."""
assert (
wrap_mod._codex_dotted_key("model_providers", "litellm_prod", "base_url")
== "model_providers.litellm_prod.base_url"
)
# Hyphens are valid in bare keys (header names under env_http_headers).
assert (
wrap_mod._codex_dotted_key("env_http_headers", "X-Headroom-Base-Url")
== "env_http_headers.X-Headroom-Base-Url"
)
def test_codex_dotted_key_quotes_only_unsafe_segments() -> None:
# A provider name that would corrupt the dotted path if emitted bare keeps
# its quotes; every safe neighbor stays bare.
assert (
wrap_mod._codex_dotted_key("model_providers", "my.provider", "base_url")
== 'model_providers."my.provider".base_url'
)
def test_wrap_codex_rejects_custom_provider_without_upstream_base_url(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
codex_home = tmp_path / "custom-codex-home"
codex_home.mkdir()
monkeypatch.setenv("CODEX_HOME", str(codex_home))
(codex_home / "config.toml").write_text(
'model_provider = "company"\n[model_providers.company]\nname = "Company"\n',
encoding="utf-8",
)
def fake_launch(**kwargs: object) -> None:
configure_launch = kwargs["configure_launch"]
assert callable(configure_launch)
configure_launch(
8787,
kwargs["args"],
kwargs["env"],
kwargs["env_vars_display"],
)
with patch(
"headroom.cli.wrap.shutil.which",
side_effect=lambda cmd: "/fake/codex" if cmd == "codex" else None,
):
with patch("headroom.cli.wrap._launch_tool", side_effect=fake_launch):
result = runner.invoke(
main,
[
"wrap",
"codex",
"--port",
"8787",
"--no-mcp",
"--no-tokensave",
"--no-serena",
],
)
assert result.exit_code != 0
assert "custom provider 'company' has no upstream base_url" in result.output
def test_wrap_codex_routes_model_provider_selected_by_config_argument(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
codex_home = tmp_path / "custom-codex-home"
codex_home.mkdir()
monkeypatch.setenv("CODEX_HOME", str(codex_home))
monkeypatch.setattr(wrap_mod, "_project_name_from_cwd", lambda: None)
(codex_home / "config.toml").write_text(
'[model_providers.company]\nbase_url = "https://api.example.test/v1"\n',
encoding="utf-8",
)
configured_env: dict[str, str] = {}
def fake_launch(**kwargs: object) -> None:
configure_launch = kwargs["configure_launch"]
assert callable(configure_launch)
_, env, _ = configure_launch(
8787,
kwargs["args"],
kwargs["env"],
kwargs["env_vars_display"],
)
configured_env.update(env)
with patch(
"headroom.cli.wrap.shutil.which",
side_effect=lambda cmd: "/fake/codex" if cmd == "codex" else None,
):
with patch("headroom.cli.wrap._launch_tool", side_effect=fake_launch):
result = runner.invoke(
main,
[
"wrap",
"codex",
"--no-mcp",
"--no-tokensave",
"--no-serena",
"--",
"--config",
'model_provider="company"',
],
)
assert result.exit_code == 0, result.output
assert configured_env[wrap_mod._UPSTREAM_BASE_URL_ENV_VAR] == ("https://api.example.test/v1")
def test_unwrap_codex_without_codex_home_warns_on_ambiguous_noop(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
codex_home = tmp_path / "custom-codex-home"
codex_home.mkdir()
monkeypatch.setenv("CODEX_HOME", str(codex_home))
wrap_result = runner.invoke(
main,
[
"wrap",
"codex",
"--prepare-only",
"--no-mcp",
"--no-serena",
"--port",
"8787",
],
)
assert wrap_result.exit_code == 0, wrap_result.output
config_file = codex_home / "config.toml"
assert 'openai_base_url = "http://127.0.0.1:8787/v1"' in config_file.read_text(encoding="utf-8")
monkeypatch.delenv("CODEX_HOME", raising=False)
unwrap_result = runner.invoke(main, ["unwrap", "codex", "--no-stop-proxy"])
assert unwrap_result.exit_code == 0, unwrap_result.output
assert "Warning: found no Headroom wrap markers in the default Codex config" in (
unwrap_result.output
)
assert "If you wrapped Codex with CODEX_HOME" in unwrap_result.output
assert "CODEX_HOME=/path/to/codex-home headroom unwrap codex" in unwrap_result.output
assert "Nothing to undo" in unwrap_result.output
assert 'openai_base_url = "http://127.0.0.1:8787/v1"' in config_file.read_text(encoding="utf-8")
def test_start_proxy_uses_separate_session_for_signal_isolation(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Proxy child should not receive Ctrl-C intended for the wrapped CLI."""
popen_kwargs: dict[str, object] = {}
class FakeProc:
returncode = None
def poll(self) -> None:
return None
def fake_popen(*args: object, **kwargs: object) -> FakeProc:
popen_kwargs.update(kwargs)
return FakeProc()
monkeypatch.setattr(wrap_mod, "_get_log_path", lambda port=None: tmp_path / "proxy.log")
monkeypatch.setattr(wrap_mod, "_check_proxy", lambda port: True)
monkeypatch.setattr(wrap_mod.subprocess, "Popen", fake_popen)
proc = wrap_mod._start_proxy(8787, agent_type="codex")
assert isinstance(proc, FakeProc)
assert popen_kwargs["start_new_session"] == (wrap_mod.os.name == "posix")
@pytest.mark.parametrize("agent_type", ["claude", "codex", "cursor"])
def test_start_proxy_does_not_apply_agent_90_defaults(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, agent_type: str
) -> None:
"""Wrapped coding agents keep agent-savings opt-in by default."""
# Clean baseline: the proxy's out-of-box coding profile seeds these into the
# process env at startup (``seed_proxy_env_defaults``), which another test in
# the shard can leave behind in ``os.environ``. This test is about what the
# WRAPPER adds, so start from an unset env rather than inheriting pollution.
for _var in (
"HEADROOM_SAVINGS_PROFILE",
"HEADROOM_TARGET_RATIO",
"HEADROOM_MAX_ITEMS",
"HEADROOM_SMART_CRUSHER_COMPACTION",
):
monkeypatch.delenv(_var, raising=False)
popen_kwargs: dict[str, object] = {}
class FakeProc:
returncode = None
def poll(self) -> None:
return None
def fake_popen(*args: object, **kwargs: object) -> FakeProc:
popen_kwargs.update(kwargs)
return FakeProc()
monkeypatch.setattr(wrap_mod, "_get_log_path", lambda port=None: tmp_path / "proxy.log")
monkeypatch.setattr(wrap_mod, "_check_proxy", lambda port: True)
monkeypatch.setattr(wrap_mod.subprocess, "Popen", fake_popen)
wrap_mod._start_proxy(8787, agent_type=agent_type)
env = popen_kwargs["env"]
assert isinstance(env, dict)
assert "HEADROOM_SAVINGS_PROFILE" not in env
assert "HEADROOM_TARGET_RATIO" not in env
assert "HEADROOM_MAX_ITEMS" not in env
assert "HEADROOM_SMART_CRUSHER_COMPACTION" not in env
def test_start_proxy_preserves_explicit_savings_overrides(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""User-provided savings env vars should override wrapper defaults."""
popen_kwargs: dict[str, object] = {}
class FakeProc:
returncode = None
def poll(self) -> None:
return None
def fake_popen(*args: object, **kwargs: object) -> FakeProc:
popen_kwargs.update(kwargs)
return FakeProc()
monkeypatch.setenv("HEADROOM_TARGET_RATIO", "0.20")
monkeypatch.setenv("HEADROOM_MAX_ITEMS", "12")
monkeypatch.setattr(wrap_mod, "_get_log_path", lambda port=None: tmp_path / "proxy.log")
monkeypatch.setattr(wrap_mod, "_check_proxy", lambda port: True)
monkeypatch.setattr(wrap_mod.subprocess, "Popen", fake_popen)
wrap_mod._start_proxy(8787, agent_type="codex")
env = popen_kwargs["env"]
assert isinstance(env, dict)
assert env["HEADROOM_TARGET_RATIO"] == "0.20"
assert env["HEADROOM_MAX_ITEMS"] == "12"
def test_launch_tool_ignores_sigint_in_wrapper(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Ctrl-C should be handled by the child CLI, not kill the proxy from wrapper."""
signal_handlers: dict[object, object] = {}
class FakeCompleted:
returncode = 0
monkeypatch.setattr(wrap_mod, "_ensure_proxy", lambda *args, **kwargs: (None, 8787))
monkeypatch.setattr(
wrap_mod.signal, "signal", lambda sig, fn: signal_handlers.setdefault(sig, fn)
)
monkeypatch.setattr(wrap_mod.subprocess, "run", lambda *args, **kwargs: FakeCompleted())
with pytest.raises(SystemExit) as exc:
wrap_mod._launch_tool(
binary="codex",
args=(),
env={},
port=8787,
no_proxy=True,
tool_label="CODEX",
env_vars_display=[],
)
assert exc.value.code == 0
assert signal_handlers[wrap_mod.signal.SIGINT] is wrap_mod._ignore_child_sigint
def test_wrap_codex_prepare_only_updates_stale_mcp_proxy_url(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
config_file.write_text(
"# --- Headroom MCP server ---\n"
"[mcp_servers.headroom]\n"
'command = "headroom"\n'
'args = ["mcp", "serve"]\n'
"\n"
"[mcp_servers.headroom.env]\n"
'HEADROOM_PROXY_URL = "http://127.0.0.1:9000"\n'
"# --- end Headroom MCP server ---\n",
encoding="utf-8",
)
result = runner.invoke(main, ["wrap", "codex", "--prepare-only", "--port", "8787"])
assert result.exit_code == 0, result.output
content = config_file.read_text(encoding="utf-8")
parsed = tomllib.loads(content)
expected = build_headroom_spec()
headroom_mcp = parsed["mcp_servers"]["headroom"]
assert "[mcp_servers.headroom]" in content
assert headroom_mcp["command"] == expected.command
assert headroom_mcp["args"] == list(expected.args)
assert "env" not in headroom_mcp or "HEADROOM_PROXY_URL" not in headroom_mcp["env"]
assert "http://127.0.0.1:9000" not in content
def test_wrap_codex_memory_prepare_only_uses_local_db_without_persisting_it(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
monkeypatch.setenv("USER", "codex-user")
project_dir = tmp_path / "project-a"
project_dir.mkdir()
monkeypatch.chdir(project_dir)
backend_paths: list[str] = []
imported_users: list[str] = []
class FakeBackend:
async def _ensure_initialized(self) -> None:
return None
async def close(self) -> None:
return None
class FakeClaudeCodeAdapter:
def __init__(self, memory_dir: Path) -> None:
self.memory_dir = memory_dir
def fake_build_sync_backend(db_path: str) -> FakeBackend:
backend_paths.append(db_path)
return FakeBackend()
async def fake_sync_import(
backend: FakeBackend, adapter: FakeClaudeCodeAdapter, user_id: str
) -> int:
imported_users.append(user_id)
return 0
with patch("headroom.memory.sync._build_sync_backend", side_effect=fake_build_sync_backend):
with patch("headroom.memory.sync.sync_import", side_effect=fake_sync_import):
with patch(
"headroom.memory.sync_adapters.claude_code.ClaudeCodeAdapter",
FakeClaudeCodeAdapter,
):
with patch(
"headroom.memory.sync_adapters.claude_code.get_claude_memory_dir",
return_value=tmp_path / "claude-memory",
):
result = runner.invoke(
main,
[
"wrap",
"codex",
"--memory",
"--prepare-only",
"--no-mcp",
"--no-serena",
],
)
assert result.exit_code == 0, result.output
assert backend_paths == [str(project_dir / ".headroom" / "memory.db")]
assert imported_users == ["codex-user"]
content = (tmp_path / ".codex" / "config.toml").read_text()
assert "[mcp_servers.headroom_memory]" in content
assert '"--user", "codex-user"' in content
assert "--db" not in content
def test_wrap_codex_prepare_only_registers_serena_when_uvx_exists(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
monkeypatch.setenv("HEADROOM_CODE_MEMORY", "serena")
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
def fake_which(cmd: str) -> str | None:
if cmd == "uvx":
return "/usr/local/bin/uvx"
return None
with patch("headroom.cli.wrap.shutil.which", side_effect=fake_which):
# Serena is opted in; assert it lands in the codex config.
result = runner.invoke(main, ["wrap", "codex", "--prepare-only"])
assert result.exit_code == 0, result.output
content = config_file.read_text(encoding="utf-8")
assert "[mcp_servers.serena]" in content
assert 'command = "uvx"' in content
assert '"--context", "codex"' in content
def test_wrap_codex_prepare_only_no_serena_skips_serena(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
result = runner.invoke(main, ["wrap", "codex", "--prepare-only", "--no-serena"])
assert result.exit_code == 0, result.output
assert "[mcp_servers.serena]" not in config_file.read_text(encoding="utf-8")
def test_unwrap_codex_restores_prior_config_end_to_end(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""The bug report, reproduced: wrap → unwrap must round-trip cleanly."""
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
original = (
"[profiles.default]\n"
'model = "gpt-4o"\n'
"\n"
"[model_providers.openai]\n"
'base_url = "https://api.openai.com/v1"\n'
)
config_file.write_text(original, encoding="utf-8")
wrap_result = runner.invoke(main, ["wrap", "codex", "--prepare-only", "--port", "8787"])
assert wrap_result.exit_code == 0, wrap_result.output
assert 'model_provider = "headroom"' in config_file.read_text(encoding="utf-8")
stopped: list[int] = []
with patch(
"headroom.cli.wrap._stop_local_proxy_for_unwrap",
side_effect=lambda port: stopped.append(port) or "stopped",
):
unwrap_result = runner.invoke(main, ["unwrap", "codex", "--port", "9999"])
assert unwrap_result.exit_code == 0, unwrap_result.output
# Config must be byte-for-byte what the user had before wrap, and the
# injected block must be gone — no more "Missing OPENAI_API_KEY" when the
# proxy is stopped.
assert config_file.read_text(encoding="utf-8") == original
assert 'model_provider = "headroom"' not in config_file.read_text(encoding="utf-8")
assert not (tmp_path / ".codex" / "config.toml.headroom-backup").exists()
assert stopped == [9999]
assert "Stopped local Headroom proxy on port 9999" in unwrap_result.output
def test_unwrap_codex_no_stop_proxy_leaves_proxy_alone(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
monkeypatch.setenv("CODEX_HOME", str(tmp_path / "explicit-codex-home"))
with patch("headroom.cli.wrap._stop_local_proxy_for_unwrap") as stop_proxy:
result = runner.invoke(main, ["unwrap", "codex", "--no-stop-proxy"])
assert result.exit_code == 0, result.output
stop_proxy.assert_not_called()
def test_wrap_codex_memory_prepare_only_unwrap_removes_memory_mcp_without_prior_config(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
monkeypatch.setenv("USER", "codex-user")
project_dir = tmp_path / "project-a"
project_dir.mkdir()
monkeypatch.chdir(project_dir)
class FakeBackend:
async def _ensure_initialized(self) -> None:
return None
async def close(self) -> None:
return None
async def fake_sync_import(backend: FakeBackend, adapter: object, user_id: str) -> int:
return 0
with patch("headroom.memory.sync._build_sync_backend", return_value=FakeBackend()):
with patch("headroom.memory.sync.sync_import", side_effect=fake_sync_import):
with patch(
"headroom.memory.sync_adapters.claude_code.ClaudeCodeAdapter",
autospec=True,
):
with patch(
"headroom.memory.sync_adapters.claude_code.get_claude_memory_dir",
return_value=tmp_path / "claude-memory",
):
wrap_result = runner.invoke(
main,
[
"wrap",
"codex",
"--memory",
"--prepare-only",
"--no-mcp",
"--no-serena",
],
)
assert wrap_result.exit_code == 0, wrap_result.output
config_file = tmp_path / ".codex" / "config.toml"
content = config_file.read_text()
assert "[mcp_servers.headroom_memory]" in content
assert '"--user", "codex-user"' in content
with patch("headroom.cli.wrap._stop_local_proxy_for_unwrap") as stop_proxy:
unwrap_result = runner.invoke(main, ["unwrap", "codex", "--no-stop-proxy"])
assert unwrap_result.exit_code == 0, unwrap_result.output
assert not config_file.exists()
assert not (tmp_path / ".codex" / "config.toml.headroom-backup").exists()
stop_proxy.assert_not_called()
def test_wrap_codex_memory_launch_failure_unwrap_cleans_memory_only_config(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
monkeypatch.setenv("USER", "codex-user")
project_dir = tmp_path / "project-a"
project_dir.mkdir()
monkeypatch.chdir(project_dir)
class FakeBackend:
async def _ensure_initialized(self) -> None:
return None
async def close(self) -> None:
return None
async def fake_sync_import(backend: FakeBackend, adapter: object, user_id: str) -> int:
return 0
def fake_which(cmd: str) -> str | None:
return None if cmd == "codex" else shutil.which(cmd)
with patch("headroom.cli.wrap.shutil.which", side_effect=fake_which):
with patch("headroom.memory.sync._build_sync_backend", return_value=FakeBackend()):
with patch("headroom.memory.sync.sync_import", side_effect=fake_sync_import):
with patch(
"headroom.memory.sync_adapters.claude_code.ClaudeCodeAdapter",
autospec=True,
):
with patch(
"headroom.memory.sync_adapters.claude_code.get_claude_memory_dir",
return_value=tmp_path / "claude-memory",
):
wrap_result = runner.invoke(
main,
["wrap", "codex", "--memory", "--no-mcp", "--no-serena"],
)
assert wrap_result.exit_code == 1
config_file = tmp_path / ".codex" / "config.toml"
assert not config_file.exists()
assert not (tmp_path / ".codex" / "config.toml.headroom-backup").exists()
with patch("headroom.cli.wrap._stop_local_proxy_for_unwrap") as stop_proxy:
unwrap_result = runner.invoke(main, ["unwrap", "codex", "--no-stop-proxy"])
assert unwrap_result.exit_code == 0, unwrap_result.output
assert "Nothing to undo" in unwrap_result.output
stop_proxy.assert_not_called()
def test_stop_local_proxy_for_unwrap_kills_identified_headroom_proxy(
monkeypatch: pytest.MonkeyPatch,
) -> None:
killed: list[tuple[int, int]] = []
monkeypatch.setattr(wrap_mod, "_check_proxy", lambda port: True)
monkeypatch.setattr(wrap_mod, "_query_proxy_config", lambda port: {"pid": "12345"})
monkeypatch.setattr(
wrap_mod,
"_kill_proxy_by_pid",
lambda pid, port: killed.append((pid, port)) or True,
)
assert wrap_mod._stop_local_proxy_for_unwrap(8787) == "stopped"
assert killed == [(12345, 8787)]
def test_stop_local_proxy_for_unwrap_refuses_unidentified_listener(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(wrap_mod, "_check_proxy", lambda port: True)
monkeypatch.setattr(wrap_mod, "_query_proxy_config", lambda port: None)
with patch("headroom.cli.wrap._kill_proxy_by_pid") as kill_proxy:
assert wrap_mod._stop_local_proxy_for_unwrap(8787) == "unidentified"
kill_proxy.assert_not_called()
def test_unwrap_codex_is_safe_noop_with_explicit_codex_home(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
monkeypatch.setenv("CODEX_HOME", str(tmp_path / "explicit-codex-home"))
result = runner.invoke(main, ["unwrap", "codex"])
assert result.exit_code == 0, result.output
assert "Nothing to undo" in result.output
assert "Warning:" not in result.output
assert not (tmp_path / ".codex" / "config.toml").exists()
def test_unwrap_codex_removes_headroom_only_config_file(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
wrap_result = runner.invoke(main, ["wrap", "codex", "--prepare-only", "--port", "8787"])
assert wrap_result.exit_code == 0, wrap_result.output
config_file = tmp_path / ".codex" / "config.toml"
assert config_file.exists()
unwrap_result = runner.invoke(main, ["unwrap", "codex"])
assert unwrap_result.exit_code == 0, unwrap_result.output
assert not config_file.exists()
def test_unwrap_codex_preserves_unrelated_sections(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
# A config with an MCP server the user configured by hand.
original = '[mcp_servers.local_thing]\ncommand = "/usr/local/bin/thing"\nargs = ["--serve"]\n'
config_file.write_text(original, encoding="utf-8")
runner.invoke(main, ["wrap", "codex", "--prepare-only", "--port", "8787"])
result = runner.invoke(main, ["unwrap", "codex"])
assert result.exit_code == 0, result.output
restored = config_file.read_text(encoding="utf-8")
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
# ---------------------------------------------------------------------------
class TestCodexProjectHeaderConfig:
"""The injected provider maps X-Headroom-Project to HEADROOM_PROJECT.
Codex's ``env_http_headers`` sends a header only when the mapped env var
is set at Codex runtime, so `headroom wrap codex` exports
``HEADROOM_PROJECT`` and the proxy attributes savings per project.
"""
def test_inject_writes_env_http_headers_mapping(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
wrap_mod._inject_codex_provider_config(8787)
content = (tmp_path / ".codex" / "config.toml").read_text(encoding="utf-8")
assert 'env_http_headers = { "X-Headroom-Project" = "HEADROOM_PROJECT" }' in content
def test_env_http_headers_inside_provider_section(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""The mapping must live inside [model_providers.headroom], before
the closing marker, so it applies to the Headroom provider."""
_set_test_home(monkeypatch, tmp_path)
wrap_mod._inject_codex_provider_config(8787)
content = (tmp_path / ".codex" / "config.toml").read_text(encoding="utf-8")
section_start = content.index("[model_providers.headroom]")
mapping_pos = content.index("env_http_headers")
end_marker_pos = content.index(wrap_mod._CODEX_END_MARKER, section_start)
assert section_start < mapping_pos < end_marker_pos
def test_strip_removes_block_with_env_http_headers(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""_strip_codex_headroom_blocks removes the whole injected block,
including the new env_http_headers line, leaving user content."""
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
original = '[profiles.default]\nmodel = "gpt-4o"\n'
config_file.write_text(original, encoding="utf-8")
wrap_mod._inject_codex_provider_config(8787)
wrapped = config_file.read_text(encoding="utf-8")
assert "env_http_headers" in wrapped
cleaned = wrap_mod._strip_codex_headroom_blocks(wrapped)
assert "env_http_headers" not in cleaned
assert "X-Headroom-Project" not in cleaned
assert "[model_providers.headroom]" not in cleaned
assert 'model = "gpt-4o"' in cleaned
# ---------------------------------------------------------------------------
# Regression: codex preserves the requested port through the session-scoped runner
# ---------------------------------------------------------------------------
class TestCodexPortResolution:
"""codex() hands the requested port to the session-scoped wrap runner.
Regression for headroom#1406 round 2 review: the codex command must keep
the selected-port contract intact after the session-home refactor instead
of silently dropping or rewriting the requested port before the shared
launch path handles proxy reuse and fallback.
"""
def test_delegates_to_session_runner(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""codex() passes the requested port through to _run_codex_wrap."""
_set_test_home(monkeypatch, Path("/tmp/test_headroom_codex"))
call_kw: dict = {}
def mock_run_codex_wrap(**kwargs: object) -> None:
call_kw.update(kwargs)
monkeypatch.setattr(wrap_mod, "_run_codex_wrap", mock_run_codex_wrap)
runner = CliRunner()
result = runner.invoke(
main,
["wrap", "codex", "--port", "8787", "--no-mcp", "--no-serena"],
)
assert result.exit_code == 0, f"CLI failed: {result.output}"
assert call_kw.get("port") == 8787
assert call_kw.get("no_proxy") is False
assert call_kw.get("prepare_only") is False
class TestCodexLaunchExportsCustomUpstream:
"""`_run_codex_wrap` must export the detected custom upstream base URL into
the launch env so Codex emits the ``X-Headroom-Base-Url`` header. Otherwise
the proxy falls back to api.openai.com and the user's gateway key is sent to
the wrong host (regression of #1614)."""
def _launch_env(self, monkeypatch, tmp_path, *, custom_upstream):
captured: dict = {}
monkeypatch.setattr(wrap_mod.shutil, "which", lambda name: "/usr/bin/codex")
monkeypatch.setattr(wrap_mod, "_codex_home_dir", lambda: tmp_path)
monkeypatch.setattr(wrap_mod, "_offer_dangling_codex_recovery", lambda active_home: None)
monkeypatch.setattr(wrap_mod, "_prepare_codex_wrap_state", lambda **kwargs: None)
if custom_upstream:
(tmp_path / "config.toml").write_text(
"\n".join(
(
'model_provider = "gateway"',
"[model_providers.gateway]",
f'base_url = "{custom_upstream}"',
)
)
+ "\n",
encoding="utf-8",
)
def _fake_launch(*, env, port, configure_launch, args=(), env_vars_display=(), **kwargs):
if configure_launch is not None:
_args, env, _display = configure_launch(port, args, env, list(env_vars_display))
captured["env"] = env
monkeypatch.setattr(wrap_mod, "_launch_tool", _fake_launch)
wrap_mod._run_codex_wrap(
port=8787,
no_mcp=True,
no_tokensave=True,
serena=False,
no_serena=True,
code_graph=False,
no_proxy=True,
learn=False,
memory=False,
backend=None,
anyllm_provider=None,
region=None,
verbose=False,
prepare_only=False,
codex_args=(),
)
return captured["env"]
def test_custom_upstream_exported_into_launch_env(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
env = self._launch_env(monkeypatch, tmp_path, custom_upstream="https://api.freemodel.dev")
assert env[wrap_mod._UPSTREAM_BASE_URL_ENV_VAR] == "https://api.freemodel.dev"
def test_no_custom_upstream_leaves_env_var_unset(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
env = self._launch_env(monkeypatch, tmp_path, custom_upstream=None)
assert wrap_mod._UPSTREAM_BASE_URL_ENV_VAR not in env
@pytest.mark.parametrize("original", ["", 'model = "gpt-5"\n'])
def test_unwrap_init_snapshot_removes_unreferenced_auth_helper(monkeypatch, tmp_path, original):
from headroom.cli import init as init_cli
from headroom.providers.codex.install import codex_auth_helper_path
_set_test_home(monkeypatch, tmp_path)
config = tmp_path / ".codex/config.toml"
config.parent.mkdir()
config.write_text(original, encoding="utf-8")
auth = config.with_name("auth.json")
auth.write_text('{"OPENAI_API_KEY":"test-key"}', encoding="utf-8")
init_cli._ensure_codex_provider(config, 8787)
helper = codex_auth_helper_path(auth, config_path=config)
assert helper.exists()
backup = wrap_mod._codex_config_paths()[1]
backup.write_text(config.read_text(encoding="utf-8"), encoding="utf-8")
wrap_mod._restore_codex_provider_config()
assert not helper.exists()
assert not backup.exists()
if original:
assert tomllib.loads(config.read_text(encoding="utf-8")) == tomllib.loads(original)
else:
assert not config.exists()
@pytest.mark.parametrize("with_backup", [False, True])
def test_unwrap_preserves_adopted_provider_options(monkeypatch, tmp_path, with_backup):
from headroom.cli import init as init_cli
_set_test_home(monkeypatch, tmp_path)
config = tmp_path / ".codex/config.toml"
config.parent.mkdir()
original = '[model_providers.headroom]\nbase_url = "http://127.0.0.1:9200/v1"\nrequest_max_retries = 7\n'
config.write_text(original, encoding="utf-8")
init_cli._ensure_codex_provider(config, 8787)
init_cli._ensure_codex_provider(config, 9500)
if with_backup:
backup = wrap_mod._codex_config_paths()[1]
backup.write_text(config.read_text(encoding="utf-8"), encoding="utf-8")
wrap_mod._restore_codex_provider_config()
assert tomllib.loads(config.read_text(encoding="utf-8")) == tomllib.loads(original)