mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
refactor(cli): remove test-only and dead helpers from wrap, proxy and mcp (#4118)
## Description Removes private CLI helpers that no product code calls any more. Each one lost its last caller in an earlier rewrite, so only its own unit tests still called it. The tests that pinned the dead code go with it. Refs #4136 ## 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 - [x] Code refactoring (no functional changes) ## Changes Made - `headroom/cli/wrap.py`: removed six dead helpers and constants. - `_wrap_marker_proxy_is_dead`: the self-heal path now calls `_wrap_proxy_alive` inline. - `_agent_savings_config_mismatches` and `_AGENT_SAVINGS_TARGET_AGENTS`: the live restart check only compares `savings_profile`. - The `_normalize_openclaw_gateway_provider_ids` forwarder and its import alias. - A dead copy of `_opencode_home_dir`; the real one lives in `providers/opencode/config.py`. - The unused `_CONTEXT_1M_SUFFIX` and `_OPENCLAUDE_INSTRUCTIONS_FILE` constants. - `headroom/cli/proxy.py`: removed `_get_env_float_optional`, which had no callers. - `headroom/cli/mcp.py`: removed `get_headroom_command`, `load_mcp_config`, `save_mcp_config`, `find_headroom_registration` and the `CLAUDE_CONFIG_DIR` / `MCP_CONFIG_PATH` / `CLAUDE_JSON_PATH` constants. - `mcp install`, `mcp status` and `mcp uninstall` all go through `headroom.mcp_registry` registrars now. - `load_mcp_config` returned `{}` on corrupt JSON, and `save_mcp_config` would then overwrite the file. That data-loss path goes away with them. - Tests removed, because they only exercised the deleted code: - `tests/test_cli/test_mcp_status.py`, all of which tested `find_headroom_registration`; - `TestMCPConfigFunctions` and its path fixtures in `tests/test_cli/test_mcp.py`; - 3 `_wrap_marker_proxy_is_dead` tests; - 5 `_agent_savings_config_mismatches` tests; - 1 forwarder test. - The remaining `mcp uninstall` / `mcp status` tests already patch the registrars. They no longer take the path fixture. Evidence: `rg -n -w '<name>' headroom crates plugins sdk examples benchmarks scripts e2e docs wiki .github pyproject.toml tests <consumer repos>` for each name finds only the definition and the removed tests. Live behaviour stays covered: - `test_wrap_dead_marker_selfheal.py`: `test_dead_port_*`, `test_live_port_is_never_cleared` and the `_wrap_proxy_alive` tests; - `tests/test_provider_openclaw_wrap.py`; - `test_mcp.py::TestMCPStatusCommand` / `TestMCPUninstallCommand`. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text $ pytest -q -p no:cacheprovider tests/test_cli/test_wrap_dead_marker_selfheal.py tests/test_agent_savings.py tests/test_cli/test_wrap_openclaw.py tests/test_cli/test_wrap_opencode.py tests/test_cli/test_mcp.py tests/test_cli/test_wrap_helpers.py tests/test_provider_openclaw_wrap.py tests/test_cli/test_main_help_version.py 253 passed in 33.08s $ uvx ruff@0.16.8 check headroom/cli tests/test_cli tests/test_agent_savings.py All checks passed! $ mypy headroom/cli/wrap.py headroom/cli/mcp.py headroom/cli/proxy.py --ignore-missing-imports Success: no issues found in 3 source files ``` ## Real Behavior Proof - Environment: macOS, Python 3.12, repo `.venv`, branch cut from `origin/main` ata9815bbb. - Exact command / steps: ran the pytest files above, which cover `wrap`, `unwrap`, `mcp status` and `mcp uninstall` via CliRunner, plus `headroom --help` / `--version`. - Observed result: all 253 passed; ruff and mypy are clean. - Smoke harness (real proxy started from this checkout against a local fake upstream; temp HOME and workspace, offline): ```text branch: cleanup/cli-integrations-dead-cli-helpers @5f450556health: 200 POST /v1/messages -> HTTP200 smoke-ok POST /v1/chat/completions -> HTTP200 smoke-ok stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82 proxy.log WARNING/ERROR lines (<tmp>/ws/logs/proxy-63492.log): 2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you configured, operator-configured local endpoints, loopback health probes. 4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base 4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection. (smoke dir: <tmp>) ``` - Direct runtime command on this PR's own path (temp HOME, HEADROOM_WORKSPACE_DIR and CODEX_HOME): ```text $ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom mcp install --agent claude exit=0 --- stdout Installing Headroom MCP server... claude: registered (restart the agent if it was already running) Next steps: 1. Start the Headroom proxy (if not running): headroom proxy 2. Start your agent (e.g.) ANTHROPIC_BASE_URL=http://127.0.0.1:8787 claude 3. Restart any agent that was already running so it picks up the new MCP server. --- stderr $ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom mcp status exit=0 --- stdout Headroom MCP Status ======================================== MCP SDK: ✓ Installed Agent Config: Antigravity IDE: ✗ Not detected Claude Code: ✓ Configured $ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom mcp uninstall exit=0 --- stdout ✓ Claude Code: removed headroom MCP server(s) --- stderr ``` - Not tested: a live `headroom wrap` session against a real agent binary. Only unreferenced private code was deleted, so no runtime path changes. ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: N/A, no rollout-managed behaviour. - Stable/default behavior changed: No. Only code with no callers is removed. - Kill switch / disable path: N/A. - 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 - [ ] 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 - [ ] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [x] I did **not** edit `CHANGELOG.md` — it is generated by release-please from my Conventional Commit PR title (a CI guard enforces this) ## Screenshots (if applicable) N/A ## Additional Notes - Part of maintainer-requested cleanup #4136 (dead code, duplication, debuggability), split into small PRs for review. - No new tests or docs are needed, because this is a pure removal and none of the removed names were documented. - `_DEFAULT_1M_MODEL` stays, because `tests/test_cli/test_wrap_helpers.py` pins it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4118" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a> <!-- devin-review-badge-end --> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
31d378b0e5
commit
73f59a32cc
@@ -5,78 +5,16 @@ Claude Code subscription users to use CCR (Compress-Cache-Retrieve) without
|
||||
needing API key access.
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import click
|
||||
|
||||
from .main import main
|
||||
|
||||
# Default paths
|
||||
CLAUDE_CONFIG_DIR = Path.home() / ".claude"
|
||||
MCP_CONFIG_PATH = CLAUDE_CONFIG_DIR / "mcp.json"
|
||||
# Servers registered via `claude mcp add` (user scope) live in ~/.claude.json,
|
||||
# NOT in ~/.claude/mcp.json. Status must check both to avoid a false negative.
|
||||
CLAUDE_JSON_PATH = Path.home() / ".claude.json"
|
||||
DEFAULT_PROXY_URL = "http://127.0.0.1:8787"
|
||||
DEFAULT_HTTP_HOST = "127.0.0.1"
|
||||
DEFAULT_HTTP_PORT = 8788
|
||||
DEFAULT_HTTP_PATH = "/mcp"
|
||||
|
||||
|
||||
def get_headroom_command() -> list[str]:
|
||||
"""Get the command to run headroom MCP server.
|
||||
|
||||
Returns the CLI invocation used by Claude Code config.
|
||||
"""
|
||||
return ["headroom", "mcp", "serve"]
|
||||
|
||||
|
||||
def load_mcp_config() -> dict[str, Any]:
|
||||
"""Load existing MCP config or return empty structure."""
|
||||
if MCP_CONFIG_PATH.exists():
|
||||
try:
|
||||
with open(MCP_CONFIG_PATH, encoding="utf-8") as f:
|
||||
result: dict[str, Any] = json.load(f)
|
||||
return result
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return {"mcpServers": {}}
|
||||
return {"mcpServers": {}}
|
||||
|
||||
|
||||
def save_mcp_config(config: dict) -> None:
|
||||
"""Save MCP config, creating directory if needed."""
|
||||
CLAUDE_CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
with open(MCP_CONFIG_PATH, "w", encoding="utf-8") as f:
|
||||
json.dump(config, f, indent=2)
|
||||
f.write("\n") # Trailing newline
|
||||
|
||||
|
||||
def find_headroom_registration() -> tuple[Path, dict[str, Any]] | None:
|
||||
"""Locate an existing 'headroom' MCP server registration.
|
||||
|
||||
Claude Code stores servers registered with `claude mcp add` (user scope) in
|
||||
~/.claude.json under "mcpServers". Headroom's own `mcp install` fallback
|
||||
writes ~/.claude/mcp.json, and a project may define ./.mcp.json. Check all of
|
||||
them so `status` reflects reality instead of only looking at mcp.json.
|
||||
|
||||
Returns (config_path, server_config) for the first match, else None.
|
||||
"""
|
||||
for path in (CLAUDE_JSON_PATH, MCP_CONFIG_PATH, Path.cwd() / ".mcp.json"):
|
||||
if not path.exists():
|
||||
continue
|
||||
try:
|
||||
with open(path) as f:
|
||||
data = json.load(f)
|
||||
except (json.JSONDecodeError, OSError):
|
||||
continue
|
||||
servers = data.get("mcpServers", {})
|
||||
if isinstance(servers, dict) and "headroom" in servers:
|
||||
return path, servers["headroom"]
|
||||
return None
|
||||
|
||||
|
||||
@main.group()
|
||||
def mcp() -> None:
|
||||
"""MCP server for Claude Code integration.
|
||||
|
||||
@@ -195,16 +195,6 @@ def _get_env_int(name: str, default: int) -> int:
|
||||
return default if value is None else value
|
||||
|
||||
|
||||
def _get_env_float_optional(name: str) -> float | None:
|
||||
val = os.environ.get(name)
|
||||
if val is None or val == "":
|
||||
return None
|
||||
try:
|
||||
return float(val)
|
||||
except ValueError:
|
||||
raise click.ClickException(f"{name} must be a number, got {val!r}") from None
|
||||
|
||||
|
||||
@main.command()
|
||||
@click.option(
|
||||
"--port",
|
||||
|
||||
@@ -87,7 +87,6 @@ from headroom.providers.antigravity import (
|
||||
render_setup_lines as _render_antigravity_setup_lines,
|
||||
)
|
||||
from headroom.providers.claude import (
|
||||
CONTEXT_1M_SUFFIX,
|
||||
DEFAULT_1M_MODEL,
|
||||
HEADROOM_1M_MODEL_ENV,
|
||||
REMOTE_CONTROL_BASE_URL_ENV,
|
||||
@@ -193,9 +192,6 @@ from headroom.providers.openclaw import (
|
||||
from headroom.providers.openclaw import (
|
||||
decode_entry_json as _decode_openclaw_entry_json_impl,
|
||||
)
|
||||
from headroom.providers.openclaw import (
|
||||
normalize_gateway_provider_ids as _normalize_openclaw_gateway_provider_ids_impl,
|
||||
)
|
||||
from headroom.providers.opencode import build_launch_env as _build_opencode_launch_env
|
||||
from headroom.providers.opencode.config import (
|
||||
_MCP_MARKER_END, # noqa: F401
|
||||
@@ -331,15 +327,6 @@ def _append_text(path: Path, content: str) -> None:
|
||||
fsutil.append_text(path, content)
|
||||
|
||||
|
||||
_AGENT_SAVINGS_TARGET_AGENTS = {
|
||||
"antigravity",
|
||||
"claude",
|
||||
"codex",
|
||||
"cursor",
|
||||
"grok",
|
||||
"grok_build",
|
||||
"opencode",
|
||||
}
|
||||
_WRAP_PROXY_TIMEOUT_ENV = "HEADROOM_WRAP_PROXY_TIMEOUT"
|
||||
_WRAP_PROXY_TIMEOUT_DEFAULT_SECONDS = 45
|
||||
_WRAP_PROXY_TIMEOUT_ML_DEFAULT_SECONDS = 90
|
||||
@@ -373,10 +360,8 @@ _CLAUDE_PROJECT_SETTINGS_ENV = "HEADROOM_CLAUDE_PROJECT_SETTINGS"
|
||||
_ANTHROPIC_MODEL_ENV = "ANTHROPIC_MODEL"
|
||||
# Private aliases preserve the standalone wrapper's existing test and import
|
||||
# surface while the provider runtime owns the 1M selection contract.
|
||||
_CONTEXT_1M_SUFFIX = CONTEXT_1M_SUFFIX
|
||||
_1M_MODEL_ENV = HEADROOM_1M_MODEL_ENV
|
||||
_DEFAULT_1M_MODEL = DEFAULT_1M_MODEL
|
||||
_OPENCLAUDE_INSTRUCTIONS_FILE = "CONVENTIONS.md"
|
||||
|
||||
|
||||
_resolve_1m_model = resolve_1m_model
|
||||
@@ -1703,25 +1688,6 @@ def _wrap_proxy_alive(port: int, *, attempts: int = 3, delay: float = 0.25) -> b
|
||||
return False
|
||||
|
||||
|
||||
def _wrap_marker_proxy_is_dead(marker: dict[str, Any]) -> bool:
|
||||
"""True if ``marker`` records a proxy ``port`` that no longer accepts
|
||||
connections.
|
||||
|
||||
Port liveness is the authoritative signal for a wrap session that vanished
|
||||
without running its cleanup (hard reboot / SIGKILL, issue #2221): the
|
||||
recorded PID is unreliable because a reboot can recycle it onto an
|
||||
unrelated live process, so a PID that still looks alive does not prove the
|
||||
proxy is up. A marker with no recorded port returns False here (fall back
|
||||
to PID-based staleness); a marker whose port IS responding is a live
|
||||
session and must never be treated as dead. Uses the retry-hardened
|
||||
``_wrap_proxy_alive`` so a momentary blip never reads as dead.
|
||||
"""
|
||||
port = marker.get("port")
|
||||
if not isinstance(port, int):
|
||||
return False
|
||||
return not _wrap_proxy_alive(port)
|
||||
|
||||
|
||||
def _clear_wrap_marker(settings_path: Path, *, key: str) -> None:
|
||||
marker = _read_wrap_marker(settings_path)
|
||||
if marker is not None and marker.get("key") == key:
|
||||
@@ -4069,76 +4035,6 @@ def _env_bool_value(value: str) -> bool:
|
||||
return value.strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _agent_savings_config_mismatches(
|
||||
running_config: dict[str, Any],
|
||||
agent_type: str,
|
||||
) -> list[str]:
|
||||
"""Return restart reasons when a running proxy lacks target agent savings."""
|
||||
|
||||
if agent_type not in _AGENT_SAVINGS_TARGET_AGENTS:
|
||||
return []
|
||||
|
||||
if _wrap_agent_savings_profile(agent_type) is None:
|
||||
return []
|
||||
|
||||
desired_env = os.environ.copy()
|
||||
apply_agent_savings_env_defaults(desired_env)
|
||||
checks: tuple[tuple[str, str, str, str], ...] = (
|
||||
("HEADROOM_SAVINGS_PROFILE", "savings_profile", "savings-profile", "str"),
|
||||
("HEADROOM_TARGET_RATIO", "target_ratio", "target-ratio", "float"),
|
||||
(
|
||||
"HEADROOM_COMPRESS_USER_MESSAGES",
|
||||
"compress_user_messages",
|
||||
"compress-user-messages",
|
||||
"bool",
|
||||
),
|
||||
(
|
||||
"HEADROOM_COMPRESS_SYSTEM_MESSAGES",
|
||||
"compress_system_messages",
|
||||
"compress-system-messages",
|
||||
"bool",
|
||||
),
|
||||
("HEADROOM_PROTECT_RECENT", "protect_recent", "protect-recent", "int"),
|
||||
(
|
||||
"HEADROOM_PROTECT_ANALYSIS_CONTEXT",
|
||||
"protect_analysis_context",
|
||||
"protect-analysis-context",
|
||||
"bool",
|
||||
),
|
||||
("HEADROOM_MIN_TOKENS", "min_tokens_to_crush", "min-tokens", "int"),
|
||||
("HEADROOM_MAX_ITEMS", "max_items_after_crush", "max-items", "int"),
|
||||
(
|
||||
"HEADROOM_SMART_CRUSHER_COMPACTION",
|
||||
"smart_crusher_with_compaction",
|
||||
"smart-crusher-compaction",
|
||||
"bool",
|
||||
),
|
||||
("HEADROOM_ACCURACY_GUARD", "accuracy_guard", "accuracy-guard", "str"),
|
||||
)
|
||||
|
||||
mismatches: list[str] = []
|
||||
for env_key, config_key, label, value_type in checks:
|
||||
expected = desired_env.get(env_key)
|
||||
if expected is None:
|
||||
continue
|
||||
actual = running_config.get(config_key)
|
||||
try:
|
||||
if value_type == "float":
|
||||
matches = actual is not None and abs(float(actual) - float(expected)) < 1e-9
|
||||
elif value_type == "int":
|
||||
matches = actual is not None and int(actual) == int(expected)
|
||||
elif value_type == "bool":
|
||||
matches = actual is not None and bool(actual) is _env_bool_value(expected)
|
||||
else:
|
||||
matches = str(actual or "").strip().lower() == expected.strip().lower()
|
||||
except (TypeError, ValueError):
|
||||
matches = False
|
||||
if not matches:
|
||||
mismatches.append(label)
|
||||
|
||||
return mismatches
|
||||
|
||||
|
||||
def _proxy_active_session_count(payload: dict[str, Any] | None) -> int:
|
||||
"""Return active session count from /health runtime metadata."""
|
||||
if payload is None:
|
||||
@@ -5642,11 +5538,6 @@ def _resolve_openclaw_extensions_dir(openclaw_bin: str) -> Path:
|
||||
return config_path.parent / "extensions"
|
||||
|
||||
|
||||
def _normalize_openclaw_gateway_provider_ids(provider_ids: tuple[str, ...] | None) -> list[str]:
|
||||
"""Normalize configured OpenClaw provider ids, defaulting to openai-codex."""
|
||||
return _normalize_openclaw_gateway_provider_ids_impl(provider_ids)
|
||||
|
||||
|
||||
def _read_openclaw_config_value(openclaw_bin: str, path: str) -> Any | None:
|
||||
"""Read an OpenClaw config value when present, returning None on missing paths."""
|
||||
result = run(
|
||||
@@ -8738,14 +8629,6 @@ def opencode(
|
||||
_opencode_proxy.kill()
|
||||
|
||||
|
||||
def _opencode_home_dir() -> Path:
|
||||
"""Return the OpenCode home/config directory."""
|
||||
env_path = os.environ.get("OPENCODE_HOME", "").strip()
|
||||
if env_path:
|
||||
return Path(env_path).expanduser()
|
||||
return Path.home() / ".config" / "opencode"
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# OpenCode (unwrap)
|
||||
# =============================================================================
|
||||
|
||||
@@ -333,12 +333,6 @@ def test_wrap_agent_savings_profile_is_opt_in(monkeypatch) -> None:
|
||||
assert wrap_module._wrap_agent_savings_profile("codex") == AGENT_90_PROFILE
|
||||
|
||||
|
||||
def test_agent_savings_config_mismatches_requires_explicit_profile(monkeypatch) -> None:
|
||||
monkeypatch.delenv("HEADROOM_SAVINGS_PROFILE", raising=False)
|
||||
|
||||
assert wrap_module._agent_savings_config_mismatches({}, "claude") == []
|
||||
|
||||
|
||||
def test_start_proxy_does_not_inject_agent_savings_by_default(monkeypatch, tmp_path) -> None:
|
||||
captured_env: dict[str, str] = {}
|
||||
|
||||
@@ -389,77 +383,6 @@ def test_start_proxy_injects_explicit_agent_savings_profile(monkeypatch, tmp_pat
|
||||
assert captured_env["HEADROOM_TARGET_RATIO"] == "0.10"
|
||||
|
||||
|
||||
def test_agent_savings_config_mismatches_returns_specific_labels(monkeypatch) -> None:
|
||||
monkeypatch.setenv("HEADROOM_SAVINGS_PROFILE", AGENT_90_PROFILE)
|
||||
profile = get_agent_savings_profile(AGENT_90_PROFILE)
|
||||
running_config = {
|
||||
"savings_profile": profile.name,
|
||||
"target_ratio": 0.20,
|
||||
"compress_user_messages": profile.compress_user_messages,
|
||||
"compress_system_messages": profile.compress_system_messages,
|
||||
"protect_recent": profile.protect_recent,
|
||||
"protect_analysis_context": profile.protect_analysis_context,
|
||||
"min_tokens_to_crush": profile.min_tokens_to_compress,
|
||||
"max_items_after_crush": profile.max_items_after_crush,
|
||||
"smart_crusher_with_compaction": profile.smart_crusher_with_compaction,
|
||||
"accuracy_guard": profile.accuracy_guard,
|
||||
}
|
||||
|
||||
assert wrap_module._agent_savings_config_mismatches(running_config, "codex") == ["target-ratio"]
|
||||
|
||||
|
||||
def test_agent_savings_config_mismatches_ignores_non_target_agents() -> None:
|
||||
assert wrap_module._agent_savings_config_mismatches({}, "openhands") == []
|
||||
|
||||
|
||||
def test_agent_savings_config_mismatches_accepts_matching_runtime_config(monkeypatch) -> None:
|
||||
monkeypatch.setenv("HEADROOM_SAVINGS_PROFILE", AGENT_90_PROFILE)
|
||||
profile = get_agent_savings_profile(AGENT_90_PROFILE)
|
||||
running_config = {
|
||||
"savings_profile": profile.name,
|
||||
"target_ratio": "0.10",
|
||||
"compress_user_messages": True,
|
||||
"compress_system_messages": True,
|
||||
"protect_recent": "2",
|
||||
"protect_analysis_context": True,
|
||||
"min_tokens_to_crush": "120",
|
||||
"max_items_after_crush": "8",
|
||||
"smart_crusher_with_compaction": False,
|
||||
"accuracy_guard": "strict",
|
||||
}
|
||||
|
||||
assert wrap_module._agent_savings_config_mismatches(running_config, "cursor") == []
|
||||
|
||||
|
||||
def test_agent_savings_config_mismatches_reports_unparseable_values(monkeypatch) -> None:
|
||||
monkeypatch.setenv("HEADROOM_SAVINGS_PROFILE", AGENT_90_PROFILE)
|
||||
running_config = {
|
||||
"savings_profile": None,
|
||||
"target_ratio": "not-a-float",
|
||||
"compress_user_messages": None,
|
||||
"compress_system_messages": None,
|
||||
"protect_recent": "not-an-int",
|
||||
"protect_analysis_context": None,
|
||||
"min_tokens_to_crush": object(),
|
||||
"max_items_after_crush": object(),
|
||||
"smart_crusher_with_compaction": None,
|
||||
"accuracy_guard": None,
|
||||
}
|
||||
|
||||
assert wrap_module._agent_savings_config_mismatches(running_config, "claude") == [
|
||||
"savings-profile",
|
||||
"target-ratio",
|
||||
"compress-user-messages",
|
||||
"compress-system-messages",
|
||||
"protect-recent",
|
||||
"protect-analysis-context",
|
||||
"min-tokens",
|
||||
"max-items",
|
||||
"smart-crusher-compaction",
|
||||
"accuracy-guard",
|
||||
]
|
||||
|
||||
|
||||
def test_agent_90_profile_applies_to_proxy_config_runtime_kwargs() -> None:
|
||||
config = ProxyConfig(savings_profile="agent-90")
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ These are real tests that:
|
||||
- Test MCP server initialization (when MCP SDK is available)
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
@@ -14,11 +13,6 @@ import pytest
|
||||
from click.testing import CliRunner
|
||||
|
||||
from headroom.cli.main import main
|
||||
from headroom.cli.mcp import (
|
||||
get_headroom_command,
|
||||
load_mcp_config,
|
||||
save_mcp_config,
|
||||
)
|
||||
from headroom.mcp_registry.base import ServerSpec
|
||||
|
||||
# Check if MCP SDK is available
|
||||
@@ -30,23 +24,6 @@ except ImportError:
|
||||
MCP_AVAILABLE = False
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_claude_dir(tmp_path):
|
||||
"""Create a temporary .claude directory for testing."""
|
||||
claude_dir = tmp_path / ".claude"
|
||||
claude_dir.mkdir()
|
||||
return claude_dir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_claude_config_path(temp_claude_dir):
|
||||
"""Patch the MCP config path to use temp directory."""
|
||||
config_path = temp_claude_dir / "mcp.json"
|
||||
with patch("headroom.cli.mcp.MCP_CONFIG_PATH", config_path):
|
||||
with patch("headroom.cli.mcp.CLAUDE_CONFIG_DIR", temp_claude_dir):
|
||||
yield config_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_mcp_available():
|
||||
"""Mock MCP SDK as available for testing install/uninstall commands."""
|
||||
@@ -79,70 +56,10 @@ class FakeRegistrar:
|
||||
return False
|
||||
|
||||
|
||||
class TestMCPConfigFunctions:
|
||||
"""Test config file handling functions."""
|
||||
|
||||
def test_get_headroom_command_returns_list(self):
|
||||
"""Command should be a list suitable for subprocess."""
|
||||
cmd = get_headroom_command()
|
||||
assert isinstance(cmd, list)
|
||||
assert len(cmd) >= 1
|
||||
# Should end with mcp serve args
|
||||
assert "mcp" in cmd or "-m" in cmd
|
||||
|
||||
def test_load_mcp_config_empty_when_no_file(self, mock_claude_config_path):
|
||||
"""Loading non-existent config returns empty structure."""
|
||||
config = load_mcp_config()
|
||||
assert config == {"mcpServers": {}}
|
||||
|
||||
def test_save_and_load_config(self, mock_claude_config_path):
|
||||
"""Config can be saved and loaded back."""
|
||||
test_config = {
|
||||
"mcpServers": {
|
||||
"headroom": {
|
||||
"command": "headroom",
|
||||
"args": ["mcp", "serve"],
|
||||
}
|
||||
}
|
||||
}
|
||||
save_mcp_config(test_config)
|
||||
|
||||
# File should exist
|
||||
assert mock_claude_config_path.exists()
|
||||
|
||||
# Load it back
|
||||
loaded = load_mcp_config()
|
||||
assert loaded == test_config
|
||||
|
||||
def test_save_config_creates_directory(self, tmp_path):
|
||||
"""save_mcp_config creates parent directory if needed."""
|
||||
claude_dir = tmp_path / "new_dir" / ".claude"
|
||||
config_path = claude_dir / "mcp.json"
|
||||
|
||||
with patch("headroom.cli.mcp.MCP_CONFIG_PATH", config_path):
|
||||
with patch("headroom.cli.mcp.CLAUDE_CONFIG_DIR", claude_dir):
|
||||
save_mcp_config({"mcpServers": {}})
|
||||
|
||||
assert config_path.exists()
|
||||
|
||||
def test_load_config_preserves_other_servers(self, mock_claude_config_path):
|
||||
"""Loading preserves other MCP servers in config."""
|
||||
# Write config with another server
|
||||
existing_config = {
|
||||
"mcpServers": {
|
||||
"other-server": {"command": "other", "args": []},
|
||||
}
|
||||
}
|
||||
mock_claude_config_path.write_text(json.dumps(existing_config))
|
||||
|
||||
loaded = load_mcp_config()
|
||||
assert "other-server" in loaded["mcpServers"]
|
||||
|
||||
|
||||
#
|
||||
# Note: Tests for the 'mcp install' command's writes/idempotency/CLI-vs-file
|
||||
# fallback used to live here, but they were tightly coupled to private
|
||||
# globals (MCP_CONFIG_PATH, shutil.which) and exercised the same surface
|
||||
# module globals (config paths, shutil.which) and exercised the same surface
|
||||
# already covered by:
|
||||
# - tests/test_mcp_registry/test_claude_registrar.py (file/CLI behavior
|
||||
# with proper constructor injection — no patches)
|
||||
@@ -179,7 +96,7 @@ class TestMCPUninstallCommand:
|
||||
assert result.exit_code == 0
|
||||
assert registrar.removed == ["headroom"]
|
||||
|
||||
def test_uninstall_no_config_file(self, mock_claude_config_path):
|
||||
def test_uninstall_no_config_file(self):
|
||||
"""Uninstall with no config file exits cleanly."""
|
||||
runner = CliRunner()
|
||||
with patch("headroom.mcp_registry.get_all_registrars", return_value=[]):
|
||||
@@ -188,7 +105,7 @@ class TestMCPUninstallCommand:
|
||||
assert result.exit_code == 0
|
||||
assert "nothing to uninstall" in result.output.lower()
|
||||
|
||||
def test_uninstall_not_configured(self, mock_claude_config_path):
|
||||
def test_uninstall_not_configured(self):
|
||||
"""Uninstall when headroom not in config exits cleanly."""
|
||||
registrar = FakeRegistrar(configured=False)
|
||||
|
||||
@@ -230,7 +147,7 @@ class TestMCPUninstallCommand:
|
||||
class TestMCPStatusCommand:
|
||||
"""Test 'headroom mcp status' command."""
|
||||
|
||||
def test_status_not_configured(self, mock_claude_config_path):
|
||||
def test_status_not_configured(self):
|
||||
"""Status shows not configured when no config."""
|
||||
runner = CliRunner()
|
||||
registrar = FakeRegistrar(configured=False)
|
||||
@@ -246,7 +163,7 @@ class TestMCPStatusCommand:
|
||||
or "No config" in result.output
|
||||
)
|
||||
|
||||
def test_status_configured(self, mock_claude_config_path, mock_mcp_available):
|
||||
def test_status_configured(self, mock_mcp_available):
|
||||
"""Status reports configured when a registrar has headroom."""
|
||||
registrar = FakeRegistrar(configured=True)
|
||||
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from headroom.cli import mcp as mcp_cli
|
||||
|
||||
|
||||
def _write_servers(path: Path, servers: dict) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps({"mcpServers": servers}), encoding="utf-8")
|
||||
|
||||
|
||||
def test_find_registration_in_claude_json(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
claude_json = tmp_path / ".claude.json"
|
||||
_write_servers(
|
||||
claude_json,
|
||||
{
|
||||
"headroom": {
|
||||
"command": "headroom",
|
||||
"args": ["mcp", "serve"],
|
||||
"env": {"HEADROOM_PROXY_URL": "http://x:1"},
|
||||
}
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(mcp_cli, "CLAUDE_JSON_PATH", claude_json)
|
||||
monkeypatch.setattr(mcp_cli, "MCP_CONFIG_PATH", tmp_path / ".claude" / "mcp.json")
|
||||
monkeypatch.chdir(tmp_path)
|
||||
|
||||
found = mcp_cli.find_headroom_registration()
|
||||
assert found is not None
|
||||
path, cfg = found
|
||||
assert path == claude_json
|
||||
assert cfg["env"]["HEADROOM_PROXY_URL"] == "http://x:1"
|
||||
|
||||
|
||||
def test_find_registration_falls_back_to_mcp_json(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
mcp_json = tmp_path / "mcp.json"
|
||||
_write_servers(mcp_json, {"headroom": {"command": "headroom"}})
|
||||
monkeypatch.setattr(mcp_cli, "CLAUDE_JSON_PATH", tmp_path / ".claude.json") # absent
|
||||
monkeypatch.setattr(mcp_cli, "MCP_CONFIG_PATH", mcp_json)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
|
||||
found = mcp_cli.find_headroom_registration()
|
||||
assert found is not None and found[0] == mcp_json
|
||||
|
||||
|
||||
def test_find_registration_prefers_claude_json(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
claude_json = tmp_path / ".claude.json"
|
||||
mcp_json = tmp_path / "mcp.json"
|
||||
_write_servers(claude_json, {"headroom": {"command": "a"}})
|
||||
_write_servers(mcp_json, {"headroom": {"command": "b"}})
|
||||
monkeypatch.setattr(mcp_cli, "CLAUDE_JSON_PATH", claude_json)
|
||||
monkeypatch.setattr(mcp_cli, "MCP_CONFIG_PATH", mcp_json)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
|
||||
found = mcp_cli.find_headroom_registration()
|
||||
assert found is not None and found[0] == claude_json # ~/.claude.json takes precedence
|
||||
|
||||
|
||||
def test_find_registration_none_when_absent(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(mcp_cli, "CLAUDE_JSON_PATH", tmp_path / ".claude.json")
|
||||
monkeypatch.setattr(mcp_cli, "MCP_CONFIG_PATH", tmp_path / "mcp.json")
|
||||
monkeypatch.chdir(tmp_path)
|
||||
|
||||
assert mcp_cli.find_headroom_registration() is None
|
||||
|
||||
|
||||
def test_find_registration_skips_malformed_json(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
claude_json = tmp_path / ".claude.json"
|
||||
claude_json.write_text("{ not valid json", encoding="utf-8")
|
||||
mcp_json = tmp_path / "mcp.json"
|
||||
_write_servers(mcp_json, {"headroom": {"command": "ok"}})
|
||||
monkeypatch.setattr(mcp_cli, "CLAUDE_JSON_PATH", claude_json)
|
||||
monkeypatch.setattr(mcp_cli, "MCP_CONFIG_PATH", mcp_json)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
|
||||
found = mcp_cli.find_headroom_registration()
|
||||
assert found is not None and found[0] == mcp_json # malformed file skipped, next match used
|
||||
@@ -49,23 +49,6 @@ def _listening_port() -> Iterator[int]:
|
||||
s.close()
|
||||
|
||||
|
||||
# --- _wrap_marker_proxy_is_dead -------------------------------------------
|
||||
|
||||
|
||||
def test_proxy_is_dead_when_port_not_listening() -> None:
|
||||
assert wrap_cli._wrap_marker_proxy_is_dead({"port": _closed_port()}) is True
|
||||
|
||||
|
||||
def test_proxy_is_not_dead_when_port_listening() -> None:
|
||||
with _listening_port() as port:
|
||||
assert wrap_cli._wrap_marker_proxy_is_dead({"port": port}) is False
|
||||
|
||||
|
||||
def test_proxy_is_not_dead_when_no_port_recorded() -> None:
|
||||
# No port → fall back to PID-based staleness, so not "dead" by port here.
|
||||
assert wrap_cli._wrap_marker_proxy_is_dead({}) is False
|
||||
|
||||
|
||||
# --- _check_and_clear_dead_wrap_marker ------------------------------------
|
||||
|
||||
|
||||
|
||||
@@ -432,13 +432,6 @@ def test_wrap_openclaw_accepts_repeatable_gateway_provider_ids(runner: CliRunner
|
||||
assert payload["config"]["gatewayProviderIds"] == ["openai-codex", "anthropic"]
|
||||
|
||||
|
||||
def test_normalize_openclaw_gateway_provider_ids_dedupes_blanks_and_defaults() -> None:
|
||||
assert wrap_cli._normalize_openclaw_gateway_provider_ids(
|
||||
(" openai-codex ", "", "anthropic", "openai-codex", " ")
|
||||
) == ["openai-codex", "anthropic"]
|
||||
assert wrap_cli._normalize_openclaw_gateway_provider_ids(None) == ["openai-codex"]
|
||||
|
||||
|
||||
def test_read_openclaw_config_value_handles_missing_and_raw_strings() -> None:
|
||||
missing = MagicMock(returncode=1, stdout="", stderr="missing")
|
||||
raw_string = MagicMock(returncode=0, stdout="plain-text-value\n", stderr="")
|
||||
|
||||
Reference in New Issue
Block a user