mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
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.
This commit is contained in:
+224
-15
@@ -25,7 +25,11 @@ import click
|
||||
|
||||
from headroom._version import format_version_label, normalize_release_version
|
||||
from headroom.install.health import probe_json
|
||||
from headroom.install.paths import claude_settings_path, codex_config_path
|
||||
from headroom.install.paths import (
|
||||
claude_settings_path,
|
||||
codex_config_path,
|
||||
codex_project_config_path,
|
||||
)
|
||||
from headroom.install.state import list_manifests
|
||||
from headroom.paths import savings_path
|
||||
from headroom.providers.claude import (
|
||||
@@ -41,6 +45,7 @@ from headroom.providers.claude import (
|
||||
)
|
||||
|
||||
from .main import get_version, main
|
||||
from .port_discovery import find_live_proxy_elsewhere, is_headroom_livez
|
||||
from .wrap import _read_wrap_marker, _wrap_marker_is_stale
|
||||
|
||||
PASS = "pass"
|
||||
@@ -117,6 +122,166 @@ def check_proxy_liveness(livez: dict[str, Any] | None, base_url: str) -> CheckRe
|
||||
)
|
||||
|
||||
|
||||
def note_live_proxy_elsewhere(check: CheckResult, live_port: int | None) -> CheckResult:
|
||||
"""Point an unreachable-proxy row at a live Headroom proxy on another port."""
|
||||
if live_port is None or check.status == PASS:
|
||||
return check
|
||||
check.summary += f"; a Headroom proxy IS running on port {live_port}"
|
||||
check.hint = (
|
||||
f"re-run with: headroom doctor --port {live_port} "
|
||||
f"(or export HEADROOM_PORT={live_port}); to use port {live_port} from agents, "
|
||||
f"re-run `headroom wrap <agent> --port {live_port}` / `headroom init --port {live_port} "
|
||||
"<agent>`"
|
||||
)
|
||||
return check
|
||||
|
||||
|
||||
def check_proxy_readiness(
|
||||
livez: dict[str, Any] | None, readyz: dict[str, Any] | None, base_url: str
|
||||
) -> CheckResult:
|
||||
"""Is the live proxy also *ready* (``/readyz``: upstream reachable, warmed up)?
|
||||
|
||||
``/livez`` only proves the event loop answers. ``/readyz`` answers 503 --
|
||||
which the probe reports as ``None`` -- while the upstream check fails or
|
||||
startup work is pending, so a live-but-unready proxy is a WARN, not a FAIL.
|
||||
"""
|
||||
name = "readiness"
|
||||
if livez is None:
|
||||
return CheckResult(name=name, status=SKIP, summary="proxy not reachable")
|
||||
if readyz is not None and (readyz.get("ready") or readyz.get("status") == "healthy"):
|
||||
return CheckResult(name=name, status=PASS, summary="/readyz reports ready")
|
||||
return CheckResult(
|
||||
name=name,
|
||||
status=WARN,
|
||||
summary="proxy is live but /readyz is not ready (upstream unreachable or still starting)",
|
||||
hint=f"inspect component state: curl {base_url}/health",
|
||||
)
|
||||
|
||||
|
||||
_HOOK_MARKERS = {"claude": "headroom-init-claude", "codex": "headroom-init-codex"}
|
||||
|
||||
|
||||
def _hook_commands(payload: Any) -> list[str]:
|
||||
"""Every ``command`` string under a Claude/Codex-style ``hooks`` mapping."""
|
||||
commands: list[str] = []
|
||||
hooks = payload.get("hooks") if isinstance(payload, dict) else None
|
||||
if not isinstance(hooks, dict):
|
||||
return commands
|
||||
for entries in hooks.values():
|
||||
if not isinstance(entries, list):
|
||||
continue
|
||||
for entry in entries:
|
||||
items = entry.get("hooks") if isinstance(entry, dict) else None
|
||||
if isinstance(items, list):
|
||||
for item in items:
|
||||
if isinstance(item, dict) and item.get("command"):
|
||||
commands.append(str(item["command"]))
|
||||
elif isinstance(entry, dict) and entry.get("command"):
|
||||
commands.append(str(entry["command"]))
|
||||
return commands
|
||||
|
||||
|
||||
def _missing_hook_executable(command: str) -> str | None:
|
||||
"""The hook command's program when it no longer resolves, else None."""
|
||||
import shlex
|
||||
import shutil
|
||||
|
||||
try:
|
||||
tokens = shlex.split(command, posix=os.name != "nt")
|
||||
except ValueError:
|
||||
return None
|
||||
if not tokens:
|
||||
return None
|
||||
program = tokens[0].strip('"')
|
||||
if Path(program).exists() or shutil.which(program):
|
||||
return None
|
||||
return program
|
||||
|
||||
|
||||
def check_installed_hooks(expected: Sequence[tuple[str, str, Path, str]]) -> CheckResult:
|
||||
"""Are the hooks ``headroom init`` installed still present and runnable?
|
||||
|
||||
``expected`` holds ``(agent, scope_label, hooks_file, init_command)`` for
|
||||
each agent an init deployment manifest says was configured. A missing
|
||||
hook means the proxy is never auto-started for new sessions; a hook whose
|
||||
program vanished (uninstalled venv, moved checkout) fails silently.
|
||||
"""
|
||||
name = "hooks"
|
||||
if not expected:
|
||||
return CheckResult(name=name, status=SKIP, summary="no `headroom init` hooks expected")
|
||||
problems: list[str] = []
|
||||
fixes: list[str] = []
|
||||
installed: list[str] = []
|
||||
for agent, scope, path, fix in expected:
|
||||
marker = _HOOK_MARKERS.get(agent, f"headroom-init-{agent}")
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
|
||||
except (OSError, ValueError):
|
||||
problems.append(f"{agent} ({scope}): could not parse {path}")
|
||||
fixes.append(fix)
|
||||
continue
|
||||
commands = [cmd for cmd in _hook_commands(payload) if marker in cmd]
|
||||
if not commands:
|
||||
problems.append(f"{agent} ({scope}): no Headroom hook in {path}")
|
||||
fixes.append(fix)
|
||||
continue
|
||||
missing = {prog for cmd in commands if (prog := _missing_hook_executable(cmd))}
|
||||
if missing:
|
||||
problems.append(
|
||||
f"{agent} ({scope}): hook program not found: {', '.join(sorted(missing))}"
|
||||
)
|
||||
fixes.append(fix)
|
||||
continue
|
||||
installed.append(f"{agent} ({scope})")
|
||||
if problems:
|
||||
return CheckResult(
|
||||
name=name,
|
||||
status=WARN,
|
||||
summary="; ".join(problems),
|
||||
hint="re-install with: " + " && ".join(dict.fromkeys(fixes)),
|
||||
)
|
||||
return CheckResult(name=name, status=PASS, summary="installed for " + ", ".join(installed))
|
||||
|
||||
|
||||
def expected_init_hooks(
|
||||
manifests: Sequence[Any], cwd: Path | None = None
|
||||
) -> list[tuple[str, str, Path, str]]:
|
||||
"""Hook files ``headroom init`` should have written, from its deployment manifests."""
|
||||
from headroom.install.paths import codex_hooks_path
|
||||
|
||||
from .init import _GLOBAL_PROFILE, _local_profile
|
||||
|
||||
root = cwd or Path.cwd()
|
||||
try:
|
||||
local_profile = _local_profile(root)
|
||||
except Exception: # noqa: BLE001 - odd cwd names must not crash doctor
|
||||
local_profile = None
|
||||
expected: list[tuple[str, str, Path, str]] = []
|
||||
for manifest in manifests:
|
||||
profile = getattr(manifest, "profile", "")
|
||||
if profile == _GLOBAL_PROFILE:
|
||||
scope, flag = "user", " -g"
|
||||
elif local_profile is not None and profile == local_profile:
|
||||
scope, flag = "project", ""
|
||||
else:
|
||||
continue
|
||||
port = getattr(manifest, "port", 8787)
|
||||
port_flag = f" --port {port}" if port != 8787 else ""
|
||||
for agent in getattr(manifest, "targets", []) or []:
|
||||
if agent == "claude":
|
||||
path = (
|
||||
claude_settings_path()
|
||||
if scope == "user"
|
||||
else root / ".claude" / "settings.local.json"
|
||||
)
|
||||
elif agent == "codex":
|
||||
path = codex_hooks_path() if scope == "user" else root / ".codex" / "hooks.json"
|
||||
else:
|
||||
continue
|
||||
expected.append((agent, scope, path, f"headroom init{flag}{port_flag} {agent}"))
|
||||
return expected
|
||||
|
||||
|
||||
def check_version_drift(livez: dict[str, Any] | None, installed: str) -> CheckResult:
|
||||
"""Does the running proxy match the installed package version?"""
|
||||
if livez is None:
|
||||
@@ -400,36 +565,65 @@ def check_wrap_marker_staleness(settings_path: Path) -> CheckResult:
|
||||
)
|
||||
|
||||
|
||||
def check_codex_routing(config_path: Path, port: int) -> CheckResult:
|
||||
def codex_active_base_url(text: str) -> tuple[str, str | None]:
|
||||
"""Return ``(provider_id, base_url)`` for the active Codex provider in ``text``."""
|
||||
active_match = _CODEX_MODEL_PROVIDER_RE.search(text)
|
||||
provider_id = active_match.group(1) if active_match else "headroom"
|
||||
return provider_id, _codex_provider_base_url(text, provider_id)
|
||||
|
||||
|
||||
def check_codex_routing(
|
||||
config_path: Path,
|
||||
port: int,
|
||||
project_config_paths: Sequence[Path] | None = None,
|
||||
) -> CheckResult:
|
||||
"""Is Codex configured to route through the proxy?
|
||||
|
||||
Detection prefers the active ``model_provider`` section's loopback
|
||||
``base_url``, while retaining the ``[model_providers.headroom]`` fallback
|
||||
emitted by persistent and wrap installs. Best-effort matching keeps
|
||||
malformed TOML a WARN instead of a crash.
|
||||
|
||||
``config_path`` is the user config (``$CODEX_HOME/config.toml``, so a
|
||||
relocated Codex home is inspected rather than ``~/.codex``). Codex layers a
|
||||
trusted project's ``.codex/config.toml`` over it, and ``headroom init
|
||||
codex`` without ``-g`` writes there, so project candidates are consulted
|
||||
first and the summary names the file that supplied the routing.
|
||||
"""
|
||||
name = "codex"
|
||||
if not config_path.exists():
|
||||
candidates = [*(project_config_paths or []), config_path]
|
||||
existing = [path for path in candidates if path.exists()]
|
||||
if not existing:
|
||||
return CheckResult(
|
||||
name=name,
|
||||
status=WARN,
|
||||
summary="not routed (no ~/.codex/config.toml)",
|
||||
summary=f"not routed (no {config_path})",
|
||||
hint="wrap it: headroom wrap codex",
|
||||
)
|
||||
try:
|
||||
text = config_path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError as exc:
|
||||
return CheckResult(name=name, status=WARN, summary=f"could not read {config_path}: {exc}")
|
||||
active_match = _CODEX_MODEL_PROVIDER_RE.search(text)
|
||||
provider_id = active_match.group(1) if active_match else "headroom"
|
||||
base_url = _codex_provider_base_url(text, provider_id)
|
||||
if base_url is None:
|
||||
first_error: CheckResult | None = None
|
||||
found: tuple[Path, str, str, str] | None = None
|
||||
for candidate in existing:
|
||||
try:
|
||||
text = candidate.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError as exc:
|
||||
first_error = first_error or CheckResult(
|
||||
name=name, status=WARN, summary=f"could not read {candidate}: {exc}"
|
||||
)
|
||||
continue
|
||||
provider_id, base_url = codex_active_base_url(text)
|
||||
if base_url is not None:
|
||||
found = (candidate, text, provider_id, base_url)
|
||||
break
|
||||
if found is None:
|
||||
if first_error is not None:
|
||||
return first_error
|
||||
return CheckResult(
|
||||
name=name,
|
||||
status=WARN,
|
||||
summary="not routed (no active provider base_url in config.toml)",
|
||||
hint="wrap it: headroom wrap codex",
|
||||
)
|
||||
config_path, text, provider_id, base_url = found
|
||||
routing = _classify_routing_url(name, base_url, port, source=str(config_path))
|
||||
if routing.status != PASS:
|
||||
return routing
|
||||
@@ -939,14 +1133,28 @@ def doctor(port: int, emit_json: bool, network: bool, network_urls: tuple[str, .
|
||||
"""
|
||||
base_url = f"http://127.0.0.1:{port}"
|
||||
livez = probe_json(f"{base_url}/livez")
|
||||
readyz = probe_json(f"{base_url}/readyz", timeout=3.0) if livez else None
|
||||
health = probe_json(f"{base_url}/health", timeout=5.0) if livez else None
|
||||
stats = probe_json(f"{base_url}/stats", timeout=5.0) if livez else None
|
||||
installed = get_version()
|
||||
manifests = list_manifests()
|
||||
live_elsewhere = None
|
||||
if livez is None:
|
||||
# Cheap, bounded: only ports Headroom recorded (HEADROOM_PORT, 8787,
|
||||
# deployment manifests, the project's wrap marker), probed in parallel.
|
||||
live_elsewhere = find_live_proxy_elsewhere(
|
||||
port,
|
||||
manifests=manifests,
|
||||
probe=lambda p: is_headroom_livez(
|
||||
probe_json(f"http://127.0.0.1:{p}/livez", timeout=0.5)
|
||||
),
|
||||
)
|
||||
|
||||
project_claude_settings = Path.cwd() / ".claude" / "settings.json"
|
||||
project_local_claude_settings = Path.cwd() / ".claude" / "settings.local.json"
|
||||
checks = [
|
||||
check_proxy_liveness(livez, base_url),
|
||||
note_live_proxy_elsewhere(check_proxy_liveness(livez, base_url), live_elsewhere),
|
||||
check_proxy_readiness(livez, readyz, base_url),
|
||||
check_version_drift(livez, installed),
|
||||
check_claude_routing(
|
||||
claude_settings_path(),
|
||||
@@ -954,7 +1162,8 @@ def doctor(port: int, emit_json: bool, network: bool, network_urls: tuple[str, .
|
||||
[project_local_claude_settings, project_claude_settings],
|
||||
),
|
||||
check_wrap_marker_staleness(project_local_claude_settings),
|
||||
check_codex_routing(codex_config_path(), port),
|
||||
check_codex_routing(codex_config_path(), port, [codex_project_config_path()]),
|
||||
check_installed_hooks(expected_init_hooks(manifests)),
|
||||
check_shell_env(os.environ, port),
|
||||
check_kompress_health(health),
|
||||
check_savings(stats, savings_path()),
|
||||
@@ -994,7 +1203,7 @@ def doctor(port: int, emit_json: bool, network: bool, network_urls: tuple[str, .
|
||||
desktop_check = check_claude_desktop(claude_desktop_config_dir())
|
||||
if desktop_check is not None:
|
||||
checks.append(desktop_check)
|
||||
deployments = check_deployments(list_manifests())
|
||||
deployments = check_deployments(manifests)
|
||||
if deployments is not None:
|
||||
checks.append(deployments)
|
||||
|
||||
|
||||
+198
-6
@@ -24,9 +24,22 @@ except ModuleNotFoundError: # Python < 3.11
|
||||
import tomli as tomllib # type: ignore[no-redef]
|
||||
|
||||
import click
|
||||
from click.core import ParameterSource
|
||||
|
||||
from headroom.cli.port_discovery import (
|
||||
DEFAULT_PROXY_PORT,
|
||||
env_port,
|
||||
reconcile_default_port,
|
||||
warn_codex_provider_port_change,
|
||||
)
|
||||
from headroom.install.models import ConfigScope, InstallPreset, RuntimeKind, SupervisorKind
|
||||
from headroom.install.paths import claude_settings_path, codex_config_path, validate_profile_name
|
||||
from headroom.install.paths import (
|
||||
claude_settings_path,
|
||||
codex_config_path,
|
||||
codex_hooks_path,
|
||||
codex_project_config_path,
|
||||
validate_profile_name,
|
||||
)
|
||||
from headroom.install.planner import build_manifest
|
||||
from headroom.install.providers import _apply_unix_env_scope, _apply_windows_env_scope
|
||||
from headroom.install.runtime import (
|
||||
@@ -136,7 +149,11 @@ def _copilot_config_path() -> Path:
|
||||
|
||||
|
||||
def _codex_hooks_path(global_scope: bool) -> Path:
|
||||
return (Path.home() if global_scope else Path.cwd()) / ".codex" / "hooks.json"
|
||||
# User scope follows Codex's own home resolution (CODEX_HOME, else ~/.codex)
|
||||
# so `init -g codex` writes the hooks file Codex will actually load.
|
||||
if global_scope:
|
||||
return codex_hooks_path()
|
||||
return Path.cwd() / ".codex" / "hooks.json"
|
||||
|
||||
|
||||
def _claude_scope_path(global_scope: bool) -> Path:
|
||||
@@ -148,7 +165,7 @@ def _claude_scope_path(global_scope: bool) -> Path:
|
||||
def _codex_scope_path(global_scope: bool) -> Path:
|
||||
if global_scope:
|
||||
return codex_config_path()
|
||||
return Path.cwd() / ".codex" / "config.toml"
|
||||
return codex_project_config_path()
|
||||
|
||||
|
||||
def _json_file(path: Path) -> dict[str, Any]:
|
||||
@@ -332,6 +349,7 @@ def _ensure_codex_provider(path: Path, port: int) -> None:
|
||||
import re
|
||||
|
||||
logger.debug("ensure codex provider block: %s (port=%s)", path, port)
|
||||
warn_codex_provider_port_change(path, port)
|
||||
# Emit requires_openai_auth only for ChatGPT-OAuth users (restores the
|
||||
# account menu); omitting it for API-key users avoids forcing an OAuth
|
||||
# login (#406).
|
||||
@@ -970,14 +988,33 @@ def _install_headroom_mcp_for_targets(*, targets: list[str], port: int) -> None:
|
||||
click.echo(line)
|
||||
|
||||
|
||||
def _resolve_init_port(ctx: click.Context, port: int) -> int:
|
||||
"""Honor ``--port``; otherwise ``HEADROOM_PORT``; otherwise reconcile with a live proxy.
|
||||
|
||||
Skipped for the internal ``init hook`` group: hooks run non-interactively
|
||||
on every session start and must stay silent and fast.
|
||||
"""
|
||||
if ctx.invoked_subcommand == "hook":
|
||||
return port
|
||||
if ctx.get_parameter_source("port") is not ParameterSource.DEFAULT:
|
||||
return port
|
||||
configured = env_port()
|
||||
if configured is not None:
|
||||
return configured
|
||||
return reconcile_default_port(port)
|
||||
|
||||
|
||||
@main.group(invoke_without_command=True)
|
||||
@click.option("-g", "--global", "global_scope", is_flag=True, help="Install for the current user.")
|
||||
@click.option(
|
||||
"--port",
|
||||
default=8787,
|
||||
default=DEFAULT_PROXY_PORT,
|
||||
type=click.IntRange(1, 65535),
|
||||
show_default=True,
|
||||
help="Headroom proxy port.",
|
||||
help=(
|
||||
"Headroom proxy port. When omitted, HEADROOM_PORT is used if set; otherwise a "
|
||||
"live Headroom proxy on another port is detected and offered."
|
||||
),
|
||||
)
|
||||
@click.option("--backend", default="anthropic", show_default=True, help="Proxy backend.")
|
||||
@click.option("--anyllm-provider", default=None, help="Provider for any-llm backends.")
|
||||
@@ -1004,6 +1041,7 @@ def init(
|
||||
"""Install durable Headroom integrations for supported agents."""
|
||||
if verbose:
|
||||
_enable_verbose_logging()
|
||||
port = _resolve_init_port(ctx, port)
|
||||
logger.debug(
|
||||
"init: global_scope=%s port=%s backend=%s anyllm_provider=%s region=%s memory=%s "
|
||||
"invoked_subcommand=%s",
|
||||
@@ -1122,7 +1160,6 @@ def init_hook() -> None:
|
||||
@click.option("--marker", default=None, hidden=True)
|
||||
def init_hook_ensure(profile: str | None, marker: str | None) -> None:
|
||||
"""Best-effort ensure used by installed agent hooks."""
|
||||
del marker
|
||||
|
||||
def _has_manifest(name: str) -> bool:
|
||||
# Best-effort: a corrupt manifest must not crash the session-start hook.
|
||||
@@ -1142,3 +1179,158 @@ def init_hook_ensure(profile: str | None, marker: str | None) -> None:
|
||||
profiles.append(_GLOBAL_PROFILE)
|
||||
for name in profiles:
|
||||
_ensure_profile_running(name)
|
||||
_emit_alignment_warning(marker, profiles)
|
||||
|
||||
|
||||
_HOOK_AGENT_BY_MARKER = {_CLAUDE_HOOK_MARKER: "claude", _CODEX_HOOK_MARKER: "codex"}
|
||||
_HOOK_STDIN_WAIT_SECONDS = 0.5
|
||||
|
||||
|
||||
def _read_hook_event_name() -> str | None:
|
||||
"""``hook_event_name`` from the hook's stdin JSON, read with a hard time bound.
|
||||
|
||||
Claude Code and Codex pipe a JSON object into command hooks. A reader
|
||||
thread keeps a host that never closes stdin from stalling the hook.
|
||||
"""
|
||||
import threading
|
||||
|
||||
try:
|
||||
stream = sys.stdin
|
||||
if stream is None or stream.isatty():
|
||||
return None
|
||||
except (AttributeError, ValueError, OSError):
|
||||
return None
|
||||
box: dict[str, str] = {}
|
||||
|
||||
def _read() -> None:
|
||||
try:
|
||||
box["raw"] = stream.read(1 << 20)
|
||||
except Exception: # noqa: BLE001 - best effort
|
||||
pass
|
||||
|
||||
reader = threading.Thread(target=_read, daemon=True)
|
||||
reader.start()
|
||||
reader.join(_HOOK_STDIN_WAIT_SECONDS)
|
||||
raw = box.get("raw")
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
event = payload.get("hook_event_name") if isinstance(payload, dict) else None
|
||||
return event if isinstance(event, str) else None
|
||||
|
||||
|
||||
def _claude_configured_base_url(cwd: Path) -> str | None:
|
||||
"""Effective ``ANTHROPIC_BASE_URL`` from Claude settings (local > project > user)."""
|
||||
for path in (
|
||||
cwd / ".claude" / "settings.local.json",
|
||||
cwd / ".claude" / "settings.json",
|
||||
claude_settings_path(),
|
||||
):
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8")) if path.exists() else None
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
env_block = payload.get("env") if isinstance(payload, dict) else None
|
||||
if isinstance(env_block, dict) and env_block.get("ANTHROPIC_BASE_URL"):
|
||||
return str(env_block["ANTHROPIC_BASE_URL"])
|
||||
return os.environ.get("ANTHROPIC_BASE_URL") or None
|
||||
|
||||
|
||||
def _codex_configured_base_url(cwd: Path) -> str | None:
|
||||
"""Active Codex provider ``base_url`` (project ``.codex`` first, then ``$CODEX_HOME``)."""
|
||||
from .doctor import codex_active_base_url
|
||||
|
||||
for path in (codex_project_config_path(cwd), codex_config_path()):
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8", errors="replace") if path.exists() else ""
|
||||
except OSError:
|
||||
continue
|
||||
if not text:
|
||||
continue
|
||||
_provider, base_url = codex_active_base_url(text)
|
||||
if base_url:
|
||||
return base_url
|
||||
return None
|
||||
|
||||
|
||||
def alignment_warning(
|
||||
agent: str,
|
||||
profile: str,
|
||||
*,
|
||||
cwd: Path | None = None,
|
||||
probe: Any = None,
|
||||
) -> str | None:
|
||||
"""Message when ``agent``'s configured proxy port differs from ``profile``'s.
|
||||
|
||||
Returns None when aligned, unconfigured, or anything cannot be read.
|
||||
"""
|
||||
from .port_discovery import loopback_port, probe_headroom_proxy
|
||||
|
||||
try:
|
||||
manifest = load_manifest(profile)
|
||||
except ManifestError:
|
||||
return None
|
||||
if manifest is None:
|
||||
return None
|
||||
root = cwd or Path.cwd()
|
||||
if agent == "claude":
|
||||
base_url = _claude_configured_base_url(root)
|
||||
elif agent == "codex":
|
||||
base_url = _codex_configured_base_url(root)
|
||||
else:
|
||||
return None
|
||||
configured = loopback_port(base_url or "")
|
||||
expected = int(manifest.port)
|
||||
if configured is None or configured == expected:
|
||||
return None
|
||||
check = probe or probe_headroom_proxy
|
||||
configured_live = bool(check(configured))
|
||||
scope_flag = " -g" if profile == _GLOBAL_PROFILE else ""
|
||||
label = "Claude Code" if agent == "claude" else "Codex"
|
||||
if configured_live:
|
||||
state = f"a Headroom proxy is running on {configured}, not the managed one"
|
||||
fix_port = configured
|
||||
else:
|
||||
state = f"nothing Headroom answers on {configured}, so requests may fail"
|
||||
fix_port = expected
|
||||
return (
|
||||
f"Headroom: {label} is configured for http://127.0.0.1:{configured} but the Headroom "
|
||||
f"proxy managed by `headroom init` ({profile}) uses port {expected}; {state}. "
|
||||
f"Fix: headroom init{scope_flag} --port {fix_port} {agent}"
|
||||
)
|
||||
|
||||
|
||||
def _emit_alignment_warning(marker: str | None, profiles: list[str]) -> None:
|
||||
"""Surface a base_url/proxy port mismatch through the SessionStart hook channel.
|
||||
|
||||
Emitted only for Claude/Codex SessionStart hooks, as hook JSON
|
||||
(``systemMessage`` for the user, ``additionalContext`` for the agent).
|
||||
Must never raise or block: any failure silently emits nothing.
|
||||
"""
|
||||
try:
|
||||
agent = _HOOK_AGENT_BY_MARKER.get(marker or "")
|
||||
if agent is None or not profiles:
|
||||
return
|
||||
if _read_hook_event_name() != "SessionStart":
|
||||
return
|
||||
message = alignment_warning(agent, profiles[0])
|
||||
if not message:
|
||||
return
|
||||
sys.stdout.write(
|
||||
json.dumps(
|
||||
{
|
||||
"systemMessage": message,
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "SessionStart",
|
||||
"additionalContext": message,
|
||||
},
|
||||
}
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
sys.stdout.flush()
|
||||
except Exception: # noqa: BLE001 - a hook must never break the session
|
||||
return
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
"""Resolve which local port the Headroom proxy is (or should be) on.
|
||||
|
||||
``wrap``, ``init`` and ``doctor`` all default to port 8787. When a proxy is
|
||||
already running elsewhere (``HEADROOM_PORT``, a persistent deployment on a
|
||||
custom port, a live wrap session), silently defaulting to 8787 either starts a
|
||||
second proxy or points an agent at a dead port. These helpers make the default
|
||||
port follow ``HEADROOM_PORT`` and cheaply discover a live Headroom proxy on the
|
||||
other ports Headroom itself recorded, so the CLI can warn -- or, on a TTY, ask
|
||||
-- instead of guessing.
|
||||
|
||||
Discovery is deliberately bounded: loopback only, a handful of candidate ports
|
||||
(the requested/default port, ``HEADROOM_PORT``, 8787, deployment-manifest ports
|
||||
and the project's wrap marker), probed concurrently with a sub-second timeout.
|
||||
It never scans port ranges. ``HEADROOM_PORT_DISCOVERY=0`` disables it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from collections.abc import Callable, Iterable, Mapping, Sequence
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import click
|
||||
|
||||
DEFAULT_PROXY_PORT = 8787
|
||||
PORT_ENV = "HEADROOM_PORT"
|
||||
DISCOVERY_ENV = "HEADROOM_PORT_DISCOVERY"
|
||||
_PROBE_TIMEOUT_SECONDS = 0.5
|
||||
_MAX_CANDIDATES = 8
|
||||
_HEADROOM_SERVICE = "headroom-proxy"
|
||||
_LOOPBACK_PORT_RE = re.compile(r"^https?://(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)")
|
||||
|
||||
Probe = Callable[[int], bool]
|
||||
|
||||
|
||||
def _valid_port(value: Any) -> int | None:
|
||||
try:
|
||||
port = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return port if 1 <= port <= 65535 else None
|
||||
|
||||
|
||||
def env_port(environ: Mapping[str, str] | None = None) -> int | None:
|
||||
"""Return ``HEADROOM_PORT`` as a port number, or None when unset/invalid."""
|
||||
env = os.environ if environ is None else environ
|
||||
raw = (env.get(PORT_ENV) or "").strip()
|
||||
return _valid_port(raw) if raw else None
|
||||
|
||||
|
||||
def default_port(environ: Mapping[str, str] | None = None) -> int:
|
||||
"""The port a command should use absent ``--port``: ``HEADROOM_PORT`` or 8787."""
|
||||
return env_port(environ) or DEFAULT_PROXY_PORT
|
||||
|
||||
|
||||
def discovery_enabled(environ: Mapping[str, str] | None = None) -> bool:
|
||||
"""Whether live-proxy discovery may run (``HEADROOM_PORT_DISCOVERY=0`` disables)."""
|
||||
env = os.environ if environ is None else environ
|
||||
return (env.get(DISCOVERY_ENV) or "").strip().lower() not in {"0", "false", "no", "off"}
|
||||
|
||||
|
||||
def loopback_port(url: str) -> int | None:
|
||||
"""Port of a loopback ``http(s)://127.0.0.1|localhost:<port>`` URL, else None."""
|
||||
match = _LOOPBACK_PORT_RE.match((url or "").strip())
|
||||
return _valid_port(match.group(1)) if match else None
|
||||
|
||||
|
||||
def _manifest_ports(manifests: Iterable[Any] | None) -> list[int]:
|
||||
if manifests is None:
|
||||
try:
|
||||
from headroom.install.state import list_manifests
|
||||
|
||||
manifests = list_manifests()
|
||||
except Exception: # noqa: BLE001 - discovery is best-effort
|
||||
return []
|
||||
ports: list[int] = []
|
||||
for manifest in manifests:
|
||||
port = _valid_port(getattr(manifest, "port", None))
|
||||
if port is not None:
|
||||
ports.append(port)
|
||||
return ports
|
||||
|
||||
|
||||
def _wrap_marker_ports(cwd: Path | None) -> list[int]:
|
||||
"""Ports recorded by ``wrap claude``'s project marker (read-only, no import of wrap)."""
|
||||
marker = (cwd or Path.cwd()) / ".claude" / ".headroom_wrap_marker.json"
|
||||
try:
|
||||
payload = json.loads(marker.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return []
|
||||
port = _valid_port(payload.get("port")) if isinstance(payload, dict) else None
|
||||
return [port] if port is not None else []
|
||||
|
||||
|
||||
def candidate_ports(
|
||||
requested: int,
|
||||
*,
|
||||
environ: Mapping[str, str] | None = None,
|
||||
manifests: Iterable[Any] | None = None,
|
||||
cwd: Path | None = None,
|
||||
extra: Sequence[int] = (),
|
||||
) -> list[int]:
|
||||
"""Ordered, de-duplicated, bounded list of ports worth probing."""
|
||||
ordered: list[int] = [requested]
|
||||
env_value = env_port(environ)
|
||||
if env_value is not None:
|
||||
ordered.append(env_value)
|
||||
ordered.append(DEFAULT_PROXY_PORT)
|
||||
ordered.extend(extra)
|
||||
ordered.extend(_manifest_ports(manifests))
|
||||
ordered.extend(_wrap_marker_ports(cwd))
|
||||
seen: list[int] = []
|
||||
for port in ordered:
|
||||
if port not in seen:
|
||||
seen.append(port)
|
||||
return seen[:_MAX_CANDIDATES]
|
||||
|
||||
|
||||
def probe_headroom_proxy(port: int, timeout: float = _PROBE_TIMEOUT_SECONDS) -> bool:
|
||||
"""True when a Headroom proxy answers ``/livez`` on loopback ``port``.
|
||||
|
||||
Requires the ``service: headroom-proxy`` identity (or the legacy
|
||||
``alive``+``version`` shape) so an unrelated local server on the port is
|
||||
never mistaken for Headroom.
|
||||
"""
|
||||
from headroom.install.health import probe_json
|
||||
|
||||
return is_headroom_livez(probe_json(f"http://127.0.0.1:{port}/livez", timeout=timeout))
|
||||
|
||||
|
||||
def is_headroom_livez(payload: Mapping[str, Any] | None) -> bool:
|
||||
"""Whether a ``/livez`` payload identifies a Headroom proxy."""
|
||||
if not payload:
|
||||
return False
|
||||
if payload.get("service") == _HEADROOM_SERVICE:
|
||||
return True
|
||||
return "alive" in payload and "version" in payload and "service" not in payload
|
||||
|
||||
|
||||
def live_ports(ports: Sequence[int], probe: Probe | None = None) -> list[int]:
|
||||
"""Return the subset of ``ports`` with a live Headroom proxy, preserving order."""
|
||||
if not ports:
|
||||
return []
|
||||
check = probe or probe_headroom_proxy
|
||||
if len(ports) == 1:
|
||||
return [ports[0]] if check(ports[0]) else []
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
with ThreadPoolExecutor(max_workers=len(ports)) as pool:
|
||||
results = list(pool.map(check, ports))
|
||||
return [port for port, alive in zip(ports, results, strict=True) if alive]
|
||||
|
||||
|
||||
def find_live_proxy_elsewhere(
|
||||
requested: int,
|
||||
*,
|
||||
environ: Mapping[str, str] | None = None,
|
||||
manifests: Iterable[Any] | None = None,
|
||||
cwd: Path | None = None,
|
||||
probe: Probe | None = None,
|
||||
extra: Sequence[int] = (),
|
||||
) -> int | None:
|
||||
"""Port of a live Headroom proxy when ``requested`` has none, else None.
|
||||
|
||||
Returns None when discovery is disabled, when ``requested`` itself is live
|
||||
(nothing to reconcile), or when no candidate answers. Never raises.
|
||||
"""
|
||||
if not discovery_enabled(environ):
|
||||
return None
|
||||
try:
|
||||
candidates = candidate_ports(
|
||||
requested, environ=environ, manifests=manifests, cwd=cwd, extra=extra
|
||||
)
|
||||
alive = live_ports(candidates, probe=probe)
|
||||
except Exception: # noqa: BLE001 - discovery must never break a command
|
||||
return None
|
||||
if requested in alive:
|
||||
return None
|
||||
return next((port for port in alive if port != requested), None)
|
||||
|
||||
|
||||
def _is_interactive() -> bool:
|
||||
try:
|
||||
return sys.stdin.isatty() and sys.stdout.isatty()
|
||||
except (AttributeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def reconcile_default_port(
|
||||
requested: int,
|
||||
*,
|
||||
option_name: str = "--port",
|
||||
interactive: bool | None = None,
|
||||
environ: Mapping[str, str] | None = None,
|
||||
manifests: Iterable[Any] | None = None,
|
||||
cwd: Path | None = None,
|
||||
probe: Probe | None = None,
|
||||
) -> int:
|
||||
"""Return the port to use when the user did not choose one explicitly.
|
||||
|
||||
* No live proxy elsewhere (or ``requested`` is live): ``requested``.
|
||||
* A live Headroom proxy on another port and a TTY: ask whether to connect
|
||||
to it, keep ``requested``, or abort (``click.Abort``).
|
||||
* Non-interactive: keep ``requested`` -- never adopt a port silently -- and
|
||||
warn on stderr naming the live port and the flag that selects it.
|
||||
"""
|
||||
live = find_live_proxy_elsewhere(
|
||||
requested, environ=environ, manifests=manifests, cwd=cwd, probe=probe
|
||||
)
|
||||
if live is None:
|
||||
return requested
|
||||
click.echo(
|
||||
f"headroom: no Headroom proxy on port {requested}, but one is running on port {live}.",
|
||||
err=True,
|
||||
)
|
||||
if interactive is None:
|
||||
interactive = _is_interactive()
|
||||
if not interactive:
|
||||
click.echo(
|
||||
f"headroom: continuing with port {requested}. To use the running proxy, pass "
|
||||
f"{option_name} {live} (or set {PORT_ENV}={live}).",
|
||||
err=True,
|
||||
)
|
||||
return requested
|
||||
choice = click.prompt(
|
||||
f"Connect to the running proxy on {live} [c], keep port {requested} [k], or abort [a]?",
|
||||
type=click.Choice(["c", "k", "a"], case_sensitive=False),
|
||||
default="c",
|
||||
err=True,
|
||||
)
|
||||
choice = choice.lower()
|
||||
if choice == "a":
|
||||
raise click.Abort()
|
||||
return live if choice == "c" else requested
|
||||
|
||||
|
||||
def port_option_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
|
||||
"""Click callback: reconcile a defaulted ``--port`` with any live proxy.
|
||||
|
||||
An explicit ``--port`` (command line) or ``HEADROOM_PORT`` (the option's
|
||||
envvar) is always honored as-is. Only a pure default triggers discovery.
|
||||
"""
|
||||
from click.core import ParameterSource
|
||||
|
||||
if value is None or param.name is None:
|
||||
return value
|
||||
if ctx.resilient_parsing:
|
||||
return value
|
||||
if ctx.get_parameter_source(param.name) is not ParameterSource.DEFAULT:
|
||||
return value
|
||||
option_name = next((opt for opt in param.opts if opt.startswith("--")), "--port")
|
||||
return reconcile_default_port(int(value), option_name=option_name)
|
||||
|
||||
|
||||
def proxy_port_option(*param_decls: str, help_text: str | None = None) -> Callable[[Any], Any]:
|
||||
"""``--port`` option shared by ``wrap`` subcommands.
|
||||
|
||||
Defaults to ``HEADROOM_PORT`` (else 8787) and, when left at the default,
|
||||
detects a live Headroom proxy on another recorded port (see module docs).
|
||||
"""
|
||||
decls = param_decls or ("--port", "-p")
|
||||
option: Callable[[Any], Any] = click.option(
|
||||
*decls,
|
||||
default=DEFAULT_PROXY_PORT,
|
||||
envvar=PORT_ENV,
|
||||
show_envvar=False,
|
||||
type=click.IntRange(1, 65535),
|
||||
callback=port_option_callback,
|
||||
help=help_text
|
||||
or (
|
||||
f"Proxy port (default: ${PORT_ENV}, else {DEFAULT_PROXY_PORT}; a live "
|
||||
"Headroom proxy on another port is detected and offered)"
|
||||
),
|
||||
)
|
||||
return option
|
||||
|
||||
|
||||
_CODEX_HEADROOM_TABLE_RE = re.compile(
|
||||
r"(?ms)^[ \t]*\[model_providers\.headroom\][^\n]*\n(?P<body>.*?)(?=^[ \t]*\[|\Z)"
|
||||
)
|
||||
_CODEX_BASE_URL_LINE_RE = re.compile(r'(?m)^[ \t]*base_url[ \t]*=[ \t]*"(?P<url>[^"\n]*)"')
|
||||
|
||||
|
||||
def codex_headroom_provider_port(content: str) -> int | None:
|
||||
"""Port in an existing ``[model_providers.headroom]`` loopback ``base_url``."""
|
||||
table = _CODEX_HEADROOM_TABLE_RE.search(content or "")
|
||||
if table is None:
|
||||
return None
|
||||
base = _CODEX_BASE_URL_LINE_RE.search(table.group("body"))
|
||||
return loopback_port(base.group("url")) if base else None
|
||||
|
||||
|
||||
def warn_codex_provider_port_change(config_path: Path, new_port: int) -> int | None:
|
||||
"""Warn (stderr) before a Codex headroom provider is repointed to a new port.
|
||||
|
||||
Returns the previous port when it differs from ``new_port``; None otherwise.
|
||||
Never raises.
|
||||
"""
|
||||
try:
|
||||
if not config_path.exists():
|
||||
return None
|
||||
previous = codex_headroom_provider_port(
|
||||
config_path.read_text(encoding="utf-8", errors="replace")
|
||||
)
|
||||
except OSError:
|
||||
return None
|
||||
if previous is None or previous == new_port:
|
||||
return None
|
||||
click.echo(
|
||||
f"headroom: warning: {config_path} routes Codex's [model_providers.headroom] to "
|
||||
f"port {previous}; repointing it to port {new_port}. Pass --port {previous} to keep "
|
||||
"the existing route.",
|
||||
err=True,
|
||||
)
|
||||
return previous
|
||||
@@ -2,12 +2,12 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import click
|
||||
|
||||
from headroom.cli.main import main
|
||||
from headroom.install.paths import codex_home_dir
|
||||
from headroom.providers.codex.recovery import (
|
||||
audit_codex_history,
|
||||
discover_dangling_homes,
|
||||
@@ -38,7 +38,7 @@ def recover() -> None:
|
||||
@click.option("--yes", is_flag=True, help="Apply the recovery without prompting.")
|
||||
def recover_codex(sources: tuple[Path, ...], target: Path | None, yes: bool) -> None:
|
||||
"""Merge sessions and configuration from dangling Codex homes."""
|
||||
target = target or Path(os.environ.get("CODEX_HOME", Path.home() / ".codex"))
|
||||
target = target or codex_home_dir()
|
||||
selected_sources = list(sources) or [
|
||||
*discover_dangling_homes(),
|
||||
*discover_retained_sources(target),
|
||||
|
||||
+53
-61
@@ -61,6 +61,7 @@ from headroom._version import normalize_release_version as _normalize_release_ve
|
||||
from headroom.agent_savings import (
|
||||
apply_agent_savings_env_defaults,
|
||||
)
|
||||
from headroom.cli.port_discovery import proxy_port_option, warn_codex_provider_port_change
|
||||
from headroom.cli.proxy import ensure_proxy_dependencies
|
||||
from headroom.copilot_auth import (
|
||||
_API_TOKEN_ENV_VARS,
|
||||
@@ -1670,16 +1671,42 @@ def _selfheal_dead_wrap_base_url() -> None:
|
||||
"""
|
||||
try:
|
||||
settings_path = Path.cwd() / ".claude" / "settings.local.json"
|
||||
marker_before = _read_wrap_marker(settings_path)
|
||||
for key in (
|
||||
_claude_wrap_base_url_env_key(),
|
||||
_claude_wrap_base_url_env_key(foundry_mode=True),
|
||||
_claude_wrap_base_url_env_key(vertex_mode=True),
|
||||
):
|
||||
_check_and_clear_dead_wrap_marker(settings_path, key=key)
|
||||
# The prior value a clear restores may itself be None, so detect the
|
||||
# clear by the marker changing rather than by the return value.
|
||||
if marker_before is not None and _read_wrap_marker(settings_path) != marker_before:
|
||||
_warn_live_proxy_after_selfheal(marker_before)
|
||||
except Exception: # noqa: BLE001 - hook must never break session startup
|
||||
pass
|
||||
|
||||
|
||||
def _warn_live_proxy_after_selfheal(dead_marker: dict[str, Any] | None) -> None:
|
||||
"""After clearing a dead wrap route, point at a live proxy if one exists.
|
||||
|
||||
Deliberately warn-only: repointing settings at another session's proxy
|
||||
would silently adopt a proxy this project never chose (different backend,
|
||||
mode, or owner). The message names the exact command instead.
|
||||
"""
|
||||
from headroom.cli.port_discovery import find_live_proxy_elsewhere
|
||||
|
||||
dead_port = dead_marker.get("port") if isinstance(dead_marker, dict) else None
|
||||
requested = dead_port if isinstance(dead_port, int) else 8787
|
||||
live = find_live_proxy_elsewhere(requested)
|
||||
if live is None:
|
||||
return
|
||||
click.echo(
|
||||
f"headroom: a Headroom proxy is running on port {live}; route this project "
|
||||
f"through it with: headroom wrap claude --port {live}",
|
||||
err=True,
|
||||
)
|
||||
|
||||
|
||||
def _wrap_selfheal_hook_command() -> str:
|
||||
"""Command string for the SessionStart self-heal hook (mirrors init hooks)."""
|
||||
from headroom.cli.init import _command_string
|
||||
@@ -2636,10 +2663,9 @@ _CODEX_CONFIG_BACKUP_SUFFIX = ".headroom-backup"
|
||||
|
||||
def _codex_home_dir() -> Path:
|
||||
"""Return Codex's config directory, respecting ``CODEX_HOME`` when set."""
|
||||
codex_home = os.environ.get("CODEX_HOME")
|
||||
if codex_home:
|
||||
return Path(codex_home).expanduser()
|
||||
return Path.home() / ".codex"
|
||||
from headroom.install.paths import codex_home_dir
|
||||
|
||||
return codex_home_dir()
|
||||
|
||||
|
||||
def _codex_profile_from_args(codex_args: tuple[str, ...]) -> str | None:
|
||||
@@ -3147,6 +3173,9 @@ def _inject_codex_provider_config(port: int) -> str | None:
|
||||
"""
|
||||
config_file, backup_file = _codex_config_paths()
|
||||
config_dir = config_file.parent
|
||||
# Never repoint an existing headroom provider to another port silently: a
|
||||
# different live proxy (or a persistent install) may own the old route.
|
||||
warn_codex_provider_port_change(config_file, port)
|
||||
|
||||
# Detect an existing custom OpenAI-compatible provider BEFORE building the
|
||||
# injected block below, so it can be preserved as the upstream the proxy
|
||||
@@ -5266,13 +5295,8 @@ def wrap_selfheal(marker: str | None) -> None:
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@_retired_context_tool_option
|
||||
@_serena_instructions_option
|
||||
@click.option(
|
||||
# no "-p" short alias here: claude's own -p/--print must fall through to CLAUDE_ARGS
|
||||
"--port",
|
||||
default=8787,
|
||||
type=click.IntRange(1, 65535),
|
||||
help="Proxy port (default: 8787)",
|
||||
)
|
||||
# no "-p" short alias here: claude's own -p/--print must fall through to CLAUDE_ARGS
|
||||
@proxy_port_option("--port")
|
||||
@click.option(
|
||||
"--no-mcp",
|
||||
is_flag=True,
|
||||
@@ -5849,9 +5873,7 @@ def _require_copilot_subscription_resolution() -> CopilotSubscriptionTokenResolu
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@_retired_context_tool_option
|
||||
@click.option(
|
||||
"--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"
|
||||
)
|
||||
@proxy_port_option()
|
||||
@click.option("--no-proxy", is_flag=True, help="Skip proxy startup (use existing proxy)")
|
||||
@click.option(
|
||||
"--backend",
|
||||
@@ -6189,7 +6211,7 @@ def copilot(
|
||||
|
||||
|
||||
@wrap.command("vscode")
|
||||
@click.option("--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port")
|
||||
@proxy_port_option()
|
||||
@click.option("--memory", is_flag=True, help="Enable persistent cross-session memory")
|
||||
@click.option(
|
||||
"--settings-file",
|
||||
@@ -6272,7 +6294,7 @@ def unwrap_vscode_copilot(settings_file: Path | None) -> None:
|
||||
|
||||
|
||||
@wrap.command("vscode-claude")
|
||||
@click.option("--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port")
|
||||
@proxy_port_option()
|
||||
@click.option("--memory", is_flag=True, help="Enable persistent cross-session memory")
|
||||
@click.option(
|
||||
"--settings-file",
|
||||
@@ -6594,9 +6616,7 @@ def _run_codex_wrap(
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@_retired_context_tool_option
|
||||
@_serena_instructions_option
|
||||
@click.option(
|
||||
"--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"
|
||||
)
|
||||
@proxy_port_option()
|
||||
@click.option(
|
||||
"--no-mcp",
|
||||
is_flag=True,
|
||||
@@ -6706,9 +6726,7 @@ def codex(
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@_retired_context_tool_option
|
||||
@click.option(
|
||||
"--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"
|
||||
)
|
||||
@proxy_port_option()
|
||||
@click.option(
|
||||
"--code-graph",
|
||||
is_flag=True,
|
||||
@@ -6788,9 +6806,7 @@ def aider(
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@_retired_context_tool_option
|
||||
@click.option(
|
||||
"--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"
|
||||
)
|
||||
@proxy_port_option()
|
||||
@click.option(
|
||||
"--code-graph",
|
||||
is_flag=True,
|
||||
@@ -6859,9 +6875,7 @@ def vibe(
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@_retired_context_tool_option
|
||||
@click.option(
|
||||
"--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"
|
||||
)
|
||||
@proxy_port_option()
|
||||
@click.option(
|
||||
"--code-graph",
|
||||
is_flag=True,
|
||||
@@ -6953,9 +6967,7 @@ def kimi(
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@_retired_context_tool_option
|
||||
@_serena_instructions_option
|
||||
@click.option(
|
||||
"--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"
|
||||
)
|
||||
@proxy_port_option()
|
||||
@click.option("--no-mcp", is_flag=True, help="Skip headroom MCP server registration")
|
||||
@_code_memory_option
|
||||
@click.option(
|
||||
@@ -7084,9 +7096,7 @@ def grok(
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@_retired_context_tool_option
|
||||
@click.option(
|
||||
"--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"
|
||||
)
|
||||
@proxy_port_option()
|
||||
@click.option("--no-proxy", is_flag=True, help="Skip proxy startup (use existing proxy)")
|
||||
@click.option(
|
||||
"--learn", is_flag=True, help="Enable live traffic learning (patterns saved to .cursor/rules/)"
|
||||
@@ -7143,9 +7153,7 @@ def cursor(
|
||||
|
||||
@wrap.command("grok-build", context_settings={"ignore_unknown_options": True})
|
||||
@_retired_context_tool_option
|
||||
@click.option(
|
||||
"--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"
|
||||
)
|
||||
@proxy_port_option()
|
||||
@click.option("--no-proxy", is_flag=True, help="Skip proxy startup (use existing proxy)")
|
||||
@click.option("--learn", is_flag=True, help="Enable live traffic learning")
|
||||
@click.option("--memory", is_flag=True, help="Enable persistent cross-session memory")
|
||||
@@ -7213,9 +7221,7 @@ def grok_build(
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@_retired_context_tool_option
|
||||
@click.option(
|
||||
"--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"
|
||||
)
|
||||
@proxy_port_option()
|
||||
@click.option("--no-proxy", is_flag=True, help="Skip proxy startup (use existing proxy)")
|
||||
@click.option("--learn", is_flag=True, help="Enable live traffic learning")
|
||||
@click.option("--memory", is_flag=True, help="Enable persistent cross-session memory")
|
||||
@@ -7278,9 +7284,7 @@ def cline(
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@_retired_context_tool_option
|
||||
@click.option(
|
||||
"--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"
|
||||
)
|
||||
@proxy_port_option()
|
||||
@click.option("--no-proxy", is_flag=True, help="Skip proxy startup (use existing proxy)")
|
||||
@click.option("--learn", is_flag=True, help="Enable live traffic learning")
|
||||
@click.option("--memory", is_flag=True, help="Enable persistent cross-session memory")
|
||||
@@ -7344,9 +7348,7 @@ def zcode(
|
||||
|
||||
@wrap.command("continue", context_settings={"ignore_unknown_options": True})
|
||||
@_retired_context_tool_option
|
||||
@click.option(
|
||||
"--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"
|
||||
)
|
||||
@proxy_port_option()
|
||||
@click.option("--no-proxy", is_flag=True, help="Skip proxy startup (use existing proxy)")
|
||||
@click.option("--learn", is_flag=True, help="Enable live traffic learning")
|
||||
@click.option("--memory", is_flag=True, help="Enable persistent cross-session memory")
|
||||
@@ -7444,8 +7446,8 @@ def continue_dev(
|
||||
is_flag=True,
|
||||
help="Install by copying plugin path instead of using --link",
|
||||
)
|
||||
@click.option(
|
||||
"--proxy-port", default=8787, type=click.IntRange(1, 65535), help="Headroom proxy port"
|
||||
@proxy_port_option(
|
||||
"--proxy-port", help_text="Headroom proxy port (default: $HEADROOM_PORT, else 8787)"
|
||||
)
|
||||
@click.option("--startup-timeout-ms", default=20000, type=int, help="Proxy startup timeout")
|
||||
@click.option(
|
||||
@@ -7686,9 +7688,7 @@ def openclaw(
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@_retired_context_tool_option
|
||||
@_serena_instructions_option
|
||||
@click.option(
|
||||
"--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"
|
||||
)
|
||||
@proxy_port_option()
|
||||
@click.option("--no-mcp", is_flag=True, help="Skip headroom MCP server registration")
|
||||
@click.option("--no-serena", is_flag=True, help="Skip Serena MCP server registration")
|
||||
@click.option(
|
||||
@@ -8220,9 +8220,7 @@ def unwrap_codex(port: int, no_stop_proxy: bool) -> None:
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@_retired_context_tool_option
|
||||
@click.option(
|
||||
"--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"
|
||||
)
|
||||
@proxy_port_option()
|
||||
@click.option(
|
||||
"--code-graph",
|
||||
is_flag=True,
|
||||
@@ -8494,13 +8492,7 @@ def _make_registry_command(target: WrapTarget) -> click.Command:
|
||||
is_flag=True,
|
||||
help="Enable code graph indexing via codebase-memory-mcp (optional)",
|
||||
),
|
||||
click.option(
|
||||
"--port",
|
||||
"-p",
|
||||
default=8787,
|
||||
type=click.IntRange(1, 65535),
|
||||
help="Proxy port (default: 8787)",
|
||||
),
|
||||
proxy_port_option(),
|
||||
_retired_context_tool_option,
|
||||
):
|
||||
command = decorator(command)
|
||||
|
||||
@@ -109,10 +109,41 @@ def claude_settings_path() -> Path:
|
||||
return Path.home() / ".claude" / "settings.json"
|
||||
|
||||
|
||||
def codex_config_path() -> Path:
|
||||
"""Return the Codex config path."""
|
||||
def codex_home_dir() -> Path:
|
||||
"""Return Codex's user config directory, honoring ``CODEX_HOME``.
|
||||
|
||||
return Path.home() / ".codex" / "config.toml"
|
||||
Codex itself resolves its home from ``CODEX_HOME`` (falling back to
|
||||
``~/.codex``); every Headroom reader and writer of Codex state must agree
|
||||
with it, or ``doctor`` inspects one file while ``wrap``/``init`` write
|
||||
another.
|
||||
"""
|
||||
|
||||
configured = os.environ.get("CODEX_HOME", "").strip()
|
||||
if configured:
|
||||
return Path(configured).expanduser()
|
||||
return Path.home() / ".codex"
|
||||
|
||||
|
||||
def codex_config_path() -> Path:
|
||||
"""Return the user-level Codex config path (``$CODEX_HOME/config.toml``)."""
|
||||
|
||||
return codex_home_dir() / "config.toml"
|
||||
|
||||
|
||||
def codex_hooks_path() -> Path:
|
||||
"""Return the user-level Codex hooks file (``$CODEX_HOME/hooks.json``)."""
|
||||
|
||||
return codex_home_dir() / "hooks.json"
|
||||
|
||||
|
||||
def codex_project_config_path(cwd: Path | None = None) -> Path:
|
||||
"""Return the project-scoped Codex config (``<cwd>/.codex/config.toml``).
|
||||
|
||||
Codex layers a trusted project's ``.codex/config.toml`` over the user
|
||||
config, and ``headroom init codex`` (without ``-g``) writes there.
|
||||
"""
|
||||
|
||||
return (cwd or Path.cwd()) / ".codex" / "config.toml"
|
||||
|
||||
|
||||
def openclaw_config_path() -> Path:
|
||||
|
||||
@@ -12,7 +12,6 @@ anything else the user has configured.
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -53,10 +52,10 @@ class CodexRegistrar(MCPRegistrar):
|
||||
def __init__(self, *, home_dir: Path | None = None) -> None:
|
||||
if home_dir is not None:
|
||||
self._codex_dir = home_dir / ".codex"
|
||||
elif os.environ.get("CODEX_HOME"):
|
||||
self._codex_dir = Path(os.environ["CODEX_HOME"]).expanduser()
|
||||
else:
|
||||
self._codex_dir = Path.home() / ".codex"
|
||||
from headroom.install.paths import codex_home_dir
|
||||
|
||||
self._codex_dir = codex_home_dir()
|
||||
self._config_file = self._codex_dir / "config.toml"
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@@ -90,6 +90,17 @@ def _disable_telemetry_beacon(monkeypatch, _scrub_developer_headroom_env):
|
||||
monkeypatch.setenv("HEADROOM_BEACON", "off")
|
||||
|
||||
|
||||
# `wrap`/`init`/`doctor` probe loopback ports (and read deployment manifests)
|
||||
# to find a live Headroom proxy when --port is left at its default. A
|
||||
# developer's running proxy would make CLI tests non-deterministic, so
|
||||
# discovery is off unless a test turns it back on. A developer's CODEX_HOME
|
||||
# would likewise redirect every Codex path helper away from the test's tmp home.
|
||||
@pytest.fixture(autouse=True)
|
||||
def _disable_live_proxy_discovery(monkeypatch, _scrub_developer_headroom_env):
|
||||
monkeypatch.setenv("HEADROOM_PORT_DISCOVERY", "0")
|
||||
monkeypatch.delenv("CODEX_HOME", raising=False)
|
||||
|
||||
|
||||
# The MCP install ledger defaults to ``~/.headroom/mcp_installs.json``, so any
|
||||
# test that registers a server (directly or through `wrap`) writes into the
|
||||
# developer's REAL ledger — observed adding a live `claude/serena` entry during a
|
||||
|
||||
@@ -0,0 +1,591 @@
|
||||
"""CODEX_HOME resolution, live-proxy port discovery, and agent/proxy alignment.
|
||||
|
||||
Every test isolates HOME/CODEX_HOME/cwd under ``tmp_path`` and injects fake
|
||||
probes, so no real ``~/.codex``, ``~/.headroom`` or listening proxy is touched.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import click
|
||||
import pytest
|
||||
from click.testing import CliRunner
|
||||
|
||||
import headroom.cli.doctor as doctor_mod
|
||||
import headroom.cli.init as init_mod
|
||||
import headroom.cli.port_discovery as pd
|
||||
import headroom.cli.wrap as wrap_mod
|
||||
from headroom.cli.main import main
|
||||
from headroom.install import paths as install_paths
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
"""Fake home + cwd; discovery enabled; HEADROOM_WORKSPACE_DIR sandboxed."""
|
||||
fake_home = tmp_path / "home"
|
||||
project = tmp_path / "project"
|
||||
fake_home.mkdir()
|
||||
project.mkdir()
|
||||
monkeypatch.setattr(Path, "home", classmethod(lambda cls: fake_home))
|
||||
monkeypatch.setenv("HOME", str(fake_home))
|
||||
monkeypatch.setenv("USERPROFILE", str(fake_home))
|
||||
monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path / "workspace"))
|
||||
monkeypatch.delenv("CODEX_HOME", raising=False)
|
||||
monkeypatch.delenv("HEADROOM_PORT", raising=False)
|
||||
monkeypatch.delenv("HEADROOM_PORT_DISCOVERY", raising=False)
|
||||
monkeypatch.chdir(project)
|
||||
return fake_home
|
||||
|
||||
|
||||
def _manifest(profile: str, port: int, targets: list[str] | None = None) -> Any:
|
||||
return SimpleNamespace(profile=profile, port=port, targets=targets or [])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. CODEX_HOME
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestCodexHome:
|
||||
def test_defaults_to_dot_codex(self, home: Path) -> None:
|
||||
assert install_paths.codex_home_dir() == home / ".codex"
|
||||
assert install_paths.codex_config_path() == home / ".codex" / "config.toml"
|
||||
assert install_paths.codex_hooks_path() == home / ".codex" / "hooks.json"
|
||||
|
||||
def test_honors_codex_home(self, home: Path, tmp_path: Path, monkeypatch) -> None:
|
||||
custom = tmp_path / "custom-codex"
|
||||
monkeypatch.setenv("CODEX_HOME", str(custom))
|
||||
assert install_paths.codex_config_path() == custom / "config.toml"
|
||||
assert install_paths.codex_hooks_path() == custom / "hooks.json"
|
||||
# Every consumer resolves through the one helper.
|
||||
assert wrap_mod._codex_home_dir() == custom
|
||||
from headroom.mcp_registry.codex import CodexRegistrar
|
||||
|
||||
assert CodexRegistrar()._config_file == custom / "config.toml"
|
||||
|
||||
def test_blank_codex_home_falls_back(self, home: Path, monkeypatch) -> None:
|
||||
monkeypatch.setenv("CODEX_HOME", " ")
|
||||
assert install_paths.codex_home_dir() == home / ".codex"
|
||||
|
||||
def test_init_global_codex_paths_follow_codex_home(
|
||||
self, home: Path, tmp_path: Path, monkeypatch
|
||||
) -> None:
|
||||
custom = tmp_path / "custom-codex"
|
||||
monkeypatch.setenv("CODEX_HOME", str(custom))
|
||||
assert init_mod._codex_scope_path(True) == custom / "config.toml"
|
||||
assert init_mod._codex_hooks_path(True) == custom / "hooks.json"
|
||||
# Project scope stays in the project.
|
||||
assert init_mod._codex_scope_path(False) == Path.cwd() / ".codex" / "config.toml"
|
||||
assert init_mod._codex_hooks_path(False) == Path.cwd() / ".codex" / "hooks.json"
|
||||
|
||||
def test_doctor_reads_codex_home_config(self, home: Path, tmp_path: Path, monkeypatch) -> None:
|
||||
custom = tmp_path / "custom-codex"
|
||||
custom.mkdir()
|
||||
(custom / "config.toml").write_text(
|
||||
'model_provider = "headroom"\n[model_providers.headroom]\n'
|
||||
'base_url = "http://127.0.0.1:8787/v1"\nrequires_openai_auth = true\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.setenv("CODEX_HOME", str(custom))
|
||||
monkeypatch.setattr(doctor_mod, "probe_json", lambda *a, **k: None)
|
||||
monkeypatch.setattr(doctor_mod, "list_manifests", lambda: [])
|
||||
monkeypatch.setattr(doctor_mod, "claude_settings_path", lambda: home / "settings.json")
|
||||
monkeypatch.setattr(doctor_mod, "savings_path", lambda: home / "savings.json")
|
||||
result = CliRunner().invoke(main, ["doctor", "--json"])
|
||||
codex = next(c for c in json.loads(result.output)["checks"] if c["name"] == "codex")
|
||||
assert codex["status"] == "pass", codex
|
||||
assert str(custom / "config.toml") in codex["summary"]
|
||||
|
||||
def test_doctor_prefers_project_codex_config(self, tmp_path: Path) -> None:
|
||||
user = tmp_path / "user.toml"
|
||||
user.write_text(
|
||||
'[model_providers.headroom]\nbase_url = "http://127.0.0.1:9999/v1"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
project = tmp_path / "project.toml"
|
||||
project.write_text(
|
||||
'[model_providers.headroom]\nbase_url = "http://127.0.0.1:8787/v1"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
result = doctor_mod.check_codex_routing(user, 8787, [project])
|
||||
assert result.status == doctor_mod.PASS
|
||||
assert str(project) in result.summary
|
||||
|
||||
def test_doctor_missing_config_names_actual_path(self, tmp_path: Path) -> None:
|
||||
result = doctor_mod.check_codex_routing(tmp_path / "nope.toml", 8787, [])
|
||||
assert result.status == doctor_mod.WARN
|
||||
assert str(tmp_path / "nope.toml") in result.summary
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. Default port: HEADROOM_PORT + live-proxy discovery
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestPortDiscovery:
|
||||
def test_default_port_reads_env(self) -> None:
|
||||
assert pd.default_port({}) == 8787
|
||||
assert pd.default_port({"HEADROOM_PORT": "9100"}) == 9100
|
||||
assert pd.default_port({"HEADROOM_PORT": "not-a-port"}) == 8787
|
||||
assert pd.default_port({"HEADROOM_PORT": "70000"}) == 8787
|
||||
|
||||
def test_candidates_include_env_manifests_and_wrap_marker(self, tmp_path: Path) -> None:
|
||||
(tmp_path / ".claude").mkdir()
|
||||
(tmp_path / ".claude" / ".headroom_wrap_marker.json").write_text(
|
||||
json.dumps({"port": 9300}), encoding="utf-8"
|
||||
)
|
||||
ports = pd.candidate_ports(
|
||||
8787,
|
||||
environ={"HEADROOM_PORT": "9100"},
|
||||
manifests=[_manifest("a", 9200), _manifest("b", 8787)],
|
||||
cwd=tmp_path,
|
||||
)
|
||||
assert ports == [8787, 9100, 9200, 9300]
|
||||
|
||||
def test_candidates_are_bounded(self, tmp_path: Path) -> None:
|
||||
manifests = [_manifest(str(i), 10000 + i) for i in range(50)]
|
||||
ports = pd.candidate_ports(8787, environ={}, manifests=manifests, cwd=tmp_path)
|
||||
assert len(ports) == pd._MAX_CANDIDATES
|
||||
|
||||
def test_finds_live_proxy_on_other_port(self, tmp_path: Path) -> None:
|
||||
live = pd.find_live_proxy_elsewhere(
|
||||
8787,
|
||||
environ={},
|
||||
manifests=[_manifest("p", 9200)],
|
||||
cwd=tmp_path,
|
||||
probe=lambda port: port == 9200,
|
||||
)
|
||||
assert live == 9200
|
||||
|
||||
def test_requested_port_live_means_nothing_to_reconcile(self, tmp_path: Path) -> None:
|
||||
live = pd.find_live_proxy_elsewhere(
|
||||
8787,
|
||||
environ={},
|
||||
manifests=[_manifest("p", 9200)],
|
||||
cwd=tmp_path,
|
||||
probe=lambda port: True,
|
||||
)
|
||||
assert live is None
|
||||
|
||||
def test_discovery_can_be_disabled(self, tmp_path: Path) -> None:
|
||||
live = pd.find_live_proxy_elsewhere(
|
||||
8787,
|
||||
environ={"HEADROOM_PORT_DISCOVERY": "0"},
|
||||
manifests=[_manifest("p", 9200)],
|
||||
cwd=tmp_path,
|
||||
probe=lambda port: port == 9200,
|
||||
)
|
||||
assert live is None
|
||||
|
||||
def test_probe_errors_never_raise(self, tmp_path: Path) -> None:
|
||||
def boom(port: int) -> bool:
|
||||
raise RuntimeError("nope")
|
||||
|
||||
assert (
|
||||
pd.find_live_proxy_elsewhere(
|
||||
8787, environ={}, manifests=[_manifest("p", 9200)], cwd=tmp_path, probe=boom
|
||||
)
|
||||
is None
|
||||
)
|
||||
|
||||
def test_livez_identity_required(self) -> None:
|
||||
assert pd.is_headroom_livez({"service": "headroom-proxy", "alive": True})
|
||||
assert pd.is_headroom_livez({"alive": True, "version": "1.0"}) # legacy shape
|
||||
assert not pd.is_headroom_livez({"service": "something-else", "alive": True})
|
||||
assert not pd.is_headroom_livez({"status": "ok"})
|
||||
assert not pd.is_headroom_livez(None)
|
||||
|
||||
def test_non_interactive_keeps_requested_and_warns(self, tmp_path: Path, capsys) -> None:
|
||||
port = pd.reconcile_default_port(
|
||||
8787,
|
||||
interactive=False,
|
||||
environ={},
|
||||
manifests=[_manifest("p", 9200)],
|
||||
cwd=tmp_path,
|
||||
probe=lambda p: p == 9200,
|
||||
)
|
||||
assert port == 8787
|
||||
err = capsys.readouterr().err
|
||||
assert "port 9200" in err
|
||||
assert "--port 9200" in err
|
||||
|
||||
@pytest.mark.parametrize(("answer", "expected"), [("c", 9200), ("k", 8787)])
|
||||
def test_interactive_prompt_connect_or_keep(
|
||||
self, tmp_path: Path, monkeypatch, answer: str, expected: int
|
||||
) -> None:
|
||||
monkeypatch.setattr(pd.click, "prompt", lambda *a, **k: answer)
|
||||
port = pd.reconcile_default_port(
|
||||
8787,
|
||||
interactive=True,
|
||||
environ={},
|
||||
manifests=[_manifest("p", 9200)],
|
||||
cwd=tmp_path,
|
||||
probe=lambda p: p == 9200,
|
||||
)
|
||||
assert port == expected
|
||||
|
||||
def test_interactive_prompt_abort(self, tmp_path: Path, monkeypatch) -> None:
|
||||
monkeypatch.setattr(pd.click, "prompt", lambda *a, **k: "a")
|
||||
with pytest.raises(click.Abort):
|
||||
pd.reconcile_default_port(
|
||||
8787,
|
||||
interactive=True,
|
||||
environ={},
|
||||
manifests=[_manifest("p", 9200)],
|
||||
cwd=tmp_path,
|
||||
probe=lambda p: p == 9200,
|
||||
)
|
||||
|
||||
def test_no_live_proxy_is_silent(self, tmp_path: Path, capsys) -> None:
|
||||
port = pd.reconcile_default_port(
|
||||
8787, interactive=False, environ={}, manifests=[], cwd=tmp_path, probe=lambda p: False
|
||||
)
|
||||
assert port == 8787
|
||||
assert capsys.readouterr().err == ""
|
||||
|
||||
|
||||
class TestProxyPortOption:
|
||||
@pytest.fixture
|
||||
def cmd(self) -> click.Command:
|
||||
@click.command()
|
||||
@pd.proxy_port_option()
|
||||
def _cmd(port: int) -> None:
|
||||
click.echo(f"port={port}")
|
||||
|
||||
return _cmd
|
||||
|
||||
@pytest.fixture
|
||||
def reconcile_calls(self, monkeypatch) -> list[int]:
|
||||
calls: list[int] = []
|
||||
|
||||
def fake(requested: int, **kwargs: Any) -> int:
|
||||
calls.append(requested)
|
||||
return 9200
|
||||
|
||||
monkeypatch.setattr(pd, "reconcile_default_port", fake)
|
||||
return calls
|
||||
|
||||
def test_default_triggers_reconcile(self, cmd, reconcile_calls) -> None:
|
||||
result = CliRunner().invoke(cmd, [])
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "port=9200" in result.output
|
||||
assert reconcile_calls == [8787]
|
||||
|
||||
def test_explicit_port_is_honored_without_discovery(self, cmd, reconcile_calls) -> None:
|
||||
result = CliRunner().invoke(cmd, ["--port", "9500"])
|
||||
assert "port=9500" in result.output
|
||||
assert reconcile_calls == []
|
||||
|
||||
def test_headroom_port_env_is_honored_without_discovery(self, cmd, reconcile_calls) -> None:
|
||||
result = CliRunner().invoke(cmd, [], env={"HEADROOM_PORT": "9400"})
|
||||
assert "port=9400" in result.output
|
||||
assert reconcile_calls == []
|
||||
|
||||
def test_wrap_subcommands_use_shared_option(self) -> None:
|
||||
# Every wrap subcommand with a port option resolves it through the callback.
|
||||
wrap_group = main.commands["wrap"]
|
||||
assert isinstance(wrap_group, click.Group)
|
||||
checked = 0
|
||||
for name, command in wrap_group.commands.items():
|
||||
for param in command.params:
|
||||
if param.name in {"port", "proxy_port"}:
|
||||
assert param.callback is pd.port_option_callback, name
|
||||
assert param.envvar == "HEADROOM_PORT", name
|
||||
checked += 1
|
||||
assert checked >= 15
|
||||
|
||||
|
||||
class TestCodexProviderPortWarning:
|
||||
def test_warns_when_repointing(self, tmp_path: Path, capsys) -> None:
|
||||
config = tmp_path / "config.toml"
|
||||
config.write_text(
|
||||
'[model_providers.headroom]\nname = "x"\nbase_url = "http://127.0.0.1:9200/v1"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
assert pd.warn_codex_provider_port_change(config, 8787) == 9200
|
||||
err = capsys.readouterr().err
|
||||
assert "9200" in err and "8787" in err and "--port 9200" in err
|
||||
|
||||
def test_silent_when_same_port_or_absent(self, tmp_path: Path, capsys) -> None:
|
||||
config = tmp_path / "config.toml"
|
||||
assert pd.warn_codex_provider_port_change(config, 8787) is None
|
||||
config.write_text(
|
||||
'[model_providers.headroom]\nbase_url = "http://127.0.0.1:8787/v1"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
assert pd.warn_codex_provider_port_change(config, 8787) is None
|
||||
assert capsys.readouterr().err == ""
|
||||
|
||||
def test_init_provider_write_warns(self, tmp_path: Path, capsys, monkeypatch) -> None:
|
||||
monkeypatch.setattr(init_mod, "retag_to_headroom", lambda _path: None)
|
||||
config = tmp_path / "config.toml"
|
||||
config.write_text(
|
||||
'[model_providers.headroom]\nbase_url = "http://127.0.0.1:9200/v1"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
init_mod._ensure_codex_provider(config, 8787)
|
||||
assert "port 9200" in capsys.readouterr().err
|
||||
assert 'base_url = "http://127.0.0.1:8787/v1"' in config.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
class TestInitPortResolution:
|
||||
def _ctx(self, args: list[str]) -> click.Context:
|
||||
group = main.commands["init"]
|
||||
return group.make_context("init", list(args), resilient_parsing=False)
|
||||
|
||||
def test_explicit_port_wins(self, monkeypatch) -> None:
|
||||
monkeypatch.setattr(init_mod, "reconcile_default_port", lambda p, **k: 1)
|
||||
ctx = self._ctx(["--port", "9500"])
|
||||
assert init_mod._resolve_init_port(ctx, 9500) == 9500
|
||||
|
||||
def test_env_port_used_when_no_flag(self, monkeypatch) -> None:
|
||||
monkeypatch.setattr(init_mod, "reconcile_default_port", lambda p, **k: 1)
|
||||
monkeypatch.setenv("HEADROOM_PORT", "9400")
|
||||
ctx = self._ctx([])
|
||||
assert init_mod._resolve_init_port(ctx, 8787) == 9400
|
||||
|
||||
def test_default_reconciles_with_live_proxy(self, monkeypatch) -> None:
|
||||
monkeypatch.setattr(init_mod, "reconcile_default_port", lambda p, **k: 9200)
|
||||
ctx = self._ctx([])
|
||||
assert init_mod._resolve_init_port(ctx, 8787) == 9200
|
||||
|
||||
def test_hook_subcommand_skips_discovery(self, monkeypatch) -> None:
|
||||
def fail(*a: Any, **k: Any) -> int:
|
||||
raise AssertionError("hook must not run discovery")
|
||||
|
||||
monkeypatch.setattr(init_mod, "reconcile_default_port", fail)
|
||||
ctx = self._ctx([])
|
||||
ctx.invoked_subcommand = "hook"
|
||||
assert init_mod._resolve_init_port(ctx, 8787) == 8787
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. init hook ensure alignment warning
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestHookAlignment:
|
||||
@pytest.fixture
|
||||
def claude_settings(self, home: Path, monkeypatch) -> Path:
|
||||
path = home / ".claude" / "settings.json"
|
||||
path.parent.mkdir(parents=True)
|
||||
monkeypatch.setattr(init_mod, "claude_settings_path", lambda: path)
|
||||
monkeypatch.setattr(init_mod, "load_manifest", lambda profile: _manifest(profile, 8787))
|
||||
monkeypatch.setattr(init_mod, "_ensure_profile_running", lambda profile: None)
|
||||
return path
|
||||
|
||||
def _route_claude(self, path: Path, port: int) -> None:
|
||||
path.write_text(
|
||||
json.dumps({"env": {"ANTHROPIC_BASE_URL": f"http://127.0.0.1:{port}"}}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
def test_aligned_returns_none(self, claude_settings: Path) -> None:
|
||||
self._route_claude(claude_settings, 8787)
|
||||
assert init_mod.alignment_warning("claude", "init-user", probe=lambda p: True) is None
|
||||
|
||||
def test_mismatch_to_dead_port_suggests_managed_port(self, claude_settings: Path) -> None:
|
||||
self._route_claude(claude_settings, 9200)
|
||||
message = init_mod.alignment_warning("claude", "init-user", probe=lambda p: False)
|
||||
assert message is not None
|
||||
assert "9200" in message and "8787" in message
|
||||
assert "headroom init -g --port 8787 claude" in message
|
||||
|
||||
def test_mismatch_to_live_port_suggests_live_port(self, claude_settings: Path) -> None:
|
||||
self._route_claude(claude_settings, 9200)
|
||||
message = init_mod.alignment_warning("claude", "init-user", probe=lambda p: p == 9200)
|
||||
assert message is not None
|
||||
assert "headroom init -g --port 9200 claude" in message
|
||||
|
||||
def test_codex_mismatch_uses_codex_home(self, home: Path, tmp_path: Path, monkeypatch) -> None:
|
||||
custom = tmp_path / "custom-codex"
|
||||
custom.mkdir()
|
||||
(custom / "config.toml").write_text(
|
||||
'model_provider = "headroom"\n[model_providers.headroom]\n'
|
||||
'base_url = "http://127.0.0.1:9200/v1"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.setenv("CODEX_HOME", str(custom))
|
||||
monkeypatch.setattr(init_mod, "load_manifest", lambda profile: _manifest(profile, 8787))
|
||||
message = init_mod.alignment_warning("codex", "init-user", probe=lambda p: False)
|
||||
assert message is not None and "--port 8787 codex" in message
|
||||
|
||||
def test_session_start_emits_hook_json(self, claude_settings: Path) -> None:
|
||||
self._route_claude(claude_settings, 9200)
|
||||
result = CliRunner().invoke(
|
||||
main,
|
||||
[
|
||||
"init",
|
||||
"hook",
|
||||
"ensure",
|
||||
"--profile",
|
||||
"init-user",
|
||||
"--marker",
|
||||
"headroom-init-claude",
|
||||
],
|
||||
input=json.dumps({"hook_event_name": "SessionStart"}),
|
||||
)
|
||||
assert result.exit_code == 0, result.output
|
||||
payload = json.loads(result.output.strip().splitlines()[-1])
|
||||
assert "9200" in payload["systemMessage"]
|
||||
assert payload["hookSpecificOutput"]["hookEventName"] == "SessionStart"
|
||||
assert payload["hookSpecificOutput"]["additionalContext"] == payload["systemMessage"]
|
||||
|
||||
def test_pre_tool_use_stays_silent(self, claude_settings: Path) -> None:
|
||||
self._route_claude(claude_settings, 9200)
|
||||
result = CliRunner().invoke(
|
||||
main,
|
||||
[
|
||||
"init",
|
||||
"hook",
|
||||
"ensure",
|
||||
"--profile",
|
||||
"init-user",
|
||||
"--marker",
|
||||
"headroom-init-claude",
|
||||
],
|
||||
input=json.dumps({"hook_event_name": "PreToolUse"}),
|
||||
)
|
||||
assert result.exit_code == 0
|
||||
assert result.output.strip() == ""
|
||||
|
||||
def test_never_raises(self, claude_settings: Path, monkeypatch) -> None:
|
||||
def boom(*a: Any, **k: Any) -> str:
|
||||
raise RuntimeError("broken")
|
||||
|
||||
monkeypatch.setattr(init_mod, "alignment_warning", boom)
|
||||
result = CliRunner().invoke(
|
||||
main,
|
||||
["init", "hook", "ensure", "--profile", "init-user", "--marker", "headroom-init-codex"],
|
||||
input=json.dumps({"hook_event_name": "SessionStart"}),
|
||||
)
|
||||
assert result.exit_code == 0
|
||||
assert result.output.strip() == ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. Doctor: readiness, hooks, live proxy elsewhere
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestDoctorAdditions:
|
||||
def test_readiness(self) -> None:
|
||||
live = {"service": "headroom-proxy"}
|
||||
base = "http://127.0.0.1:8787"
|
||||
assert doctor_mod.check_proxy_readiness(None, None, base).status == doctor_mod.SKIP
|
||||
assert doctor_mod.check_proxy_readiness(live, None, base).status == doctor_mod.WARN
|
||||
assert (
|
||||
doctor_mod.check_proxy_readiness(live, {"ready": True}, base).status == doctor_mod.PASS
|
||||
)
|
||||
|
||||
def _hooks_file(self, path: Path, command: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"matcher": "startup",
|
||||
"hooks": [{"type": "command", "command": command}],
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
def test_hooks_present(self, tmp_path: Path) -> None:
|
||||
exe = tmp_path / "headroom-bin"
|
||||
exe.write_text("", encoding="utf-8")
|
||||
hooks = tmp_path / "hooks.json"
|
||||
self._hooks_file(hooks, f"{exe.as_posix()} init hook ensure --marker headroom-init-codex")
|
||||
result = doctor_mod.check_installed_hooks(
|
||||
[("codex", "user", hooks, "headroom init -g codex")]
|
||||
)
|
||||
assert result.status == doctor_mod.PASS, result
|
||||
|
||||
def test_hooks_missing(self, tmp_path: Path) -> None:
|
||||
result = doctor_mod.check_installed_hooks(
|
||||
[("claude", "user", tmp_path / "settings.json", "headroom init -g claude")]
|
||||
)
|
||||
assert result.status == doctor_mod.WARN
|
||||
assert "headroom init -g claude" in (result.hint or "")
|
||||
|
||||
def test_hook_program_missing(self, tmp_path: Path) -> None:
|
||||
hooks = tmp_path / "settings.json"
|
||||
gone = (tmp_path / "gone" / "headroom").as_posix()
|
||||
self._hooks_file(hooks, f"{gone} init hook ensure --marker headroom-init-claude")
|
||||
result = doctor_mod.check_installed_hooks(
|
||||
[("claude", "user", hooks, "headroom init -g claude")]
|
||||
)
|
||||
assert result.status == doctor_mod.WARN
|
||||
assert "not found" in result.summary
|
||||
|
||||
def test_no_init_means_skip(self) -> None:
|
||||
assert doctor_mod.check_installed_hooks([]).status == doctor_mod.SKIP
|
||||
|
||||
def test_expected_hooks_from_manifests(self, home: Path, tmp_path: Path, monkeypatch) -> None:
|
||||
custom = tmp_path / "custom-codex"
|
||||
monkeypatch.setenv("CODEX_HOME", str(custom))
|
||||
monkeypatch.setattr(doctor_mod, "claude_settings_path", lambda: home / "settings.json")
|
||||
local = init_mod._local_profile(Path.cwd())
|
||||
expected = doctor_mod.expected_init_hooks(
|
||||
[
|
||||
_manifest("init-user", 9200, ["claude", "codex"]),
|
||||
_manifest(local, 8787, ["claude"]),
|
||||
_manifest("someone-else", 8787, ["claude"]),
|
||||
],
|
||||
cwd=Path.cwd(),
|
||||
)
|
||||
assert ("codex", "user", custom / "hooks.json", "headroom init -g --port 9200 codex") in (
|
||||
expected
|
||||
)
|
||||
assert (
|
||||
"claude",
|
||||
"project",
|
||||
Path.cwd() / ".claude" / "settings.local.json",
|
||||
"headroom init claude",
|
||||
) in expected
|
||||
assert len(expected) == 3
|
||||
|
||||
def test_doctor_names_live_proxy_on_other_port(self, home: Path, monkeypatch) -> None:
|
||||
def fake_probe(url: str, timeout: float = 2.0) -> dict[str, Any] | None:
|
||||
if url == "http://127.0.0.1:9200/livez":
|
||||
return {"service": "headroom-proxy", "alive": True, "version": "1"}
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(doctor_mod, "probe_json", fake_probe)
|
||||
monkeypatch.setattr(doctor_mod, "list_manifests", lambda: [_manifest("prod", 9200)])
|
||||
monkeypatch.setattr(doctor_mod, "check_deployments", lambda manifests: None)
|
||||
monkeypatch.setattr(doctor_mod, "claude_settings_path", lambda: home / "settings.json")
|
||||
monkeypatch.setattr(doctor_mod, "savings_path", lambda: home / "savings.json")
|
||||
result = CliRunner().invoke(main, ["doctor", "--json"])
|
||||
payload = json.loads(result.output)
|
||||
assert payload["exit_code"] == 2 # still a failure at the probed port
|
||||
proxy = next(c for c in payload["checks"] if c["name"] == "proxy")
|
||||
assert "port 9200" in proxy["summary"]
|
||||
assert "headroom doctor --port 9200" in proxy["hint"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# wrap selfheal: warn (never repoint) when a live proxy exists elsewhere
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestSelfhealWarning:
|
||||
def test_warns_with_live_port(self, monkeypatch, capsys) -> None:
|
||||
monkeypatch.setattr(pd, "find_live_proxy_elsewhere", lambda requested, **k: 9200)
|
||||
wrap_mod._warn_live_proxy_after_selfheal({"port": 8787})
|
||||
err = capsys.readouterr().err
|
||||
assert "headroom wrap claude --port 9200" in err
|
||||
|
||||
def test_silent_without_live_proxy(self, monkeypatch, capsys) -> None:
|
||||
monkeypatch.setattr(pd, "find_live_proxy_elsewhere", lambda requested, **k: None)
|
||||
wrap_mod._warn_live_proxy_after_selfheal({"port": 8787})
|
||||
assert capsys.readouterr().err == ""
|
||||
@@ -796,6 +796,9 @@ class TestDoctorCommand:
|
||||
"""Point all filesystem/network surfaces at controlled fakes."""
|
||||
monkeypatch.setattr(doctor_mod, "claude_settings_path", lambda: tmp_path / "settings.json")
|
||||
monkeypatch.setattr(doctor_mod, "codex_config_path", lambda: tmp_path / "config.toml")
|
||||
monkeypatch.setattr(
|
||||
doctor_mod, "codex_project_config_path", lambda: tmp_path / "project-codex.toml"
|
||||
)
|
||||
monkeypatch.setattr(doctor_mod, "savings_path", lambda: tmp_path / "savings.json")
|
||||
monkeypatch.setattr(doctor_mod, "list_manifests", lambda: [])
|
||||
for var in (
|
||||
|
||||
Reference in New Issue
Block a user