Commit Graph
20 Commits
Author SHA1 Message Date
Abhay SinghandJerrettDavis 2b0315b2d4 fix(doctor): recognize IPv6 loopback and case-insensitive proxy routing URLs (#3255)
## Description

`headroom doctor`'s routing check matches the configured
`ANTHROPIC_BASE_URL` against:

```python
_LOOPBACK_URL_RE = re.compile(r"https?://(?:127\.0\.0\.1|localhost):(\d+)")
```

This misses two loopback URL forms that route correctly through the
proxy, so `check_claude_routing` (and `check_codex_routing`, which uses
the parallel `_CODEX_BASE_URL_RE`) reports a **correctly-routed**
session as "not routed" and sends the user off to debug a working setup:

1. **IPv6 loopback literal** — `http://[::1]:8787` never matches, so an
IPv6-configured route reads as unrouted.
2. **Case** — the regex is case-sensitive, but URL schemes and hostnames
are not. `HTTP://Localhost:8787` or `http://LOCALHOST:8787` (valid) both
fail to match.

```text
http://127.0.0.1:8787   -> MATCH
http://[::1]:8787       -> NO MATCH  -> doctor: "not routed" (false negative)
HTTP://Localhost:8787   -> NO MATCH  -> doctor: "not routed" (false negative)
```

This is the same false-negative class the routing check was already
corrected for twice (#3205, #3213): a diagnostic that tells a routed
user they are not routed is actively misleading.

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

- Replace loopback URL prefix matching with a shared
urllib.parse.urlsplit classifier. Require an exact loopback host,
HTTP(S), an explicit valid port, and no userinfo; support IPv6 loopback
and case-insensitive schemes/hosts.
- Retain active Codex provider selection and classify its extracted
base_url through the same parser. Remote URLs, hostname-suffix
lookalikes and malformed ports remain warnings.
- Add routing/classifier regressions for accepted URL variants and
rejected lookalikes. Health probes retain current main behavior; this
change does not add IPv6-only health probing.

## Testing

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

### Test Output

```text
tests/test_cli_doctor.py  ->  95 passed in 1.19s
(4 of the 5 new variants FAIL on pre-fix code — [::1] and the upper-cased URLs — verified via git stash)
uvx ruff@0.16.2 check headroom/cli/doctor.py tests/test_cli_doctor.py  ->  All checks passed!
uvx mypy@1.20.2 headroom/cli/doctor.py  ->  Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.12.11, project venv, pytest 9.1.1,
ruff 0.16.2 and mypy 1.20.2 via uvx.
- Exact command / steps: with `ANTHROPIC_BASE_URL=http://[::1]:8787`
(and the upper-cased variants) in a settings file,
`check_claude_routing(path, 8787)` returned WARN "not routed" before the
fix and PASS "routed" after; `http://127.0.0.1:8788` still WARNs on the
port mismatch and `https://gateway.corp.example/v1` still WARNs as
non-proxy.
- Observed result: IPv6 and case-variant loopback URLs now classify as
routed; port-mismatch and non-loopback WARNs are unchanged.
- Not tested: no live `headroom doctor` invocation against a running
proxy; the pure classifier `check_claude_routing` is exercised directly
(it is what the command calls).

## Runtime Rollout Safety

- Rollout-managed feature(s): none. This is the `headroom doctor`
diagnostic classifier, not a rollout-channel-gated runtime feature.
- Minimum rollout channel: N/A.
- Stable/default behavior changed: only the false-negative is corrected
— additional valid loopback forms now classify as routed. Port-mismatch,
Ollama-collision, and non-loopback WARNs are unchanged, and no URL that
was previously WARNed as non-proxy now passes except genuine loopback
forms.
- Kill switch / disable path: N/A.
- Unsafe override required: no.
- Qualification impact: none.
- Rollback path: revert this PR.

## 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 (N/A:
internal behavior)
- [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`

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

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3255"
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 `922badceae5536e91e63f299685d77ff3bc3ce29`, upstream main
`c01cf07d943d816cfd9d97e6838ed4e38f1ff9a4`.

Clean mechanical sync with upstream main
c01cf07d94. Re-read current discussion and
all three Devin notes. Exact URL parsing preserves active-provider
selection, IPv6/mixed-case support and rejection of userinfo, suffix
lookalikes, invalid ports and remote hosts. Current-main port-discovery
behavior is retained. All131 doctor tests pass;2-file Ruff lint/format
and main-relative whitespace pass. Devin IPv6-only health-probe
observation concerns the unchanged IPv4-only doctor probe implementation
already on main; this PR changes routing classification, not
health-probe binding, so the inherited limitation is not used to
withhold source approval. No fresh live IPv6-only doctor/proxy or
provider call is claimed; current verification is classifier/CLI tests,
not broader runtime proof. The description Changes Made section is being
corrected to describe urlsplit rather than the superseded regex
implementation. No contributor routing logic rewritten. Formal approval
awaits exact-head hosted qualification; maintainers handle CI. Nothing
merged.


Exact-head hosted checks are being handled by maintainers. No new
finding in the reviewed scope; formal approval awaits exact-head hosted
qualification; nothing merged.

---------

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-11-06 10:18:02 -06:00
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 420c2d636 and current author
response, including isolated workspace/port fixtures and live-marker
ordering/pruning regressions. Clean integration with upstream/main
2d3ee51846. Explicit CLI ports and
HEADROOM_PORT retain precedence; discovery bounds candidate probes,
verifies Headroom health identity, prefers newest live wrap markers, and
preserves configured-agent discovery. No new PR-specific correctness
blocker found in scope.

All 436
dashboard/port/discovery/wrap/doctor/inspect/learn/release/version/MCP
tests pass. All 14 changed Python files pass Ruff check/format;
whitespace passes. Previous cached-read freeze-boundary failure was
independently reproduced on main and is not a contributor-code blocker.
Maintainers handle fresh exact-head qualification and distinguish
inherited failures; no contributor CI execution requested. Existing
native extension supported startup, not a fresh native build. No
contributor discovery logic rewritten; nothing merged.


Exact-head hosted checks are being handled by maintainers. No new
finding in the reviewed scope; formal approval awaits exact-head hosted
qualification; nothing merged.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-11-05 21:10:06 -06:00
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 (fd5e6fd5): a real `headroom doctor --json` process
from 85d32990 and from fd5e6fd5, each in a clean `HOME` (`env -i
HOME=<tmp> PATH=/usr/bin:/bin`, so no `ANTHROPIC_BASE_URL` from the
shell), against the same live 6767 proxy:

```text
A  root openai_base_url 6767 + [model_providers.headroom] 8787, no model_provider, --port 6767
   85d32990  codex warn  routed to port 8787, but doctor probed port 6767
   fd5e6fd5  codex pass  routed via <home>/.codex/config.toml
B  root openai_base_url 6767 + [profiles.work] model_provider = "azure", --port 6767
   85d32990  codex warn  not routed (no active provider base_url in config.toml)
   fd5e6fd5  codex pass  routed via <home>/.codex/config.toml
C  only <project>/.codex/config.toml (root openai_base_url 6767), no --port
   85d32990  proxy fail  not reachable at http://127.0.0.1:8787
   fd5e6fd5  proxy fail  not reachable at http://127.0.0.1:8787; a Headroom proxy IS running on port 6767
```

Live, for the built-in provider's credentials: Codex CLI 0.164.0 signed
in with ChatGPT (`auth_mode = chatgpt`, no API key), config root
`model_provider = "openai"` + `openai_base_url =
"http://127.0.0.1:6767/v1"`, `codex exec --skip-git-repo-check -s
read-only "Reply with exactly the word OK and nothing else."` answered
`OK` (16,982 tokens). A routed request without credentials would have
been rejected upstream.

- Not tested: Windows, the reporter's platform (the change is
platform-independent TOML and URL parsing).

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: Stable.
- Stable/default behavior changed: Yes, diagnostics only: `doctor`
reports Codex as routed for root `openai_base_url` configs and probes
the agents' configured loopback ports; the proxy is untouched.
- Kill switch / disable path: `HEADROOM_PORT_DISCOVERY=0` disables the
extra probing; the Codex detection has none, as it only changes a
read-only report.
- 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)

Not applicable (CLI output above).

## Additional Notes

Documentation: no doc describes the doctor's Codex detection or
discovery candidates, so nothing to update. Related: #842 (Codex Desktop
doctor support) and #3855 (doctor/live-port alignment).

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

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

---

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-10-28 23:38:11 -05:00
natoriandJD Davis 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` (c400f908) in the
same
container. Restricted to just those files, base and branch are
identical:

```text
origin/main c400f908: 13 failed, 119 passed, 15 skipped, 66 warnings in 14.57s
this branch:          13 failed, 119 passed, 15 skipped, 66 warnings in 14.58s
```

They are `test_cli/test_wrap_helpers.py`, `test_image_compression.py`,
`test_memory_bridge.py`, `test_proxy/test_cc_switch_reconciler.py` and
`test_startup_log_noise.py`. Counts differ between the full and
file-scoped
runs because `test_memory_bridge` and `test_startup_log_noise` are
order-dependent — also true on the base.

```text
$ mypy headroom --ignore-missing-imports
pyproject.toml: note: unused section(s): module = ['mlx.*']
Success: no issues found in 505 source files
```

New and changed tests, green on this branch:

```text
tests/test_docker_healthcheck_port.py ......                   [100%]
6 passed in 0.15s

tests/test_cli_doctor.py .............................         [100%]
67 passed in 0.68s
```

Both go red with only the tests applied on top of `origin/main`:

```text
FAILED tests/test_docker_healthcheck_port.py::test_no_healthcheck_hardcodes_the_default_port
FAILED tests/test_docker_healthcheck_port.py::test_every_healthcheck_resolves_the_port_from_the_environment
FAILED tests/test_docker_healthcheck_port.py::test_distroless_stage_healthcheck_stays_shell_free
FAILED tests/test_docker_healthcheck_port.py::test_debian_stage_healthcheck_expands_the_port_variable
FAILED tests/test_docker_healthcheck_port.py::test_no_stage_bakes_a_port_into_cmd
5 failed, 1 passed in 0.23s

tests/test_cli_doctor.py:
E   ImportError: cannot import name 'DEFAULT_PROXY_PORT' from 'headroom.cli.doctor'
```

## Real Behavior Proof

- Environment: macOS 15 (Darwin 25.3.0) arm64, Docker 29.1.3, image
built from this branch with `docker build -t headroom:pr2432 .`; control
is the published `ghcr.io/headroomlabs-ai/headroom:latest`.
- Exact command / steps: started three containers — the patched image
with `HEADROOM_PORT=8789`, the patched image with no env at all, and the
published image with `HEADROOM_PORT=8790` as a control — then read
`docker ps` health and probed `/readyz` from inside each. Full commands
below.
- Observed result: the patched image binds 8789 and its probe follows,
reporting healthy; with no env it still binds 8787, so the published
default is unchanged; the published image ignores `HEADROOM_PORT`
entirely and stays on 8787. Output below.
- Not tested: `headroom deploy` was not driven end to end — the manifest
was written directly rather than produced by the deploy command, so the
manifest *contents* are assumed to match what deploy records (`port` is
the field `headroom install status` already reads). Non-Docker
supervisors were not exercised.

### Containers

```bash
docker run -d --name hr-fixed   -e HEADROOM_PORT=8789 -p 8789:8789 headroom:pr2432
docker run -d --name hr-default                       -p 8791:8787 headroom:pr2432
docker run -d --name hr-control -e HEADROOM_PORT=8790 -p 8790:8790 \
    ghcr.io/headroomlabs-ai/headroom:latest
```

```text
NAMES        STATUS
hr-fixed     Up (healthy)   HEADROOM_PORT=8789 -> listener on 8789
hr-default   Up (healthy)   no env             -> listener on 8787
hr-control   Up (healthy)   HEADROOM_PORT=8790 -> listener on 8787
```

Probing from inside each container confirms which port is actually
serving:

```text
hr-fixed:   8789=OK
hr-default: 8787=OK
hr-control: 8787=OK
```

`hr-control` is the published image ignoring `HEADROOM_PORT` entirely —
the CMD
half of the bug. Baked image config, before and after:

```text
published: ["CMD","curl","--fail","--silent","http://127.0.0.1:8787/readyz"]
this PR:   ["CMD-SHELL","curl --fail --silent \"http://127.0.0.1:${HEADROOM_PORT:-8787}/readyz\""]
```

The distroless stage was verified the same way — `docker build --target
runtime-slim` with `-e HEADROOM_PORT=8795` reports healthy and answers
`GET /readyz` with 200 from the host.

### doctor

Running the real CLI against a seeded `default` deployment manifest
recording
port 8789, with `HEADROOM_PORT` unset in the shell — the reported
situation,
where the port lives in the deployment rather than in the shell:

```text
origin/main c400f908: doctor probed port: 8787
this branch:          doctor probed port: 8789
```

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from
      my Conventional Commit PR title (a CI guard enforces this)

## Screenshots (if applicable)

N/A — no UI surface.

## Additional Notes

"I have made corresponding changes to the documentation" is checked in
the sense
that the `--port` help text now describes the new resolution order; no
prose
docs referenced the baked CMD port. `README.md` and the wiki reference
`headroom proxy --port 8787` as a host command, which is unaffected.

`docker/differential-network-capture/docker-compose.yml` passes `--port
8787`
explicitly in its own `command:`, which still overrides everything and
keeps
working.

Adjacent, deliberately not in this PR: `docker-compose.yml`'s
healthcheck is
hardcoded to 8787 the same way. It is inert today because that file
never sets
`HEADROOM_PORT`, and making it configurable also means parameterising
the
published `ports:` mapping — a separate change. Happy to open a
follow-up if
you want it.

## Runtime Rollout Safety

- Rollout-managed feature(s): Docker runtime port selection and
`headroom doctor` probe-port resolution.
- Minimum rollout channel: Standard Docker image release and persistent
Docker deployments.
- Stable/default behavior changed: No. Unset `HEADROOM_PORT` continues
to use port 8787.
- Kill switch / disable path: No new feature flag; revert the image or
this PR.
- Unsafe override required: No.
- Qualification impact: None. No data or schema migration; existing
port-8787 deployments remain compatible.
- Rollback path: Redeploy the previous image or revert this PR; no
migration cleanup is required.

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

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/2436"
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: JD Davis <mxjerrett@gmail.com>
2026-10-05 08:36:54 -05:00
d5318ac235 fix(doctor): recognize Azure Foundry routing for Claude Code (#1339)
## Description

`headroom doctor` only inspected `ANTHROPIC_BASE_URL` when checking
Claude Code routing. In Azure Foundry mode, Claude Code routes through
`ANTHROPIC_FOUNDRY_BASE_URL` when `CLAUDE_CODE_USE_FOUNDRY=1`, so a
correctly wired setup was reported as `claude: not routed`.

This PR falls back to `ANTHROPIC_FOUNDRY_BASE_URL` only when the Foundry
flag is present, then sends that URL through the existing routing
classifier. Non-Foundry Claude routing behavior is unchanged.

## Type of Change

- [x] Bug fix
- [ ] New feature
- [ ] Documentation
- [ ] Refactor
- [ ] Tests only

## Changes Made

- `headroom/cli/doctor.py`: recognize `ANTHROPIC_FOUNDRY_BASE_URL` when
`CLAUDE_CODE_USE_FOUNDRY=1` and `ANTHROPIC_BASE_URL` is absent.
- `tests/test_cli_doctor.py`: add coverage for a valid Foundry route,
missing Foundry URL, and a Foundry URL without the Foundry flag.

## Testing

- [x] Unit tests
- [x] Lint/static checks
- [ ] Integration tests

### Test Output

```text
uv run --extra dev python -m pytest tests/test_cli_doctor.py -q
44 passed in 0.96s

uv run --extra dev ruff check headroom/cli/doctor.py tests/test_cli_doctor.py
All checks passed!
```

## Real Behavior Proof

- Environment: macOS; Claude Code with `CLAUDE_CODE_USE_FOUNDRY=1` and
`ANTHROPIC_FOUNDRY_BASE_URL` set in `~/.claude/settings.json`; Headroom
proxy on `:8787` with the Foundry URL pointed at an Azure APIM upstream.
- Exact command / steps: set `ANTHROPIC_FOUNDRY_BASE_URL` to
`http://localhost:8787` in the Claude settings env block, then run `uv
run headroom doctor`.
- Observed result: the Claude row changed from a false `not routed`
warning to a routed/pass result, and a live `/v1/messages` request
forwarded through the proxy to the Azure upstream and returned 200.
- Not tested: non-loopback Foundry URLs; those reuse the existing
`_classify_routing_url` warning path.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

Co-authored-by: Juri Kern <juri.kern@illumio.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-10-01 23:05:34 -05:00
JD Davis 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.
2026-09-29 15:02:20 -05:00
宇宙的山峰andUniversePeak ca54c2aba1 fix(proxy): fall back when forced Kompress is cold (#3381)
## Description

Closes #3363

A savings profile can set `force_kompress=True`. When the Kompress model
is installed but its weights are still cold or unavailable, the forced
router selected `KOMPRESS`, which passed content through unchanged. That
made structured payloads lose their normal SmartCrusher/log/search
fallback and looked like a chat-completions compression outage.

## Type of Change

- [x] Bug fix (non-breaking change)

## Changes Made

- Check Kompress readiness before honoring forced routing.
- Trigger the existing background model warmup when the model is cold.
- Re-enter normal content detection while the model is unavailable,
preserving structural compressors instead of silently forcing a no-op.
- Extend `headroom doctor` to query `/health` and report the optional
Kompress component as ready, disabled, or not ready with an actionable
hint.

## Testing

- [x] Focused doctor tests pass (`python -m pytest -q
tests/test_cli_doctor.py`)
- [x] Ruff check and format check pass on all changed files
- [x] Python compile checks pass for all changed files
- [x] Added a regression test for cold forced-Kompress routing with a
structural fallback

### Test Output

```text
python -m pytest -q tests/test_cli_doctor.py
96 passed in 31.66s

python -m ruff check headroom/cli/doctor.py headroom/transforms/content_router.py tests/test_cli_doctor.py tests/test_agent_savings.py
All checks passed!
```

## Real Behavior Proof

- Environment: Windows, Python 3.11.9; Headroom source checkout at the
current `main` base.
- Exact command / steps: The regression test supplies a cold Kompress
implementation (`is_ready() == False`) and a structural log compressor,
then runs `ContentRouter.compress()` with forced routing enabled.
- Observed result: The router requests background warmup and chooses the
structural `LOG` strategy, returning the compacted output rather than a
forced-KOMPRESS passthrough. `headroom doctor` now surfaces a cold model
as `not ready — content compression is passing through`.
- Not tested: Full native Rust-backed proxy integration on this host.
The repository's supported editable setup reached the Rust build but
failed because the Windows MSVC linker is not installed (`link: extra
operand`; the environment has no Visual Studio C++ build tools).

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: Default behavior is unchanged unless forced
Kompress routing is enabled.
- Stable/default behavior changed: Cold forced routing now uses the
existing detector and safe structural compressor.
- Kill switch / disable path: Existing Kompress disable settings remain
unchanged.
- 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] One logical bug fix
- [x] Added regression coverage
- [x] Did not edit `CHANGELOG.md`

---------

Signed-off-by: UniversePeak <UniversePeak@users.noreply.github.com>
Co-authored-by: UniversePeak <UniversePeak@users.noreply.github.com>
2026-09-24 16:58:40 -05:00
AxelRayandJD Davis 4794d688a9 fix(doctor): detect Codex routing via active provider base_url (#2618)
## Description

`headroom doctor` only treated Codex as routed when `config.toml`
contained a literal `[model_providers.headroom]` section. Safe installs
that keep a preserved provider ID (for example `codex-lb`) and only
point that provider's `base_url` at the local proxy were reported as not
routed, with a misleading wrap hint.

This change resolves the active `model_provider`, reads that section's
`base_url`, and classifies loopback routing the same way as other doctor
checks. The headroom section remains the fallback when no active
provider is set.

Closes #2614

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

- Resolve `model_provider` and scope `base_url` lookup to that provider
table in `check_codex_routing`
- Reuse `_classify_routing_url` for pass / port-mismatch / non-loopback
outcomes
- Keep best-effort WARN-not-crash behavior for missing or malformed
configs
- Add regression tests for preserved provider IDs and active-provider
precedence

## Testing

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

### Test Output

```text
$ PYTHONPATH=. python -m pytest -q tests/test_cli_doctor.py -o addopts=
71 passed, 1 warning in 0.78s

$ uvx --from ruff==0.15.17 ruff check headroom/cli/doctor.py tests/test_cli_doctor.py
All checks passed!

$ uvx --from ruff==0.15.17 ruff format --check headroom/cli/doctor.py tests/test_cli_doctor.py
2 files already formatted
```

## Real Behavior Proof

- Environment: Linux VPS, Python 3.11.15, shallow checkout of headroom
main at fix/doctor-codex-preserved-provider-id (cab1dde)
- Exact command / steps: Wrote a temp Codex config with `model_provider
= "codex-lb"` and `base_url = "http://127.0.0.1:8787/v1"`; ran
`PYTHONPATH=. python -m pytest -q
tests/test_cli_doctor.py::TestCodexRouting -o addopts=`; also ran full
`tests/test_cli_doctor.py` and ruff check/format on the two touched
files
- Observed result: Preserved-provider case now PASSes without a wrap
hint; port-mismatch WARNs with the wrong port; existing headroom-marker
and no-marker cases still pass; 71 doctor tests green
- Not tested: Live `headroom doctor` against a real Codex install on
this machine; mypy; full monorepo CI

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

- Scoped to doctor routing detection only; no wrap/install writer
changes
- mypy not run on this VPS for this change

Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-09-09 13:36:11 -05:00
2f81fa5931 fix(codex): detect ChatGPT auth from id_token claims so wrap/init emit requires_openai_auth (#3212)
Fixes #3206.

## The report

`headroom wrap codex` / `init codex` write a provider block without
`requires_openai_auth = true`. Codex then attaches **no `Authorization`
header**, and every request through the proxy 401s:

```
unexpected status 401 Unauthorized: Missing bearer or basic authentication in header
```

Silently — `headroom doctor` reported green throughout. The reporter
lost ~15h of scheduled Codex automation before bisecting it.

## Not the fix the issue suggested

The issue proposes adding the line unconditionally. **That would
re-break API-key users**, which is the regression `requires_openai_auth`
was made conditional for in the first place (#406) — the flag forces
Codex to demand an OpenAI OAuth login.

All three writers (install provider-scope, `init codex`, `wrap codex`)
*already* call `codex_uses_chatgpt_auth()` and emit the key when it
returns True. **The bug is in the detection, not the writers.**

## Root cause

`codex_uses_chatgpt_auth` recognised two shapes:

1. `auth_mode == "chatgpt"`
2. a top-level `tokens.account_id`

Newer Codex can write an `auth.json` with **neither** — the account
identity lives only in the `id_token` claims, under
`https://api.openai.com/auth.chatgpt_account_id`. That config reads as
API-key mode, the flag is omitted, and every request 401s.

Verified against a real `auth.json`: the JWT claim carries the *same*
account id as the top-level key, so it is a faithful signal for the
shape that lacks it.

## Fix

A third detection tier, consulted only when the first two are absent:

| Shape | Before | After |
|---|---|---|
| `auth_mode = "chatgpt"` | True | True |
| legacy `tokens.account_id` | True | True |
| **only the `id_token` claim** | **False** ← the bug | **True** |
| `auth_mode = "apikey"` + ChatGPT id_token | False | **False** (#406
stays closed) |
| API key, no tokens | False | False |
| id_token without the claim / malformed / blank id | False | False |

The payload is **decoded, not verified**. It is a local file the user
already owns, and the result only chooses which key we write into their
own `config.toml` — nothing is authenticated or authorised on the
strength of it. An API-key user has no ChatGPT id_token, so this cannot
resurrect #406, and an explicit `auth_mode` still wins outright (pinned
by test).

## Doctor stops reporting a false green

This failure is invisible from every other signal — proxy up, provider
block present. So the codex check now WARNs when the config is routed,
the user is on ChatGPT auth, **and** the block lacks the flag, naming
the re-run that repairs it.

It only runs when the flag is already missing, and the keyring fallback
it can reach is bounded by an existing 3s timeout, so `doctor` stays
fast. API-key users are never nagged.

## Existing configs

Self-healing — all three writers strip and regenerate the managed block
on every run, so re-running `wrap`/`init` emits the key now that
detection is correct. No separate migration needed.

## Testing

99 passing across the two suites. Confirmed **discriminating**: 3 of the
new tests fail against unfixed source and pass after —

- `test_chatgpt_auth_detected_from_id_token_claims_alone`
- `test_provider_block_emits_requires_openai_auth_for_the_new_shape`
-
`TestCodexRouting::test_chatgpt_auth_without_requires_openai_auth_warns`

plus explicit coverage for the #406 guard, malformed tokens, blank
account ids, and the API-key-not-nagged case.

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

Co-authored-by: Tejas Chopra <tejas@Tejass-MacBook-Pro.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-22 15:29:54 -07:00
8f3e33a00e fix(doctor): report project-scoped Claude routing instead of a false negative (#3213)
Refs #3205 — **issue 2 of 2**. The `wrap`-session crashes reported in
that issue are *not* addressed here; see the note at the bottom.

## The report

A session routed via `headroom init claude` was reported by `headroom
doctor` as **not routed**, while it demonstrably was:

- `ps eww` on the live `claude` process showed
`ANTHROPIC_BASE_URL=http://127.0.0.1:8787`
- the `mcp__headroom__*` tools were present and firing
- `headroom_stats` showed **164 of 174 requests compressed** on that
very session

The cost wasn't cosmetic. The team believed 3 of 4 sessions were
unrouted on doctor's word, and hand-checked `ps eww` plus MCP tool
presence on each one to find the real state.

## Root cause — a scope mismatch

| | Path |
|---|---|
| `init claude` (non-global) **writes** |
`./.claude/settings.local.json` |
| `doctor` **read** | `~/.claude/settings.json` only |

Claude Code layers project settings over user settings, so
project-scoped routing — what `init` writes by default — was invisible
to the check.

## Fix

`check_claude_routing` now takes the project-scoped candidates and
consults them in **Claude's own precedence order** (project-local,
project, then user), reporting the first that carries
`ANTHROPIC_BASE_URL`. The summary names the file that supplied it, so
which scope is in effect is never ambiguous — that ambiguity is what
made this expensive to diagnose.

Reading more files must not turn a routed session into a crash or a
silent skip:

- a per-file parse failure is surfaced verbatim (`could not parse …`)
rather than swallowed into the misleading "not routed"
- the non-dict guard is preserved **per file** — a hand-edited settings
file containing `[]` or `null` would otherwise raise `AttributeError`
inside the very command run to diagnose it
- a missing project file is skipped, not fatal

The third argument is optional and defaults to the previous single-file
behaviour, so existing callers and tests are unaffected.

## Not scraping `ps`

The reporter suggested inspecting live `claude` process environments.
That isn't needed and would be platform-specific — the routing is
written to a file whose path we already know. The gap was that we read
the wrong scope, so that's what this fixes.

## Testing

86 passing. Confirmed **discriminating** — all 7 new tests fail against
unfixed `doctor.py` and pass after:

| Test | Covers |
|---|---|
| project-local counts as routed | the reported bug |
| project `settings.json` counts as routed | the other project file |
| project takes precedence over user | Claude's layering |
| falls back to user when project has no base URL | no false positive |
| still warns when nothing routes | no blanket pass |
| missing project file skipped | not fatal |
| unparseable project file surfaces | not silently "not routed" |
| no project paths → original behaviour | backward compatibility |

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

Co-authored-by: Tejas Chopra <tejas@Tejass-MacBook-Pro.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-22 15:25:47 -07:00
Abhay SinghandJD Davis be5b26d807 fix(doctor): surface that Claude Desktop agent sessions bypass the proxy (#2987)
## Description

`headroom doctor` reports the `claude` check as a pass whenever
`~/.claude/settings.json` carries an `ANTHROPIC_BASE_URL` pointing at
the proxy. That is correct for the terminal Claude Code CLI. But Claude
Desktop (`com.anthropic.claudefordesktop`) unconditionally overwrites
that variable when spawning agent sessions (#869), so on a
Desktop-primary machine `doctor` asserts routing that is in fact
discarded, and nothing in the output hints that Desktop sessions are
unrouted (#2925).

## Fix

Add a per-surface `claude desktop` check that warns about the bypass
when Claude Desktop's config directory is detected, pointing at #869.
Following the issue's suggestion, it models per-surface reporting like
the existing `wrap_marker` / `shell env` rows: it is a separate row
emitted only when Desktop is present, so it never contradicts a
genuinely routed CLI, and the existing `claude` check is left unchanged.

Detection uses Claude Desktop's per-user config directory (distinct from
the CLI's `~/.claude`):
- macOS: `~/Library/Application Support/Claude`
- Windows: `%APPDATA%\Claude`
- Linux: `$XDG_CONFIG_HOME/Claude` (or `~/.config/Claude`)

Fixes #2925

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/cli/doctor.py`: add `claude_desktop_config_dir()`
(cross-platform) and `check_claude_desktop()` (WARN when the dir exists,
`None` otherwise); append it to the `doctor()` check list when present.
- `tests/test_cli_doctor.py`: `TestClaudeDesktop` -- no row when absent;
WARN naming the bypass and #869 when present; the `doctor --json`
entrypoint appends the row only when Desktop is detected.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check`)
- [x] Type checking passes (`mypy`)
- [x] New tests added

### Test Output

```text
tests/test_cli_doctor.py  78 passed
# uvx ruff@0.15.22 check  -> All checks passed!
# uvx mypy@1.20.2 headroom/cli/doctor.py -> Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.12.11, project venv, pytest 9.1.1,
ruff 0.15.22 and mypy 1.20.2 via uvx.
- Exact command / steps: `uvx ruff@0.15.22 check headroom/cli/doctor.py
tests/test_cli_doctor.py`; `uvx mypy@1.20.2 headroom/cli/doctor.py`;
`python -m pytest tests/test_cli_doctor.py -q`; then drove the check
directly and through the `doctor --json` entrypoint with
`claude_desktop_config_dir` pointed at a tmp dir (created the dir, ran
`doctor --json`, then removed it and reran).
- Observed result: with the dir present, a `claude desktop` row appears
with status `warn` and a `#869` hint; with the dir absent, no such row
is emitted and the rest of the report is unchanged. A Desktop-primary
machine now gets an explicit warning that Desktop agent sessions bypass
the proxy, instead of a bare `claude: pass` that reads as though all
Claude routing is live.
- Not tested: a live Claude Desktop install (detection is
directory-existence, exercised against a tmp dir).

## Runtime Rollout Safety

- Rollout-managed feature(s): none. This adds a read-only diagnostic row
to `headroom doctor`; it is not behind any rollout channel or feature
flag.
- Minimum rollout channel: N/A (no rollout-managed behavior).
- Stable/default behavior changed: no. The existing `claude` check and
all other rows are unchanged; the new `claude desktop` row is additive
and only appears when Claude Desktop's config directory is detected.
- Kill switch / disable path: N/A. The row self-suppresses (returns
`None`) on any machine without the Desktop config directory.
- Unsafe override required: no.
- Qualification impact: none. No proxy request path, routing, or token
accounting is touched; the change is confined to the doctor diagnostic
surface.
- Rollback path: revert this PR; the doctor output returns to its prior
set of rows with no state or migration to undo.

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

## Additional Notes

Scope: this warns whenever Claude Desktop is present, which is accurate
(Desktop agent sessions always bypass per #869) and matches the
precedent for doctor-accuracy fixes (#2618/#2614 Codex, #2566 ollama).
The issue's stronger refinement -- suppress the warning when a
`client=claude-code` request has recently reached the proxy -- would
need per-client traffic observation the doctor does not have today; I
left that as a follow-up rather than build new traffic-tracking infra
into this fix. Happy to add it if you'd prefer the conditional form.

Rebased onto current `main` to resolve an overlap with the newly merged
`check_claude_auth_conflict` in `doctor.py`; both checks now coexist.

Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-08-16 15:04:44 -07:00
JD Davis 2d88e31a40 fix(claude): reject conflicting auth before proxy startup (#2993)
## Description

Fixes #1443.

Claude Code rejects an effective configuration containing both
ANTHROPIC_API_KEY and ANTHROPIC_AUTH_TOKEN before any request reaches
Headroom. The existing wrapper started the proxy and mutated project
settings before Claude surfaced its generic Invalid API key message,
leaving users to guess which credential came from their shell, global
settings, or project settings.

Headroom does not own either credential, and both represent legitimate
but different auth/billing modes, so automatically deleting one would be
destructive. This PR detects the contradiction before any proxy/config
mutation and tells the user which source contains each key without
exposing credential values.

## Changes Made

- Add a pure Claude auth-conflict classifier with explicit
settings-layer precedence.
- Cover user settings, project .claude/settings.json, project
.claude/settings.local.json, and shell environment.
- Treat higher-precedence empty values as clearing inherited
credentials.
- Abort wrap claude before proxy registration/startup when both keys
remain effective.
- Add a headroom doctor failure with the same source-aware,
value-redacted remediation.
- Preserve both user credentials and require an explicit choice between
API-key billing and token/gateway auth.

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

## Testing

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

### Test Output

```text
151 Claude runtime, wrap, doctor, Remote Control, and MCP dependency-contract tests passed
ruff check and format checks passed
git diff --check passed
```

Branch contains current main, including the MCP v1 cap and the five
just-merged blocker PRs.

## Real Behavior Proof

- Environment: isolated local worktree on current `main` with Claude
wrapper and doctor fixtures.
- Exact command / steps: exercised conflicting and non-conflicting
shell, user, project, and local-project credential layers through the
focused wrap and doctor test suites.
- Observed result: conflicting effective credentials fail before proxy
startup or settings mutation, report only credential sources, and never
expose values.
- Not tested: a live Claude Code login with production credentials;
credential precedence and side-effect boundaries are covered by
fixtures.

## Runtime Rollout Safety

- Rollout-managed feature(s): Claude authentication-conflict preflight.
- Minimum rollout channel: normal patch release.
- Stable/default behavior changed: only configurations with both
effective credentials now stop early with actionable diagnostics.
- Kill switch / disable path: remove or clear either conflicting
credential in its reported source.
- Unsafe override required: none; Headroom deliberately does not choose
or delete a user credential.
- Qualification impact: Claude wrap, doctor, Remote Control, and MCP
dependency-contract tests must remain green.
- Rollback path: human revert restores the previous late Claude Code
rejection; no persisted migration is involved.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Safety

No credential value is returned by the classifier, printed by wrap, or
emitted in doctor JSON. The preflight runs before
_register_proxy_client, proxy startup, MCP registration, or settings
writes.
2026-08-13 23:01:59 -05:00
9fde127534 fix(proxy): relocate stray system-role messages to the top-level system param (#765) (#1357)
## Description

On requests large enough to trigger compression, the proxy emitted an
upstream Anthropic request whose `messages[0]` had `role: "system"`.
Anthropic's Messages API rejects any `system` role inside `messages[]`:

```
400 invalid_request_error: "messages.0: use the top-level 'system' parameter for the initial system prompt"
```

The original request correctly carries its system prompt in the
top-level `system` parameter; a compression/transform/pipeline step
relocates the harness system block into `messages[0]`, so the request
fails outright (intermittent only because it requires a context large
enough to compress).

This adds a wire-contract guard in the Anthropic forwarder: as the
**last** step before sending upstream (after every transform, memory
injection, tool sort, and pipeline extension, covering both the Bedrock
and direct paths), any stray `role="system"` message is relocated out of
`messages[]` and merged back into the top-level `system` parameter.
Content order is preserved (existing system first, relocated content
after) and block-level `cache_control` survives. The guard is a no-op on
the common path (no system-role entry → inputs pass through unchanged).

Closes #765

## 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/proxy/helpers.py`: new pure helper
`relocate_system_messages_to_top_level(messages, system) ->
(clean_messages, new_system, changed)` plus `_system_message_to_blocks`.
Handles `system` being `None`/`str`/`list`, never drops content,
preserves order and content blocks.
- `headroom/proxy/handlers/anthropic.py`: invoke the guard just before
the byte-faithful forward block; on relocation, update
`body["messages"]`/`body["system"]`, mark the body mutated
(`system_role_relocated`) so the byte-faithful forwarder re-serializes,
and log a warning.
- `tests/test_proxy_handler_helpers.py`: 3 unit tests (relocate stray
system into top-level, append-to-existing-system order, no-op without a
system entry).
- `CHANGELOG.md`: Bug Fixes entry.

## 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 --extra dev python -m pytest tests/test_proxy_handler_helpers.py -q
29 passed in 4.95s

# Regression on the forward path (byte-faithful forwarding, system-prompt immutability, cache stability):
$ uv run --extra dev python -m pytest tests/test_proxy_handler_helpers.py tests/test_proxy_byte_faithful_forwarding.py tests/test_proxy_system_prompt_immutable.py tests/test_proxy_anthropic_cache_stability.py -q
90 passed, 15 warnings in 29.72s

$ uv run ruff check headroom/proxy/helpers.py headroom/proxy/handlers/anthropic.py tests/test_proxy_handler_helpers.py
All checks passed!

$ uv run ruff format --check ...   # 3 files already formatted
$ uv run mypy headroom/proxy/helpers.py headroom/proxy/handlers/anthropic.py
Success: no issues found in 2 source files
```

## Test verification (RED → GREEN)

The new tests exercise the guard directly and import the new helper at
module top, so reverting the production fix makes them fail at
collection.

**RED — production fix reverted (helper removed):**
```text
ImportError while importing test module 'tests/test_proxy_handler_helpers.py'.
E   ImportError: cannot import name 'relocate_system_messages_to_top_level' from 'headroom.proxy.helpers'
=========================== 1 error in 0.41s ===============================
```

**GREEN — production fix applied:**
```text
tests/test_proxy_handler_helpers.py ...                                  [100%]
======================= 3 passed, 26 deselected in 1.50s =======================
```

## Real Behavior Proof

- Environment: Python 3.13, `uv run` in this repo, branch
`fix/issue-765`.
- Exact command / steps: ran the guard on a body in the exact #765
failure shape — `system: None` and a `role="system"` harness block at
`messages[0]`:
- Observed result:
  ```text
  BEFORE: messages[0].role = system (Anthropic 400 trigger)
  changed       = True
  AFTER roles   = ['user', 'assistant']
system param = [{"type": "text", "text": "You are Claude Code.
<system-reminder>...</system-reminder>"}]
OK: no role=system in messages[]; system content preserved in top-level
param
  ```
The illegal `role="system"` entry is removed from `messages[]` and its
content lands in the top-level `system` parameter — exactly the body
Anthropic accepts.
- Not tested: a full live 250k+-token Claude Code session against the
real Anthropic API (needs a large live context + API key); the fix is
validated at the request-shaping boundary the 400 is raised on.

## 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 have updated the CHANGELOG.md if applicable

## Additional Notes

The guard intentionally fires at the forwarder boundary rather than in
any single transform: the issue's captures show the relocation can
originate from the compression path, and pipeline extensions / hooks can
also mutate `messages` late. Enforcing Anthropic's wire contract once,
at the point the body is serialized upstream, fixes the 400 regardless
of which step introduced the stray entry and matches the architecture
invariant "never produce a `system`-role entry within `messages[]`".

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-08-13 11:52:09 -05:00
TenderDeve 7f24d695ee fix(doctor): flag ollama launch claude proxy bypass instead of misdirecting (#2566)
## Description

Addresses the diagnostic half of #2199.

`ollama launch claude` sets `ANTHROPIC_BASE_URL=http://127.0.0.1:11434`
in the launched Claude Code child. That process env outranks the `env`
block a persistent Headroom install writes to `~/.claude/settings.json`,
so Claude Code talks to Ollama and never reaches the proxy — 0% savings,
nothing on the dashboard, no error.

`headroom doctor`'s routing classifier made it worse: seeing a loopback
`:11434`, it reported `routed to port 11434, but doctor probed port
8787` and hinted `re-run with: headroom doctor --port 11434` — sending
the user to re-probe Ollama's endpoint as if it were their proxy.

Closes #2199

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- `_classify_routing_url` now recognizes Ollama's fixed default port:
the check names the `ollama launch claude` bypass and points at the
proxy-chaining path instead of the red-herring `--port 11434` re-probe
hint.
- Fires for both the shell-env and settings-file routing checks that
share the classifier.

## Testing

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

### Test Output

```text
$ pytest tests/test_cli_doctor.py -q
1 failed, 68 passed in 3.05s
# The lone failure is test_remote_control_warning_exits_1 — pre-existing and
# unrelated: it reads real ~/.headroom stats and fails on a clean tree with or
# without this change (does not exist / does not pass on main either).

$ pytest tests/test_cli_doctor.py -k ollama -q
1 passed, 68 deselected

$ ruff check headroom/cli/doctor.py tests/test_cli_doctor.py
All checks passed!

$ mypy headroom
Success: no issues found in 509 source files
```

## Real Behavior Proof

- Environment: local checkout, Python venv, `pytest`/`ruff`/`mypy` as
above.
- Exact command / steps: `tests/test_cli_doctor.py` pins the
Ollama-aware message + hint emitted by `_classify_routing_url` for a
loopback `:11434` routing URL.
- Observed result: doctor now reports the `ollama launch claude` bypass
and the proxy-chaining fix instead of `re-run with: headroom doctor
--port 11434`.
- Not tested: no live `ollama launch claude` run; verified at the
classifier boundary.

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

## Additional Notes

Scope: this is only the *diagnostic* ask (#2199 part 3, requested as the
minimum). The launcher-composition and model-aware routing halves depend
on #1279's direction and are left for a maintainer steer. Documentation
item is N/A (diagnostic message change, no docs surface). The
pre-existing `test_remote_control_warning_exits_1` failure is unrelated
as noted above.
2026-08-12 00:19:44 -05:00
ParideboyandClaude Opus 5 01df245252 fix(proxy/cost): mark estimated-basis budget records and add an enforcement policy (#2713) (#2725)
## Description

`CostTracker.check_budget()` is a hard spend control — the Anthropic
handler refuses the request with a 429 once the period budget is gone.
The ledger that control reads could not tell a measured dollar from a
guessed one.

When a provider response carries no input-token breakdown,
`record_tokens()` substitutes Headroom's own `tokens_sent` estimate for
the input count so input cost isn't silently dropped from the budget.
That fallback is the right call, but the resulting record was
byte-identical to a provider-measured one: no field, no log line, no
separation in `/stats`. `RequestOutcome.uncached_input_tokens` defaults
to `0`, so any route whose response omits usage lands on this branch in
production. An estimate can drift in either direction, so a budget check
could pass after real spend had already gone over — with nothing saying
the decision rested on an estimate.

This keeps the fallback and makes it visible, then lets operators decide
what an estimate is allowed to do to a hard limit.

Closes #2713

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- New `headroom/proxy/budget_basis_policy.py` (pure policy module,
matching the existing `*_policy.py` convention): the
`measured`/`estimated` basis constants, the `count`/`ignore`/`block`
policy values, and `resolve_estimated_basis_policy()` (explicit value →
`HEADROOM_BUDGET_ESTIMATED_BASIS` → `count`; an unknown value warns once
and falls back rather than failing proxy startup).
- `headroom/proxy/cost.py`: ledger entries are now `CostEntry(timestamp,
cost_usd, basis)` instead of a bare tuple; `record_tokens()` marks the
fallback branch `estimated` and logs one WARNING per model (deduped the
same way pricing warnings are, per #2504 — an unguarded warning on this
path fires once per request for a provider that never reports usage);
new `period_cost_breakdown()` and an optional `basis` filter on
`get_period_cost()`; new `budget_denial_detail()` builds the 429 body
where the ledger lives; `check_budget()` honors the policy while keeping
its `(allowed, remaining)` signature.
- `stats()` gains `budget_estimated_basis` (the active policy) and
`budget_basis` (the period split: `total_usd`, `measured_usd`,
`estimated_usd`, `estimated_pct`, `records`, `estimated_records`).
`merge_cost_stats()` already spreads `**cost_stats`, so both reach
`/stats["cost"]` with no extra plumbing.
- Operator knob wired through every config layer:
`ProxyConfig.budget_estimated_basis` (`models.py`), the Click
`--budget-estimated-basis` option with `envvar=` (`cli/proxy.py`), the
argparse `--budget-estimated-basis` flag (`server.py`, `default=None` so
the env var stays reachable), and a `SettingField` in the `Budget` group
(`settings_store.py`).
- `headroom/proxy/handlers/anthropic.py`: the 429 body now comes from
`budget_denial_detail()`, which names how much of the period's spend was
booked from an estimate and distinguishes "you overspent" from "I refuse
to enforce a hard limit on a guess".
- `headroom/cli/doctor.py`: the budget check stays **PASS** and appends
the estimated share (and the policy, when it isn't the default). No new
WARN state — a provider that never reports usage would otherwise sit at
a permanent WARN. Every new read is `.get()` + type-guarded so `doctor`
still works against an older running proxy.
- `docs/content/docs/metrics.mdx`: a "Measured vs Estimated Spend"
subsection with the `/stats` shape and the three policy values.
- Tests: new `tests/test_cost_budget_basis.py` (20 tests) plus 4 new
`doctor` tests; `tests/test_anthropic_pre_upstream_backpressure.py`'s
cost-tracker double gained `budget_denial_detail()` to match the
handler's duck-typed contract.

### Policy values

| `HEADROOM_BUDGET_ESTIMATED_BASIS` | Effect on the hard limit |
|---|---|
| `count` (default) | Unchanged behavior — estimated spend consumes the
budget. |
| `ignore` | Booked and reported, but only measured spend enforces. |
| `block` | Fail closed — refuse rather than enforce a hard limit on a
guess. |

Default enforcement is unchanged. `CHANGELOG.md` is untouched.

## Testing

- [x] Unit tests pass (`pytest`) — every test covering the changed
modules; see `Not tested` for this machine's pre-existing environment
failures
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`) — clean on every file this
PR touches
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ python -m pytest tests/test_cost_budget_basis.py tests/test_cost_tracker_counterfactual.py tests/test_cost_pricing_warning_dedup.py -q
31 passed

$ python -m pytest tests/test_cli_doctor.py -q
72 passed

$ python -m pytest tests/test_anthropic_pre_upstream_backpressure.py -q
25 passed

$ python -m pytest tests/test_proxy_settings_endpoints.py tests/test_proxy/test_settings_store.py -q
50 passed

# full suite (see "Not tested" below for the excluded modules and the pre-existing failures)
$ python -m pytest -q
...
tests\test_cost_budget_basis.py ....................                     [ 25%]
tests\test_cost_pricing_warning_dedup.py ...                             [ 25%]
tests\test_cost_tracker_counterfactual.py ........                       [ 25%]
...
217 failed, 8807 passed, 657 skipped, 5318 warnings, 59 errors in 716.30s (0:11:56)

# same failing files re-run on clean upstream/main with the change stashed -> identical count
$ git stash push -u -- headroom tests docs
$ python -m pytest tests/test_log_compressor.py tests/test_cache/test_client_integration.py \
    tests/test_fsutil.py tests/test_savings_ledger.py tests/test_ccr_mcp_http.py \
    tests/test_router_registry_dispatch.py tests/test_proxy_savings_history.py \
    tests/test_text_compressors.py tests/test_builtin_compressor_adapters.py \
    tests/test_cli_proxy_env.py -q
73 failed, 182 passed in 34.82s     # 40+16+2+2+1+1+1+4+3+3 = 73, matching the run above

$ python -m mypy headroom --ignore-missing-imports --python-version 3.13
# 12 errors, all in release_version.py / ccr/mcp_server.py / memory/mcp_server.py
# (stale local `mcp` stubs) — none in any file this PR touches

$ python -m ruff check headroom/proxy/budget_basis_policy.py headroom/proxy/cost.py headroom/proxy/server.py headroom/proxy/models.py headroom/proxy/handlers/anthropic.py headroom/cli/proxy.py headroom/cli/doctor.py headroom/settings_store.py tests/test_cost_budget_basis.py tests/test_cli_doctor.py tests/test_anthropic_pre_upstream_backpressure.py
All checks passed!

$ python -m ruff format --check <same 11 files>
11 files already formatted
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.13.11, branch
`fix/budget-estimated-basis-2713` off `upstream/main` @ `232fb49c`,
`PYTHONPATH` pointed at the working tree so the repo copy of `headroom`
is imported rather than the installed one.
- Exact command / steps: ran the repro script from the issue body
verbatim, then extended it to print `stats()["budget_basis"]` for both
trackers, to construct the same tracker with
`estimated_basis_policy="block"` and with `"ignore"`, and to record
twice against the same model to check the warning dedup. Separately
drove `headroom doctor`'s `check_budget` against stub `/stats` payloads
(mixed basis, all-measured, non-default policy, and an older proxy that
omits the new keys).
- Observed result: the issue's two figures are unchanged, so the
fallback still works — no breakdown `$0.008100`, with breakdown
`$0.005100`, ratio `1.59x`. The two are now separable: the no-breakdown
tracker reports `{'total_usd': 0.0081, 'measured_usd': 0.0,
'estimated_usd': 0.0081, 'estimated_pct': 100.0, 'records': 1,
'estimated_records': 1}` and the with-breakdown tracker reports
`estimated_usd: 0.0, estimated_pct: 0.0, estimated_records: 0`. One
`WARNING headroom.proxy: budget basis estimated: no usage breakdown from
provider for gpt-4o-mini — input cost booked from Headroom's own token
count` fires across repeated records, not one per request. With
`policy=block`, `check_budget()` returns `(False, 0.0)` and the 429
detail reads `Budget enforcement blocked for daily period: $0.0081 of
$0.0081 was booked from Headroom's own token estimate because the
provider returned no usage breakdown, and
HEADROOM_BUDGET_ESTIMATED_BASIS=block refuses to enforce a budget on an
estimate. Set it to 'count' or 'ignore' to serve these requests.` With
`policy=ignore`, `check_budget()` returns `(True, 0.0001)` while the
spend is still booked and reported (`0.7506`). `doctor` prints `pass
$10.0/daily budget enforced — 62% of period spend ($1.2400) booked from
Headroom token estimates`, appends `— estimated-basis policy: block` for
a non-default policy, and degrades to the plain `$10.0/daily budget
enforced` against a proxy that doesn't report the new fields.
`--budget-estimated-basis [count|ignore|block]` shows in `headroom proxy
--help`; the argparse path resolves the env var when the flag is absent
and an explicit flag wins over the env.
- Not tested: no live end-to-end run against a real provider that omits
usage in its response — the estimated basis was exercised through
`record_tokens()` directly, which is the single funnel
`emit_request_outcome()` uses. The `settings_store` field was not
exercised through the settings UI. The full-suite run above excludes
three things this machine cannot run, none of which touch the changed
files: `tests/test_hermes_passthrough_compression.py` (`respx` not
installed), `tests/test_memory/test_embedder_mps_serialization.py`
(`sentence_transformers` pins `tokenizers<=0.23.0`, local has `0.23.1`),
and `tests/test_cli/` (its subprocess-spawning tests wedge against a
leftover local proxy on :8787; each file passes in isolation, e.g.
`test_wrap_bridge.py` 7/7). Its 217 failures are all pre-existing
environment breakage — a stale local Rust `_core` build
(`test_log_compressor.py`, `test_text_compressors.py`,
`test_builtin_compressor_adapters.py`, `test_cli_proxy_env.py`, the
`test_transforms*` files) and the broken `sentence_transformers` install
(`tests/test_memory/*`, `test_memory_system.py`,
`test_sqlite_graph_store.py`) — with zero overlap with the modules this
PR changes; the stashed baseline above reproduces them 1:1. CI is the
authority for a green full suite.

## 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 — the
only local failures are pre-existing and reproduce with the change
stashed
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Additional Notes

The estimated-basis WARNING is deduped per model rather than emitted per
request, following the precedent set by #2504 for pricing warnings — the
whole point of this code path is that it fires on every request for a
provider that never reports usage, so an unguarded `logger.warning`
would flood `proxy.log`.

`headroom doctor` deliberately stays PASS. A WARN would be permanent,
not actionable, for anyone whose provider simply doesn't report usage;
the note tells them the number, and the `block` policy is there for
operators who want the hard failure.

`check_budget()` keeps its `(allowed, remaining)` signature and its
default `count` semantics, so
`tests/test_cost_tracker_counterfactual.py` — including
`test_budget_input_cost_counted_without_usage_breakdown`, the contract
that the fallback keeps working — passes unmodified.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 23:05:44 -07:00
Abhay Singh 7524854da7 fix(doctor): don't crash on a valid-but-non-object settings.json (#2482)
## Description

`headroom doctor` parses `~/.claude/settings.json` in two checks:

```python
try:
    payload = json.loads(settings_path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
    return CheckResult(... WARN "could not parse" ...)
...
env_block = payload.get("env")
```

`json.loads` returns a non-dict for any valid JSON that is not an
object: `[]`, `null`, `42`, `"a string"`. None of those raise
`JSONDecodeError`, so they slip past the `except (OSError, ValueError)`
guard, and the following `payload.get("env")` raises `AttributeError`.
`AttributeError` is not in the caught tuple, so it escapes and crashes
`doctor` with a traceback. That is the worst moment for it: `doctor` is
the command a user runs precisely because their config is suspect, and a
hand-edited or reset `settings.json` holding `[]` or `null` is exactly
the kind of file it should report on, not fall over on.

Two functions have this shape: `check_claude_routing` (the `.get` is
after the `try` returns) and `check_claude_remote_control_gate` (the
`.get` is inside a `try` whose `except` is also `(OSError,
ValueError)`).

## Fix

Guard `payload` for dict-ness in both checks. `check_claude_routing` now
returns the same WARN it already returns for unparseable files, with a
"not a JSON object" summary; `check_claude_remote_control_gate` treats a
non-object as having no `env` block, so the shell environment still
drives the gate. Well-formed object settings behave exactly as before.

## 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/doctor.py`: guard `payload` for dict-ness in
`check_claude_routing` and `check_claude_remote_control_gate` before
calling `.get`.
- `tests/test_cli_doctor.py`: parametrized regressions feeding `[]`,
`null`, `42`, and a bare string to both checks.

## Testing

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

### Test Output

```text
$ python -m pytest tests/test_cli_doctor.py -q
68 passed

# with the fix reverted, the new tests fail with
# AttributeError: 'list' object has no attribute 'get'

$ uvx ruff@0.15.17 check headroom/cli/doctor.py tests/test_cli_doctor.py
All checks passed!
$ uvx mypy@1.20.2 --ignore-missing-imports headroom/cli/doctor.py
Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.12, project venv (`uv sync --extra
proxy`), `uvx ruff@0.15.17` / `uvx mypy@1.20.2`, pytest in the venv.
- Exact command / steps: wrote a `settings.json` containing `[]` (and
`null`, `42`, `"a string"`) into a tmp path and called
`check_claude_routing(path, 8787)` and
`check_claude_remote_control_gate(path, {"ANTHROPIC_BASE_URL":
"http://127.0.0.1:8787"})`; then reverted `doctor.py` and re-ran.
- Observed result: with the fix both checks return a WARN result instead
of raising; with the fix reverted both raise `AttributeError: 'list'
object has no attribute 'get'` (and the analogous message for
`null`/`42`/string). Ran against the actual module via
`tests/test_cli_doctor.py`.
- Not tested: the full `headroom doctor` CLI end to end against a real
`~/.claude/settings.json`.

## 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
- [ ] I have updated the CHANGELOG.md if applicable
2026-07-22 06:10:23 -07:00
daeff69a75 fix(wrap): surface Claude Remote Control base-URL gate accurately (#1… (#1883)
…779)

Claude Code 2.1.196 deterministically disables first-party Remote
Control (/remote-control, /rc) behind a custom ANTHROPIC_BASE_URL, which
Headroom always sets. Make the wrap/doctor warning accurate (state the
disable as fact, name the /rc command, detect the installed version),
suppress it for auth modes that never had RC (API key,
Bedrock/Vertex/Foundry) and for builds older than 2.1.196, co-report the
sibling #746/#1158 gates session-accurately, and fix
is_custom_anthropic_base_url host handling (scheme-less hosts, malformed
URLs). UX/notice-only; no request bytes touched.

## Description

<!-- Briefly explain the change and why it is needed. -->

Closes #

## Type of Change

- [ ] 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

- 

## Testing

<!-- Check what you actually ran, then paste the real command output
below. -->

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

### Test Output

```text
# Paste relevant command output or artifact links here
```

## Real Behavior Proof

- Environment:
- Exact command / steps:
- Observed result:
- Not tested:

## Review Readiness

- [ ] I have performed a self-review
- [ ] This PR is ready for human review

## Checklist

- [ ] My code follows the project's style guidelines
- [ ] I have performed a self-review of my code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] I have updated the CHANGELOG.md if applicable

## Screenshots (if applicable)

Add screenshots to help explain your changes.

## Additional Notes

<!-- Mention any N/A checklist items, tradeoffs, follow-ups, or
maintainer context. -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Tejas Chopra <chopratejas@gmail.com>
2026-07-13 14:01:37 -04:00
Vinay Gupta 38074888ac fix(docker): report source build version (#1862)
## Description

Closes #1858

Docker/Compose source builds could report stale or misleading version
information: the dashboard initially rendered a hardcoded `v0.3.0`, then
`/health` replaced it with installed package metadata, which can be
stale when building locally from `main` without release metadata in the
image.

This change makes source Docker Compose builds report an explicit
source-build identity, removes the stale dashboard fallback, and keeps
CLI/doctor version checks from treating source-build labels as
release-version drift.

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

- Add `HEADROOM_VERSION` / `HEADROOM_BUILD_VERSION` runtime version
overrides and optional packaged `_build_info.py` metadata.
- Teach Docker Compose source builds to pass a `source-build` sentinel
that the Dockerfile expands to `source-build+g<sha>` when git metadata
is available, or `source-build+sha256.<digest>` otherwise.
- Keep release/published image builds on normal package metadata when
`HEADROOM_BUILD_VERSION` is unset.
- Include only minimal `.git` metadata in the Docker build context so
the source-build label can identify the checkout without copying git
objects.
- Treat source-build labels and raw hashes as non-release labels in
`wrap` and `doctor`, avoiding false stale-proxy restarts and drift
warnings.
- Replace the dashboard hardcoded `0.3.0` fallback with `loading` /
`unknown` and format non-release build labels without a `v` prefix.
- Include the runtime version in proxy startup logs, `/health`,
`/livez`, and OTEL service version reporting.

## Testing

- [x] Unit tests pass (`pytest` in GitHub CI)
- [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
GitHub CI: all checks passing
- CI: build, build-wheel, lint, test shards, test-extras, test-agno, test-dashboard-ui
- Docker: docker-native-e2e, docker-wrap-e2e, docker-init-e2e
- Native wrappers: macOS, Windows, Ubuntu
- Security: CodeQL, gitleaks, pip-audit
- Governance: template, label, merge-conflicts, commitlint

$ HEADROOM_REQUIRE_RUST_CORE=false PYTHONPATH=/Users/vinaygupta/Desktop/git/headroom-fix-1858-version-mismatch pytest tests/test_package_init_lazy.py::test_version_prefers_explicit_build_env tests/test_package_init_lazy.py::test_version_label_helpers_only_prefix_release_versions tests/test_package_init_lazy.py::test_version_uses_packaged_build_metadata tests/test_package_init_lazy.py::test_observability_version_uses_runtime_version tests/test_docker_compose_persistence.py tests/test_cli_doctor.py::TestProxyLiveness::test_up_leaves_source_label_unprefixed tests/test_cli_doctor.py::TestVersionDrift::test_non_release_version_labels_skip_drift_comparison tests/test_cli/test_wrap_persistent.py::test_proxy_version_restart_ignores_non_release_source_labels tests/test_proxy_dashboard_stats_cache.py::test_dashboard_uses_cached_stats_and_lazy_history_feed_polling -q
13 passed, 1 warning

$ uvx ruff==0.15.17 check .
All checks passed!

$ uvx ruff==0.15.17 format --check .
1058 files already formatted

$ uvx mypy==1.20.2 headroom --ignore-missing-imports
Success: no issues found in 407 source files

$ git diff --check
# no output

$ docker compose config
# resolved headroom-proxy build args include HEADROOM_BUILD_VERSION: source-build

$ HEADROOM_BUILD_VERSION=6266a1d docker compose config
# explicit override is preserved as HEADROOM_BUILD_VERSION: 6266a1d

$ docker build --check --build-arg HEADROOM_BUILD_VERSION=source-build .
Check complete, no warnings found.
```

## Real Behavior Proof

- Environment: macOS local checkout, Python 3.13.5, Docker Desktop
builder `desktop-linux`, plus GitHub Actions CI.
- Exact command / steps: `docker compose config`,
`HEADROOM_BUILD_VERSION=6266a1d docker compose config`, and `docker
build --check --build-arg HEADROOM_BUILD_VERSION=source-build .`.
- Observed result: Compose defaults the top-level `headroom-proxy` build
arg to the `source-build` sentinel, preserves explicit overrides, and
Dockerfile syntax/check validation passes for the source-build path.
- Not tested: Full end-to-end release publishing flow; this PR only
changes local/source-build reporting.
- CI proof: GitHub Actions completed successfully across Docker E2E, CI
test shards, lint/type checks, native wrapper checks, security checks,
and PR governance.

## 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/CI with my changes
- [ ] I have updated the CHANGELOG.md if applicable

## Screenshots (if applicable)

N/A

## Additional Notes

Docs and changelog are N/A for this runtime-reporting bug fix. The PR is
open and ready for review with all GitHub checks passing.
2026-07-08 13:32:04 -05:00
Rod Boev 4bf7f92417 fix(claude): surface Remote Control proxy incompatibility (#1610)
## Description

Claude Code hides Remote Control when it sees a custom
`ANTHROPIC_BASE_URL`, so `headroom wrap claude` can make the menu
disappear even though normal API requests still route through Headroom.
The reported proxy logs show no Remote Control registration, session
bootstrap, or device-attestation request at all, which means the
decision happens inside Claude before Headroom can forward anything.

This change makes that client-side incompatibility explicit in
Headroom's Claude launch flow, `headroom doctor`, and troubleshooting
docs. API proxying and the existing `ENABLE_TOOL_SEARCH` compatibility
shim stay unchanged; users who need Remote Control get a direct
instruction to launch Claude without the Headroom proxy for that
session.

Closes #1601

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

- Add a Claude-specific helper and warning text for the Remote Control
custom-base incompatibility.
- Surface that warning from `headroom wrap claude` when Claude is
launched through `ANTHROPIC_BASE_URL`.
- Add a separate `headroom doctor` warning for Claude Remote Control
availability, while keeping Claude API-routing status independent.
- Document the limitation and workaround next to the existing Claude
custom-endpoint troubleshooting guidance.
- Add focused regression tests for gated and non-gated Claude routing
states, plus preservation coverage for `ENABLE_TOOL_SEARCH`.

## Testing

- [x] Unit tests pass (`uv run pytest
tests/test_issue_1601_remote_control_gate.py tests/test_cli_doctor.py
tests/test_cli/test_wrap_claude_vertex_proxy_env.py -q`)
- [x] Unit tests pass (`uv run pytest
tests/test_issue_746_tool_search.py
tests/test_cli/test_init_enable_tool_search.py -q`)
- [x] Linting passes (`uv run ruff check headroom/cli/wrap.py
tests/test_cli_doctor.py
tests/test_cli/test_wrap_claude_vertex_proxy_env.py`)
- [x] Formatting passes (`uv run ruff format --check
headroom/cli/wrap.py tests/test_cli_doctor.py
tests/test_cli/test_wrap_claude_vertex_proxy_env.py`)
- [ ] Type checking passes (`uv run mypy headroom`)
- [x] New tests added for the bugfix
- [ ] Manual testing performed

### Test Output

```text
rtk uv run pytest tests/test_issue_1601_remote_control_gate.py tests/test_cli_doctor.py tests/test_cli/test_wrap_claude_vertex_proxy_env.py -q
============================= test session starts =============================
collected 62 items
62 passed, 1 warning

rtk uv run pytest tests/test_issue_746_tool_search.py tests/test_cli/test_init_enable_tool_search.py -q
============================= test session starts =============================
collected 33 items
33 passed, 1 warning

rtk uv run ruff check headroom/cli/wrap.py tests/test_cli_doctor.py tests/test_cli/test_wrap_claude_vertex_proxy_env.py
All checks passed!

rtk uv run ruff format --check headroom/cli/wrap.py tests/test_cli_doctor.py tests/test_cli/test_wrap_claude_vertex_proxy_env.py
3 files already formatted
```

## Real Behavior Proof

- Environment: Windows, Python via `uv`, focused Claude CLI and doctor
tests.
- Exact command / steps: with Claude settings or shell environment
containing `ANTHROPIC_BASE_URL=http://127.0.0.1:8787`, run the focused
helper and doctor tests, then run the existing `ENABLE_TOOL_SEARCH`
preservation tests.
- Observed result: Headroom surfaces a Claude Remote Control warning for
custom `ANTHROPIC_BASE_URL`, while Claude API routing and
`ENABLE_TOOL_SEARCH` behavior stay intact.
- Not tested: live Claude Remote Control UI automation. The issue
evidence says Claude hides the menu before any request reaches Headroom,
so this PR proves Headroom's launch, diagnostics, and docs behavior.

## 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
- [ ] 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
- [ ] I have updated the CHANGELOG.md if applicable

## Additional Notes

`CHANGELOG.md` stays untouched because this repo's release pipeline
generates changelog entries from conventional commits.

This is a visibility fix, not a proxy transport restore. The issue
evidence shows Claude never sends a Remote Control request while the
custom-base gate is active, so the surviving slice is launch-time
warning, doctor warning, and documentation.

PR `#1600` is adjacent and non-blocking because `#1601` reproduces from
process-env `ANTHROPIC_BASE_URL` alone.

This intentionally changes `headroom doctor` for fully routed Claude
sessions from an all-pass result to one warnings-only result, because
the proxied Claude setup is operational for API traffic but still
incompatible with Remote Control.
2026-07-01 23:19:25 -05:00
e45cf4e061 feat(cli): add headroom doctor setup diagnostics (#926)
## Description

Headroom fails silently: a client not routed through the proxy (or a
proxy running stale code) keeps working — it just stops saving tokens.
State that determines whether you are actually saving lives in five
places nothing reconciles. `headroom doctor` correlates them in one
command (the diagnostic idiom of `claude doctor` / `pnpm doctor`, and
the repo's own `headroom tools doctor`).

Closes # <!-- no tracked issue; setup-diagnosis gap found this session
-->

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] 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/doctor.py`: new command with 8 pure checks (proxy
liveness, version drift, claude/codex routing, shell env, savings flow,
budget, deployments); exit codes 0/1/2; `--json`;
`--port`/`HEADROOM_PORT`.
- `headroom/proxy/cost.py`: expose `budget_limit_usd`/`budget_period` in
`CostTracker.stats()` so the budget check can read it (older proxies
degrade to a warning).
- `headroom/cli/main.py`: register the command.
- `tests/test_cli_doctor.py`: 41 tests, zero network (probed payloads /
paths / env injected).

## 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 tests/test_cli_doctor.py -q
41 passed
```

## Real Behavior Proof

- Environment: local macOS, Python 3.11, against a real proxy running
for 3 days, branch `feat/doctor-command`.
- Exact command / steps: `headroom doctor` (live), plus `pytest
tests/test_cli_doctor.py -q`.
- Observed result: Correctly flagged real version drift (proxy 0.25.0 vs
installed 0.26.0), an unrouted claude client, and a shell
`OPENAI_BASE_URL` pointed at a non-Headroom gateway; savings check
showed 17.6M tokens / $7.82 saved; exit code 1 (warnings).
- Not tested: Windows path handling for client config files (logic is
OS-agnostic via pathlib).

## 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
- [ ] I have updated the CHANGELOG.md if applicable

## Screenshots (if applicable)

Terminal output of `headroom doctor` (rich table) can be attached; the
rendered table is reproduced in the live-proof bullet above.

## Additional Notes

Branched fresh from main. The budget check connects to the enforcement
fix in #885.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-06-17 23:28:23 -05:00