mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 12:05:34 +08:00
fix(cli): name the broken Codex config, write init configs atomically, keep the identity check (#4129)
## Description
This PR fixes four small CLI problems.
1. **`wrap codex` with a broken `~/.codex/config.toml`.** The warning
looked like this:
```
Warning: could not update Codex config: Invalid value (at line 6, column
10)
```
The line number pointed into Headroom's own merged text, not the user's
file, and the file was never named. The warning now names the file,
gives the parse error in the user's own lines, and says what to do. The
generic Codex and Grok config warnings now also name the file.
2. **`headroom init` truncated config files while rewriting them.** It
rewrote `~/.claude/settings.json`, Codex `hooks.json` and
`~/.codex/config.toml` with `Path.write_text`. That truncates the file
before writing, so a crash or ENOSPC mid-write left a half-written file.
`init` now uses `fsutil.write_text`, the atomic writer `wrap` already
uses for these same files.
3. **The runtime identity check could be silently skipped.** `init` and
`wrap` each had a `_wait_for_runtime_ready` wrapper. It caught
`TypeError` "for test doubles" and then retried `wait_ready` without
`require_identity=True`. So any real `TypeError` inside `wait_ready`
dropped the runtime identity check. Both wrappers are removed, and
callers now pass `require_identity=True` directly.
4. **A failed hook recovery left no trace.** `_ensure_profile_running`
(the init hook's recovery path) ended in `except Exception: return`. It
now catches only what the start paths raise (`click.ClickException`,
`RuntimeError`, `OSError`, `subprocess.SubprocessError`) and logs one
WARNING after the suppressed-output block: `headroom: could not start
persistent proxy '<profile>': <error>. Check it with `headroom install
status --profile <profile>`.` A start that succeeds but never becomes
ready within 45s logs the same line with `it did not become ready within
45s` as the reason. It goes to stderr; stdout stays clean for the hook.
Any other exception is a bug and now surfaces.
Refs #4136
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)
## Changes Made
- `headroom/cli/wrap.py` `_inject_codex_provider_config`: it now parses
the user's own content, with Headroom blocks stripped, before building
the candidate.
- If that content does not parse, it warns `could not update Codex
config <path>: it is not valid TOML (<user's own parse error>); Codex
WebSocket traffic will bypass Headroom. Fix or remove the file, then
re-run.`
- If the content parses only once the Headroom block is removed, the old
repair path runs instead.
- The snapshot still happens first, so `unwrap codex` restores the file
exactly as before.
- `headroom/cli/wrap.py`: the generic Codex and Grok config warnings now
include the file path (`grok_config_paths()`).
- `headroom/cli/init.py`: `_write_json`, `_ensure_codex_provider` and
the Codex feature-block writer now call `fsutil.write_text`.
- `headroom/cli/init.py` and `headroom/cli/wrap.py`: removed
`_wait_for_runtime_ready`; callers call `wait_ready(...,
require_identity=True)` directly.
- `headroom/cli/init.py` `_ensure_profile_running`: narrowed `except
Exception: return` to the start-path exceptions and log the failure
once, as above.
- Tests:
- New `test_invalid_user_config_is_named_and_left_untouched` in
`test_wrap_codex.py`.
- New `test_write_json_keeps_the_existing_file_when_the_write_fails` in
`test_init_cli.py`. It simulates ENOSPC at fsync and checks that the
original file survives and no temp file is left.
- New
`test_ensure_profile_running_never_retries_wait_ready_without_identity`:
its `wait_ready` double raises `TypeError` whenever `require_identity`
is passed. It asserts the error propagates and `wait_ready` was called
once, with `require_identity=True`. It fails if the fallback comes back.
- New `test_ensure_profile_running_logs_a_failed_recovery`: no log on a
clean start; exactly the one WARNING above when `start_supervisor`
raises.
- New
`test_ensure_profile_running_logs_a_recovery_that_never_becomes_ready`:
the start succeeds, the 45s `wait_ready` returns False, and the WARNING
names that reason.
- The `wait_ready` doubles in `test_init_cli.py` and
`test_wrap_persistent.py` now accept, or assert, `require_identity`;
`test_recover_persistent_proxy_routes_docker_task_to_docker_supervisor`
asserts `require_identity=True`.
- All four new tests fail on origin/main and pass here.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed
### Test Output
```text
$ pytest -q -p no:cacheprovider tests/test_cli/test_init_cli.py tests/test_cli/test_wrap_persistent.py tests/test_cli/test_wrap_codex.py tests/test_cli/test_wrap_grok.py tests/test_cli/test_init_enable_tool_search.py tests/test_cli/test_install_cli.py tests/test_install/test_providers.py tests/test_install/test_runtime.py tests/test_plugin_manifests.py tests/test_cli/test_wrap_helpers.py tests/test_cli/test_port_alignment.py
4 failed, 595 passed in 29.13s
# The 4 failures are in tests/test_cli/test_wrap_persistent.py ("'_Manifest' object has no attribute 'runtime_kind'"). They are pre-existing: clean origin/main gives "4 failed, 59 passed" for that file.
# The new tests against origin/main code:
test_invalid_user_config_is_named_and_left_untouched: 1 failed (old message names no file)
test_write_json_keeps_the_existing_file_when_the_write_fails: 1 failed (DID NOT RAISE: the old write_text never fsyncs and overwrote the file)
test_ensure_profile_running_never_retries_wait_ready_without_identity: 1 failed (DID NOT RAISE: the fallback retried without require_identity)
test_ensure_profile_running_logs_a_failed_recovery: 1 failed (no log record)
$ uvx ruff@0.16.8 check headroom/cli/init.py headroom/cli/wrap.py tests/test_cli/test_init_cli.py tests/test_cli/test_wrap_persistent.py tests/test_cli/test_wrap_codex.py
All checks passed!
$ mypy headroom/cli/init.py headroom/cli/wrap.py --ignore-missing-imports
Success: no issues found in 2 source files
```
## Real Behavior Proof
- Environment: macOS 25.6, Python 3.12, repo `.venv`.
- Exact command / steps:
1. Ran `python -m headroom.cli wrap codex --prepare-only` with a scratch
`HOME` whose `.codex/config.toml` is `model = [unterminated`. This is
the audit's reproduction, and the new test covers it.
2. Called `_recover_persistent_proxy` and `_restart_persistent_proxy`
directly, with the supervisor and `wait_ready` stubbed, and recorded the
arguments `wait_ready` received.
- Observed result:
1. Before: `Warning: could not update Codex config: Invalid value (at
line 6, column 10)`. After: the warning names
`<HOME>/.codex/config.toml`, reports the error at line 1 (the user's
line), and tells the user to fix or remove the file.
2. Both calls passed `{'timeout_seconds': 45, 'require_identity':
True}`.
- Smoke harness (real proxy started from this checkout against a local
fake upstream; temp HOME and workspace, offline):
```text
branch: cleanup/cli-integrations-config-errors-atomic-init @ 08386d03
health: 200
POST /v1/messages -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines (<tmp>/ws/logs/proxy-49764.log):
2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you configured, operator-configured local endpoints, loopback health probes.
4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base
4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection.
(smoke dir: <tmp>)
```
- Direct runtime command on this PR's own path (temp HOME,
HEADROOM_WORKSPACE_DIR and CODEX_HOME):
```text
## pr5
$ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom init hook ensure --profile hookdemo
exit=0
--- stdout
--- stderr
headroom: could not start persistent proxy 'hookdemo': [Errno 2] No such file or directory: 'docker'. Check it with `headroom install status --profile hookdemo`.
## clean
$ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom init hook ensure --profile hookdemo
exit=0
--- stdout
--- stderr
## pr5
$ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom wrap codex --prepare-only
exit=0
--- stdout
Warning: could not update Codex config <tmp>/codex/config.toml: it is not valid TOML (Invalid value (at line 1, column 10)); Codex WebSocket traffic will bypass Headroom. Fix or remove the file, then re-run.
--- stderr
## clean
$ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom wrap codex --prepare-only
exit=0
--- stdout
Warning: could not update Codex config: Invalid value (at line 6, column 10)
--- stderr
```
- Not tested: a real disk-full condition; the regression test simulates
ENOSPC at fsync. Windows was not tested either.
## Runtime Rollout Safety
- Rollout-managed feature(s): None.
- Minimum rollout channel: N/A, not rollout-managed.
- Stable/default behavior changed: Yes, in small ways:
- The warning text for an invalid Codex config changes. It stays
non-fatal, and `--prepare-only` still exits 0.
- `init` writes its config files atomically. On Windows they get LF line
endings, the same as `wrap` already writes. New files get mode 0600 from
mkstemp, and existing files keep their mode.
- `wait_ready` is always called with the identity check.
- A failed init-hook recovery now writes one WARNING line to stderr
instead of nothing.
- Kill switch / disable path: None needed.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert this commit.
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Checklist
- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)
## Screenshots (if applicable)
N/A
## Additional Notes
- Part of maintainer-requested cleanup #4136 (dead code, duplication,
debuggability), split into small PRs for review.
- Docs impact is recorded in the cleanup docs ledger; there are no doc
edits in this PR.
- **For the maintainer:** should `wrap codex --prepare-only` exit
non-zero when it cannot inject? `scripts/install.sh` relies on that
command. I left it non-fatal, as before.
- **Test-isolation hazard (separate issue, not fixed here):** while
checking the 4 pre-existing `test_wrap_persistent.py` failures, I added
a `runtime_kind` attribute to its `_Manifest` fixture locally. With that
one change, `test_ensure_proxy_restarts_*` started a **real** `headroom
proxy --port 8787` with the real `HOME`. Those tests do not fully stub
process start.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- devin-review-badge-begin -->
---
<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4129"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
e6eaa41179
commit
976aa714ef
+27
-18
@@ -16,6 +16,7 @@ from hashlib import sha1
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from headroom import fsutil
|
||||
from headroom._subprocess import run
|
||||
|
||||
try:
|
||||
@@ -69,15 +70,6 @@ from .main import main
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _wait_for_runtime_ready(manifest: Any, timeout_seconds: int) -> bool:
|
||||
"""Keep hook recovery gated by both readiness and runtime identity."""
|
||||
try:
|
||||
return wait_ready(manifest, timeout_seconds=timeout_seconds, require_identity=True)
|
||||
except TypeError:
|
||||
# Compatibility for test doubles that predate the keyword-only guard.
|
||||
return wait_ready(manifest, timeout_seconds=timeout_seconds)
|
||||
|
||||
|
||||
_VERBOSE_HANDLER_ATTR = "_headroom_init_verbose_handler"
|
||||
|
||||
_GLOBAL_PROFILE = "init-user"
|
||||
@@ -208,7 +200,7 @@ def _json_file(path: Path) -> dict[str, Any]:
|
||||
def _write_json(path: Path, payload: dict[str, Any]) -> None:
|
||||
logger.debug("write json: %s (keys=%s)", path, sorted(payload.keys()))
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
|
||||
fsutil.write_text(path, json.dumps(payload, indent=2) + "\n")
|
||||
|
||||
|
||||
def _ensure_claude_hooks(path: Path, profile: str, port: int) -> None:
|
||||
@@ -491,7 +483,7 @@ def _ensure_codex_provider(path: Path, port: int) -> None:
|
||||
)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tomllib.loads(content)
|
||||
path.write_text(content, encoding="utf-8")
|
||||
fsutil.write_text(path, content)
|
||||
# Codex filters its history menu by the active model_provider, so existing
|
||||
# native threads vanish once we switch to "headroom". Retag them to match the
|
||||
# active provider so the history stays whole (#961), mirroring the install
|
||||
@@ -621,7 +613,7 @@ def _ensure_codex_feature_flag(path: Path) -> None:
|
||||
content.rstrip() + "\n\n[features]\n\n" + _codex_feature_block() + "\n"
|
||||
).lstrip()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(content, encoding="utf-8")
|
||||
fsutil.write_text(path, content)
|
||||
|
||||
|
||||
def _ensure_codex_hooks(path: Path, profile: str) -> None:
|
||||
@@ -883,17 +875,22 @@ def _ensure_profile_running(profile: str) -> None:
|
||||
return
|
||||
if manifest is None:
|
||||
return
|
||||
failure: str | None = None
|
||||
with _suppress_hook_output():
|
||||
if _wait_for_runtime_ready(manifest, timeout_seconds=1):
|
||||
if wait_ready(manifest, timeout_seconds=1, require_identity=True):
|
||||
return
|
||||
try:
|
||||
with acquire_runtime_start_lock(manifest.profile) as acquired:
|
||||
if not acquired:
|
||||
return
|
||||
if _wait_for_runtime_ready(manifest, timeout_seconds=1):
|
||||
if wait_ready(manifest, timeout_seconds=1, require_identity=True):
|
||||
return
|
||||
if runtime_status(manifest) == "running":
|
||||
if _wait_for_runtime_ready(manifest, _STARTUP_READY_TIMEOUT_SECONDS):
|
||||
if wait_ready(
|
||||
manifest,
|
||||
timeout_seconds=_STARTUP_READY_TIMEOUT_SECONDS,
|
||||
require_identity=True,
|
||||
):
|
||||
return
|
||||
stop_runtime(manifest)
|
||||
if runtime_ownership(manifest) == "docker-supervisor":
|
||||
@@ -902,9 +899,21 @@ def _ensure_profile_running(profile: str) -> None:
|
||||
start_supervisor(manifest)
|
||||
else:
|
||||
start_detached_agent(manifest.profile)
|
||||
_wait_for_runtime_ready(manifest, 45)
|
||||
except Exception:
|
||||
return
|
||||
if not wait_ready(manifest, timeout_seconds=45, require_identity=True):
|
||||
failure = "it did not become ready within 45s"
|
||||
except (click.ClickException, RuntimeError, OSError, subprocess.SubprocessError) as exc:
|
||||
# Supervisor and runtime starts raise these; anything else is a bug
|
||||
# and should surface. Report outside the suppressed block so the
|
||||
# one line reaches stderr while stdout stays clean for the hook.
|
||||
failure = str(exc)
|
||||
if failure is not None:
|
||||
logger.warning(
|
||||
"headroom: could not start persistent proxy %r: %s. "
|
||||
"Check it with `headroom install status --profile %s`.",
|
||||
manifest.profile,
|
||||
failure,
|
||||
manifest.profile,
|
||||
)
|
||||
|
||||
|
||||
def _probe_init_targets(global_scope: bool) -> list[tuple[str, str | None]]:
|
||||
|
||||
+29
-18
@@ -171,6 +171,7 @@ from headroom.providers.grok import (
|
||||
)
|
||||
from headroom.providers.grok_build import render_setup_lines as _render_grok_build_setup_lines
|
||||
from headroom.providers.grok_build.config import (
|
||||
grok_config_paths,
|
||||
inject_grok_provider_config,
|
||||
restore_grok_provider_config,
|
||||
)
|
||||
@@ -3641,12 +3642,31 @@ def _inject_codex_provider_config(port: int) -> str | None:
|
||||
_snapshot_codex_config_if_unwrapped(config_file, backup_file)
|
||||
|
||||
if config_file.exists():
|
||||
content = _read_text(config_file)
|
||||
original = _read_text(config_file)
|
||||
# Remove any prior Headroom-managed blocks before re-injecting so
|
||||
# the operation is idempotent and supports port changes.
|
||||
content = _strip_codex_headroom_blocks(content)
|
||||
content = _strip_codex_headroom_blocks(original)
|
||||
content = _strip_existing_codex_headroom_provider_table(content)
|
||||
|
||||
# Report a broken file in the user's own terms. The candidate
|
||||
# validated below is the merged text, so its parse error would
|
||||
# name a line the user never wrote. Only the user's part has to
|
||||
# parse: stripping a stale Headroom block may be what repairs it.
|
||||
try:
|
||||
tomllib.loads(content)
|
||||
except tomllib.TOMLDecodeError:
|
||||
try:
|
||||
tomllib.loads(original)
|
||||
reason = "it is no longer valid TOML once Headroom's block is removed"
|
||||
except tomllib.TOMLDecodeError as exc:
|
||||
reason = f"it is not valid TOML ({exc})"
|
||||
click.echo(
|
||||
f" Warning: could not update Codex config {config_file}: {reason}; "
|
||||
"Codex WebSocket traffic will bypass Headroom. Fix or remove the file, "
|
||||
"then re-run."
|
||||
)
|
||||
return None
|
||||
|
||||
# Bare top-level keys must precede any [section] in TOML, and
|
||||
# TOML rejects duplicate top-level keys. Rewrite any existing
|
||||
# top-level ``model_provider`` / ``openai_base_url`` in place
|
||||
@@ -3697,7 +3717,7 @@ def _inject_codex_provider_config(port: int) -> str | None:
|
||||
# history list stays whole once it routes through Headroom. Best-effort.
|
||||
retag_to_headroom(_codex_home_dir())
|
||||
except Exception as e:
|
||||
click.echo(f" Warning: could not update Codex config: {e}")
|
||||
click.echo(f" Warning: could not update Codex config {config_file}: {e}")
|
||||
return None
|
||||
|
||||
return custom_upstream_base_url
|
||||
@@ -4516,17 +4536,6 @@ def _find_persistent_manifest(port: int) -> Any:
|
||||
return manifests[0] if manifests else None
|
||||
|
||||
|
||||
def _wait_for_runtime_ready(manifest: Any, timeout_seconds: int) -> bool:
|
||||
"""Keep wrap recovery gated by both readiness and runtime identity."""
|
||||
from headroom.install.runtime import wait_ready
|
||||
|
||||
try:
|
||||
return wait_ready(manifest, timeout_seconds=timeout_seconds, require_identity=True)
|
||||
except TypeError:
|
||||
# Compatibility for test doubles that predate the keyword-only guard.
|
||||
return wait_ready(manifest, timeout_seconds=timeout_seconds)
|
||||
|
||||
|
||||
def _recover_persistent_proxy(port: int) -> bool:
|
||||
"""Start or recover a matching persistent deployment for the requested port."""
|
||||
from headroom.install.models import SupervisorKind
|
||||
@@ -4535,6 +4544,7 @@ def _recover_persistent_proxy(port: int) -> bool:
|
||||
runtime_ready,
|
||||
start_detached_agent,
|
||||
start_persistent_docker,
|
||||
wait_ready,
|
||||
)
|
||||
from headroom.install.supervisors import start_supervisor
|
||||
|
||||
@@ -4569,7 +4579,7 @@ def _recover_persistent_proxy(port: int) -> bool:
|
||||
)
|
||||
return False
|
||||
|
||||
if _wait_for_runtime_ready(manifest, 45):
|
||||
if wait_ready(manifest, timeout_seconds=45, require_identity=True):
|
||||
click.echo(f" Recovered persistent deployment '{manifest.profile}' on port {port}")
|
||||
return True
|
||||
|
||||
@@ -4585,6 +4595,7 @@ def _restart_persistent_proxy(manifest: Any, port: int) -> bool:
|
||||
start_detached_agent,
|
||||
start_persistent_docker,
|
||||
stop_runtime,
|
||||
wait_ready,
|
||||
)
|
||||
from headroom.install.supervisors import start_supervisor
|
||||
|
||||
@@ -4609,7 +4620,7 @@ def _restart_persistent_proxy(manifest: Any, port: int) -> bool:
|
||||
)
|
||||
return False
|
||||
|
||||
if _wait_for_runtime_ready(manifest, 45):
|
||||
if wait_ready(manifest, timeout_seconds=45, require_identity=True):
|
||||
click.echo(f" Restarted persistent deployment '{manifest.profile}' on port {port}")
|
||||
return True
|
||||
|
||||
@@ -7815,7 +7826,7 @@ def grok_build(
|
||||
config_file = inject_grok_provider_config(port, project=project)
|
||||
click.echo(f" Grok config: injected Headroom proxy override into {config_file}")
|
||||
except Exception as e:
|
||||
click.echo(f" Warning: could not update Grok config: {e}")
|
||||
click.echo(f" Warning: could not update Grok config {grok_config_paths()[0]}: {e}")
|
||||
return
|
||||
|
||||
def _print_grok_build_setup(actual_port: int) -> None:
|
||||
@@ -7824,7 +7835,7 @@ def grok_build(
|
||||
click.echo(f" Grok config: injected Headroom proxy override into {config_file}")
|
||||
click.echo()
|
||||
except Exception as e:
|
||||
click.echo(f" Warning: could not update Grok config: {e}")
|
||||
click.echo(f" Warning: could not update Grok config {grok_config_paths()[0]}: {e}")
|
||||
click.echo()
|
||||
for line in _render_grok_build_setup_lines(actual_port, project=project):
|
||||
click.echo(line)
|
||||
|
||||
@@ -1259,7 +1259,8 @@ def test_ensure_profile_running_covers_runtime_modes(monkeypatch) -> None:
|
||||
|
||||
monkeypatch.setattr(init_cli, "acquire_runtime_start_lock", fake_start_lock)
|
||||
|
||||
def fake_wait_ready(manifest, timeout_seconds: int) -> bool:
|
||||
def fake_wait_ready(manifest, timeout_seconds: int, require_identity: bool) -> bool:
|
||||
assert require_identity is True
|
||||
wait_calls.append((manifest.profile, timeout_seconds))
|
||||
return False
|
||||
|
||||
@@ -1297,7 +1298,9 @@ def test_ensure_profile_running_suppresses_hook_recovery_output(monkeypatch, cap
|
||||
)
|
||||
|
||||
monkeypatch.setattr(init_cli, "load_manifest", lambda profile: manifest)
|
||||
monkeypatch.setattr(init_cli, "wait_ready", lambda manifest, timeout_seconds: False)
|
||||
monkeypatch.setattr(
|
||||
init_cli, "wait_ready", lambda manifest, timeout_seconds, require_identity: False
|
||||
)
|
||||
|
||||
def noisy_start_supervisor(manifest) -> None:
|
||||
print("python stdout")
|
||||
@@ -1324,7 +1327,9 @@ def test_ensure_profile_running_returns_when_ready_or_on_exception(monkeypatch)
|
||||
)
|
||||
detached_calls: list[str] = []
|
||||
monkeypatch.setattr(init_cli, "load_manifest", lambda profile: manifest)
|
||||
monkeypatch.setattr(init_cli, "wait_ready", lambda manifest, timeout_seconds: True)
|
||||
monkeypatch.setattr(
|
||||
init_cli, "wait_ready", lambda manifest, timeout_seconds, require_identity: True
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
init_cli,
|
||||
"start_detached_agent",
|
||||
@@ -1340,7 +1345,9 @@ def test_ensure_profile_running_returns_when_ready_or_on_exception(monkeypatch)
|
||||
|
||||
monkeypatch.setattr(init_cli, "acquire_runtime_start_lock", fake_start_lock)
|
||||
monkeypatch.setattr(init_cli, "runtime_status", lambda manifest: "stopped")
|
||||
monkeypatch.setattr(init_cli, "wait_ready", lambda manifest, timeout_seconds: False)
|
||||
monkeypatch.setattr(
|
||||
init_cli, "wait_ready", lambda manifest, timeout_seconds, require_identity: False
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
init_cli,
|
||||
"start_detached_agent",
|
||||
@@ -1363,7 +1370,9 @@ def test_ensure_profile_running_skips_spawn_when_start_lock_is_held(monkeypatch)
|
||||
yield False
|
||||
|
||||
monkeypatch.setattr(init_cli, "load_manifest", lambda profile: manifest)
|
||||
monkeypatch.setattr(init_cli, "wait_ready", lambda manifest, timeout_seconds: False)
|
||||
monkeypatch.setattr(
|
||||
init_cli, "wait_ready", lambda manifest, timeout_seconds, require_identity: False
|
||||
)
|
||||
monkeypatch.setattr(init_cli, "acquire_runtime_start_lock", fake_start_lock)
|
||||
monkeypatch.setattr(
|
||||
init_cli,
|
||||
@@ -1391,7 +1400,8 @@ def test_ensure_profile_running_does_not_spawn_again_during_slow_startup(monkeyp
|
||||
def fake_start_lock(profile: str):
|
||||
yield True
|
||||
|
||||
def fake_wait_ready(manifest, timeout_seconds: int) -> bool:
|
||||
def fake_wait_ready(manifest, timeout_seconds: int, require_identity: bool) -> bool:
|
||||
assert require_identity is True
|
||||
wait_calls.append(timeout_seconds)
|
||||
return bool(detached_calls and timeout_seconds == init_cli._STARTUP_READY_TIMEOUT_SECONDS)
|
||||
|
||||
@@ -1711,3 +1721,137 @@ def test_local_profile_distinguishes_identical_non_ascii_names(monkeypatch, tmp_
|
||||
second.mkdir(parents=True)
|
||||
|
||||
assert init_cli._local_profile(first) != init_cli._local_profile(second)
|
||||
|
||||
|
||||
def test_write_json_keeps_the_existing_file_when_the_write_fails(monkeypatch, tmp_path) -> None:
|
||||
"""``init`` rewrites user-owned files such as ~/.claude/settings.json.
|
||||
|
||||
A plain ``write_text`` truncates first, so a failure mid-write (ENOSPC,
|
||||
SIGKILL) left a half-written file; the write must be atomic.
|
||||
"""
|
||||
init_cli, _ = _load_init_module(monkeypatch)
|
||||
settings = tmp_path / ".claude" / "settings.json"
|
||||
settings.parent.mkdir(parents=True)
|
||||
settings.write_text('{"theme": "dark"}\n', encoding="utf-8")
|
||||
|
||||
def fail_fsync(_fd: int) -> None:
|
||||
raise OSError(28, "No space left on device")
|
||||
|
||||
monkeypatch.setattr("headroom.fsutil.os.fsync", fail_fsync)
|
||||
|
||||
with pytest.raises(OSError, match="No space left"):
|
||||
init_cli._write_json(settings, {"theme": "dark", "env": {"A": "1"}})
|
||||
|
||||
assert settings.read_text(encoding="utf-8") == '{"theme": "dark"}\n'
|
||||
assert [p.name for p in settings.parent.iterdir()] == ["settings.json"]
|
||||
|
||||
|
||||
def test_ensure_profile_running_never_retries_wait_ready_without_identity(monkeypatch) -> None:
|
||||
"""A TypeError from wait_ready must surface, not trigger an unchecked retry.
|
||||
|
||||
A removed fallback caught TypeError and re-called wait_ready without
|
||||
require_identity=True, silently dropping the runtime identity check.
|
||||
"""
|
||||
init_cli, _ = _load_init_module(monkeypatch)
|
||||
manifest = SimpleNamespace(
|
||||
preset=init_cli.InstallPreset.PERSISTENT_TASK.value,
|
||||
supervisor_kind=init_cli.SupervisorKind.NONE.value,
|
||||
profile="task-profile",
|
||||
)
|
||||
calls: list[dict[str, object]] = []
|
||||
|
||||
def strict_wait_ready(manifest, **kwargs) -> bool:
|
||||
calls.append(kwargs)
|
||||
if "require_identity" in kwargs:
|
||||
raise TypeError("boom")
|
||||
return False
|
||||
|
||||
@contextmanager
|
||||
def held_lock(profile: str):
|
||||
yield False
|
||||
|
||||
monkeypatch.setattr(init_cli, "load_manifest", lambda profile: manifest)
|
||||
monkeypatch.setattr(init_cli, "wait_ready", strict_wait_ready)
|
||||
monkeypatch.setattr(init_cli, "acquire_runtime_start_lock", held_lock)
|
||||
|
||||
with pytest.raises(TypeError, match="boom"):
|
||||
init_cli._ensure_profile_running("task-profile")
|
||||
|
||||
assert calls == [{"timeout_seconds": 1, "require_identity": True}]
|
||||
|
||||
|
||||
def test_ensure_profile_running_logs_a_failed_recovery(monkeypatch, caplog) -> None:
|
||||
init_cli, _ = _load_init_module(monkeypatch)
|
||||
manifest = SimpleNamespace(
|
||||
preset=init_cli.InstallPreset.PERSISTENT_TASK.value,
|
||||
supervisor_kind=init_cli.SupervisorKind.SERVICE.value,
|
||||
profile="service-profile",
|
||||
)
|
||||
|
||||
@contextmanager
|
||||
def fake_start_lock(profile: str):
|
||||
yield True
|
||||
|
||||
monkeypatch.setattr(init_cli, "load_manifest", lambda profile: manifest)
|
||||
monkeypatch.setattr(init_cli, "acquire_runtime_start_lock", fake_start_lock)
|
||||
monkeypatch.setattr(init_cli, "runtime_status", lambda manifest: "stopped")
|
||||
monkeypatch.setattr(init_cli, "runtime_ownership", lambda manifest: "service")
|
||||
monkeypatch.setattr(
|
||||
init_cli,
|
||||
"wait_ready",
|
||||
lambda manifest, timeout_seconds, require_identity: timeout_seconds == 45,
|
||||
)
|
||||
monkeypatch.setattr(init_cli, "start_supervisor", lambda manifest: None)
|
||||
|
||||
with caplog.at_level("WARNING", logger="headroom.cli.init"):
|
||||
init_cli._ensure_profile_running("service-profile")
|
||||
assert not [r for r in caplog.records if r.name == "headroom.cli.init"]
|
||||
|
||||
monkeypatch.setattr(
|
||||
init_cli,
|
||||
"start_supervisor",
|
||||
lambda manifest: (_ for _ in ()).throw(RuntimeError("launchctl bootstrap failed")),
|
||||
)
|
||||
with caplog.at_level("WARNING", logger="headroom.cli.init"):
|
||||
init_cli._ensure_profile_running("service-profile")
|
||||
|
||||
messages = [r.getMessage() for r in caplog.records if r.name == "headroom.cli.init"]
|
||||
assert messages == [
|
||||
"headroom: could not start persistent proxy 'service-profile': launchctl bootstrap "
|
||||
"failed. Check it with `headroom install status --profile service-profile`."
|
||||
]
|
||||
|
||||
|
||||
def test_ensure_profile_running_logs_a_recovery_that_never_becomes_ready(
|
||||
monkeypatch, caplog
|
||||
) -> None:
|
||||
init_cli, _ = _load_init_module(monkeypatch)
|
||||
manifest = SimpleNamespace(
|
||||
preset=init_cli.InstallPreset.PERSISTENT_TASK.value,
|
||||
supervisor_kind=init_cli.SupervisorKind.NONE.value,
|
||||
profile="task-profile",
|
||||
)
|
||||
started: list[str] = []
|
||||
|
||||
@contextmanager
|
||||
def fake_start_lock(profile: str):
|
||||
yield True
|
||||
|
||||
monkeypatch.setattr(init_cli, "load_manifest", lambda profile: manifest)
|
||||
monkeypatch.setattr(init_cli, "acquire_runtime_start_lock", fake_start_lock)
|
||||
monkeypatch.setattr(init_cli, "runtime_status", lambda manifest: "stopped")
|
||||
monkeypatch.setattr(init_cli, "runtime_ownership", lambda manifest: "task")
|
||||
monkeypatch.setattr(
|
||||
init_cli, "wait_ready", lambda manifest, timeout_seconds, require_identity: False
|
||||
)
|
||||
monkeypatch.setattr(init_cli, "start_detached_agent", started.append)
|
||||
|
||||
with caplog.at_level("WARNING", logger="headroom.cli.init"):
|
||||
init_cli._ensure_profile_running("task-profile")
|
||||
|
||||
assert started == ["task-profile"]
|
||||
messages = [r.getMessage() for r in caplog.records if r.name == "headroom.cli.init"]
|
||||
assert messages == [
|
||||
"headroom: could not start persistent proxy 'task-profile': it did not become ready "
|
||||
"within 45s. Check it with `headroom install status --profile task-profile`."
|
||||
]
|
||||
|
||||
@@ -437,6 +437,27 @@ class TestCodexMemoryMcpConfig:
|
||||
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:
|
||||
|
||||
@@ -48,7 +48,8 @@ def test_ensure_proxy_recovers_matching_persistent_deployment(monkeypatch) -> No
|
||||
lambda manifest: calls.append(f"start:{manifest.profile}"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"headroom.install.runtime.wait_ready", lambda manifest, timeout_seconds=45: True
|
||||
"headroom.install.runtime.wait_ready",
|
||||
lambda manifest, timeout_seconds=45, require_identity=False: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
wrap_cli,
|
||||
@@ -81,7 +82,8 @@ def test_ensure_proxy_recovers_persistent_deployment_when_socket_is_bound(monkey
|
||||
lambda manifest: calls.append(f"start:{manifest.profile}"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"headroom.install.runtime.wait_ready", lambda manifest, timeout_seconds=45: True
|
||||
"headroom.install.runtime.wait_ready",
|
||||
lambda manifest, timeout_seconds=45, require_identity=False: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
wrap_cli,
|
||||
@@ -332,12 +334,15 @@ def test_recover_persistent_proxy_routes_docker_task_to_docker_supervisor(monkey
|
||||
"headroom.install.runtime.start_persistent_docker",
|
||||
lambda manifest: calls.append("docker"),
|
||||
)
|
||||
waits: list[dict[str, object]] = []
|
||||
monkeypatch.setattr(
|
||||
"headroom.install.runtime.wait_ready", lambda manifest, timeout_seconds=45: True
|
||||
"headroom.install.runtime.wait_ready",
|
||||
lambda manifest, **kwargs: waits.append(kwargs) or True,
|
||||
)
|
||||
|
||||
assert wrap_cli._recover_persistent_proxy(8787) is True
|
||||
assert calls == ["docker"]
|
||||
assert waits == [{"timeout_seconds": 45, "require_identity": True}]
|
||||
|
||||
|
||||
def test_ensure_proxy_restarts_idle_stale_ephemeral_proxy(monkeypatch) -> None:
|
||||
|
||||
Reference in New Issue
Block a user