mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-25 12:11:49 +08:00
feat/https-compose-caddy
5
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
02c4e922f7 |
fix(cli): resolve active proxy port for read commands (#3522)
## Description `headroom wrap copilot` can intentionally start a dedicated proxy on port 8788 (or fall forward when 8787 is busy), but read-only CLI commands previously defaulted directly to 8787. As a result, `headroom dashboard` could open a dead or unrelated dashboard even though the wrapped session reported its proxy on 8788. This change extends the shared `headroom/cli/port_discovery.py` resolver (introduced by #3855) to include live wrap-client markers, preferring the newest healthy session while preserving explicit `--port` and `HEADROOM_PORT` overrides. Closes: N/A (no matching open issue found) ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [x] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - Extended the shared port discovery module from #3855 with live wrap-client marker validation (PID liveness and reuse checks), newest-session ordering, and `/health` verification. - Updated `dashboard`, `inspect`, and the runtime probe used by `learn` to follow the newest healthy live wrap session after explicit and `HEADROOM_PORT` overrides. - Kept `doctor`'s requested-port behavior; it now reports a healthy proxy discovered from wrap-client markers elsewhere, with a `--port` hint. - Added a warning when `dashboard` cannot reach the resolved port. - Exported the actual proxy port as `HEADROOM_PORT` into every wrapped agent environment. - Reused #3855's port-discovery module rather than introducing a parallel resolver. - Added regression coverage for stale/recycled markers, multiple sessions, explicit/environment overrides, dashboard output, doctor diagnostics, inspect/learn routing, and wrapped child environments. - Documented automatic discovery and wrong-port troubleshooting. ## 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 $ uv run pytest tests/test_cli/test_proxy_port_discovery.py \ tests/test_cli/test_dashboard_port_discovery.py \ tests/test_cli/test_port_alignment.py \ tests/test_cli/test_wrap_helpers.py \ tests/test_cli_doctor.py tests/test_cli_inspect.py tests/test_cli_learn.py -q 267 passed in 5.49s $ uv run ruff check . All checks passed! $ uv run ruff format --check . 1677 files already formatted $ uv run mypy headroom/cli/port_discovery.py headroom/cli/proxy.py \ headroom/cli/doctor.py headroom/cli/inspect.py headroom/cli/learn.py Success: no issues found in 5 source files $ uv run pre-commit run --all-files Sync plugin versions.....................................................Passed Verify Ruff version alignment............................................Passed check for merge conflicts................................................Passed ruff (legacy alias)......................................................Passed ruff format..............................................................Passed mypy.....................................................................Passed ``` After the first rebase, `make ci-precheck` completed `cargo fmt --check` and `cargo clippy --workspace -- -D warnings`, then stalled in the existing Rust Magika/detection tests (multiple tests exceeded 60 seconds). The same stall recurred during the push hook; it was stopped after confirming the affected suite. The final rebase onto #3883 was followed by the Python/CLI regression suite and all repository pre-commit gates above, but not another Rust test run. ## Real Behavior Proof - Environment: Ubuntu 22.04.5 LTS x86_64; Python 3.10.12; uv 0.12.10; Headroom proxy 0.40.0-dev, started on isolated port 18788 with an isolated live-client marker. - Exact command / steps: Started an isolated process that wrote its live PID marker and launched `headroom proxy --port 18788` under a temporary workspace, with `HEADROOM_PORT` unset; then ran `env -u HEADROOM_PORT -u HEADROOM_PORT_DISCOVERY HEADROOM_WORKSPACE_DIR=/tmp/headroom-port-discovery-proof-20260930/workspace ./.venv/bin/headroom dashboard --no-open` and curled `http://127.0.0.1:18788/dashboard`. ```text $ env -u HEADROOM_PORT -u HEADROOM_PORT_DISCOVERY \ HEADROOM_WORKSPACE_DIR=/tmp/headroom-port-discovery-proof-20260930/workspace \ ./.venv/bin/headroom dashboard --no-open Detected live proxy on port 18788 Dashboard: http://127.0.0.1:18788/dashboard $ curl --max-time 5 -sS -o /dev/null -w '%{http_code}\n' \ http://127.0.0.1:18788/dashboard 200 # Proxy health before discovery returned: service=headroom-proxy status=healthy ready=true ``` - Observed result: With `HEADROOM_PORT` unset, the CLI selected the marker-associated healthy proxy on 18788, printed the matching dashboard URL, and the endpoint returned HTTP 200. The earlier manual run with a real wrapped Copilot session also confirmed discovery on 8788 before this rebase. - Not tested: Starting a new interactive `wrap copilot` session after this rebase (avoided launching an agent); Windows/macOS PID-identity behavior; multiple simultaneous real proxies; browser UI launch. Unit tests cover marker ordering, PID reuse, and explicit/environment overrides. ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: N/A. - Stable/default behavior changed: `dashboard`, `inspect`, and `learn` now follow the newest healthy live wrap proxy when no port override is set; `doctor` remains on the requested/default port and reports a live proxy elsewhere. - Kill switch / disable path: Pass `--port`, set `HEADROOM_PORT`, or set `HEADROOM_PORT_DISCOVERY=0` to bypass automatic discovery. - Unsafe override required: No. - Qualification impact: None. - Rollback path: Revert this commit; commands return to the fixed 8787 default. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [x] I did **not** edit `CHANGELOG.md` — it is generated by release-please from my Conventional Commit PR title ## Screenshots (if applicable) N/A — terminal output above captures the behavior. ## Additional Notes Port discovery is integrated into #3855's shared `port_discovery.py`; candidates are accepted only when `/health` identifies `service: headroom-proxy`, so an unrelated local JSON service cannot be mistaken for a Headroom proxy. <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3522" 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 current-main requalification Exact head `e66a6393f83278aa07e9965f5b87fed820603677`, upstream main `2d3ee51846435ef5b320eea4806af14e602b0d8c`. Re-reviewed latest integration head |
||
|
|
222f2d1df3 |
fix(doctor): detect root openai_base_url Codex routing and agent-configured proxy ports (#4490)
## Description `headroom doctor` gives two false negatives on machines where the proxy is healthy (reported by a Headroom Desktop user on Windows 11; reproduced on macOS): 1. **Codex "not routed" when Codex routes through a root `openai_base_url`.** `check_codex_routing` only reads `[model_providers.<active>].base_url`. Codex also routes its built-in `openai` provider (the default when `model_provider` is unset) through a root `openai_base_url`. Headroom Desktop writes that layout, because the ChatGPT desktop app hides Dots, dictation and voice for any other `model_provider` (`openai/codex#55783`). Doctor now reads the root key for the `openai` provider and for configs with no `model_provider`, where it wins over a leftover `[model_providers.headroom]` table. Both keys only count at the TOML root (before the first table header): a `model_provider` under `[profiles.*]` applies only when that profile is selected, so it no longer hides the default session's route. 2. **A bare `headroom doctor` can't find a proxy on a port only the agents know about.** Without `--port`, discovery probes 8787, `HEADROOM_PORT`, deployment manifests and the wrap marker. Headroom Desktop (port 6767) and `wrap --port N` leave none of these, so the proxy row read "not reachable at 8787" with no hint. Discovery now also probes the loopback ports in Claude Code's `ANTHROPIC_BASE_URL` and Codex's active base URL, read from the same project and user configs as the routing rows (`.claude/settings.local.json`, `.claude/settings.json`, `.codex/config.toml`, then the user files), through the existing `extra=` hook of `find_live_proxy_elsewhere`. It still never adopts a port silently: the proxy row names the live port, as it already does for manifest ports. `codex_active_base_url` is shared with `init`'s port-alignment warning, which now sees the same routing. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) ## Changes Made - `headroom/cli/doctor.py`: `codex_active_base_url` reads `model_provider` and `openai_base_url` from the TOML root only; with no root `model_provider` (or `"openai"`), a root `openai_base_url` wins, else the active provider table, else the legacy `[model_providers.headroom]` table. - `headroom/cli/doctor.py`: new `_configured_client_ports(claude_paths, codex_paths)` feeds the project and user Claude/Codex loopback ports to `find_live_proxy_elsewhere(extra=...)`. - `tests/test_cli_doctor.py`: root `openai_base_url` passes (with and without `model_provider`), beats an inactive `[model_providers.headroom]` table, is not hidden by a `[profiles.work] model_provider`; an `openai_base_url` inside a table is not root; a bare `doctor` names a live proxy on the port a user config, a project `.codex/config.toml` or a project `.claude/settings.local.json` routes to. - `tests/test_cli/test_port_alignment.py`: `init`'s alignment warning reads the root `openai_base_url` over an inactive `[model_providers.headroom]` table. ## 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 $ uv run --frozen --extra dev pytest tests/test_cli_doctor.py tests/test_cli/test_port_alignment.py -q 167 passed in 0.99s $ uv run --frozen --extra dev pytest tests/test_cli_doctor.py tests/test_cli/test_init_cli.py tests/test_cli/test_port_alignment.py tests/test_cli/test_wrap_stale_marker.py tests/test_corporate_tls.py tests/test_install/test_codex_install.py tests/test_offline_egress_chokepoint.py -q 477 passed, 2 skipped in 81.50s $ uvx ruff@0.17.0 check headroom/cli/doctor.py tests/test_cli_doctor.py tests/test_cli/test_port_alignment.py All checks passed! $ uvx ruff@0.17.0 format --check headroom/cli/doctor.py tests/test_cli_doctor.py tests/test_cli/test_port_alignment.py 3 files already formatted $ uv run --frozen --extra dev mypy headroom/cli/doctor.py Success: no issues found in 1 source file ``` ## Real Behavior Proof - Environment: macOS, Headroom Desktop proxy (wheel 0.41.0) live on 127.0.0.1:6767, `~/.codex/config.toml` with root `model_provider = "openai"` + `openai_base_url = "http://127.0.0.1:6767/v1"`, Claude `ANTHROPIC_BASE_URL=http://127.0.0.1:6767` in `~/.claude/settings.json`. - Exact command / steps: `headroom doctor --json` and `headroom doctor --port 6767 --json`, once with the installed 0.41.0 wheel and once from this branch (`uv run --frozen headroom doctor`). - Observed result: The branch reports Codex as routed and names the live 6767 proxy, where 0.41.0 reported Codex as not routed and gave no hint. ```text 0.41.0, no --port: proxy fail not reachable at http://127.0.0.1:8787 codex warn not routed (no active provider base_url in config.toml) 0.41.0, --port 6767: codex warn not routed (no active provider base_url in config.toml) branch, no --port: proxy fail not reachable at http://127.0.0.1:8787; a Headroom proxy IS running on port 6767 codex warn routed to port 6767, but doctor probed port 8787 (~/.codex/config.toml) branch, --port 6767: proxy pass running at http://127.0.0.1:6767 claude pass routed via ~/.claude/settings.json codex pass routed via ~/.codex/config.toml ``` Review follow-up ( |
||
|
|
a6523b1967 |
fix(codex): preserve auth.json API keys through Headroom (#3355)
## Description Closes #3354. When Codex uses an OpenAI API key stored in auth.json, Headroom's generated provider block did not configure authentication. Codex therefore sent requests to the local Headroom proxy without an Authorization header and received 401 Missing bearer. This is separate from #3206: that issue covers ChatGPT OAuth authentication, while this change covers file-backed API-key authentication. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature - [ ] Breaking change - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring ## Changes Made - Resolve API-key and OAuth credentials from `codex_home_dir()` for both project and user configurations, honoring `CODEX_HOME`. - Generate a private, config-specific helper beside `auth.json`; API keys stay out of generated TOML and Headroom environment variables. - Configure Codex's supported `auth.command` field for persistent install, init, and wrap. - Serialize command and argument paths with literal Unicode and validate generated TOML before writing provider configurations. - Abort provider updates with an actionable error if a helper collides with another file/symlink or cannot be created. - Use exclusive creation, 0600 permissions on Unix, and content checks for helper ownership. - Give project and user configurations independent helper lifetimes. Retain legacy shared helpers and helpers referenced by restored/remaining providers or unparseable configurations. - Preserve unrelated files and the original provider config when authentication setup fails. - Remove an unused config-specific helper on uninstall/unwrap. ## Testing - [x] Focused unit and integration tests pass - [x] Linting and formatting pass - [ ] Type checking - [x] New regression tests added - [x] Manual runtime testing performed ### Test Output ```text $ .venv/bin/python -m pytest tests/test_provider_codex_install.py tests/test_install/test_codex_install.py tests/test_cli/test_init_cli.py tests/test_install/test_providers.py tests/test_cli/test_wrap_codex.py -q 284 passed $ .venv/bin/ruff check . All checks passed! $ .venv/bin/ruff format --check . 1744 files already formatted ``` Ruff 0.16.8 matches this branch's CI pin. A focused coverage run reports 93% line/branch coverage for `headroom/providers/codex/install.py` and covers 44/45 newly added executable lines across the three production files in this follow-up. This is local focused coverage, not a claim about the hosted Codecov aggregate. Before the follow-up implementation, the added local-init/Unicode/helper-isolation regressions produced 6 failures while 118 existing tests passed. ## Real Behavior Proof - Environment: macOS 26.6.2, Apple Silicon arm64, Python 3.12.11, Headroom source from this PR, Codex CLI 0.160.0, Sub2API OpenAI-compatible provider, model `gpt-6-luna`, existing API key in the user's Codex `auth.json`. - Setup: start an isolated Headroom proxy on an unused loopback port with `ProxyConfig(optimize=False, cache_enabled=False, rate_limit_enabled=False, openai_api_url=<existing upstream>)`. Generate a temporary provider config with `_ensure_codex_provider(config_path, port)` while credentials resolve from the user's Codex home. Add `model = "gpt-6-luna"` and `model_reasoning_effort = "low"` at the document root. Run the child with its own temporary `CODEX_HOME` and no `OPENAI_API_KEY` or `OPENAI_BASE_URL` environment variable; its home contains the generated config, not a copied credential file. - Exact child command: ```sh CODEX_HOME=<temporary-home> codex exec --ephemeral --skip-git-repo-check --sandbox read-only --json -C <temporary-workspace> 'Reply with exactly OK. Do not call tools.' ``` Captured after-fix output on 2026-10-07: ```text Headroom test proxy: ready (optimization disabled) Codex: 0.160.0; model: gpt-6-luna; auth: generated command, no API-key environment variable codex exec exit: 0 agent messages: ['OK'] Responses bearer matches auth.json: True ``` The last line comes from an ASGI wrapper that compares the HTTP/WebSocket Responses request bearer with the file-backed key without logging either value. The command completed against the real upstream; no mocked model response was used. The temporary provider config/helper and test proxy were removed after validation. - Observed limitation: this upstream rejects WebSocket negotiation with HTTP 426, so Headroom's existing HTTP streaming fallback completed the request. This run proves file-backed command authentication and successful proxy routing, not a successful upstream WebSocket session. - Not tested in this follow-up: a new Windows/Linux runtime run, full test suite, native-extension rebuild, or optimization behavior. The focused Python suite reused the existing local native extension; no Rust code changed. ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: N/A. - Stable/default behavior changed: Yes, only when Codex has a file-backed API key and Headroom writes a provider block. - Kill switch / disable path: Remove the Headroom-managed provider block or run the existing Codex unwrap command. - Unsafe override required: No. - Qualification impact: None. - Rollback path: Revert the generated provider block; auth.json is unchanged. ## 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 the code - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective - [x] New and existing unit tests pass locally with my changes - [x] I did not edit CHANGELOG.md ## Additional Notes Helpers contain no credential value and read the user's existing credential file at runtime, so key rotation does not require reinstalling. Helper names now include a hash of the owning config's canonical path. Legacy fixed-name helpers are retained conservatively because other project configurations may still use them. <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3355" 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 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: JD Davis <mxjerrett@gmail.com> |
||
|
|
1b7977cecd |
fix: honor configured port in container startup and healthcheck (#2436)
## Description Deploying on a non-default port produced a working proxy that the surrounding tooling reported as broken. Tracing the probe turned up a second defect upstream of it: the container could not change its port via `HEADROOM_PORT` at all. `headroom proxy --port` is a click option with `envvar="HEADROOM_PORT"`, and an explicit CLI argument beats the envvar. The Dockerfile baked `--port 8787` into CMD, so `HEADROOM_PORT` was inert for a plain `docker run` — while `docker-compose.yml` already passes `command: ["--host", "0.0.0.0"]` with no port, which is the intended shape. The Dockerfile was the outlier. The two halves have to move together. An earlier revision of this change fixed only the HEALTHCHECK; that made the probe follow `HEADROOM_PORT` while the listener stayed pinned to 8787, and the container went from misleadingly healthy to genuinely unhealthy. Evidence in Real Behavior Proof below. Closes #2432 ## 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 - `Dockerfile`, both runtime stages: dropped the baked `--port` from CMD so `HEADROOM_PORT` stays authoritative. `docker run` with no env still binds 8787 (click's default), so the published default is unchanged. - `Dockerfile` (`runtime-slim-base`): shell-form HEALTHCHECK so `${HEADROOM_PORT:-8787}` expands at probe time. - `Dockerfile` (`runtime-slim`): distroless, no shell — the port is resolved inside Python instead, keeping exec form. - `headroom/cli/doctor.py`: added `resolve_probe_port()`. `--port` / `HEADROOM_PORT` wins, then an unambiguous deployment manifest (`default` profile, or a lone named profile), then 8787. `headroom deploy --port N` writes N into the deployment's environment, not into the shell `doctor` runs in, which is why the manifest tier is needed; with several named profiles and no explicit request there is no non-arbitrary pick, so it stays on the default and the existing per-deployment section reports each one. `list_manifests()` is now read once and shared with that check. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom --ignore-missing-imports`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output Full suite, run inside this repo's own builder image so the maturin-compiled Rust core is the one under test: ```text 9 failed, 9248 passed, 853 skipped, 2230 warnings in 384.56s (0:06:24) ``` All 9 failures reproduce unchanged on `origin/main` ( |
||
|
|
5bf6612326 |
fix(cli): honor CODEX_HOME and align wrap/init/doctor with the live proxy port (#3855)
## Description Closes several CLI usability gaps where `wrap`, `init` and `doctor` disagreed about *where* things are: 1. **CODEX_HOME was ignored by `doctor` / `install` / `init -g codex` hooks.** `codex_config_path()` hardcoded `~/.codex/config.toml`, while `wrap` and the MCP registrar honored `CODEX_HOME`. With a relocated Codex home, `doctor` reported "not routed" for a correctly wrapped Codex (and `install apply` edited the wrong file). 2. **Hard-coded 8787.** `wrap <tool> --port` (~20 subcommands) and `init --port` ignored `HEADROOM_PORT` and never noticed a proxy already running on another port, so they would start a second proxy or point the agent at a dead port. 3. **`init hook ensure` output was fully suppressed**, so an agent whose `base_url` drifted from the managed proxy's port failed silently every session. 4. **`doctor`** only probed `/livez`, did not check the hooks `init` installs, and did not notice a live proxy on another port. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [x] New feature (non-breaking change that adds functionality) ## Changes Made **CODEX_HOME (one helper, reused everywhere)** - `headroom.install.paths`: new `codex_home_dir()` (`CODEX_HOME`, blank-safe, else `~/.codex`), `codex_hooks_path()`, `codex_project_config_path()`; `codex_config_path()` now goes through it. - Reused by `wrap._codex_home_dir`, `CodexRegistrar`, `recover codex`, `init` (`-g` config **and** `hooks.json`), `install` (via `codex_config_path`), and `doctor`. - `doctor`'s `codex` check consults the project `.codex/config.toml` first (Codex layers it over the user config; `init codex` without `-g` writes there), then `$CODEX_HOME/config.toml`, and names the file that supplied the routing. The "no config" summary now names the real path instead of `~/.codex/config.toml`. **Port resolution (`headroom/cli/port_discovery.py`)** - Every `wrap` subcommand's `--port` / `--proxy-port` (shared `proxy_port_option`) and `init --port`: - explicit `--port` -> honored as-is, no discovery; - `HEADROOM_PORT` -> honored as-is, no discovery; - otherwise default 8787 **plus** cheap discovery: candidates are the requested port, `HEADROOM_PORT`, 8787, deployment-manifest ports and the project's wrap marker (max 8, de-duplicated), probed **concurrently** on loopback `/livez` with a 0.5 s timeout. A port counts only if `/livez` identifies `service: headroom-proxy` (unrelated local servers are ignored). No port-range scanning. - If the requested port has no Headroom proxy but another candidate does: - **TTY (stdin and stdout)**: prompt `Connect to the running proxy on N [c], keep port 8787 [k], or abort [a]?` (default `c`); - **non-interactive**: keep the requested port (nothing is adopted silently) and print to stderr the live port and the exact `--port N` / `HEADROOM_PORT=N` to use it. - `init hook ...` never runs discovery (hooks must stay silent/fast). - Kill switch: `HEADROOM_PORT_DISCOVERY=0`. - Before `wrap codex` / `init codex` rewrite an existing `[model_providers.headroom]` whose loopback `base_url` port differs, a warning names the old and new port and how to keep the old one. **`init hook ensure` alignment warning** - After the (still suppressed) ensure step, for Claude/Codex hooks on **SessionStart only** (event read from the hook's stdin JSON with a 0.5 s bound), compare the agent's configured base URL port -- Claude: `settings.local.json` > `settings.json` > `~/.claude/settings.json` > env; Codex: project `.codex/config.toml` > `$CODEX_HOME/config.toml` -- with the managed manifest's port. On mismatch it prints hook JSON: `systemMessage` (user) + `hookSpecificOutput.additionalContext` (agent), including the fix command (`headroom init [-g] --port N <agent>`; N = the configured port if a Headroom proxy is live there, else the managed port). PreToolUse / Copilot stay silent. Wrapped in a catch-all: never raises, never blocks. **`doctor`** - New `readiness` row: probes `/readyz` (3 s) when `/livez` answered; live-but-not-ready is a WARN. - New `hooks` row: for each `init` manifest in scope (`init-user`, or this project's profile), checks the Claude settings / Codex `hooks.json` (CODEX_HOME-aware) still contain the Headroom hook and that the hook's program still resolves; WARN with the exact `headroom init ...` re-install command. SKIP when no init hooks are expected. - When the probed port is down, discovery (same bounded candidates) names a live proxy on another port in the `proxy` row with `headroom doctor --port N` and the matching `wrap`/`init --port N` commands. Exit-code semantics unchanged (still 2 when the probed proxy is down). **`wrap selfheal`** - After clearing a dead wrap route, if a live Headroom proxy exists elsewhere it prints `headroom wrap claude --port N` to stderr. Deliberately **warn-only** (no automatic repoint): adopting another session's proxy could silently change backend/mode/owner. **Tests** - `tests/test_cli/test_port_alignment.py` (47 tests): CODEX_HOME helpers + consumers, doctor CODEX_HOME/project precedence, port candidates/bounds/identity/disable switch, TTY prompt c/k/a, non-TTY warning, click option source handling (default vs `--port` vs `HEADROOM_PORT`), all wrap subcommands wired to the shared option, init port resolution (incl. hook skip), Codex provider repoint warning, hook JSON on SessionStart / silent on PreToolUse / never raises, doctor readiness/hooks/live-elsewhere, selfheal warning. All homes/cwd/workspace under `tmp_path`, probes injected -- no real `~/.codex`, `~/.headroom`, or proxy. - `tests/conftest.py`: autouse sets `HEADROOM_PORT_DISCOVERY=0` and unsets `CODEX_HOME` so a developer's running proxy / Codex home can't leak into CLI tests (tests that need discovery re-enable it). ## Testing - [x] Unit tests pass (`pytest`) -- affected suites, see below - [x] Linting passes (`ruff check .`, `ruff format --check`) - [x] Type checking passes (`mypy headroom`) -- no new errors - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text $ python -m pytest tests/test_cli/test_port_alignment.py -q 47 passed in 1.61s $ python -m pytest tests/test_cli tests/test_cli_doctor.py tests/test_install tests/test_mcp_registry tests/test_provider_codex_runtime.py -q 2 failed, 1314 passed, 8 skipped FAILED tests/test_cli/test_unwrap_claude.py::test_unwrap_claude_removes_mcp_purges_retired_hook_and_stops_proxy FAILED tests/test_cli/test_wrap_stale_marker.py::test_signal_handler_unwinds_so_the_restore_can_run # both fail identically on unmodified upstream/main on Windows (signal.SIGHUP missing; retired rtk hook cleanup) -- pre-existing, unrelated $ ruff check headroom tests/... && ruff format --check ... All checks passed! $ mypy headroom headroom/fileperms.py:71 (os.fchmod on Windows) and headroom/integrations/langchain/chat_model.py:394 -- both pre-existing, files untouched ``` ## Real Behavior Proof - Environment: Windows 11, Python 3.12.13, worktree checkout. Fully sandboxed: `HOME`/`USERPROFILE`/`APPDATA`, `CODEX_HOME` and `HEADROOM_WORKSPACE_DIR` pointed at a scratch dir; a stand-in server answering only `/livez` with `service: headroom-proxy` on port 47311; a hand-written deployment manifest on 47311 and an `init-user` manifest on 8787; Claude settings and `$CODEX_HOME/config.toml` routed to 47311. - Exact command / steps: run each `$` command below in the sandboxed environment (doctor, init hook alignment, port reconcile, codex provider repoint). - Observed result: each command's output is shown directly beneath it; doctor names the live proxy on 47311 and honors CODEX_HOME, the hook warns on port mismatch, and non-interactive reconcile keeps the requested port. ```text $ headroom doctor --port 47399 --json (rows) proxy fail | not reachable at http://127.0.0.1:47399; a Headroom proxy IS running on port 47311 | re-run with: headroom doctor --port 47311 (or export HEADROOM_PORT=47311); to use port 47311 from agents, re-run `headroom wrap <agent> --port 47311` / `headroom init --port 47311 <agent>` codex warn | routed to port 47311, but doctor probed port 47399 (<scratch>\codex\config.toml) | re-run with: headroom doctor --port 47311 $ headroom doctor --port 47311 --json (rows) proxy pass | running at http://127.0.0.1:47311 (up, demo) readiness warn | proxy is live but /readyz is not ready (upstream unreachable or still starting) codex pass | routed via <scratch>\codex\config.toml <- CODEX_HOME honored hooks warn | claude (user): no Headroom hook in <scratch>\home\.claude\settings.json; codex (user): no Headroom hook in <scratch>\codex\hooks.json | re-install with: headroom init -g claude && headroom init -g codex $ echo '{"hook_event_name":"SessionStart"}' | <init hook alignment, marker headroom-init-claude, profile init-user> {"systemMessage": "Headroom: Claude Code is configured for http://127.0.0.1:47311 but the Headroom proxy managed by `headroom init` (init-user) uses port 8787; a Headroom proxy is running on 47311, not the managed one. Fix: headroom init -g --port 47311 claude", "hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": "..."}} (same for codex via CODEX_HOME; PreToolUse -> no output) $ non-interactive default-port reconcile (requested 47398) headroom: no Headroom proxy on port 47398, but one is running on port 47311. headroom: continuing with port 47398. To use the running proxy, pass --port 47311 (or set HEADROOM_PORT=47311). $ codex provider repoint headroom: warning: cfg.toml routes Codex's [model_providers.headroom] to port 47311; repointing it to port 8787. Pass --port 47311 to keep the existing route. ``` - Not tested: the interactive TTY prompt end-to-end in a real terminal (covered by unit tests with a stubbed prompt); a full `wrap <agent>` launch against a real proxy; the hook JSON as rendered inside a live Claude Code / Codex session (Codex's acceptance of `hookSpecificOutput.additionalContext` for SessionStart is assumed to mirror Claude's schema); Linux/macOS. ## Runtime Rollout Safety - Rollout-managed feature(s): none (CLI only; proxy runtime untouched). - Minimum rollout channel: Stable. - Stable/default behavior changed: default `wrap`/`init` port now follows `HEADROOM_PORT`; discovery only warns or prompts, never switches ports non-interactively. - Kill switch / disable path: `HEADROOM_PORT_DISCOVERY=0`; explicit `--port` bypasses discovery. - Unsafe override required: No. - Qualification impact: None (CLI only; no proxy runtime or qualification-gated behavior touched). - Rollback path: revert this PR. ## Review Readiness - [x] I have performed a self-review - [ ] 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 (CLI help text updated; no docs pages changed) - [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 (2 pre-existing Windows-only failures noted above) - [x] I did **not** edit `CHANGELOG.md` ## Additional Notes Design points for review: - `HEADROOM_PORT` is treated as an explicit choice (no discovery/prompt), same as `--port`. - The TTY prompt defaults to *connect* to the live proxy; non-TTY never adopts. - `unwrap` commands were intentionally left on their old `--port` default: discovering a port there could stop a proxy the user did not target. - `wrap` subcommand `--port` now also reads `HEADROOM_PORT` via Click's envvar, so an invalid `HEADROOM_PORT` is a usage error for `wrap` (init/hook ignore invalid values). - The hook reads stdin for `hook_event_name` in a daemon thread bounded to 0.5 s so a host that never closes stdin cannot stall session start. |