Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
test: expand persistent install coverage
JerrettDavisbd242fc62d80
diff --git a/tests/test_cli/test_install_cli.py b/tests/test_cli/test_install_cli.pyindex b5df92c3c..4fd5ba23f 100644--- a/tests/test_cli/test_install_cli.py+++ b/tests/test_cli/test_install_cli.py@@ -239,3 +239,105 @@ def test_install_start_rejects_task_lifecycle(monkeypatch) -> None:assert result.exit_code != 0assert "headroom install start" in result.output+++def test_install_apply_uses_docker_runtime_for_persistent_docker(monkeypatch) -> None:+ runner = CliRunner()+ calls: list[str] = []++ class Manifest:+ profile = "default"+ preset = "persistent-docker"+ runtime_kind = "docker"+ supervisor_kind = "none"+ scope = "user"+ health_url = "http://127.0.0.1:8787/readyz"+ targets: list[str] = []+ mutations = []+ artifacts = []++ monkeypatch.setattr("headroom.cli.install.build_manifest", lambda **_: Manifest())+ monkeypatch.setattr("headroom.cli.install.load_manifest", lambda profile: None)+ monkeypatch.setattr("headroom.cli.install.apply_mutations", lambda deployment: [])+ monkeypatch.setattr("headroom.cli.install.install_supervisor", lambda deployment: [])+ monkeypatch.setattr("headroom.cli.install.save_manifest", lambda deployment: None)+ monkeypatch.setattr(+ "headroom.cli.install.start_persistent_docker",+ lambda deployment: calls.append("start_docker"),+ )+ monkeypatch.setattr(+ "headroom.cli.install.wait_ready", lambda deployment, timeout_seconds=45: True+ )++ result = runner.invoke(main, ["install", "apply", "--preset", "persistent-docker"])++ assert result.exit_code == 0, result.output+ assert calls == ["start_docker"]+++def test_install_remove_continues_when_runtime_teardown_errors(monkeypatch) -> None:+ runner = CliRunner()+ calls: list[str] = []++ class Manifest:+ profile = "default"+ preset = "persistent-service"+ runtime_kind = "python"+ supervisor_kind = "service"+ scope = "user"+ health_url = "http://127.0.0.1:8787/readyz"++ monkeypatch.setattr("headroom.cli.install.load_manifest", lambda profile: Manifest())+ monkeypatch.setattr(+ "headroom.cli.install.stop_supervisor",+ lambda manifest: (_ for _ in ()).throw(RuntimeError("boom")),+ )+ monkeypatch.setattr(+ "headroom.cli.install.stop_runtime",+ lambda manifest: (_ for _ in ()).throw(RuntimeError("boom")),+ )+ monkeypatch.setattr(+ "headroom.cli.install.remove_supervisor", lambda manifest: calls.append("remove_supervisor")+ )+ monkeypatch.setattr(+ "headroom.cli.install.revert_mutations", lambda manifest: calls.append("revert")+ )+ monkeypatch.setattr(+ "headroom.cli.install.delete_manifest", lambda profile: calls.append("delete")+ )++ result = runner.invoke(main, ["install", "remove"])++ assert result.exit_code == 0, result.output+ assert calls == ["remove_supervisor", "revert", "delete"]+++def test_install_agent_ensure_reports_already_healthy(monkeypatch) -> None:+ runner = CliRunner()++ class Manifest:+ profile = "default"+ health_url = "http://127.0.0.1:8787/readyz"++ monkeypatch.setattr("headroom.cli.install.load_manifest", lambda profile: Manifest())+ monkeypatch.setattr("headroom.cli.install.probe_ready", lambda url: True)++ result = runner.invoke(main, ["install", "agent", "ensure"])++ assert result.exit_code == 0, result.output+ assert "already healthy" in result.output+++def test_install_agent_run_exits_with_foreground_status(monkeypatch) -> None:+ runner = CliRunner()++ class Manifest:+ profile = "default"+ health_url = "http://127.0.0.1:8787/readyz"++ monkeypatch.setattr("headroom.cli.install.load_manifest", lambda profile: Manifest())+ monkeypatch.setattr("headroom.cli.install.run_foreground", lambda manifest: 7)++ result = runner.invoke(main, ["install", "agent", "run"])++ assert result.exit_code == 7diff --git a/tests/test_cli/test_wrap_persistent.py b/tests/test_cli/test_wrap_persistent.pyindex 61143a353..31acdd78c 100644--- a/tests/test_cli/test_wrap_persistent.py+++ b/tests/test_cli/test_wrap_persistent.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport click-from headroom.cli.wrap import _ensure_proxy+from headroom.cli.wrap import _ensure_proxy, _find_persistent_manifest, _recover_persistent_proxyclass _Manifest:@@ -70,3 +70,39 @@ def test_ensure_proxy_rejects_unhealthy_persistent_deployment(monkeypatch) -> Noassert "is not healthy" in str(exc)else:raise AssertionError("expected unhealthy persistent deployment to raise")+++def test_find_persistent_manifest_prefers_default_profile(monkeypatch) -> None:+ class DefaultManifest:+ profile = "default"+ port = 8787++ class OtherManifest:+ profile = "custom"+ port = 8787++ monkeypatch.setattr(+ "headroom.install.state.list_manifests",+ lambda: [OtherManifest(), DefaultManifest()],+ )++ manifest = _find_persistent_manifest(8787)++ assert manifest.profile == "default"+++def test_recover_persistent_proxy_reuses_healthy_deployment(monkeypatch) -> None:+ monkeypatch.setattr("headroom.cli.wrap._find_persistent_manifest", lambda port: _Manifest())+ monkeypatch.setattr("headroom.install.health.probe_ready", lambda url: True)++ assert _recover_persistent_proxy(8787) is True+++def test_recover_persistent_proxy_warns_for_task_deployment(monkeypatch) -> None:+ class TaskManifest(_Manifest):+ supervisor_kind = "task"++ monkeypatch.setattr("headroom.cli.wrap._find_persistent_manifest", lambda port: TaskManifest())+ monkeypatch.setattr("headroom.install.health.probe_ready", lambda url: False)++ assert _recover_persistent_proxy(8787) is Falsediff --git a/tests/test_install/test_health.py b/tests/test_install/test_health.pynew file mode 100644index 000000000..0e2a6bea0--- /dev/null+++ b/tests/test_install/test_health.py@@ -0,0 +1,57 @@+from __future__ import annotations++import urllib.error++from headroom.install.health import probe_json, probe_ready+++class _Response:+ def __init__(self, payload: bytes) -> None:+ self._payload = payload++ def __enter__(self) -> _Response:+ return self++ def __exit__(self, exc_type, exc, tb) -> None:+ return None++ def read(self) -> bytes:+ return self._payload+++def test_probe_json_returns_dict(monkeypatch) -> None:+ monkeypatch.setattr(+ "urllib.request.urlopen",+ lambda url, timeout=2.0: _Response(b'{"ready": true}'),+ )++ assert probe_json("http://example.test") == {"ready": True}+++def test_probe_json_returns_none_for_invalid_payloads(monkeypatch) -> None:+ monkeypatch.setattr("urllib.request.urlopen", lambda url, timeout=2.0: _Response(b"[]"))+ assert probe_json("http://example.test") is None++ monkeypatch.setattr("urllib.request.urlopen", lambda url, timeout=2.0: _Response(b"{"))+ assert probe_json("http://example.test") is None++ monkeypatch.setattr(+ "urllib.request.urlopen",+ lambda url, timeout=2.0: (_ for _ in ()).throw(urllib.error.URLError("boom")),+ )+ assert probe_json("http://example.test") is None+++def test_probe_ready_accepts_ready_and_healthy(monkeypatch) -> None:+ monkeypatch.setattr(+ "headroom.install.health.probe_json", lambda url, timeout=2.0: {"ready": True}+ )+ assert probe_ready("http://example.test")++ monkeypatch.setattr(+ "headroom.install.health.probe_json", lambda url, timeout=2.0: {"status": "healthy"}+ )+ assert probe_ready("http://example.test")++ monkeypatch.setattr("headroom.install.health.probe_json", lambda url, timeout=2.0: None)+ assert not probe_ready("http://example.test")diff --git a/tests/test_install/test_planner.py b/tests/test_install/test_planner.pyindex 9bbe3c449..0a672c78d 100644--- a/tests/test_install/test_planner.py+++ b/tests/test_install/test_planner.py@@ -1,6 +1,6 @@from __future__ import annotations-from headroom.install.models import InstallPreset, ProviderSelectionMode, ToolTarget+from headroom.install.models import ConfigScope, InstallPreset, ProviderSelectionMode, ToolTargetfrom headroom.install.planner import build_manifest, resolve_targets@@ -42,3 +42,24 @@ def test_build_manifest_for_persistent_docker_sets_expected_defaults() -> None:assert manifest.tool_envs["claude"]["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:8787"assert manifest.tool_envs["copilot"]["COPILOT_PROVIDER_TYPE"] == "anthropic"assert "--memory" in manifest.proxy_args+++def test_resolve_targets_provider_scope_auto_excludes_copilot(monkeypatch) -> None:+ monkeypatch.setattr("headroom.install.planner.detect_targets", lambda: [])++ targets = resolve_targets(+ ProviderSelectionMode.AUTO.value,+ [],+ scope=ConfigScope.PROVIDER.value,+ )++ assert targets == [ToolTarget.CLAUDE.value, ToolTarget.CODEX.value]+++def test_resolve_targets_manual_dedupes_and_filters_invalid() -> None:+ targets = resolve_targets(+ ProviderSelectionMode.MANUAL.value,+ ["claude", "copilot", "claude", "invalid"],+ )++ assert targets == [ToolTarget.CLAUDE.value, ToolTarget.COPILOT.value]diff --git a/tests/test_install/test_providers.py b/tests/test_install/test_providers.pyindex d22971b93..40350c3ce 100644--- a/tests/test_install/test_providers.py+++ b/tests/test_install/test_providers.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport jsonfrom pathlib import Path-from headroom.install.models import DeploymentManifest+from headroom.install.models import DeploymentManifest, ManagedMutationfrom headroom.install.providers import (_apply_claude_provider_scope,_apply_codex_provider_scope,@@ -138,3 +138,42 @@ def test_windows_env_scope_restores_previous_values(monkeypatch, tmp_path: Path)in command[-1]for command in calls)+++def test_remove_windows_env_scope_requires_name_and_scope() -> None:+ try:+ _remove_windows_env_scope([ManagedMutation(target="env", kind="windows-env", data={})])+ except ValueError as exc:+ assert "variable name" in str(exc)+ else:+ raise AssertionError("expected missing variable name to raise")++ try:+ _remove_windows_env_scope(+ [ManagedMutation(target="env", kind="windows-env", data={"name": "X", "scope": 1})]+ )+ except ValueError as exc:+ assert "valid scope" in str(exc)+ else:+ raise AssertionError("expected invalid scope to raise")+++def test_apply_mutations_runs_openclaw_for_user_scope(monkeypatch, tmp_path: Path) -> None:+ manifest = _manifest(tmp_path)+ manifest.scope = "user"+ manifest.targets = ["openclaw"]+ manifest.base_env = {"HEADROOM_PORT": "8787"}+ manifest.tool_envs = {}++ monkeypatch.setattr("headroom.install.providers.os.name", "posix")+ monkeypatch.setattr("headroom.install.providers._apply_unix_env_scope", lambda deployment: [])+ monkeypatch.setattr(+ "headroom.install.providers._apply_openclaw_provider_scope",+ lambda deployment: ManagedMutation(target="openclaw", kind="openclaw-wrap"),+ )++ from headroom.install.providers import apply_mutations++ mutations = apply_mutations(manifest)++ assert [mutation.kind for mutation in mutations] == ["openclaw-wrap"]diff --git a/tests/test_install/test_runtime.py b/tests/test_install/test_runtime.pyindex e555f5c81..ee8821e41 100644--- a/tests/test_install/test_runtime.py+++ b/tests/test_install/test_runtime.py@@ -3,7 +3,14 @@ from __future__ import annotationsfrom pathlib import Pathfrom headroom.install.models import DeploymentManifest-from headroom.install.runtime import build_runtime_command+from headroom.install.runtime import (+ _clear_pid,+ _read_pid,+ build_runtime_command,+ resolve_headroom_command,+ runtime_status,+ stop_runtime,+)def test_build_runtime_command_for_docker_includes_deployment_env(@@ -68,3 +75,96 @@ def test_build_runtime_command_for_docker_matches_wrapper_parity(joined = " ".join(command)assert "ANTHROPIC_API_KEY" in joinedassert "OPENAI_API_KEY" in joined+++def test_resolve_headroom_command_prefers_headroom_binary(monkeypatch) -> None:+ monkeypatch.setattr(+ "shutil.which", lambda name: "/usr/bin/headroom" if name == "headroom" else None+ )++ assert resolve_headroom_command() == ["/usr/bin/headroom"]+++def test_read_pid_handles_invalid_content(monkeypatch, tmp_path: Path) -> None:+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ pid_file = tmp_path / ".headroom" / "deploy" / "default" / "runner.pid"+ pid_file.parent.mkdir(parents=True)+ pid_file.write_text("not-a-pid", encoding="utf-8")++ assert _read_pid("default") is None+ _clear_pid("default")+ assert not pid_file.exists()+++def test_stop_runtime_for_docker_stops_and_removes_container(monkeypatch) -> None:+ calls: list[list[str]] = []+ manifest = DeploymentManifest(+ profile="default",+ preset="persistent-docker",+ runtime_kind="docker",+ supervisor_kind="none",+ scope="user",+ provider_mode="manual",+ targets=[],+ port=8787,+ host="127.0.0.1",+ backend="anthropic",+ container_name="headroom-default",+ )++ monkeypatch.setattr(+ "headroom.install.runtime.subprocess.run",+ lambda command, **kwargs: calls.append(command),+ )++ stop_runtime(manifest)++ assert calls == [+ ["docker", "stop", "headroom-default"],+ ["docker", "rm", "-f", "headroom-default"],+ ]+++def test_runtime_status_reads_container_and_pid_state(monkeypatch, tmp_path: Path) -> None:+ docker_manifest = DeploymentManifest(+ profile="default",+ preset="persistent-docker",+ runtime_kind="docker",+ supervisor_kind="none",+ scope="user",+ provider_mode="manual",+ targets=[],+ port=8787,+ host="127.0.0.1",+ backend="anthropic",+ container_name="headroom-default",+ )++ class Result:+ def __init__(self, stdout: str = "") -> None:+ self.stdout = stdout++ monkeypatch.setattr(+ "headroom.install.runtime.subprocess.run",+ lambda command, **kwargs: Result(stdout="headroom-default\n"),+ )+ assert runtime_status(docker_manifest) == "running"++ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ pid_file = tmp_path / ".headroom" / "deploy" / "default" / "runner.pid"+ pid_file.parent.mkdir(parents=True)+ pid_file.write_text("123", encoding="utf-8")+ monkeypatch.setattr("headroom.install.runtime.os.kill", lambda pid, sig: None)+ python_manifest = DeploymentManifest(+ profile="default",+ preset="persistent-service",+ runtime_kind="python",+ supervisor_kind="service",+ scope="user",+ provider_mode="manual",+ targets=[],+ port=8787,+ host="127.0.0.1",+ backend="anthropic",+ )+ assert runtime_status(python_manifest) == "running"diff --git a/tests/test_install/test_state.py b/tests/test_install/test_state.pynew file mode 100644index 000000000..eb751dd53--- /dev/null+++ b/tests/test_install/test_state.py@@ -0,0 +1,63 @@+from __future__ import annotations++from pathlib import Path++from headroom.install.models import ArtifactRecord, DeploymentManifest, ManagedMutation+from headroom.install.state import delete_manifest, list_manifests, load_manifest, save_manifest+++def _manifest() -> DeploymentManifest:+ return DeploymentManifest(+ profile="default",+ preset="persistent-service",+ runtime_kind="python",+ supervisor_kind="service",+ scope="user",+ provider_mode="manual",+ targets=["claude"],+ port=8787,+ host="127.0.0.1",+ backend="anthropic",+ mutations=[ManagedMutation(target="env", kind="shell-block", path="x")],+ artifacts=[ArtifactRecord(kind="script", path="run-headroom.sh")],+ )+++def test_save_and_load_manifest_round_trip(monkeypatch, tmp_path: Path) -> None:+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ manifest = _manifest()++ save_manifest(manifest)+ loaded = load_manifest("default")++ assert loaded is not None+ assert loaded.profile == "default"+ assert loaded.mutations[0].kind == "shell-block"+ assert loaded.artifacts[0].kind == "script"+++def test_list_manifests_ignores_invalid_payloads(monkeypatch, tmp_path: Path) -> None:+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ valid = _manifest()+ save_manifest(valid)++ broken_dir = tmp_path / ".headroom" / "deploy" / "broken"+ broken_dir.mkdir(parents=True)+ (broken_dir / "manifest.json").write_text("{not json", encoding="utf-8")++ manifests = list_manifests()++ assert [manifest.profile for manifest in manifests] == ["default"]+++def test_delete_manifest_removes_profile_root(monkeypatch, tmp_path: Path) -> None:+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ manifest = _manifest()+ save_manifest(manifest)+ extra_file = tmp_path / ".headroom" / "deploy" / "default" / "runner.log"+ extra_file.write_text("log", encoding="utf-8")++ delete_manifest("default")++ assert load_manifest("default") is None+ assert not extra_file.parent.exists()diff --git a/tests/test_install/test_supervisors.py b/tests/test_install/test_supervisors.pyindex fcfa62e21..98c5ef52c 100644--- a/tests/test_install/test_supervisors.py+++ b/tests/test_install/test_supervisors.py@@ -8,6 +8,11 @@ from headroom.install.supervisors import (_linux_task_spec,_macos_launchd_plist,_render_windows_runner,+ install_supervisor,+ remove_supervisor,+ render_runner_scripts,+ start_supervisor,+ stop_supervisor,)@@ -92,3 +97,77 @@ def test_render_windows_runner_writes_ps1_and_cmd_wrappers(tmp_path: Path) -> No'powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0run-headroom.ps1" %*'in cmd_content)+++def test_render_runner_scripts_writes_unix_scripts(monkeypatch, tmp_path: Path) -> None:+ monkeypatch.setattr("headroom.install.supervisors.os.name", "posix")+ monkeypatch.setattr(+ "headroom.install.supervisors.resolve_headroom_command", lambda: ["headroom"]+ )+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ manifest = _manifest()++ records = render_runner_scripts(manifest)++ assert {record.path.split("\\")[-1].split("/")[-1] for record in records} == {+ "run-headroom.sh",+ "ensure-headroom.sh",+ }+++def test_install_supervisor_none_returns_runner_records(monkeypatch, tmp_path: Path) -> None:+ monkeypatch.setattr("headroom.install.supervisors.os.name", "posix")+ monkeypatch.setattr(+ "headroom.install.supervisors.resolve_headroom_command", lambda: ["headroom"]+ )+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ manifest = _manifest(supervisor=SupervisorKind.NONE.value)++ records = install_supervisor(manifest)++ assert len(records) == 2+ assert all(record.kind == "script" for record in records)+++def test_start_and_stop_supervisor_use_linux_systemctl(monkeypatch) -> None:+ calls: list[list[str]] = []+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "linux")+ monkeypatch.setattr(+ "headroom.install.supervisors.subprocess.run",+ lambda command, **kwargs: calls.append(command),+ )+ manifest = _manifest()++ start_supervisor(manifest)+ stop_supervisor(manifest)++ assert calls == [+ ["systemctl", "--user", "restart", "headroom-default"],+ ["systemctl", "--user", "stop", "headroom-default"],+ ]+++def test_remove_supervisor_removes_user_crontab_block(monkeypatch) -> None:+ calls: list[tuple[list[str], str | None]] = []+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "linux")++ class Result:+ def __init__(self, returncode: int = 0, stdout: str = "") -> None:+ self.returncode = returncode+ self.stdout = stdout++ def fake_run(command: list[str], **kwargs):+ calls.append((command, kwargs.get("input")))+ if command == ["crontab", "-l"]:+ return Result(+ stdout="# >>> headroom default >>>\n@reboot /tmp/ensure\n# <<< headroom default <<<\n"+ )+ return Result()++ monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)+ manifest = _manifest(supervisor=SupervisorKind.TASK.value)++ remove_supervisor(manifest)++ assert calls[0][0] == ["crontab", "-l"]+ assert calls[1][0] == ["crontab", "-"]