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
Fix CI lint errors and test failures
chopratejas89061fd4307b
diff --git a/tests/test_cli/test_wrap_copilot.py b/tests/test_cli/test_wrap_copilot.pyindex b26b7280c..badcee1ad 100644--- a/tests/test_cli/test_wrap_copilot.py+++ b/tests/test_cli/test_wrap_copilot.py@@ -21,6 +21,7 @@ def test_wrap_copilot_auto_anthropic_injects_instructions(runner: CliRunner, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.chdir(tmp_path)+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-test-dummy")captured: dict[str, object] = {}def fake_launch_tool(**kwargs): # noqa: ANN003@@ -51,7 +52,10 @@ def test_wrap_copilot_auto_anthropic_injects_instructions(assert captured["args"] == ("--model", "claude-sonnet-4-20250514")-def test_wrap_copilot_openai_backend_sets_completions_env(runner: CliRunner) -> None:+def test_wrap_copilot_openai_backend_sets_completions_env(+ runner: CliRunner, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test-dummy")captured: dict[str, object] = {}def fake_launch_tool(**kwargs): # noqa: ANN003@@ -90,7 +94,10 @@ def test_wrap_copilot_openai_backend_sets_completions_env(runner: CliRunner) ->assert captured["args"] == ("--model", "gpt-4o")-def test_wrap_copilot_auto_detects_running_proxy_backend(runner: CliRunner) -> None:+def test_wrap_copilot_auto_detects_running_proxy_backend(+ runner: CliRunner, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test-dummy")captured: dict[str, object] = {}def fake_launch_tool(**kwargs): # noqa: ANN003@@ -153,7 +160,10 @@ def test_wrap_copilot_rejects_responses_for_translated_backends(runner: CliRunneassert "not supported with translated backends" in result.output-def test_wrap_copilot_clears_stale_wire_api_in_anthropic_mode(runner: CliRunner) -> None:+def test_wrap_copilot_clears_stale_wire_api_in_anthropic_mode(+ runner: CliRunner, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-test-dummy")captured: dict[str, object] = {}def fake_launch_tool(**kwargs): # noqa: ANN003@@ -164,7 +174,10 @@ def test_wrap_copilot_clears_stale_wire_api_in_anthropic_mode(runner: CliRunner)result = runner.invoke(main,["wrap", "copilot", "--no-rtk", "--", "--model", "claude-sonnet-4-20250514"],- env={"COPILOT_PROVIDER_WIRE_API": "responses"},+ env={+ "COPILOT_PROVIDER_WIRE_API": "responses",+ "ANTHROPIC_API_KEY": "sk-test-dummy",+ },)assert result.exit_code == 0, result.outputdiff --git a/tests/test_memory_sync.py b/tests/test_memory_sync.pyindex b7ca48c35..d801f047c 100644--- a/tests/test_memory_sync.py+++ b/tests/test_memory_sync.py@@ -12,7 +12,6 @@ Tests cover:from __future__ import annotations-import asyncioimport hashlibimport jsonimport time@@ -20,14 +19,10 @@ from dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any-from unittest.mock import MagicMockimport pytestfrom headroom.memory.sync import (- AgentMemory,- AgentMemoryAdapter,- SyncResult,sync,sync_export,sync_import,@@ -38,7 +33,6 @@ from headroom.memory.sync_adapters.claude_code import ()from headroom.memory.sync_adapters.codex_agent import CodexAdapter-# ---------------------------------------------------------------------------# Fake backend for testing (no real DB/embeddings needed)# ---------------------------------------------------------------------------@@ -116,7 +110,9 @@ class TestSyncImport:d.mkdir()return d- def _write_claude_memory(self, memory_dir: Path, name: str, content: str, **fm_fields: str) -> None:+ def _write_claude_memory(+ self, memory_dir: Path, name: str, content: str, **fm_fields: str+ ) -> None:slug = name.lower().replace(" ", "_")fields = {"name": name, "description": content[:80], "type": "project", **fm_fields}fm_lines = ["---"]@@ -142,9 +138,10 @@ class TestSyncImport:@pytest.mark.asyncioasync def test_import_skips_existing(self, backend, claude_dir):"""Memories already in DB are not re-imported."""- backend.add_memory("The secret name is TC", metadata={- "content_hash": hashlib.sha256(b"The secret name is TC").hexdigest()[:16]- })+ backend.add_memory(+ "The secret name is TC",+ metadata={"content_hash": hashlib.sha256(b"The secret name is TC").hexdigest()[:16]},+ )self._write_claude_memory(claude_dir, "Project codename", "The secret name is TC")self._write_claude_memory(claude_dir, "New fact", "Something new")@@ -184,10 +181,13 @@ class TestSyncExport:@pytest.mark.asyncioasync def test_export_new_memory_to_claude_files(self, backend, claude_dir):- backend.add_memory("Project uses Python 3.12", metadata={- "source_agent": "codex",- "sync_direction": "export", # Not from claude import- })+ backend.add_memory(+ "Project uses Python 3.12",+ metadata={+ "source_agent": "codex",+ "sync_direction": "export", # Not from claude import+ },+ )adapter = ClaudeCodeAdapter(claude_dir)exported = await sync_export(backend, adapter, "tcms")@@ -205,13 +205,19 @@ class TestSyncExport:@pytest.mark.asyncioasync def test_export_skips_claude_originated(self, backend, claude_dir):"""Don't re-export memories that were imported FROM claude (anti-echo)."""- backend.add_memory("From claude", metadata={- "source_agent": "claude",- "sync_direction": "import",- })- backend.add_memory("From codex", metadata={- "source_agent": "codex",- })+ backend.add_memory(+ "From claude",+ metadata={+ "source_agent": "claude",+ "sync_direction": "import",+ },+ )+ backend.add_memory(+ "From codex",+ metadata={+ "source_agent": "codex",+ },+ )adapter = ClaudeCodeAdapter(claude_dir)exported = await sync_export(backend, adapter, "tcms")@@ -419,15 +425,17 @@ class TestClaudeCodeAdapter:@pytest.mark.asyncioasync def test_write_creates_valid_md(self, memory_dir):adapter = ClaudeCodeAdapter(memory_dir)- written = await adapter.write_memories([- {- "content": "Project uses FastAPI",- "category": "architecture",- "headroom_id": "mem_001",- "source_agent": "codex",- "content_hash": "abc123",- }- ])+ written = await adapter.write_memories(+ [+ {+ "content": "Project uses FastAPI",+ "category": "architecture",+ "headroom_id": "mem_001",+ "source_agent": "codex",+ "content_hash": "abc123",+ }+ ]+ )assert written == 1files = list(memory_dir.glob("headroom_*.md"))@@ -499,10 +507,12 @@ class TestCodexAdapter:agents_md.write_text("# Existing instructions\n")adapter = CodexAdapter(agents_md)- written = await adapter.write_memories([- {"content": "Port 8787 is default"},- {"content": "Uses ruff for linting"},- ])+ written = await adapter.write_memories(+ [+ {"content": "Port 8787 is default"},+ {"content": "Uses ruff for linting"},+ ]+ )assert written == 2content = agents_md.read_text()@@ -568,9 +578,7 @@ class TestCrossAgentInterop:return tmp_path / "state.json"@pytest.mark.asyncio- async def test_codex_saves_claude_finds(- self, backend, claude_dir, state_path- ):+ async def test_codex_saves_claude_finds(self, backend, claude_dir, state_path):"""Memory saved via Codex MCP appears in Claude's files after sync."""# Simulate Codex saving via MCP (directly to backend)backend.add_memory(@@ -590,9 +598,7 @@ class TestCrossAgentInterop:assert "TC" in files[0].read_text()@pytest.mark.asyncio- async def test_claude_saves_codex_finds(- self, backend, claude_dir, agents_md, state_path- ):+ async def test_claude_saves_codex_finds(self, backend, claude_dir, agents_md, state_path):"""Memory saved in Claude's files appears in Codex AGENTS.md after sync."""# Claude has a memoryfm = "---\nname: Linting\ndescription: use ruff\ntype: project\n---"@@ -610,9 +616,7 @@ class TestCrossAgentInterop:assert "ruff" in agents_md.read_text()@pytest.mark.asyncio- async def test_full_round_trip(- self, backend, claude_dir, agents_md, state_path- ):+ async def test_full_round_trip(self, backend, claude_dir, agents_md, state_path):"""Full round trip: Claude → DB → Codex, Codex → DB → Claude."""# Claude has a memoryfm = "---\nname: Framework\ntype: project\n---"diff --git a/tests/test_package_init_lazy.py b/tests/test_package_init_lazy.pyindex 142e8ec54..7c9203405 100644--- a/tests/test_package_init_lazy.py+++ b/tests/test_package_init_lazy.py@@ -33,7 +33,8 @@ def test_headroom_import_stays_lazy() -> None:)data = json.loads(result.stdout.strip())- assert data["version"] == "0.5.21"+ # Version is a non-empty string; don't hardcode a specific value.+ assert isinstance(data["version"], str) and data["version"]assert data["cache_loaded"] is Falseassert data["models_registry_loaded"] is Falseassert data["memory_loaded"] is Falsediff --git a/tests/test_ws_memory_relay.py b/tests/test_ws_memory_relay.pyindex 87f4298e3..c092ab2be 100644--- a/tests/test_ws_memory_relay.py+++ b/tests/test_ws_memory_relay.py@@ -13,15 +13,13 @@ import jsonfrom dataclasses import dataclass, fieldfrom typing import Any-import pytest-from headroom.proxy.memory_handler import MEMORY_TOOL_NAMES-# ---------------------------------------------------------------------------# Minimal WS relay state machine (mirrors the logic in openai.py)# ---------------------------------------------------------------------------+@dataclassclass WSMemoryRelayState:"""State machine for WS event processing with memory tool interception.@@ -57,7 +55,6 @@ class WSMemoryRelayState:return resultevent_type = event.get("type", "")- output_index = event.get("output_index")# ---- Phase 1: Buffering (before first output item) ----if not self.decided:@@ -133,6 +130,7 @@ class WSMemoryRelayState:# Test helpers# ---------------------------------------------------------------------------+def _make_event(event_type: str, **kwargs: Any) -> str:data: dict[str, Any] = {"type": event_type}data.update(kwargs)@@ -151,9 +149,7 @@ def _output_item_added_text(index: int = 0) -> str:)-def _output_item_added_function_call(- name: str, index: int = 0, call_id: str = "call_1"-) -> str:+def _output_item_added_function_call(name: str, index: int = 0, call_id: str = "call_1") -> str:return _make_event("response.output_item.added",output_index=index,@@ -169,9 +165,7 @@ def _function_call_args_delta(index: int = 0, delta: str = '{"qu') -> str:)-def _function_call_args_done(- index: int = 0, arguments: str = '{"query": "codename"}'-) -> str:+def _function_call_args_done(index: int = 0, arguments: str = '{"query": "codename"}') -> str:return _make_event("response.function_call_arguments.done",output_index=index,@@ -356,7 +350,9 @@ class TestWSMemoryRelayMemoryTool:_output_item_added_function_call("memory_save", index=0, call_id="call_save"),_function_call_args_done(index=0, arguments='{"content": "user likes dark mode"}'),_output_item_done_function_call(- "memory_save", index=0, call_id="call_save",+ "memory_save",+ index=0,+ call_id="call_save",arguments='{"content": "user likes dark mode"}',),_response_completed("resp_B"),@@ -414,7 +410,8 @@ class TestWSMemoryRelayMemoryTool:# Verify the text contenttext_events = [- json.loads(e) for e in all_relayed+ json.loads(e)+ for e in all_relayedif json.loads(e)["type"] == "response.output_text.delta"]assert len(text_events) == 1@@ -439,7 +436,9 @@ class TestWSMemoryRelayMemoryTool:# The model decides to save something too_output_item_added_function_call("memory_save", index=1, call_id="call_2"),_output_item_done_function_call(- "memory_save", index=1, call_id="call_2",+ "memory_save",+ index=1,+ call_id="call_2",arguments='{"content": "test"}',),_response_completed("resp_multi"),