Skip to content

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.

test: expand coverage across helper slices

JerrettDavis38bf3e639c6e
diff --git a/tests/test_backend_anyllm.py b/tests/test_backend_anyllm.py
new file mode 100644
index 000000000..b75aa66b5
--- /dev/null
+++ b/tests/test_backend_anyllm.py
@@ -0,0 +1,384 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from headroom.backends import anyllm
+from headroom.backends.base import BackendResponse, StreamEvent
+
+
+class FakeAsyncStream:
+ def __init__(self, items) -> None: # noqa: ANN001
+ self._items = list(items)
+
+ def __aiter__(self):
+ self._iter = iter(self._items)
+ return self
+
+ async def __anext__(self):
+ try:
+ return next(self._iter)
+ except StopIteration as exc:
+ raise StopAsyncIteration from exc
+
+
+class FakeAnyLLMInstance:
+ def __init__(self) -> None:
+ self.calls: list[dict[str, object]] = []
+ self.response = None
+ self.raise_error: Exception | None = None
+
+ async def acompletion(self, **kwargs): # noqa: ANN003
+ self.calls.append(kwargs)
+ if self.raise_error is not None:
+ raise self.raise_error
+ return self.response
+
+
+def make_backend(
+ monkeypatch: pytest.MonkeyPatch, provider: str = "groq"
+) -> tuple[anyllm.AnyLLMBackend, FakeAnyLLMInstance]:
+ fake_instance = FakeAnyLLMInstance()
+
+ class FakeAnyLLM:
+ @staticmethod
+ def create(requested_provider: str):
+ assert requested_provider == provider
+ return fake_instance
+
+ monkeypatch.setattr(anyllm, "ANYLLM_AVAILABLE", True)
+ monkeypatch.setattr(anyllm, "AnyLLM", FakeAnyLLM)
+ return anyllm.AnyLLMBackend(provider=provider.upper()), fake_instance
+
+
+def make_choice(
+ content: str = "hello", finish_reason: str = "stop", tool_calls=None, index: int = 0
+):
+ return SimpleNamespace(
+ index=index,
+ finish_reason=finish_reason,
+ message=SimpleNamespace(role="assistant", content=content, tool_calls=tool_calls),
+ )
+
+
+def make_response(*choices, usage=None):
+ return SimpleNamespace(
+ id="resp_123",
+ created=123456,
+ choices=list(choices),
+ usage=usage,
+ )
+
+
+def make_tool_call(tool_id: str, name: str, arguments):
+ return SimpleNamespace(id=tool_id, function=SimpleNamespace(name=name, arguments=arguments))
+
+
+def test_init_raises_without_anyllm() -> None:
+ original_available = anyllm.ANYLLM_AVAILABLE
+ try:
+ anyllm.ANYLLM_AVAILABLE = False
+ with pytest.raises(ImportError):
+ anyllm.AnyLLMBackend()
+ finally:
+ anyllm.ANYLLM_AVAILABLE = original_available
+
+
+def test_init_name_and_basic_methods(monkeypatch: pytest.MonkeyPatch) -> None:
+ backend, instance = make_backend(monkeypatch, provider="groq")
+
+ assert backend.provider == "groq"
+ assert backend.name == "anyllm-groq"
+ assert backend.map_model_id("claude-3-5") == "claude-3-5"
+ assert backend.supports_model("anything") is True
+ assert backend.llm is instance
+
+
+def test_convert_content_blocks_and_messages(monkeypatch: pytest.MonkeyPatch) -> None:
+ backend, _instance = make_backend(monkeypatch)
+
+ assert backend._convert_content_blocks([{"type": "text", "text": "hello"}]) == "hello"
+ assert backend._convert_content_blocks(
+ [
+ {"type": "text", "text": "caption"},
+ {
+ "type": "image",
+ "source": {"type": "base64", "media_type": "image/jpeg", "data": "abc"},
+ },
+ {"type": "image", "source": {"type": "url", "url": "https://example.com/img.png"}},
+ ]
+ ) == [
+ {"type": "text", "text": "caption"},
+ {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,abc"}},
+ {"type": "image_url", "image_url": {"url": "https://example.com/img.png"}},
+ ]
+ assert backend._convert_content_blocks([{"type": "tool_use", "id": "ignored"}]) == ""
+
+ converted = backend._convert_messages(
+ [
+ {"role": "user", "content": "plain text"},
+ {
+ "role": "assistant",
+ "content": [{"type": "text", "text": "a"}, {"type": "text", "text": "b"}],
+ },
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "look"},
+ {"type": "image", "source": {"type": "url", "url": "https://example.com"}},
+ ],
+ },
+ {"role": "user", "content": 123},
+ ]
+ )
+
+ assert converted == [
+ {"role": "user", "content": "plain text"},
+ {"role": "assistant", "content": "a\nb"},
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "look"},
+ {"type": "image_url", "image_url": {"url": "https://example.com"}},
+ ],
+ },
+ ]
+
+
+def test_to_anthropic_response_maps_tool_calls_and_usage(monkeypatch: pytest.MonkeyPatch) -> None:
+ backend, _instance = make_backend(monkeypatch)
+ response = make_response(
+ make_choice(
+ content="hello",
+ finish_reason="tool_calls",
+ tool_calls=[
+ make_tool_call("tc1", "memory_save", '{"content":"python"}'),
+ make_tool_call("tc2", "memory_search", {"query": "python"}),
+ ],
+ ),
+ usage=SimpleNamespace(prompt_tokens=12, completion_tokens=7),
+ )
+
+ converted = backend._to_anthropic_response(response, "claude-sonnet")
+
+ assert converted["type"] == "message"
+ assert converted["role"] == "assistant"
+ assert converted["model"] == "claude-sonnet"
+ assert converted["stop_reason"] == "tool_use"
+ assert converted["usage"] == {"input_tokens": 12, "output_tokens": 7}
+ assert converted["content"][0] == {"type": "text", "text": "hello"}
+ assert converted["content"][1]["input"] == {"content": "python"}
+ assert converted["content"][2]["input"] == {"query": "python"}
+
+
+async def test_send_message_builds_anthropic_response(monkeypatch: pytest.MonkeyPatch) -> None:
+ backend, instance = make_backend(monkeypatch)
+ instance.response = make_response(
+ make_choice("done", "stop"),
+ usage=SimpleNamespace(prompt_tokens=4, completion_tokens=6),
+ )
+
+ result = await backend.send_message(
+ {
+ "model": "claude-3-7-sonnet",
+ "messages": [{"role": "user", "content": [{"type": "text", "text": "hello"}]}],
+ "system": [{"text": "system rule"}, "extra"],
+ "max_tokens": 200,
+ "temperature": 0.3,
+ "top_p": 0.8,
+ "stop_sequences": ["END"],
+ "tools": [{"name": "t"}],
+ "tool_choice": {"type": "auto"},
+ },
+ {},
+ )
+
+ assert isinstance(result, BackendResponse)
+ assert result.status_code == 200
+ assert result.headers == {"content-type": "application/json"}
+ assert result.body["content"][0]["text"] == "done"
+ assert instance.calls[0]["messages"][0] == {"role": "system", "content": "system rule extra"}
+ assert instance.calls[0]["stop"] == ["END"]
+
+
+async def test_send_message_returns_error_response(monkeypatch: pytest.MonkeyPatch) -> None:
+ backend, instance = make_backend(monkeypatch)
+ instance.raise_error = RuntimeError("authentication api_key missing")
+
+ result = await backend.send_message({"messages": []}, {})
+
+ assert result.status_code == 401
+ assert result.body["error"]["type"] == "authentication_error"
+ assert result.error == "authentication api_key missing"
+
+
+async def test_stream_message_yields_events_and_error(monkeypatch: pytest.MonkeyPatch) -> None:
+ backend, instance = make_backend(monkeypatch)
+ instance.response = FakeAsyncStream(
+ [
+ SimpleNamespace(choices=[SimpleNamespace(delta=SimpleNamespace(content="hel"))]),
+ SimpleNamespace(choices=[SimpleNamespace(delta=SimpleNamespace(content="lo"))]),
+ SimpleNamespace(choices=[]),
+ ]
+ )
+
+ events = [
+ event
+ async for event in backend.stream_message(
+ {"model": "claude", "messages": [], "system": "sys"}, {}
+ )
+ ]
+
+ assert [event.event_type for event in events] == [
+ "message_start",
+ "content_block_start",
+ "content_block_delta",
+ "content_block_delta",
+ "content_block_stop",
+ "message_delta",
+ "message_stop",
+ ]
+ assert events[0].data["message"]["model"] == "claude"
+ assert events[5].data["usage"] == {"output_tokens": 2}
+ assert instance.calls[0]["stream"] is True
+ assert instance.calls[0]["messages"][0] == {"role": "system", "content": "sys"}
+
+ backend_error, instance_error = make_backend(monkeypatch, provider="openai")
+ instance_error.raise_error = RuntimeError("stream broke")
+ error_events = [event async for event in backend_error.stream_message({"messages": []}, {})]
+ assert error_events[-1].event_type == "error"
+ assert error_events[-1].data["error"]["message"] == "stream broke"
+
+
+async def test_send_openai_message_maps_choices_and_tool_calls(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ backend, instance = make_backend(monkeypatch)
+ instance.response = make_response(
+ make_choice(
+ content="answer",
+ finish_reason="stop",
+ tool_calls=[
+ make_tool_call("tc1", "memory_search", '{"query":"python"}'),
+ SimpleNamespace(id="tc2", function=None),
+ ],
+ index=0,
+ ),
+ usage=SimpleNamespace(prompt_tokens=2, completion_tokens=3, total_tokens=5),
+ )
+
+ result = await backend.send_openai_message(
+ {
+ "model": "gpt-4o",
+ "messages": [{"role": "user", "content": "hi"}],
+ "max_tokens": 50,
+ "temperature": 0.2,
+ "top_p": 0.9,
+ "stop": ["END"],
+ "tools": [{"name": "memory"}],
+ "tool_choice": "auto",
+ "response_format": {"type": "json_object"},
+ "seed": 1,
+ "n": 2,
+ },
+ {},
+ )
+
+ assert result.status_code == 200
+ assert result.body["object"] == "chat.completion"
+ assert (
+ result.body["choices"][0]["message"]["tool_calls"][0]["function"]["name"] == "memory_search"
+ )
+ assert result.body["choices"][0]["message"]["tool_calls"][1] == {
+ "id": "tc2",
+ "type": "function",
+ }
+ assert result.body["usage"] == {"prompt_tokens": 2, "completion_tokens": 3, "total_tokens": 5}
+
+
+async def test_send_openai_message_returns_error_response(monkeypatch: pytest.MonkeyPatch) -> None:
+ backend, instance = make_backend(monkeypatch)
+ instance.raise_error = RuntimeError("model not found")
+
+ result = await backend.send_openai_message({"messages": []}, {})
+
+ assert result.status_code == 404
+ assert result.body["error"]["type"] == "model_not_found"
+
+
+async def test_stream_openai_message_yields_sse_chunks_and_done(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ backend, instance = make_backend(monkeypatch)
+ instance.response = FakeAsyncStream(
+ [
+ SimpleNamespace(
+ model_dump=lambda **kwargs: {
+ "id": "chunk1",
+ "choices": [{"delta": {"content": "a"}}],
+ }
+ ),
+ SimpleNamespace(
+ model_dump=lambda **kwargs: {
+ "id": "chunk2",
+ "choices": [{"delta": {"content": "b"}}],
+ }
+ ),
+ ]
+ )
+
+ chunks = [
+ chunk
+ async for chunk in backend.stream_openai_message(
+ {
+ "messages": [{"role": "user", "content": "hi"}],
+ "stream_options": {"include_usage": True},
+ },
+ {},
+ )
+ ]
+
+ assert chunks[0].startswith("data: {")
+ assert chunks[-1] == "data: [DONE]\n\n"
+ assert instance.calls[0]["stream"] is True
+ assert instance.calls[0]["stream_options"] == {"include_usage": True}
+
+ backend_error, instance_error = make_backend(monkeypatch, provider="anthropic")
+ instance_error.raise_error = RuntimeError("rate limit hit")
+ error_chunks = [
+ chunk async for chunk in backend_error.stream_openai_message({"messages": []}, {})
+ ]
+ assert '"backend_error"' in error_chunks[0]
+ assert error_chunks[-1] == "data: [DONE]\n\n"
+
+
+def test_error_response_classifies_common_failures(monkeypatch: pytest.MonkeyPatch) -> None:
+ backend, _instance = make_backend(monkeypatch)
+
+ auth = backend._error_response(RuntimeError("authentication api key missing"))
+ rate = backend._error_response(RuntimeError("rate limit exceeded"), openai_format=True)
+ model = backend._error_response(RuntimeError("model not found"), openai_format=True)
+ generic = backend._error_response(RuntimeError("other error"))
+
+ assert auth.status_code == 401
+ assert auth.body["error"]["type"] == "authentication_error"
+ assert rate.status_code == 429
+ assert rate.body["error"]["type"] == "rate_limit_exceeded"
+ assert model.status_code == 404
+ assert model.body["error"]["type"] == "model_not_found"
+ assert generic.status_code == 500
+ assert generic.body["error"]["type"] == "api_error"
+
+
+async def test_close_is_noop(monkeypatch: pytest.MonkeyPatch) -> None:
+ backend, _instance = make_backend(monkeypatch)
+ assert await backend.close() is None
+ assert isinstance(StreamEvent(event_type="message_start", data={}), StreamEvent)
diff --git a/tests/test_ccr_batch_store.py b/tests/test_ccr_batch_store.py
new file mode 100644
index 000000000..04a31bbf0
--- /dev/null
+++ b/tests/test_ccr_batch_store.py
@@ -0,0 +1,126 @@
+from __future__ import annotations
+
+import sys
+from dataclasses import dataclass
+
+from headroom.ccr.batch_store import (
+ BatchContext,
+ BatchContextStore,
+ BatchRequestContext,
+ get_batch_context_store,
+ reset_batch_context_store,
+)
+
+
+def test_batch_context_defaults_and_expiry(monkeypatch) -> None:
+ monkeypatch.setattr("headroom.ccr.batch_store.time.time", lambda: 100.0)
+ context = BatchContext(batch_id="batch-1", provider="anthropic", created_at=100.0)
+ assert context.expires_at == 100.0 + 86400
+ assert context.is_expired is False
+
+ request = BatchRequestContext(
+ custom_id="req-1",
+ messages=[{"role": "user", "content": "hello"}],
+ tools=[{"name": "tool"}],
+ model="gpt-4o",
+ system_instruction="system",
+ extras={"x": 1},
+ )
+ context.add_request(request)
+ assert context.get_request("req-1") is request
+ assert context.get_request("missing") is None
+
+ monkeypatch.setattr("headroom.ccr.batch_store.time.time", lambda: context.expires_at + 1)
+ assert context.is_expired is True
+
+
+async def test_batch_context_store_core_operations(monkeypatch) -> None:
+ now = {"value": 100.0}
+ monkeypatch.setattr("headroom.ccr.batch_store.time.time", lambda: now["value"])
+
+ store = BatchContextStore(ttl=10, max_contexts=2)
+ first = BatchContext(batch_id="b1", provider="anthropic")
+ second = BatchContext(batch_id="b2", provider="google")
+ third = BatchContext(batch_id="b3", provider="openai")
+
+ await store.store(first)
+ now["value"] = 101.0
+ await store.store(second)
+ assert (await store.get("b1")) is first
+
+ now["value"] = 102.0
+ await store.store(third)
+ assert await store.get("b1") is None
+ assert await store.get("b2") is second
+ assert await store.get("b3") is third
+
+ assert await store.remove("b2") is True
+ assert await store.remove("b2") is False
+
+
+async def test_batch_context_store_cleanup_stats_and_memory_stats(monkeypatch) -> None:
+ now = {"value": 200.0}
+ monkeypatch.setattr("headroom.ccr.batch_store.time.time", lambda: now["value"])
+ store = BatchContextStore(ttl=5, max_contexts=10)
+
+ first = BatchContext(batch_id="b1", provider="anthropic")
+ first.add_request(
+ BatchRequestContext(custom_id="r1", messages=[{"content": "alpha"}], tools=[])
+ )
+ second = BatchContext(batch_id="b2", provider="google")
+ second.add_request(
+ BatchRequestContext(custom_id="r2", messages=[{"content": ["nested"]}], tools=[{}])
+ )
+
+ await store.store(first)
+ await store.store(second)
+ assert await store.stats() == {
+ "total_contexts": 2,
+ "max_contexts": 10,
+ "ttl_seconds": 5,
+ "providers": {"anthropic": 1, "google": 1},
+ }
+
+ now["value"] = 210.0
+ assert await store.cleanup_expired() == 2
+ assert (await store.stats())["total_contexts"] == 0
+
+ @dataclass
+ class FakeComponentStats:
+ name: str
+ entry_count: int
+ size_bytes: int
+ budget_bytes: int | None
+ hits: int
+ misses: int
+ evictions: int
+
+ monkeypatch.setitem(
+ sys.modules,
+ "headroom.memory.tracker",
+ type("TrackerModule", (), {"ComponentStats": FakeComponentStats}),
+ )
+
+ now["value"] = 220.0
+ third = BatchContext(batch_id="b3", provider="openai")
+ third.add_request(
+ BatchRequestContext(
+ custom_id="r3", messages=[{"content": "payload"}], tools=[{"name": "t"}]
+ )
+ )
+ await store.store(third)
+ stats = store.get_memory_stats()
+ assert stats.name == "batch_context_store"
+ assert stats.entry_count == 1
+ assert stats.size_bytes > 0
+
+
+def test_global_batch_context_store_reset() -> None:
+ reset_batch_context_store()
+ store_one = get_batch_context_store()
+ store_two = get_batch_context_store()
+ assert store_one is store_two
+
+ reset_batch_context_store()
+ store_three = get_batch_context_store()
+ assert store_three is not store_one
diff --git a/tests/test_ccr_response_handler_extra.py b/tests/test_ccr_response_handler_extra.py
new file mode 100644
index 000000000..9a8e9a0a3
--- /dev/null
+++ b/tests/test_ccr_response_handler_extra.py
@@ -0,0 +1,372 @@
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import pytest
+
+from headroom.ccr.response_handler import (
+ CCRResponseHandler,
+ CCRToolCall,
+ CCRToolResult,
+ StreamingCCRBuffer,
+ StreamingCCRHandler,
+)
+from headroom.ccr.tool_injection import CCR_TOOL_NAME
+
+
+class FakeStore:
+ def __init__(
+ self, *, search_error: Exception | None = None, retrieve_error: Exception | None = None
+ ) -> None:
+ self.search_error = search_error
+ self.retrieve_error = retrieve_error
+
+ def search(self, hash_key: str, query: str) -> list[dict[str, str]]:
+ if self.search_error:
+ raise self.search_error
+ return [{"id": "1", "text": query}]
+
+ def retrieve(self, hash_key: str):
+ if self.retrieve_error:
+ raise self.retrieve_error
+ return {"unexpected": True}
+
+
+async def _async_iter(items: list[bytes]):
+ for item in items:
+ yield item
+
+
+def test_extract_tool_calls_google_and_invalid_shapes() -> None:
+ handler = CCRResponseHandler()
+ google_response = {
+ "candidates": [
+ {
+ "content": {
+ "parts": [
+ {"text": "hello"},
+ {"functionCall": {"name": CCR_TOOL_NAME, "args": {"hash": "abc"}}},
+ ]
+ }
+ }
+ ]
+ }
+ assert handler._extract_tool_calls(google_response, "google") == [
+ {"functionCall": {"name": CCR_TOOL_NAME, "args": {"hash": "abc"}}}
+ ]
+ assert handler._extract_tool_calls({"content": "bad"}, "anthropic") == []
+ with pytest.raises(IndexError):
+ handler._extract_tool_calls({"choices": []}, "openai")
+ assert handler._extract_tool_calls({"candidates": []}, "google") == []
+
+
+def test_parse_ccr_tool_calls_google_and_other_calls() -> None:
+ handler = CCRResponseHandler()
+ response = {
+ "candidates": [
+ {
+ "content": {
+ "parts": [
+ {
+ "functionCall": {
+ "name": CCR_TOOL_NAME,
+ "args": {
+ "hash": "aaaaaaaaaaaaaaaaaaaaaaaa",
+ "query": "pizza",
+ },
+ }
+ },
+ {"functionCall": {"name": "other_tool", "args": {}}},
+ ]
+ }
+ }
+ ]
+ }
+ ccr_calls, other_calls = handler._parse_ccr_tool_calls(response, "google")
+ assert ccr_calls == [
+ CCRToolCall(
+ tool_call_id=CCR_TOOL_NAME,
+ hash_key="aaaaaaaaaaaaaaaaaaaaaaaa",
+ query="pizza",
+ )
+ ]
+ assert other_calls == [{"functionCall": {"name": "other_tool", "args": {}}}]
+
+
+def test_execute_retrieval_error_paths(monkeypatch: pytest.MonkeyPatch) -> None:
+ handler = CCRResponseHandler()
+ monkeypatch.setattr(
+ "headroom.ccr.response_handler.get_compression_store",
+ lambda: FakeStore(search_error=RuntimeError("search boom")),
+ )
+ search_result = handler._execute_retrieval(
+ CCRToolCall(tool_call_id="t1", hash_key="abc", query="find")
+ )
+ assert search_result.success is False
+ assert "Retrieval failed: search boom" in search_result.content
+
+ monkeypatch.setattr(
+ "headroom.ccr.response_handler.get_compression_store",
+ lambda: FakeStore(retrieve_error=RuntimeError("retrieve boom")),
+ )
+ retrieve_result = handler._execute_retrieval(CCRToolCall(tool_call_id="t2", hash_key="abc"))
+ assert retrieve_result.success is False
+ assert "Retrieval failed: retrieve boom" in retrieve_result.content
+
+
+def test_create_tool_result_message_google_and_generic_formats() -> None:
+ handler = CCRResponseHandler()
+ results = [
+ CCRToolResult(tool_call_id="headroom_retrieve", content='{"count": 1}', success=True)
+ ]
+ google_message = handler._create_tool_result_message(results, "google")
+ assert google_message == {
+ "role": "user",
+ "parts": [{"functionResponse": {"name": "headroom_retrieve", "response": {"count": 1}}}],
+ }
+
+ generic_message = handler._create_tool_result_message(
+ [CCRToolResult(tool_call_id="tool-1", content="not-json", success=False)],
+ "other",
+ )
+ assert generic_message["role"] == "tool"
+ assert json.loads(generic_message["content"]) == [
+ {"tool_call_id": "tool-1", "result": "not-json"}
+ ]
+
+ invalid_google = handler._create_tool_result_message(
+ [CCRToolResult(tool_call_id="headroom_retrieve", content="not-json", success=True)],
+ "google",
+ )
+ assert invalid_google["parts"][0]["functionResponse"]["response"] == {"content": "not-json"}
+
+
+def test_extract_assistant_message_google_and_generic() -> None:
+ handler = CCRResponseHandler()
+ google_message = handler._extract_assistant_message(
+ {"candidates": [{"content": {"parts": [{"text": "hello"}]}}]},
+ "google",
+ )
+ assert google_message == {"role": "model", "parts": [{"text": "hello"}]}
+
+ assert handler._extract_assistant_message({}, "google") == {"role": "model", "parts": []}
+ assert handler._extract_assistant_message({"content": "plain"}, "other") == {
+ "role": "assistant",
+ "content": "plain",
+ }
+
+
+async def test_handle_response_openai_success_and_failure(monkeypatch: pytest.MonkeyPatch) -> None:
+ handler = CCRResponseHandler()
+ initial_response = {
+ "choices": [
+ {
+ "message": {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {
+ "name": CCR_TOOL_NAME,
+ "arguments": '{"hash":"aaaaaaaaaaaaaaaaaaaaaaaa"}',
+ },
+ }
+ ],
+ }
+ }
+ ]
+ }
+ monkeypatch.setattr(
+ handler,
+ "_execute_retrieval",
+ lambda call: CCRToolResult(
+ tool_call_id=call.tool_call_id,
+ content='{"hash":"aaaaaaaaaaaaaaaaaaaaaaaa"}',
+ success=True,
+ ),
+ )
+
+ captured_messages: list[list[dict[str, Any]]] = []
+
+ async def success_api_call(messages, tools):
+ captured_messages.append(messages)
+ return {"choices": [{"message": {"role": "assistant", "content": "done"}}]}
+
+ result = await handler.handle_response(
+ initial_response, [{"role": "user", "content": "hi"}], [], success_api_call, "openai"
+ )
+ assert result == {"choices": [{"message": {"role": "assistant", "content": "done"}}]}
+ assert captured_messages[0][1]["role"] == "assistant"
+ assert captured_messages[0][2]["role"] == "tool"
+ assert handler.get_stats()["total_retrievals"] == 1
+
+ async def failing_api_call(messages, tools):
+ raise RuntimeError("continuation failed")
+
+ failed = await handler.handle_response(initial_response, [], [], failing_api_call, "openai")
+ assert failed == initial_response
+
+
+def test_streaming_buffer_and_parse_sse_helpers() -> None:
+ buffer = StreamingCCRBuffer()
+ assert buffer.add_chunk(b"plain") is False
+ assert buffer.get_accumulated() == b"plain"
+
+ handler = StreamingCCRHandler(CCRResponseHandler(), provider="anthropic")
+ anthropic_data = b"\n".join(
+ [
+ b'data: {"type":"content_block_start","content_block":{"type":"text","text":"Hel"}}',
+ b'data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"lo"}}',
+ b'data: {"type":"content_block_stop"}',
+ b'data: {"type":"content_block_start","content_block":{"type":"tool_use","id":"tool_1","name":"headroom_retrieve"}}',
+ b'data: {"type":"content_block_delta","delta":{"type":"input_json_delta","partial_json":"{\\"hash\\":\\"abc\\"}"}}',
+ b'data: {"type":"content_block_stop"}',
+ b'data: {"type":"message_delta","delta":{"stop_reason":"tool_use"}}',
+ b"data: [DONE]",
+ ]
+ )
+ parsed = handler._parse_sse_stream(anthropic_data)
+ assert parsed["content"][0] == {"type": "text", "text": "Hello"}
+ assert parsed["content"][1]["name"] == "headroom_retrieve"
+ assert parsed["content"][1]["input"] == {"hash": "abc"}
+ assert parsed["stop_reason"] == "tool_use"
+
+ openai_handler = StreamingCCRHandler(CCRResponseHandler(), provider="openai")
+ parsed_openai = openai_handler._reconstruct_openai_response(
+ [
+ {"choices": [{"delta": {"content": "Hi"}}]},
+ {
+ "choices": [
+ {
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_1",
+ "function": {
+ "name": "headroom_retrieve",
+ "arguments": '{"hash":"aaaaaaaaaaaa',
+ },
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "choices": [
+ {
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "function": {"arguments": 'aaaaaaaaaaaa"}'},
+ }
+ ]
+ }
+ }
+ ]
+ },
+ ]
+ )
+ message = parsed_openai["choices"][0]["message"]
+ assert message["content"] == "Hi"
+ assert message["tool_calls"][0]["id"] == "call_1"
+ assert message["tool_calls"][0]["function"]["arguments"] == (
+ '{"hash":"aaaaaaaaaaaaaaaaaaaaaaaa"}'
+ )
+
+
+async def test_streaming_handler_process_stream_pass_through_and_ccr(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ response_handler = CCRResponseHandler()
+ handler = StreamingCCRHandler(response_handler, provider="anthropic")
+
+ passthrough_chunks = [
+ b'data: {"type":"content_block_delta","delta":{"text":"hello"}}',
+ b'data: {"stop_reason":"end_turn"}',
+ ]
+ yielded = [
+ chunk
+ async for chunk in handler.process_stream(
+ _async_iter(passthrough_chunks), [], None, lambda m, t: None
+ )
+ ]
+ assert yielded == passthrough_chunks
+
+ ccr_handler = StreamingCCRHandler(response_handler, provider="anthropic")
+ monkeypatch.setattr(
+ ccr_handler,
+ "_parse_sse_stream",
+ lambda data: {
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "tool_1",
+ "name": CCR_TOOL_NAME,
+ "input": {"hash": "abc"},
+ }
+ ]
+ },
+ )
+
+ async def fake_handle_response(response, messages, tools, api_call_fn, provider): # noqa: ANN001
+ return {"content": [{"type": "text", "text": "done"}]}
+
+ async def fake_response_to_sse(response): # noqa: ANN001
+ yield b"event: message_start\n"
+ yield b"event: message_stop\n"
+
+ monkeypatch.setattr(response_handler, "handle_response", fake_handle_response)
+ monkeypatch.setattr(ccr_handler, "_response_to_sse", fake_response_to_sse)
+
+ ccr_chunks = [
+ b'{"type":"tool_use","name":"headroom_retrieve"',
+ b',"stop_reason":"tool_use"}',
+ b"tail",
+ ]
+ streamed = [
+ chunk
+ async for chunk in ccr_handler.process_stream(
+ _async_iter(ccr_chunks), [], None, lambda m, t: None
+ )
+ ]
+ assert streamed == [b"event: message_start\n", b"event: message_stop\n"]
+
+
+async def test_streaming_handler_falls_back_to_buffer_on_processing_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ response_handler = CCRResponseHandler()
+ handler = StreamingCCRHandler(response_handler, provider="openai")
+ monkeypatch.setattr(
+ handler,
+ "_parse_sse_stream",
+ lambda data: (_ for _ in ()).throw(RuntimeError("parse failed")),
+ )
+
+ chunks = [b'{"type":"tool_use","name":"headroom_retrieve"', b',"stop_reason":"tool_use"}']
+ streamed = [
+ chunk
+ async for chunk in handler.process_stream(_async_iter(chunks), [], None, lambda m, t: None)
+ ]
+ assert streamed == [b"".join(chunks)]
+
+
+async def test_response_to_sse_formats() -> None:
+ anthropic = StreamingCCRHandler(CCRResponseHandler(), provider="anthropic")
+ anthropic_chunks = [chunk async for chunk in anthropic._response_to_sse({"content": []})]
+ assert anthropic_chunks[0] == b"event: message_start\n"
+ assert anthropic_chunks[-1] == b'data: {"type": "message_stop"}\n\n'
+
+ openai = StreamingCCRHandler(CCRResponseHandler(), provider="openai")
+ openai_chunks = [chunk async for chunk in openai._response_to_sse({"choices": []})]
+ assert openai_chunks == [b'data: {"choices": []}\n\n', b"data: [DONE]\n\n"]
diff --git a/tests/test_cli_learn.py b/tests/test_cli_learn.py
new file mode 100644
index 000000000..875a44540
--- /dev/null
+++ b/tests/test_cli_learn.py
@@ -0,0 +1,266 @@
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import click
+import click.shell_completion as click_shell_completion
+import pytest
+from click.testing import CliRunner
+
+from headroom.cli.learn import _AgentChoice
+from headroom.cli.main import main
+
+
+def runner() -> CliRunner:
+ return CliRunner()
+
+
+class FakeWriter:
+ def __init__(self) -> None:
+ self.calls: list[tuple[list[object], object, bool]] = []
+
+ def write(self, recommendations, project, dry_run: bool): # noqa: ANN001, ANN201
+ self.calls.append((recommendations, project, dry_run))
+ return SimpleNamespace(
+ dry_run=dry_run,
+ content_by_file={
+ Path(project.project_path) / "AGENTS.md": "<!-- headroom -->\nRule 1\nRule 2"
+ },
+ )
+
+
+class FakePlugin:
+ def __init__(self, name: str, display_name: str, projects: list[object]) -> None:
+ self.name = name
+ self.display_name = display_name
+ self._projects = projects
+ self.writer = FakeWriter()
+ self.scan_calls: list[tuple[object, int]] = []
+
+ def detect(self) -> bool:
+ return True
+
+ def create_writer(self) -> FakeWriter:
+ return self.writer
+
+ def discover_projects(self) -> list[object]:
+ return self._projects
+
+ def scan_project(self, project, max_workers: int = 1): # noqa: ANN001, ANN201
+ self.scan_calls.append((project, max_workers))
+ return [SimpleNamespace(events=["event"], tool_calls=[], failure_count=0)]
+
+
+class FakeAnalyzer:
+ def __init__(self, model: str | None = None) -> None:
+ self.model = model
+ self.calls: list[tuple[object, list[object]]] = []
+
+ def analyze(self, project, sessions): # noqa: ANN001, ANN201
+ self.calls.append((project, sessions))
+ return SimpleNamespace(
+ total_sessions=len(sessions),
+ total_calls=3,
+ total_failures=1,
+ failure_rate=1 / 3,
+ recommendations=[SimpleNamespace(section="Rules")],
+ )
+
+
+def test_agent_choice_convert_and_shell_complete(monkeypatch: pytest.MonkeyPatch) -> None:
+ choice = _AgentChoice()
+ monkeypatch.setattr(click, "shell_completion", click_shell_completion)
+ monkeypatch.setattr(
+ "headroom.learn.registry.get_registry",
+ lambda: {"codex": object(), "claude": object()},
+ )
+ monkeypatch.setattr(
+ "headroom.learn.registry.available_agent_names",
+ lambda: ["claude", "codex"],
+ )
+
+ assert choice.convert("auto", None, None) == "auto"
+ assert choice.convert("CODEX", None, None) == "codex"
+ with pytest.raises(Exception, match="Unknown agent: bad"):
+ choice.convert("bad", None, None)
+
+ completions = choice.shell_complete(None, None, "c") # type: ignore[arg-type]
+ assert [item.value for item in completions] == ["claude", "codex"]
+ assert choice.get_metavar(None) == "[auto|<agent>]" # type: ignore[arg-type]
+
+
+def test_learn_exits_cleanly_when_model_detection_fails(
+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner
+) -> None:
+ monkeypatch.setattr(
+ "headroom.learn.analyzer._detect_default_model",
+ lambda: (_ for _ in ()).throw(RuntimeError("no model")),
+ )
+
+ result = runner.invoke(main, ["learn"], catch_exceptions=False)
+
+ assert result.exit_code == 1
+ assert "Error: no model" in result.output
+
+
+def test_learn_auto_agent_reports_no_detected_plugins(
+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner
+) -> None:
+ monkeypatch.setattr("headroom.learn.analyzer._detect_default_model", lambda: "gpt-4o")
+ monkeypatch.setattr("headroom.learn.registry.auto_detect_plugins", lambda: [])
+ monkeypatch.setattr("headroom.learn.analyzer.SessionAnalyzer", FakeAnalyzer)
+
+ result = runner.invoke(main, ["learn"], catch_exceptions=False)
+
+ assert result.exit_code == 0
+ assert "No coding agent data found." in result.output
+
+
+def test_learn_single_agent_shows_available_projects_when_cwd_missing(
+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner, tmp_path: Path
+) -> None:
+ project = SimpleNamespace(name="demo", project_path=tmp_path / "demo")
+ plugin = FakePlugin("codex", "Codex", [project])
+
+ monkeypatch.setattr("headroom.learn.analyzer._detect_default_model", lambda: "gpt-4o")
+ monkeypatch.setattr("headroom.learn.registry.get_plugin", lambda name: plugin)
+ monkeypatch.setattr("headroom.learn.analyzer.SessionAnalyzer", FakeAnalyzer)
+
+ with runner.isolated_filesystem(temp_dir=tmp_path):
+ result = runner.invoke(main, ["learn", "--agent", "codex"], catch_exceptions=False)
+
+ assert result.exit_code == 0
+ assert "No codex project data found for" in result.output
+ assert "Available codex projects:" in result.output
+ assert "demo" in result.output
+
+
+def test_learn_project_lookup_and_apply_flow(
+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner, tmp_path: Path
+) -> None:
+ project_path = tmp_path / "project-a"
+ project_path.mkdir()
+ matched = SimpleNamespace(name="project-a", project_path=project_path)
+ unmatched = SimpleNamespace(name="project-b", project_path=tmp_path / "project-b")
+ plugin = FakePlugin("codex", "Codex", [matched, unmatched])
+ analyzer = FakeAnalyzer()
+
+ monkeypatch.setattr("headroom.learn.analyzer._detect_default_model", lambda: "gpt-4o")
+ monkeypatch.setattr("headroom.learn.registry.get_plugin", lambda name: plugin)
+ monkeypatch.setattr("headroom.learn.analyzer.SessionAnalyzer", lambda model=None: analyzer)
+
+ result = runner.invoke(
+ main,
+ ["learn", "--agent", "codex", "--project", str(project_path), "--apply", "--workers", "4"],
+ catch_exceptions=False,
+ )
+
+ assert result.exit_code == 0, result.output
+ assert "Path: " in result.output
+ assert "Analyzing with gpt-4o..." in result.output
+ assert "Recommendations: 1" in result.output
+ assert "[WROTE]" in result.output
+ assert "Rule 1" in result.output
+ assert plugin.scan_calls == [(matched, 4)]
+ assert analyzer.calls[0][0] is matched
+ assert plugin.writer.calls[0][2] is False
+
+
+def test_learn_reports_missing_requested_project_and_lists_discovered(
+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner, tmp_path: Path
+) -> None:
+ requested = tmp_path / "missing"
+ requested.mkdir()
+ discovered = SimpleNamespace(name="project-a", project_path=tmp_path / "project-a")
+ plugin = FakePlugin("claude", "Claude Code", [discovered])
+
+ monkeypatch.setattr("headroom.learn.analyzer._detect_default_model", lambda: "gpt-4o")
+ monkeypatch.setattr("headroom.learn.registry.get_plugin", lambda name: plugin)
+ monkeypatch.setattr("headroom.learn.analyzer.SessionAnalyzer", FakeAnalyzer)
+
+ result = runner.invoke(
+ main,
+ ["learn", "--agent", "claude", "--project", str(requested)],
+ catch_exceptions=False,
+ )
+
+ assert result.exit_code == 0
+ assert f"No project data found for {requested.resolve()}" in result.output
+ assert "Available discovered projects:" in result.output
+ assert "[claude]" in result.output
+
+
+def test_learn_analyze_all_uses_default_workers_and_prints_summary(
+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner, tmp_path: Path
+) -> None:
+ projects_a = [SimpleNamespace(name="a", project_path=tmp_path / "a")]
+ projects_b = [SimpleNamespace(name="b", project_path=tmp_path / "b")]
+ plugin_a = FakePlugin("codex", "Codex", projects_a)
+ plugin_b = FakePlugin("claude", "Claude Code", projects_b)
+ analyzer = FakeAnalyzer()
+
+ monkeypatch.setattr("headroom.learn.analyzer._detect_default_model", lambda: "gpt-4o")
+ monkeypatch.setattr(
+ "headroom.learn.registry.auto_detect_plugins",
+ lambda: [plugin_a, plugin_b],
+ )
+ monkeypatch.setattr("headroom.learn.analyzer.SessionAnalyzer", lambda model=None: analyzer)
+ monkeypatch.setattr("os.cpu_count", lambda: 12)
+
+ result = runner.invoke(main, ["learn", "--all"], catch_exceptions=False)
+
+ assert result.exit_code == 0, result.output
+ assert "Detected agents: Codex, Claude Code" in result.output
+ assert "Total: 2 projects, 2 failures, 2 recommendations" in result.output
+ assert plugin_a.scan_calls == [(projects_a[0], 8)]
+ assert plugin_b.scan_calls == [(projects_b[0], 8)]
+
+
+def test_learn_handles_empty_sessions_and_no_pattern_outputs(
+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner, tmp_path: Path
+) -> None:
+ no_sessions = SimpleNamespace(name="empty", project_path=tmp_path / "empty")
+ no_failures = SimpleNamespace(name="clean", project_path=tmp_path / "clean")
+ no_actions = SimpleNamespace(name="no-actions", project_path=tmp_path / "no-actions")
+
+ class BranchingPlugin(FakePlugin):
+ def scan_project(self, project, max_workers: int = 1): # noqa: ANN001, ANN201
+ self.scan_calls.append((project, max_workers))
+ if project is no_sessions:
+ return []
+ return [SimpleNamespace(events=["event"], tool_calls=[], failure_count=0)]
+
+ class BranchingAnalyzer(FakeAnalyzer):
+ def analyze(self, project, sessions): # noqa: ANN001, ANN201
+ self.calls.append((project, sessions))
+ if project is no_failures:
+ return SimpleNamespace(
+ total_sessions=1,
+ total_calls=2,
+ total_failures=0,
+ failure_rate=0.0,
+ recommendations=[],
+ )
+ return SimpleNamespace(
+ total_sessions=1,
+ total_calls=2,
+ total_failures=1,
+ failure_rate=0.5,
+ recommendations=[],
+ )
+
+ plugin = BranchingPlugin("codex", "Codex", [no_sessions, no_failures, no_actions])
+ analyzer = BranchingAnalyzer()
+
+ monkeypatch.setattr("headroom.learn.analyzer._detect_default_model", lambda: "gpt-4o")
+ monkeypatch.setattr("headroom.learn.registry.get_plugin", lambda name: plugin)
+ monkeypatch.setattr("headroom.learn.analyzer.SessionAnalyzer", lambda model=None: analyzer)
+
+ result = runner.invoke(main, ["learn", "--agent", "codex", "--all"], catch_exceptions=False)
+
+ assert result.exit_code == 0, result.output
+ assert "No conversation data found." in result.output
+ assert "No failures or patterns found." in result.output
+ assert "No actionable patterns found." in result.output
diff --git a/tests/test_cli_tools.py b/tests/test_cli_tools.py
new file mode 100644
index 000000000..f74afd13b
--- /dev/null
+++ b/tests/test_cli_tools.py
@@ -0,0 +1,266 @@
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from click.testing import CliRunner
+
+from headroom import binaries
+from headroom.cli import tools as cli_tools
+from headroom.cli.main import main
+
+
+def runner() -> CliRunner:
+ return CliRunner()
+
+
+class FakeTable:
+ def __init__(self, **kwargs) -> None: # noqa: ANN003
+ self.columns: list[str] = []
+ self.rows: list[tuple[object, ...]] = []
+
+ def add_column(self, name: str) -> None:
+ self.columns.append(name)
+
+ def add_row(self, *values: object) -> None:
+ self.rows.append(values)
+
+
+class FakeConsole:
+ instances: list[FakeConsole] = []
+
+ def __init__(self) -> None:
+ self.printed: list[object] = []
+ FakeConsole.instances.append(self)
+
+ def print(self, value: object) -> None:
+ self.printed.append(value)
+
+
+def install_fake_rich(monkeypatch: pytest.MonkeyPatch) -> None:
+ FakeConsole.instances.clear()
+ monkeypatch.setitem(sys.modules, "rich.console", SimpleNamespace(Console=FakeConsole))
+ monkeypatch.setitem(sys.modules, "rich.table", SimpleNamespace(Table=FakeTable))
+ monkeypatch.setitem(
+ sys.modules, "rich.markup", SimpleNamespace(escape=lambda value: f"escaped:{value}")
+ )
+
+
+def test_exec_tool_windows_and_posix_paths(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(cli_tools.binaries, "resolve", lambda tool: Path("C:\\bin\\sg.exe"))
+ monkeypatch.setattr(cli_tools.os, "name", "nt", raising=False)
+ captured: dict[str, object] = {}
+
+ def fake_run(cmd, check=False): # noqa: ANN001
+ captured["cmd"] = cmd
+ return SimpleNamespace(returncode=7)
+
+ monkeypatch.setattr(cli_tools.subprocess, "run", fake_run)
+ with pytest.raises(SystemExit) as excinfo:
+ cli_tools._exec_tool("ast-grep", ["--json"])
+ assert excinfo.value.code == 7
+ assert captured["cmd"] == ["C:\\bin\\sg.exe", "--json"]
+
+ monkeypatch.setattr(cli_tools.os, "name", "posix", raising=False)
+
+ def fake_execv(path: str, cmd: list[str]) -> None:
+ raise SystemExit((path, cmd))
+
+ monkeypatch.setattr(cli_tools.os, "execv", fake_execv)
+ with pytest.raises(SystemExit) as posix_exit:
+ cli_tools._exec_tool("ast-grep", ["--help"])
+ assert posix_exit.value.code == (str(Path("C:\\bin\\sg.exe")), ["C:\\bin\\sg.exe", "--help"])
+
+
+ ("error", "expected"),
+ [
+ (binaries.PlatformNotSupported("unsupported"), "error: unsupported"),
+ (binaries.OfflineError("offline"), "Hint: run `headroom tools install`"),
+ (binaries.Sha256Mismatch("bad sha"), "error: bad sha"),
+ (binaries.BinaryFetchError("fetch failed"), "error: fetch failed"),
+ ],
+)
+def test_sg_command_reports_resolution_errors(
+ monkeypatch: pytest.MonkeyPatch,
+ runner: CliRunner,
+ error: Exception,
+ expected: str,
+) -> None:
+ monkeypatch.setattr(cli_tools.binaries, "resolve", lambda tool: (_ for _ in ()).throw(error))
+ result = runner.invoke(main, ["sg", "--version"])
+ assert result.exit_code == 2
+ assert expected in result.output
+
+
+def test_tools_list_renders_registry(monkeypatch: pytest.MonkeyPatch, runner: CliRunner) -> None:
+ install_fake_rich(monkeypatch)
+ monkeypatch.setattr(
+ cli_tools.binaries,
+ "detect_platform",
+ lambda: SimpleNamespace(key=lambda: "windows-x86_64"),
+ )
+ monkeypatch.setattr(cli_tools.binaries, "cache_dir", lambda: Path("C:\\cache"))
+ monkeypatch.setattr(
+ cli_tools.binaries,
+ "_registry",
+ lambda: {
+ "tools": {
+ "ast-grep": {
+ "version": "1.2.3",
+ "source": "github",
+ "assets": {"windows-x86_64": {}, "linux-x86_64-gnu": {}},
+ },
+ "python-tool": {"version": "0.1.0", "source": "pypi", "assets": {}},
+ }
+ },
+ )
+
+ result = runner.invoke(main, ["tools", "list"])
+ assert result.exit_code == 0
+ console = FakeConsole.instances[-1]
+ assert console.printed[0] == "[dim]platform:[/dim] windows-x86_64"
+ assert console.printed[1] == "[dim]cache:[/dim] C:\\cache"
+ table = console.printed[2]
+ assert isinstance(table, FakeTable)
+ assert ("ast-grep", "1.2.3", "github", "linux-x86_64-gnu, windows-x86_64") in table.rows
+ assert ("python-tool", "0.1.0", "pypi", "(pypi)") in table.rows
+
+
+def test_tools_doctor_json_and_table_modes(
+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner
+) -> None:
+ rows = [
+ {
+ "tool": "ast-grep",
+ "state": "cached",
+ "version": "1.0",
+ "platform": "win",
+ "path": "C:\\bin\\sg.exe",
+ },
+ {
+ "tool": "difft",
+ "state": "missing",
+ "version": "2.0",
+ "platform": "win",
+ "path": None,
+ "detail": "download needed <soon>",
+ },
+ ]
+ monkeypatch.setattr(cli_tools.binaries, "status", lambda: rows)
+
+ json_result = runner.invoke(main, ["tools", "doctor", "--json"])
+ assert json_result.exit_code == 1
+ assert '"tool": "ast-grep"' in json_result.output
+ assert '"state": "missing"' in json_result.output
+
+ install_fake_rich(monkeypatch)
+ table_result = runner.invoke(main, ["tools", "doctor"])
+ assert table_result.exit_code == 1
+ console = FakeConsole.instances[-1]
+ table = console.printed[0]
+ assert isinstance(table, FakeTable)
+ assert ("ast-grep", "[green]cached[/green]", "1.0", "win", "C:\\bin\\sg.exe") in table.rows
+ assert ("difft", "[yellow]missing[/yellow]", "2.0", "win", "-") in table.rows
+ assert console.printed[1] == "[dim]difft:[/dim] escaped:download needed <soon>"
+
+
+def test_tools_install_covers_unknown_pypi_force_and_failures(
+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner, tmp_path: Path
+) -> None:
+ cached_path = tmp_path / "cached-tool.exe"
+ cached_path.write_text("x", encoding="utf-8")
+ monkeypatch.setattr(
+ cli_tools.binaries,
+ "_registry",
+ lambda: {
+ "tools": {
+ "known": {"version": "1.0"},
+ "pypi_tool": {"version": "2.0"},
+ "broken": {"version": "3.0"},
+ }
+ },
+ )
+ monkeypatch.setattr(cli_tools.binaries, "_is_pypi_tool", lambda name: name == "pypi_tool")
+ monkeypatch.setattr(
+ cli_tools.binaries,
+ "_path_lookup",
+ lambda name: Path("C:\\Python\\Scripts\\pypi_tool.exe") if name == "pypi_tool" else None,
+ )
+ monkeypatch.setattr(
+ cli_tools.binaries,
+ "detect_platform",
+ lambda: SimpleNamespace(key=lambda: "windows-x86_64"),
+ )
+ monkeypatch.setattr(cli_tools.binaries, "_cached_path", lambda name, version, plat: cached_path)
+ monkeypatch.setattr(
+ cli_tools.binaries,
+ "resolve",
+ lambda name: (_ for _ in ()).throw(binaries.OfflineError("offline"))
+ if name == "broken"
+ else Path(f"C:\\cache\\{name}.exe"),
+ )
+
+ result = runner.invoke(
+ main,
+ [
+ "tools",
+ "install",
+ "--tool",
+ "missing",
+ "--tool",
+ "pypi_tool",
+ "--tool",
+ "known",
+ "--tool",
+ "broken",
+ "--force",
+ ],
+ )
+
+ assert result.exit_code == 1
+ assert "unknown tool 'missing'; skipping" in result.output
+ assert "pypi_tool: on PATH at C:\\Python\\Scripts\\pypi_tool.exe (pypi wheel)" in result.output
+ assert "known: installed" in result.output
+ assert "broken: offline" in result.output
+ assert not cached_path.exists()
+
+
+def test_tools_install_reports_missing_pypi_and_cached_unlink_failure(
+ monkeypatch: pytest.MonkeyPatch, runner: CliRunner
+) -> None:
+ problem_path = Path("C:\\cache\\locked.exe")
+ monkeypatch.setattr(
+ cli_tools.binaries,
+ "_registry",
+ lambda: {"tools": {"pypi_tool": {"version": "1.0"}, "known": {"version": "2.0"}}},
+ )
+ monkeypatch.setattr(cli_tools.binaries, "_is_pypi_tool", lambda name: name == "pypi_tool")
+ monkeypatch.setattr(cli_tools.binaries, "_path_lookup", lambda name: None)
+ monkeypatch.setattr(
+ cli_tools.binaries,
+ "detect_platform",
+ lambda: SimpleNamespace(key=lambda: "windows-x86_64"),
+ )
+ monkeypatch.setattr(
+ cli_tools.binaries, "_cached_path", lambda name, version, plat: problem_path
+ )
+ monkeypatch.setattr(Path, "exists", lambda self: self == problem_path)
+
+ def fake_unlink(self) -> None:
+ raise OSError("locked")
+
+ monkeypatch.setattr(Path, "unlink", fake_unlink)
+ monkeypatch.setattr(cli_tools.binaries, "resolve", lambda name: Path(f"C:\\cache\\{name}.exe"))
+
+ result = runner.invoke(
+ main,
+ ["tools", "install", "--tool", "pypi_tool", "--tool", "known", "--force"],
+ )
+
+ assert result.exit_code == 1
+ assert "pypi_tool: not on PATH" in result.output
+ assert "known: failed to remove cached binary: locked" in result.output
diff --git a/tests/test_evals_datasets.py b/tests/test_evals_datasets.py
new file mode 100644
index 000000000..74dbfd849
--- /dev/null
+++ b/tests/test_evals_datasets.py
@@ -0,0 +1,538 @@
+from __future__ import annotations
+
+import json
+import sys
+import urllib.request
+from types import SimpleNamespace
+from urllib.error import URLError
+
+import pytest
+
+from headroom.evals import datasets
+
+
+def install_fake_datasets(
+ monkeypatch: pytest.MonkeyPatch,
+ mapping: dict[tuple[str, str | None, str | None], list[dict[str, object]]],
+) -> list[tuple[str, str | None, str | None]]:
+ calls: list[tuple[str, str | None, str | None]] = []
+
+ def fake_load_dataset(name: str, subset: str | None = None, split: str | None = None):
+ key = (name, subset, split)
+ calls.append(key)
+ return mapping[key]
+
+ monkeypatch.setitem(sys.modules, "datasets", SimpleNamespace(load_dataset=fake_load_dataset))
+ return calls
+
+
+def test_check_datasets_installed_errors_without_dependency(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delitem(sys.modules, "datasets", raising=False)
+
+ import builtins
+
+ real_import = builtins.__import__
+
+ def fake_import(name, globals=None, locals=None, fromlist=(), level=0): # noqa: ANN001
+ if name == "datasets":
+ raise ImportError("missing")
+ return real_import(name, globals, locals, fromlist, level)
+
+ monkeypatch.setattr(builtins, "__import__", fake_import)
+
+ with pytest.raises(ImportError, match="HuggingFace datasets required"):
+ datasets._check_datasets_installed()
+
+
+def test_load_hotpotqa_and_natural_questions(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls = install_fake_datasets(
+ monkeypatch,
+ {
+ ("hotpotqa/hotpot_qa", "fullwiki", "validation"): [
+ {
+ "context": {"title": ["Page A"], "sentences": [["Line 1", "Line 2"]]},
+ "question": "Who?",
+ "answer": "Alice",
+ "type": "bridge",
+ "level": "easy",
+ }
+ ],
+ ("google-research-datasets/natural_questions", "default", "validation"): [
+ {"document": {}, "question": {"text": "skip me"}},
+ {
+ "document": {
+ "tokens": {
+ "token": ["<p>", "Ada", "Lovelace", "wrote", "notes"],
+ "is_html": [True, False, False, False, False],
+ }
+ },
+ "question": {"text": "Who wrote notes?"},
+ "annotations": {"short_answers": [[{"start_token": 1, "end_token": 3}]]},
+ },
+ ],
+ },
+ )
+
+ hotpot = datasets.load_hotpotqa(n=1)
+ natural = datasets.load_natural_questions(n=1)
+
+ assert calls == [
+ ("hotpotqa/hotpot_qa", "fullwiki", "validation"),
+ ("google-research-datasets/natural_questions", "default", "validation"),
+ ]
+ assert hotpot.name == "HotpotQA"
+ assert hotpot.cases[0].context == "## Page A\nLine 1\nLine 2"
+ assert hotpot.cases[0].metadata["type"] == "bridge"
+ assert natural.name == "Natural_Questions"
+ assert natural.cases[0].context == "Ada Lovelace wrote notes"
+ assert natural.cases[0].ground_truth == "Ada Lovelace"
+
+
+def test_load_triviaqa_msmarco_and_squad(monkeypatch: pytest.MonkeyPatch) -> None:
+ install_fake_datasets(
+ monkeypatch,
+ {
+ ("trivia_qa", "rc", "validation"): [
+ {"question": "", "search_results": {"search_context": ["unused"]}},
+ {
+ "question": "Question 1",
+ "search_results": {"search_context": ["A", "B"]},
+ "answer": {"value": "Answer", "aliases": ["Alias"]},
+ },
+ {
+ "question": "Question 2",
+ "search_results": {"search_context": []},
+ "entity_pages": {"wiki_context": ["Wiki 1", "Wiki 2"]},
+ "answer": {"normalized_value": "Normalized"},
+ },
+ ],
+ ("microsoft/ms_marco", "v2.1", "validation"): [
+ {"query": "", "passages": {"passage_text": ["skip"], "is_selected": [True]}},
+ {
+ "query": "Find docs",
+ "passages": {"passage_text": ["Doc 1", "Doc 2"], "is_selected": [True, False]},
+ "answers": ["Primary answer"],
+ "query_type": "description",
+ },
+ ],
+ ("rajpurkar/squad_v2", None, "validation"): [
+ {"answers": {"text": []}, "context": "skip", "question": "skip"},
+ {
+ "context": "Context",
+ "question": "Question",
+ "answers": {"text": ["First answer"]},
+ "title": "Title",
+ },
+ ],
+ },
+ )
+
+ trivia = datasets.load_triviaqa(n=2)
+ msmarco = datasets.load_msmarco(n=1)
+ squad = datasets.load_squad(n=1)
+
+ assert len(trivia.cases) == 2
+ assert trivia.cases[0].context == "A\n\nB"
+ assert trivia.cases[1].ground_truth == "Normalized"
+ assert trivia.cases[1].metadata["aliases"] == []
+ assert msmarco.cases[0].context.startswith("[RELEVANT] Passage 1: Doc 1")
+ assert msmarco.cases[0].metadata["num_passages"] == 2
+ assert squad.cases[0].ground_truth == "First answer"
+ assert squad.cases[0].metadata["title"] == "Title"
+
+
+def test_load_longbench_narrativeqa_toolbench_codesearchnet_and_humaneval(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ install_fake_datasets(
+ monkeypatch,
+ {
+ ("THUDM/LongBench", "qasper", "test"): [
+ {"context": "", "input": "skip"},
+ {"context": "Long context", "input": "Question", "answers": ["Truth"]},
+ ],
+ ("deepmind/narrativeqa", None, "test"): [
+ {
+ "document": {"summary": {"text": "Story summary"}, "kind": "movie"},
+ "question": {"text": "What happened?"},
+ "answers": [{"text": "A"}, {"text": "B"}],
+ }
+ ],
+ ("ToolBench/ToolBench", "G1", "test"): [
+ {"api_list": [], "query": "skip"},
+ {
+ "api_list": [
+ {
+ "api_name": "weather",
+ "api_description": "Get weather",
+ "required_parameters": [{"name": "city"}],
+ "optional_parameters": [{"name": "unit"}],
+ }
+ ],
+ "query": "Weather in SF?",
+ "answer": "Call weather",
+ },
+ ],
+ ("code_search_net", "python", "test"): [
+ {"func_code_string": "", "func_documentation_string": "skip"},
+ {
+ "func_code_string": "def add(a, b): return a + b",
+ "func_documentation_string": "Add two numbers.",
+ "func_name": "add",
+ "repository_name": "repo",
+ },
+ ],
+ ("openai_humaneval", None, "test"): [
+ {"prompt": "", "canonical_solution": "skip"},
+ {
+ "task_id": "HumanEval/1",
+ "prompt": "def solve(x):",
+ "canonical_solution": "return x",
+ "entry_point": "solve",
+ "test": "assert solve(1) == 1",
+ },
+ ],
+ },
+ )
+
+ longbench = datasets.load_longbench(n=2, task="qasper")
+ narrative = datasets.load_narrativeqa(n=1)
+ toolbench = datasets.load_toolbench(n=1, category="G1")
+ codesearchnet = datasets.load_codesearchnet(n=1, language="python")
+ humaneval = datasets.load_humaneval(n=2)
+
+ assert longbench.name == "LongBench_qasper"
+ assert longbench.cases[0].metadata["context_length"] == len("Long context")
+ assert narrative.cases[0].metadata["all_answers"] == ["A", "B"]
+ assert toolbench.cases[0].metadata["num_tools"] == 1
+ assert '"name": "weather"' in toolbench.cases[0].context
+ assert codesearchnet.cases[0].ground_truth == "Add two numbers."
+ assert humaneval.cases[0].id == "humaneval_HumanEval/1"
+ assert humaneval.cases[0].metadata["entry_point"] == "solve"
+
+
+def test_load_longbench_toolbench_and_codesearchnet_wrap_loader_errors(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def fake_load_dataset(name: str, subset: str | None = None, split: str | None = None): # noqa: ANN001
+ raise RuntimeError(f"broken {name}:{subset}:{split}")
+
+ monkeypatch.setitem(sys.modules, "datasets", SimpleNamespace(load_dataset=fake_load_dataset))
+
+ with pytest.raises(ValueError, match="Failed to load LongBench task 'gov_report'"):
+ datasets.load_longbench(task="gov_report")
+ with pytest.raises(ValueError, match="Failed to load ToolBench category 'G2'"):
+ datasets.load_toolbench(category="G2")
+ with pytest.raises(ValueError, match="Failed to load CodeSearchNet for 'go'"):
+ datasets.load_codesearchnet(language="go")
+
+
+def test_load_bfcl_success_and_download_failure(monkeypatch: pytest.MonkeyPatch) -> None:
+ data_lines = "\n".join(
+ [
+ json.dumps(
+ {
+ "id": "case-1",
+ "question": [[{"role": "user", "content": "How is the weather?"}]],
+ "function": [{"name": "weather"}],
+ }
+ ),
+ json.dumps({"question": [123], "function": []}),
+ ]
+ )
+ gt_lines = json.dumps({"id": "case-1", "ground_truth": [{"name": "weather"}]})
+
+ def fake_urlopen(url: str): # noqa: ANN001
+ if "possible_answer/BFCL_v3_simple.json" in url:
+ return SimpleNamespace(read=lambda: gt_lines.encode("utf-8"))
+ if "BFCL_v3_simple.json" in url:
+ return SimpleNamespace(read=lambda: data_lines.encode("utf-8"))
+ raise URLError("missing")
+
+ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)
+
+ suite = datasets.load_bfcl(n=2, category="simple")
+ assert suite.name == "BFCL_simple"
+ assert suite.cases[0].query == "How is the weather?"
+ assert suite.cases[0].ground_truth == '[{"name": "weather"}]'
+ assert suite.cases[0].metadata["num_functions"] == 1
+
+ def failing_urlopen(url: str): # noqa: ANN001
+ raise URLError("offline")
+
+ monkeypatch.setattr(urllib.request, "urlopen", failing_urlopen)
+ with pytest.raises(ValueError, match="Failed to download BFCL dataset 'BFCL_v3_parallel.json'"):
+ datasets.load_bfcl(category="parallel")
+
+
+def test_tool_output_samples_custom_dataset_and_probe_generation(tmp_path) -> None:
+ tool_outputs = datasets.load_tool_output_samples()
+ assert tool_outputs.name == "ToolOutputSamples"
+ assert len(tool_outputs.cases) >= 8
+ assert tool_outputs.cases[0].ground_truth == "prompt-optimizer"
+
+ custom_path = tmp_path / "custom.jsonl"
+ custom_path.write_text(
+ json.dumps(
+ {"id": "case1", "context": "Context", "query": "Question", "ground_truth": "Answer"}
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+ custom_suite = datasets.load_custom_dataset(custom_path)
+ assert custom_suite.cases[0].id == "case1"
+
+ probes = datasets.generate_retrieval_probes(
+ 'Alice Smith deployed API on 2024-01-15 at 99.9% confidence for "Launch Ready" and build_id',
+ n_probes=5,
+ )
+ assert "Alice Smith" in probes
+ assert "2024-01-15" in probes
+ assert "API" in probes
+ assert "99.9" in probes
+ assert "Launch Ready" in probes
+
+
+def test_dataset_registry_helpers(monkeypatch: pytest.MonkeyPatch) -> None:
+ categories = datasets.list_available_datasets()
+ assert "hotpotqa" in categories["rag"]
+ assert "tool_outputs" in categories["tool_use"]
+
+ seen: list[tuple[str, dict[str, object]]] = []
+
+ def fake_loader(*, n: int = 0, **kwargs): # noqa: ANN003
+ seen.append(("with-n", {"n": n, **kwargs}))
+ return "with-n-result"
+
+ def fixed_loader(**kwargs): # noqa: ANN003
+ seen.append(("fixed", kwargs))
+ return "fixed-result"
+
+ original_registry = dict(datasets.DATASET_REGISTRY)
+ monkeypatch.setattr(
+ datasets,
+ "DATASET_REGISTRY",
+ {
+ **original_registry,
+ "fake_n": {"loader": fake_loader, "category": "x", "description": "", "default_n": 3},
+ "fake_fixed": {
+ "loader": fixed_loader,
+ "category": "x",
+ "description": "",
+ "default_n": None,
+ },
+ },
+ )
+
+ assert datasets.load_dataset_by_name("fake_n") == "with-n-result"
+ assert datasets.load_dataset_by_name("fake_n", n=7, split="test") == "with-n-result"
+ assert datasets.load_dataset_by_name("fake_fixed", path="x") == "fixed-result"
+ assert seen == [
+ ("with-n", {"n": 3}),
+ ("with-n", {"n": 7, "split": "test"}),
+ ("fixed", {"path": "x"}),
+ ]
+
+ with pytest.raises(ValueError, match="Unknown dataset 'missing'"):
+ datasets.load_dataset_by_name("missing")
+
+
+def test_dataset_loaders_cover_skip_and_limit_branches(monkeypatch: pytest.MonkeyPatch) -> None:
+ install_fake_datasets(
+ monkeypatch,
+ {
+ ("hotpotqa/hotpot_qa", "fullwiki", "validation"): [
+ {
+ "context": {"title": ["Page A"], "sentences": [["Line 1"]]},
+ "question": "Q1",
+ "answer": "A1",
+ },
+ {
+ "context": {"title": ["Page B"], "sentences": [["Line 2"]]},
+ "question": "Q2",
+ "answer": "A2",
+ },
+ ],
+ ("google-research-datasets/natural_questions", "default", "validation"): [
+ {
+ "document": {"tokens": {"token": ["x"], "is_html": [False]}},
+ "question": {"text": ""},
+ },
+ {
+ "document": {"tokens": {"token": ["<b>"], "is_html": [True]}},
+ "question": {"text": "blank context"},
+ },
+ {
+ "document": {"tokens": {"token": ["Ada", "wrote"], "is_html": [False, False]}},
+ "question": {"text": "Who?"},
+ "annotations": {"short_answers": [[{"start_token": 1, "end_token": 1}]]},
+ },
+ {
+ "document": {"tokens": {"token": ["Grace"], "is_html": [False]}},
+ "question": {"text": "Ignored by limit"},
+ },
+ ],
+ ("trivia_qa", "rc", "validation"): [
+ {"question": "skip", "search_results": {"search_context": []}, "entity_pages": {}},
+ {"question": "blank", "search_results": {"search_context": [""]}},
+ {
+ "question": "Good 1",
+ "search_results": {"search_context": ["Context 1"]},
+ "answer": {"value": "A1"},
+ },
+ {
+ "question": "Good 2",
+ "search_results": {"search_context": ["Context 2"]},
+ "answer": {"value": "A2"},
+ },
+ ],
+ ("microsoft/ms_marco", "v2.1", "validation"): [
+ {"query": "skip", "passages": {"passage_text": [], "is_selected": []}},
+ {
+ "query": "Find one",
+ "passages": {"passage_text": ["Doc 1"], "is_selected": [False]},
+ "answers": [],
+ },
+ {
+ "query": "Find two",
+ "passages": {"passage_text": ["Doc 2"], "is_selected": [True]},
+ "answers": ["A2"],
+ },
+ ],
+ ("rajpurkar/squad_v2", None, "validation"): [
+ {
+ "context": "Context 1",
+ "question": "Q1",
+ "answers": {"text": ["A1"]},
+ },
+ {
+ "context": "Context 2",
+ "question": "Q2",
+ "answers": {"text": ["A2"]},
+ },
+ ],
+ ("THUDM/LongBench", "qasper", "test"): [
+ {"context": "Context 1", "input": "Q1", "answers": ["A1"]},
+ {"context": "Has context", "input": ""},
+ {"context": "Context 2", "input": "Q2", "answers": ["A2"]},
+ ],
+ ("deepmind/narrativeqa", None, "test"): [
+ {"document": {"summary": {"text": ""}}, "question": {"text": "skip"}},
+ {"document": {"summary": {"text": "Story"}}, "question": {"text": ""}},
+ {
+ "document": {"summary": {"text": "Story 1"}, "kind": "book"},
+ "question": {"text": "Q1"},
+ "answers": [{"text": "A1"}],
+ },
+ {
+ "document": {"summary": {"text": "Story 2"}, "kind": "movie"},
+ "question": {"text": "Q2"},
+ "answers": [{"text": "A2"}],
+ },
+ ],
+ ("ToolBench/ToolBench", "G1", "test"): [
+ {"api_list": [], "query": "skip"},
+ {
+ "api_list": [
+ {
+ "api_name": "weather",
+ "required_parameters": [],
+ "optional_parameters": [],
+ }
+ ],
+ "query": "",
+ },
+ {
+ "api_list": [
+ {"api_name": "calc", "required_parameters": [], "optional_parameters": []}
+ ],
+ "query": "Good",
+ },
+ ],
+ ("code_search_net", "python", "test"): [
+ {
+ "func_code_string": "",
+ "whole_func_string": "",
+ "func_documentation_string": "skip",
+ },
+ {"whole_func_string": "def alt(): pass", "func_documentation_string": ""},
+ {
+ "whole_func_string": "def good(): pass",
+ "func_documentation_string": "Good doc",
+ "func_name": "good",
+ "repository_name": "repo",
+ },
+ {
+ "whole_func_string": "def ignored(): pass",
+ "func_documentation_string": "Ignored by limit",
+ },
+ ],
+ ("openai_humaneval", None, "test"): [
+ {
+ "task_id": "Task/1",
+ "prompt": "def solve():",
+ "canonical_solution": "return 1",
+ "test": "assert solve() == 1",
+ },
+ {
+ "task_id": "Task/2",
+ "prompt": "def other():",
+ "canonical_solution": "return 2",
+ "test": "assert other() == 2",
+ },
+ ],
+ },
+ )
+
+ assert len(datasets.load_hotpotqa(n=1).cases) == 1
+ natural = datasets.load_natural_questions(n=1)
+ assert len(natural.cases) == 1
+ assert natural.cases[0].ground_truth is None
+ assert len(datasets.load_triviaqa(n=1).cases) == 1
+ msmarco = datasets.load_msmarco(n=1)
+ assert len(msmarco.cases) == 1
+ assert msmarco.cases[0].ground_truth is None
+ assert len(datasets.load_squad(n=1).cases) == 1
+ assert len(datasets.load_longbench(n=2, task="qasper").cases) == 1
+ assert len(datasets.load_narrativeqa(n=1).cases) == 1
+ assert len(datasets.load_toolbench(n=1, category="G1").cases) == 1
+ assert len(datasets.load_codesearchnet(n=1, language="python").cases) == 1
+ assert len(datasets.load_humaneval(n=1).cases) == 1
+
+
+def test_load_bfcl_handles_optional_ground_truth_and_question_fallback(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ data_lines = "\n".join(
+ [
+ json.dumps(
+ {
+ "id": "case-1",
+ "question": [123],
+ "function": [{"name": "weather"}],
+ }
+ ),
+ json.dumps({"id": "skip", "function": []}),
+ json.dumps(
+ {
+ "id": "case-2",
+ "question": [[{"role": "user", "content": "Ignored by limit"}]],
+ "function": [{"name": "time"}],
+ }
+ ),
+ ]
+ )
+
+ def fake_urlopen(url: str): # noqa: ANN001
+ if "possible_answer" in url:
+ raise URLError("missing ground truth")
+ return SimpleNamespace(read=lambda: data_lines.encode("utf-8"))
+
+ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)
+
+ suite = datasets.load_bfcl(n=2, category="simple")
+ assert len(suite.cases) == 1
+ assert suite.cases[0].query == "[123]"
+ assert suite.cases[0].ground_truth is None
diff --git a/tests/test_evals_metrics.py b/tests/test_evals_metrics.py
new file mode 100644
index 000000000..8406be8ee
--- /dev/null
+++ b/tests/test_evals_metrics.py
@@ -0,0 +1,132 @@
+from __future__ import annotations
+
+import math
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+from headroom.evals import metrics
+
+
+def test_normalize_tokenize_and_exact_match() -> None:
+ assert metrics.normalize_text(" Hello,\nWORLD ") == "hello, world"
+ assert metrics.tokenize("Hello, world! API_v2") == ["hello", "world", "api_v2"]
+ assert metrics.compute_exact_match(" Hello World ", "hello\nworld") is True
+ assert metrics.compute_exact_match("hello", "world") is False
+
+
+def test_f1_bleu_and_rouge_cover_edge_cases() -> None:
+ assert metrics.compute_f1("", "value") == 0.0
+ assert metrics.compute_f1("alpha beta", "gamma delta") == 0.0
+ assert metrics.compute_f1("alpha beta gamma", "alpha gamma") == pytest.approx(0.8)
+
+ assert metrics.compute_bleu("", "value") == 0.0
+ assert metrics.compute_bleu("one", "one") == pytest.approx(1.0)
+ assert metrics.compute_bleu("alpha beta", "gamma delta") == 0.0
+ assert metrics.compute_bleu("alpha beta", "alpha beta gamma", max_n=4) == pytest.approx(1.0)
+
+ assert metrics.compute_rouge_l("", "value") == 0.0
+ assert metrics.compute_rouge_l("alpha beta", "gamma delta") == 0.0
+ assert metrics.compute_rouge_l("alpha beta gamma", "alpha gamma") == pytest.approx(0.8)
+
+
+def test_compute_semantic_similarity_and_zero_norm(monkeypatch: pytest.MonkeyPatch) -> None:
+ fake_numpy = SimpleNamespace(
+ dot=lambda a, b: sum(x * y for x, y in zip(a, b)),
+ linalg=SimpleNamespace(norm=lambda a: math.sqrt(sum(x * x for x in a))),
+ )
+ monkeypatch.setitem(sys.modules, "numpy", fake_numpy)
+
+ class FakeModel:
+ def __init__(self, embeddings: list[list[float]]) -> None:
+ self.embeddings = embeddings
+
+ def encode(self, values: list[str]) -> list[list[float]]:
+ assert values == ["first", "second"]
+ return self.embeddings
+
+ monkeypatch.setattr(
+ "headroom.models.ml_models.MLModelRegistry.get_sentence_transformer",
+ lambda model_name=None: FakeModel([[1.0, 0.0], [1.0, 0.0]]),
+ )
+ assert metrics.compute_semantic_similarity("first", "second") == 1.0
+
+ monkeypatch.setattr(
+ "headroom.models.ml_models.MLModelRegistry.get_sentence_transformer",
+ lambda model_name=None: FakeModel([[0.0, 0.0], [1.0, 0.0]]),
+ )
+ assert metrics.compute_semantic_similarity("first", "second") == 0.0
+
+
+def test_compute_answer_equivalence_uses_multiple_paths(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(metrics, "compute_semantic_similarity", lambda a, b: 0.2)
+ exact = metrics.compute_answer_equivalence("Answer", "answer", ground_truth="missing")
+ assert exact["exact_match"] is True
+ assert exact["equivalent"] is True
+ assert exact["ground_truth_in_a"] is False
+ assert exact["ground_truth_in_b"] is False
+
+ monkeypatch.setattr(metrics, "compute_semantic_similarity", lambda a, b: 0.1)
+ high_f1 = metrics.compute_answer_equivalence(
+ "alpha beta gamma",
+ "alpha gamma",
+ semantic_threshold=0.95,
+ f1_threshold=0.75,
+ )
+ assert high_f1["equivalent"] is True
+ assert high_f1["semantic_similarity"] == 0.1
+
+ monkeypatch.setattr(metrics, "compute_semantic_similarity", lambda a, b: 0.95)
+ semantic = metrics.compute_answer_equivalence(
+ "completely different",
+ "nothing in common",
+ semantic_threshold=0.9,
+ f1_threshold=0.99,
+ )
+ assert semantic["equivalent"] is True
+ assert semantic["semantic_similarity"] == 0.95
+
+ def raise_import_error(a: str, b: str) -> float:
+ raise ImportError("missing dependency")
+
+ monkeypatch.setattr(metrics, "compute_semantic_similarity", raise_import_error)
+ ground_truth = metrics.compute_answer_equivalence(
+ "The capital is Paris.",
+ "Paris is definitely the capital city.",
+ ground_truth="paris",
+ semantic_threshold=0.99,
+ f1_threshold=0.99,
+ )
+ assert ground_truth["semantic_similarity"] is None
+ assert ground_truth["ground_truth_in_a"] is True
+ assert ground_truth["ground_truth_in_b"] is True
+ assert ground_truth["equivalent"] is True
+
+ not_equivalent = metrics.compute_answer_equivalence(
+ "alpha beta",
+ "gamma delta",
+ ground_truth="omega",
+ semantic_threshold=0.99,
+ f1_threshold=0.99,
+ )
+ assert not_equivalent["equivalent"] is False
+
+
+def test_information_recall_reports_preserved_and_missing_facts() -> None:
+ result = metrics.compute_information_recall(
+ "Alice likes pizza and Bob likes ramen.",
+ "Alice likes pizza.",
+ ["Alice", "Bob", "ramen", "Carol"],
+ )
+ assert result == {
+ "total_probes": 4,
+ "facts_in_original": 3,
+ "facts_preserved": 1,
+ "facts_lost": ["Bob", "ramen"],
+ "recall": pytest.approx(1 / 3),
+ }
+
+ empty_original = metrics.compute_information_recall("No facts here", "Still none", ["Alice"])
+ assert empty_original["facts_in_original"] == 0
+ assert empty_original["recall"] == 1.0
diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py
new file mode 100644
index 000000000..938cb219f
--- /dev/null
+++ b/tests/test_exceptions.py
@@ -0,0 +1,40 @@
+from __future__ import annotations
+
+from headroom.exceptions import (
+ CacheError,
+ CompressionError,
+ ConfigurationError,
+ HeadroomError,
+ ProviderError,
+ StorageError,
+ TokenizationError,
+ TransformError,
+ ValidationError,
+)
+
+
+def test_headroom_error_formats_details() -> None:
+ err = HeadroomError("bad config", details={"mode": "foo", "valid": "bar"})
+ assert err.message == "bad config"
+ assert err.details == {"mode": "foo", "valid": "bar"}
+ assert str(err) == "bad config (mode=foo, valid=bar)"
+
+ plain = HeadroomError("just bad")
+ assert plain.details == {}
+ assert str(plain) == "just bad"
+
+
+def test_specialized_exceptions_inherit_headroom_error() -> None:
+ for exc_type in (
+ ConfigurationError,
+ ProviderError,
+ StorageError,
+ CompressionError,
+ TokenizationError,
+ CacheError,
+ ValidationError,
+ TransformError,
+ ):
+ err = exc_type("problem", details={"kind": exc_type.__name__})
+ assert isinstance(err, HeadroomError)
+ assert str(err) == f"problem (kind={exc_type.__name__})"
diff --git a/tests/test_graph.py b/tests/test_graph.py
new file mode 100644
index 000000000..693f7dd13
--- /dev/null
+++ b/tests/test_graph.py
@@ -0,0 +1,352 @@
+from __future__ import annotations
+
+import io
+import json
+import subprocess
+import tarfile
+from pathlib import Path
+from types import ModuleType, SimpleNamespace
+
+import pytest
+
+from headroom.graph import installer, watcher
+
+
+def _build_archive(member_name: str = installer.CBM_BIN_NAME) -> bytes:
+ payload = io.BytesIO()
+ with tarfile.open(fileobj=payload, mode="w:gz") as tar:
+ data = b"#!/bin/sh\necho version\n"
+ info = tarfile.TarInfo(name=member_name)
+ info.size = len(data)
+ tar.addfile(info, io.BytesIO(data))
+ return payload.getvalue()
+
+
+class FakeResponse:
+ def __init__(self, data: bytes) -> None:
+ self._data = data
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc, tb) -> None:
+ return None
+
+ def read(self) -> bytes:
+ return self._data
+
+
+ ("system", "machine", "expected"),
+ [
+ ("Darwin", "arm64", "darwin-arm64"),
+ ("Darwin", "x86_64", "darwin-amd64"),
+ ("Linux", "aarch64", "linux-arm64"),
+ ("Linux", "arm64", "linux-arm64"),
+ ("Linux", "x86_64", "linux-amd64"),
+ ("Windows", "AMD64", "windows-amd64"),
+ ],
+)
+def test_detect_platform_variants(monkeypatch, system: str, machine: str, expected: str) -> None:
+ monkeypatch.setattr(installer.platform, "system", lambda: system)
+ monkeypatch.setattr(installer.platform, "machine", lambda: machine)
+ assert installer._detect_platform() == expected
+
+
+def test_detect_platform_rejects_unknown_system(monkeypatch) -> None:
+ monkeypatch.setattr(installer.platform, "system", lambda: "Solaris")
+ monkeypatch.setattr(installer.platform, "machine", lambda: "sparc")
+ with pytest.raises(RuntimeError, match="Unsupported platform"):
+ installer._detect_platform()
+
+
+def test_get_cbm_path_prefers_path_then_install_dir(monkeypatch, tmp_path: Path) -> None:
+ on_path = tmp_path / "on-path"
+ installed = tmp_path / installer.CBM_BIN_NAME
+ installed.write_text("bin")
+ monkeypatch.setattr(installer, "CBM_BIN_DIR", tmp_path)
+ monkeypatch.setattr(installer.shutil, "which", lambda name: str(on_path))
+ assert installer.get_cbm_path() == on_path
+
+ monkeypatch.setattr(installer.shutil, "which", lambda name: None)
+ assert installer.get_cbm_path() == installed
+
+ installed.unlink()
+ assert installer.get_cbm_path() is None
+
+
+def test_download_cbm_success_and_verification_paths(monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(installer, "CBM_BIN_DIR", tmp_path)
+ monkeypatch.setattr(installer, "_detect_platform", lambda: "linux-amd64")
+ monkeypatch.setattr(
+ installer, "urlopen", lambda url, timeout=60: FakeResponse(_build_archive())
+ )
+
+ run_calls: list[list[str]] = []
+
+ def fake_run(command, **kwargs):
+ run_calls.append(command)
+ return SimpleNamespace(returncode=1, stdout="")
+
+ monkeypatch.setattr("subprocess.run", fake_run)
+ path = installer.download_cbm(version="v1.2.3")
+ assert path == tmp_path / installer.CBM_BIN_NAME
+ assert path.exists()
+ assert run_calls == [[str(path), "--version"]]
+
+ monkeypatch.setattr(
+ "subprocess.run", lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("boom"))
+ )
+ assert installer.download_cbm(version="v1.2.3") == path
+
+ monkeypatch.setattr(
+ "subprocess.run",
+ lambda *args, **kwargs: SimpleNamespace(returncode=0, stdout="cbm v1.2.3\n"),
+ )
+ assert installer.download_cbm(version="v1.2.3") == path
+
+
+def test_download_cbm_invalid_url_download_failure_and_extract_errors(
+ monkeypatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr(installer, "CBM_BIN_DIR", tmp_path)
+ monkeypatch.setattr(installer, "_detect_platform", lambda: "linux-amd64")
+
+ monkeypatch.setattr(installer, "GITHUB_RELEASE_URL", "ftp://example.test/releases")
+ with pytest.raises(RuntimeError, match="Invalid URL"):
+ installer.download_cbm()
+
+ monkeypatch.setattr(installer, "GITHUB_RELEASE_URL", "https://example.test/releases")
+ monkeypatch.setattr(
+ installer,
+ "urlopen",
+ lambda url, timeout=60: (_ for _ in ()).throw(OSError("network down")),
+ )
+ with pytest.raises(RuntimeError, match="Failed to download codebase-memory-mcp"):
+ installer.download_cbm()
+
+ monkeypatch.setattr(
+ installer,
+ "urlopen",
+ lambda url, timeout=60: FakeResponse(_build_archive("some/other-binary")),
+ )
+ with pytest.raises(RuntimeError, match="binary not found in archive"):
+ installer.download_cbm()
+
+ monkeypatch.setattr(installer, "urlopen", lambda url, timeout=60: FakeResponse(b"not a tar"))
+ with pytest.raises(RuntimeError, match="Failed to extract archive"):
+ installer.download_cbm()
+
+
+def test_ensure_cbm_uses_existing_or_returns_none_on_failure(monkeypatch, tmp_path: Path) -> None:
+ existing = tmp_path / installer.CBM_BIN_NAME
+ monkeypatch.setattr(installer, "get_cbm_path", lambda: existing)
+ assert installer.ensure_cbm() == existing
+
+ monkeypatch.setattr(installer, "get_cbm_path", lambda: None)
+ monkeypatch.setattr(
+ installer, "download_cbm", lambda: (_ for _ in ()).throw(RuntimeError("nope"))
+ )
+ assert installer.ensure_cbm() is None
+
+
+def test_code_graph_watcher_init_start_stop_and_event_filtering(
+ monkeypatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr("headroom.graph.installer.get_cbm_path", lambda: tmp_path / "cbm")
+ graph_watcher = watcher.CodeGraphWatcher(tmp_path)
+ assert graph_watcher.cbm_binary == str(tmp_path / "cbm")
+
+ explicit = watcher.CodeGraphWatcher(tmp_path, cbm_binary="explicit-cbm")
+ assert explicit.cbm_binary == "explicit-cbm"
+
+ missing = watcher.CodeGraphWatcher(tmp_path, cbm_binary=None)
+ missing.cbm_binary = None
+ assert missing.start() is False
+
+ watchdog_mod = ModuleType("watchdog")
+ events_mod = ModuleType("watchdog.events")
+ observers_mod = ModuleType("watchdog.observers")
+
+ class FileSystemEventHandler:
+ pass
+
+ class FakeObserver:
+ def __init__(self) -> None:
+ self.scheduled = None
+ self.daemon = False
+ self.started = False
+ self.stopped = False
+ self.join_timeout = None
+
+ def schedule(self, handler, project_dir, recursive=True) -> None:
+ self.scheduled = (handler, project_dir, recursive)
+
+ def start(self) -> None:
+ self.started = True
+
+ def stop(self) -> None:
+ self.stopped = True
+
+ def join(self, timeout=None) -> None:
+ self.join_timeout = timeout
+
+ events_mod.FileSystemEventHandler = FileSystemEventHandler
+ observers_mod.Observer = FakeObserver
+ monkeypatch.setitem(__import__("sys").modules, "watchdog", watchdog_mod)
+ monkeypatch.setitem(__import__("sys").modules, "watchdog.events", events_mod)
+ monkeypatch.setitem(__import__("sys").modules, "watchdog.observers", observers_mod)
+
+ scheduled: list[str] = []
+ monkeypatch.setattr(graph_watcher, "_schedule_reindex", lambda: scheduled.append("reindex"))
+
+ assert graph_watcher.start() is True
+ handler, project_dir, recursive = graph_watcher._observer.scheduled
+ assert project_dir == str(tmp_path)
+ assert recursive is True
+
+ handler.on_any_event(SimpleNamespace(src_path=""))
+ handler.on_any_event(SimpleNamespace(src_path=str(tmp_path / ".git" / "config")))
+ handler.on_any_event(SimpleNamespace(src_path=str(tmp_path / "notes.txt")))
+ handler.on_any_event(SimpleNamespace(src_path=str(tmp_path / ".temp.py")))
+ handler.on_any_event(SimpleNamespace(src_path=str(tmp_path / "main.py~")))
+ handler.on_any_event(SimpleNamespace(src_path=str(tmp_path / "main.py")))
+ assert scheduled == ["reindex"]
+
+ class FakeTimer:
+ def __init__(self) -> None:
+ self.cancelled = False
+
+ def cancel(self) -> None:
+ self.cancelled = True
+
+ timer = FakeTimer()
+ graph_watcher._debounce_timer = timer
+ graph_watcher._reindex_count = 1
+ graph_watcher.stop()
+ assert timer.cancelled is True
+ assert graph_watcher._observer is None
+
+
+def test_code_graph_watcher_start_returns_false_without_watchdog(
+ monkeypatch, tmp_path: Path
+) -> None:
+ graph_watcher = watcher.CodeGraphWatcher(tmp_path, cbm_binary="cbm")
+
+ import builtins
+
+ real_import = builtins.__import__
+
+ def fake_import(name, globals=None, locals=None, fromlist=(), level=0):
+ if name.startswith("watchdog"):
+ raise ImportError("missing watchdog")
+ return real_import(name, globals, locals, fromlist, level)
+
+ monkeypatch.setattr(builtins, "__import__", fake_import)
+ assert graph_watcher.start() is False
+
+
+def test_code_graph_watcher_stop_handles_missing_timer_and_observer_methods(tmp_path: Path) -> None:
+ graph_watcher = watcher.CodeGraphWatcher(tmp_path, cbm_binary="cbm")
+ graph_watcher._observer = object()
+ graph_watcher.stop()
+ assert graph_watcher._observer is None
+
+ graph_watcher.stop()
+
+
+def test_schedule_reindex_replaces_existing_timer(monkeypatch, tmp_path: Path) -> None:
+ graph_watcher = watcher.CodeGraphWatcher(tmp_path, debounce_seconds=3.5, cbm_binary="cbm")
+ timers: list[FakeTimer] = []
+
+ class FakeTimer:
+ def __init__(self, interval, callback) -> None:
+ self.interval = interval
+ self.callback = callback
+ self.daemon = False
+ self.started = False
+ self.cancelled = False
+ timers.append(self)
+
+ def start(self) -> None:
+ self.started = True
+
+ def cancel(self) -> None:
+ self.cancelled = True
+
+ monkeypatch.setattr(watcher.threading, "Timer", FakeTimer)
+ graph_watcher._schedule_reindex()
+ graph_watcher._schedule_reindex()
+
+ assert len(timers) == 2
+ assert timers[0].cancelled is True
+ assert timers[1].started is True
+ assert timers[1].daemon is True
+ assert timers[1].interval == 3.5
+
+
+def test_do_reindex_success_failure_timeout_and_stats(monkeypatch, tmp_path: Path) -> None:
+ graph_watcher = watcher.CodeGraphWatcher(tmp_path, cbm_binary="cbm")
+ graph_watcher._running = True
+
+ monotonic_values = iter([10.0, 10.4, 20.0, 20.5, 30.0, 30.5, 40.0, 40.5])
+ monkeypatch.setattr(watcher.time, "monotonic", lambda: next(monotonic_values))
+ monkeypatch.setattr(watcher.time, "time", lambda: 1234.0)
+
+ run_calls: list[list[str]] = []
+
+ def success_run(command, **kwargs):
+ run_calls.append(command)
+ return SimpleNamespace(returncode=0, stderr="indexed\nchanged=7 files\n")
+
+ monkeypatch.setattr(watcher.subprocess, "run", success_run)
+ graph_watcher._do_reindex()
+ assert graph_watcher.stats == {
+ "running": True,
+ "project_dir": str(tmp_path),
+ "reindex_count": 1,
+ "last_reindex": 1234.0,
+ "debounce_seconds": 2.0,
+ }
+ assert run_calls == [
+ ["cbm", "cli", "index_repository", json.dumps({"repo_path": str(tmp_path), "mode": "fast"})]
+ ]
+
+ monkeypatch.setattr(
+ watcher.subprocess,
+ "run",
+ lambda command, **kwargs: SimpleNamespace(returncode=1, stderr="failed"),
+ )
+ graph_watcher._do_reindex()
+ assert graph_watcher._reindex_count == 2
+
+ monkeypatch.setattr(
+ watcher.subprocess,
+ "run",
+ lambda command, **kwargs: SimpleNamespace(
+ returncode=0, stderr="indexed\nchanged=oops\nstill running\n"
+ ),
+ )
+ graph_watcher._do_reindex()
+ assert graph_watcher._reindex_count == 3
+
+ monkeypatch.setattr(
+ watcher.subprocess,
+ "run",
+ lambda command, **kwargs: (_ for _ in ()).throw(subprocess.TimeoutExpired(command, 30)),
+ )
+ graph_watcher._do_reindex()
+
+ monkeypatch.setattr(
+ watcher.subprocess,
+ "run",
+ lambda command, **kwargs: (_ for _ in ()).throw(RuntimeError("boom")),
+ )
+ graph_watcher._do_reindex()
+
+ graph_watcher._running = False
+ graph_watcher._do_reindex()
+
+ graph_watcher._running = True
+ graph_watcher.cbm_binary = None
+ graph_watcher._do_reindex()
diff --git a/tests/test_install/test_paths.py b/tests/test_install/test_paths.py
new file mode 100644
index 000000000..0d44734f2
--- /dev/null
+++ b/tests/test_install/test_paths.py
@@ -0,0 +1,68 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+import click
+import pytest
+
+from headroom.install import paths as install_paths
+
+
+def test_validate_profile_name_accepts_and_rejects_values() -> None:
+ assert install_paths.validate_profile_name("good.profile-1_2") == "good.profile-1_2"
+
+ for value in (".", "..", "bad/name", "bad space", ""):
+ with pytest.raises(click.ClickException, match="Invalid profile name"):
+ install_paths.validate_profile_name(value)
+
+
+def test_profile_and_artifact_paths(monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setattr("headroom.install.paths._paths.deploy_root", lambda: tmp_path / "deploy")
+
+ assert install_paths.deploy_root() == tmp_path / "deploy"
+ assert install_paths.profile_root("demo") == tmp_path / "deploy" / "demo"
+ assert install_paths.manifest_path("demo") == tmp_path / "deploy" / "demo" / "manifest.json"
+ assert install_paths.log_path("demo") == tmp_path / "deploy" / "demo" / "runner.log"
+ assert install_paths.pid_path("demo") == tmp_path / "deploy" / "demo" / "runner.pid"
+ assert (
+ install_paths.unix_run_script_path("demo")
+ == tmp_path / "deploy" / "demo" / "run-headroom.sh"
+ )
+ assert install_paths.unix_ensure_script_path("demo") == (
+ tmp_path / "deploy" / "demo" / "ensure-headroom.sh"
+ )
+ assert install_paths.windows_run_script_path("demo") == (
+ tmp_path / "deploy" / "demo" / "run-headroom.ps1"
+ )
+ assert install_paths.windows_run_cmd_path("demo") == (
+ tmp_path / "deploy" / "demo" / "run-headroom.cmd"
+ )
+ assert install_paths.windows_ensure_script_path("demo") == (
+ tmp_path / "deploy" / "demo" / "ensure-headroom.ps1"
+ )
+ assert install_paths.windows_ensure_cmd_path("demo") == (
+ tmp_path / "deploy" / "demo" / "ensure-headroom.cmd"
+ )
+
+
+def test_env_target_and_config_paths(monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setattr("headroom.install.paths.sys.platform", "linux")
+
+ assert install_paths.unix_user_env_targets() == [
+ tmp_path / ".bashrc",
+ tmp_path / ".zshrc",
+ tmp_path / ".profile",
+ ]
+ assert install_paths.unix_system_env_targets() == [Path("/etc/profile.d/headroom.sh")]
+
+ monkeypatch.setattr("headroom.install.paths.sys.platform", "darwin")
+ assert install_paths.unix_system_env_targets() == [
+ Path("/etc/profile"),
+ Path("/etc/zprofile"),
+ Path("/etc/bashrc"),
+ ]
+
+ assert install_paths.claude_settings_path() == tmp_path / ".claude" / "settings.json"
+ assert install_paths.codex_config_path() == tmp_path / ".codex" / "config.toml"
+ assert install_paths.openclaw_config_path() == tmp_path / ".openclaw" / "openclaw.json"
diff --git a/tests/test_install/test_runtime.py b/tests/test_install/test_runtime.py
index da0137143..205dedc0a 100644
--- a/tests/test_install/test_runtime.py
+++ b/tests/test_install/test_runtime.py
@@ -1,174 +1,468 @@
-from __future__ import annotations
-
-from pathlib import Path
-
-from headroom.install.models import DeploymentManifest
-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(
- monkeypatch, tmp_path: Path
-) -> None:
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
- manifest = DeploymentManifest(
- profile="default",
- preset="persistent-docker",
- runtime_kind="docker",
- supervisor_kind="none",
- scope="user",
- provider_mode="manual",
- targets=["claude"],
- port=8787,
- host="127.0.0.1",
- backend="anthropic",
- image="ghcr.io/chopratejas/headroom:latest",
- base_env={"HEADROOM_PORT": "8787"},
- proxy_args=["--host", "127.0.0.1", "--port", "8787"],
- )
-
- command = build_runtime_command(manifest)
-
- joined = " ".join(command)
- assert command[:3] == ["docker", "run", "--rm"]
- assert "HEADROOM_DEPLOYMENT_PROFILE=default" in joined
- assert "HEADROOM_DEPLOYMENT_PRESET=persistent-docker" in joined
- assert "127.0.0.1:8787:8787" in joined
- assert "ghcr.io/chopratejas/headroom:latest" in command
- # Canonical Headroom filesystem contract (issue #175) forwarded into
- # the container.
- assert "HEADROOM_WORKSPACE_DIR=/tmp/headroom-home/.headroom" in command
- assert "HEADROOM_CONFIG_DIR=/tmp/headroom-home/.headroom/config" in command
-
-
-def test_build_runtime_command_for_docker_matches_wrapper_parity(
- monkeypatch, tmp_path: Path
-) -> None:
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
- monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
- monkeypatch.setenv("OPENAI_API_KEY", "test-openai")
- manifest = DeploymentManifest(
- profile="default",
- preset="persistent-docker",
- runtime_kind="docker",
- supervisor_kind="none",
- scope="user",
- provider_mode="manual",
- targets=["claude"],
- port=8787,
- host="127.0.0.1",
- backend="anthropic",
- image="ghcr.io/chopratejas/headroom:latest",
- base_env={"HEADROOM_PORT": "8787"},
- proxy_args=["--host", "127.0.0.1", "--port", "8787"],
- )
-
- command = build_runtime_command(manifest)
-
- assert (tmp_path / ".headroom").is_dir()
- assert (tmp_path / ".claude").is_dir()
- assert (tmp_path / ".codex").is_dir()
- assert (tmp_path / ".gemini").is_dir()
- assert "--env" in command
- joined = " ".join(command)
- assert "ANTHROPIC_API_KEY" in joined
- assert "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"
+from __future__ import annotations
+
+import signal
+from pathlib import Path
+
+from headroom.install.models import DeploymentManifest, InstallPreset
+from headroom.install.runtime import (
+ _clear_pid,
+ _deployment_env,
+ _mount_source,
+ _read_pid,
+ _runtime_env,
+ _write_pid,
+ build_runtime_command,
+ resolve_headroom_command,
+ run_foreground,
+ runtime_status,
+ start_detached_agent,
+ start_persistent_docker,
+ stop_runtime,
+ wait_ready,
+)
+
+
+def test_build_runtime_command_for_docker_includes_deployment_env(
+ monkeypatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ manifest = DeploymentManifest(
+ profile="default",
+ preset="persistent-docker",
+ runtime_kind="docker",
+ supervisor_kind="none",
+ scope="user",
+ provider_mode="manual",
+ targets=["claude"],
+ port=8787,
+ host="127.0.0.1",
+ backend="anthropic",
+ image="ghcr.io/chopratejas/headroom:latest",
+ base_env={"HEADROOM_PORT": "8787"},
+ proxy_args=["--host", "127.0.0.1", "--port", "8787"],
+ )
+
+ command = build_runtime_command(manifest)
+
+ joined = " ".join(command)
+ assert command[:3] == ["docker", "run", "--rm"]
+ assert "HEADROOM_DEPLOYMENT_PROFILE=default" in joined
+ assert "HEADROOM_DEPLOYMENT_PRESET=persistent-docker" in joined
+ assert "127.0.0.1:8787:8787" in joined
+ assert "ghcr.io/chopratejas/headroom:latest" in command
+ # Canonical Headroom filesystem contract (issue #175) forwarded into
+ # the container.
+ assert "HEADROOM_WORKSPACE_DIR=/tmp/headroom-home/.headroom" in command
+ assert "HEADROOM_CONFIG_DIR=/tmp/headroom-home/.headroom/config" in command
+
+
+def test_build_runtime_command_for_docker_matches_wrapper_parity(
+ monkeypatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
+ monkeypatch.setenv("OPENAI_API_KEY", "test-openai")
+ manifest = DeploymentManifest(
+ profile="default",
+ preset="persistent-docker",
+ runtime_kind="docker",
+ supervisor_kind="none",
+ scope="user",
+ provider_mode="manual",
+ targets=["claude"],
+ port=8787,
+ host="127.0.0.1",
+ backend="anthropic",
+ image="ghcr.io/chopratejas/headroom:latest",
+ base_env={"HEADROOM_PORT": "8787"},
+ proxy_args=["--host", "127.0.0.1", "--port", "8787"],
+ )
+
+ command = build_runtime_command(manifest)
+
+ assert (tmp_path / ".headroom").is_dir()
+ assert (tmp_path / ".claude").is_dir()
+ assert (tmp_path / ".codex").is_dir()
+ assert (tmp_path / ".gemini").is_dir()
+ assert "--env" in command
+ joined = " ".join(command)
+ assert "ANTHROPIC_API_KEY" in joined
+ assert "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_resolve_headroom_command_falls_back_to_python_module(monkeypatch) -> None:
+ monkeypatch.setattr("shutil.which", lambda name: None)
+ monkeypatch.setattr("headroom.install.runtime.sys.executable", "/usr/bin/python")
+ assert resolve_headroom_command() == ["/usr/bin/python", "-m", "headroom.cli"]
+
+
+def test_runtime_env_and_mount_source(monkeypatch) -> None:
+ 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",
+ base_env={"EXTRA": "1"},
+ )
+ monkeypatch.setattr("headroom.install.runtime.os.environ", {"BASE": "x"})
+
+ assert _deployment_env(manifest) == {
+ "HEADROOM_DEPLOYMENT_PROFILE": "default",
+ "HEADROOM_DEPLOYMENT_PRESET": "persistent-service",
+ "HEADROOM_DEPLOYMENT_RUNTIME": "python",
+ "HEADROOM_DEPLOYMENT_SUPERVISOR": "service",
+ "HEADROOM_DEPLOYMENT_SCOPE": "user",
+ }
+ assert _runtime_env(manifest)["BASE"] == "x"
+ assert _runtime_env(manifest)["EXTRA"] == "1"
+ assert _runtime_env(manifest)["HEADROOM_DEPLOYMENT_PROFILE"] == "default"
+
+ monkeypatch.setattr("headroom.install.runtime.os.name", "nt")
+ assert _mount_source("C:\\Users\\me", ".headroom") == "C:\\Users\\me\\.headroom"
+ monkeypatch.setattr("headroom.install.runtime.os.name", "posix")
+ assert _mount_source("/home/me", ".headroom") == "/home/me/.headroom"
+
+
+def test_build_runtime_command_python_and_docker_user(monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setattr("headroom.install.runtime.sys.executable", "/usr/bin/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",
+ proxy_args=["--host", "127.0.0.1", "--port", "8787"],
+ )
+ assert build_runtime_command(manifest) == [
+ "/usr/bin/python",
+ "-m",
+ "headroom.cli",
+ "proxy",
+ "--host",
+ "127.0.0.1",
+ "--port",
+ "8787",
+ ]
+
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setattr("headroom.install.runtime.os.name", "posix")
+ monkeypatch.setattr("headroom.install.runtime.os.getuid", lambda: 1000, raising=False)
+ monkeypatch.setattr("headroom.install.runtime.os.getgid", lambda: 1001, raising=False)
+ 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",
+ image="ghcr.io/chopratejas/headroom:latest",
+ base_env={"HEADROOM_PORT": "8787"},
+ proxy_args=["--host", "127.0.0.1", "--port", "8787"],
+ )
+ command = build_runtime_command(docker_manifest)
+ assert "--user" in command
+ assert "1000:1001" in command
+
+
+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_write_read_and_clear_pid(monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ _write_pid("default", 456)
+ assert _read_pid("default") == 456
+ _clear_pid("default")
+ assert _read_pid("default") is None
+
+
+def test_run_foreground_and_detached_helpers(monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setattr(
+ "headroom.install.runtime.build_runtime_command", lambda manifest: ["headroom", "proxy"]
+ )
+ monkeypatch.setattr("headroom.install.runtime._runtime_env", lambda manifest: {"ENV": "1"})
+ signal_calls: list[int] = []
+ monkeypatch.setattr(
+ "headroom.install.runtime.signal.signal", lambda sig, fn: signal_calls.append(sig)
+ )
+
+ class FakeProc:
+ def __init__(self, returncode: int = 0, pid: int = 321) -> None:
+ self.returncode = returncode
+ self.pid = pid
+ self.terminated = False
+ self.killed = False
+
+ def wait(self, timeout: int | None = None) -> int:
+ return self.returncode
+
+ def poll(self):
+ return None if not self.terminated else self.returncode
+
+ def terminate(self) -> None:
+ self.terminated = True
+
+ def kill(self) -> None:
+ self.killed = True
+
+ fake_proc = FakeProc(returncode=7)
+ popen_calls: list[tuple[list[str], dict]] = []
+
+ def fake_popen(command: list[str], **kwargs):
+ popen_calls.append((command, kwargs))
+ return fake_proc
+
+ monkeypatch.setattr("headroom.install.runtime.subprocess.Popen", fake_popen)
+ 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 run_foreground(manifest) == 7
+ assert popen_calls[0][0] == ["headroom", "proxy"]
+ assert signal.SIGINT in signal_calls
+ assert signal.SIGTERM in signal_calls
+ assert _read_pid("default") is None
+
+ monkeypatch.setattr("headroom.install.runtime.resolve_headroom_command", lambda: ["headroom"])
+ monkeypatch.setattr("headroom.install.runtime.os.name", "nt")
+ monkeypatch.setattr("headroom.install.runtime.subprocess.DETACHED_PROCESS", 1, raising=False)
+ monkeypatch.setattr(
+ "headroom.install.runtime.subprocess.CREATE_NEW_PROCESS_GROUP", 2, raising=False
+ )
+ fake_proc_nt = FakeProc()
+ monkeypatch.setattr(
+ "headroom.install.runtime.subprocess.Popen", lambda command, **kwargs: fake_proc_nt
+ )
+ assert start_detached_agent("demo") is fake_proc_nt
+
+ monkeypatch.setattr("headroom.install.runtime.os.name", "posix")
+ fake_proc_posix = FakeProc()
+ monkeypatch.setattr(
+ "headroom.install.runtime.subprocess.Popen", lambda command, **kwargs: fake_proc_posix
+ )
+ assert start_detached_agent("demo") is fake_proc_posix
+
+
+def test_start_stop_wait_and_runtime_status_branches(monkeypatch, tmp_path: Path) -> None:
+ calls: list[list[str]] = []
+ monkeypatch.setattr(
+ "headroom.install.runtime.subprocess.run",
+ lambda command, **kwargs: calls.append(command) or type("Result", (), {"stdout": ""})(),
+ )
+ monkeypatch.setattr(
+ "headroom.install.runtime.build_runtime_command",
+ lambda manifest: [
+ "docker",
+ "run",
+ "--rm",
+ "--name",
+ "demo",
+ "-p",
+ "127.0.0.1:8787:8787",
+ "image",
+ ],
+ )
+ manifest = DeploymentManifest(
+ profile="default",
+ preset=InstallPreset.PERSISTENT_DOCKER.value,
+ 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",
+ )
+ start_persistent_docker(manifest)
+ assert calls == [
+ ["docker", "rm", "-f", "headroom-default"],
+ [
+ "docker",
+ "run",
+ "-d",
+ "--restart",
+ "unless-stopped",
+ "--name",
+ "headroom-default",
+ "-p",
+ "127.0.0.1:8787:8787",
+ "image",
+ ],
+ ]
+
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ 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",
+ health_url="http://127.0.0.1:8787/health",
+ )
+ _write_pid("default", 123)
+ killed: list[tuple[int, int]] = []
+ monkeypatch.setattr(
+ "headroom.install.runtime.os.kill", lambda pid, sig: killed.append((pid, sig))
+ )
+ stop_runtime(python_manifest)
+ assert killed == [(123, signal.SIGTERM)]
+ assert _read_pid("default") is None
+
+ _write_pid("default", 124)
+ monkeypatch.setattr(
+ "headroom.install.runtime.os.kill",
+ lambda pid, sig: (_ for _ in ()).throw(OSError("gone")),
+ )
+ stop_runtime(python_manifest)
+ assert _read_pid("default") is None
+
+ probe_results = iter([False, False, True])
+ sleeps: list[int] = []
+ monkeypatch.setattr("headroom.install.runtime.probe_ready", lambda url: next(probe_results))
+ monkeypatch.setattr(
+ "headroom.install.runtime.time.sleep", lambda seconds: sleeps.append(seconds)
+ )
+ assert wait_ready(python_manifest, timeout_seconds=3) is True
+ assert sleeps == [1, 1]
+
+ monkeypatch.setattr("headroom.install.runtime.probe_ready", lambda url: False)
+ sleeps.clear()
+ assert wait_ready(python_manifest, timeout_seconds=2) is False
+ assert sleeps == [1, 1]
+
+ class Result:
+ def __init__(self, stdout: str = "") -> None:
+ self.stdout = stdout
+
+ monkeypatch.setattr(
+ "headroom.install.runtime.subprocess.run",
+ lambda command, **kwargs: Result(stdout=""),
+ )
+ assert runtime_status(manifest) == "stopped"
+ assert runtime_status(python_manifest) == "stopped"
+
+ _write_pid("default", 125)
+ monkeypatch.setattr(
+ "headroom.install.runtime.os.kill", lambda pid, sig: (_ for _ in ()).throw(OSError())
+ )
+ assert runtime_status(python_manifest) == "stopped"
+
+
+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_supervisors.py b/tests/test_install/test_supervisors.py
index 98c5ef52c..8f39c128d 100644
--- a/tests/test_install/test_supervisors.py
+++ b/tests/test_install/test_supervisors.py
@@ -1,173 +1,473 @@
-from __future__ import annotations
-
-from pathlib import Path
-
-from headroom.install.models import DeploymentManifest, SupervisorKind
-from headroom.install.supervisors import (
- _linux_service_unit,
- _linux_task_spec,
- _macos_launchd_plist,
- _render_windows_runner,
- install_supervisor,
- remove_supervisor,
- render_runner_scripts,
- start_supervisor,
- stop_supervisor,
-)
-
-
-def _manifest(
- *, profile: str = "default", scope: str = "user", supervisor: str = "service"
-) -> DeploymentManifest:
- return DeploymentManifest(
- profile=profile,
- preset="persistent-service",
- runtime_kind="python",
- supervisor_kind=supervisor,
- scope=scope,
- provider_mode="manual",
- targets=[],
- port=8787,
- host="127.0.0.1",
- backend="anthropic",
- service_name=f"headroom-{profile}",
- )
-
-
-def test_linux_service_unit_uses_user_systemd_path(monkeypatch, tmp_path: Path) -> None:
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
- manifest = _manifest()
-
- unit_path, content = _linux_service_unit(manifest, tmp_path / "run-headroom.sh")
-
- assert unit_path == tmp_path / ".config" / "systemd" / "user" / "headroom-default.service"
- assert "ExecStart=" + str(tmp_path / "run-headroom.sh") in content
- assert "Restart=on-failure" in content
-
-
-def test_linux_task_spec_for_user_scope_includes_crontab_markers(tmp_path: Path) -> None:
- manifest = _manifest(profile="smoke", supervisor=SupervisorKind.TASK.value)
-
- cron_path, content = _linux_task_spec(manifest, tmp_path / "ensure-headroom.sh")
-
- assert cron_path is None
- assert "# >>> headroom smoke >>>" in content
- assert "# <<< headroom smoke <<<" in content
- assert "@reboot" in content
- assert "*/5 * * * *" in content
-
-
-def test_macos_launchd_plist_switches_between_keepalive_and_interval(
- monkeypatch, tmp_path: Path
-) -> None:
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
-
- service_manifest = _manifest(supervisor=SupervisorKind.SERVICE.value)
- service_path, service_content = _macos_launchd_plist(
- service_manifest, tmp_path / "run-headroom.sh"
- )
- assert service_path == tmp_path / "Library" / "LaunchAgents" / "com.headroom.default.plist"
- assert "<key>KeepAlive</key>" in service_content
- assert "<key>StartInterval</key>" not in service_content
-
- task_manifest = _manifest(profile="tasky", supervisor=SupervisorKind.TASK.value)
- task_path, task_content = _macos_launchd_plist(
- task_manifest, tmp_path / "ensure-headroom.sh", interval=300
- )
- assert task_path == tmp_path / "Library" / "LaunchAgents" / "com.headroom.tasky.plist"
- assert "<key>StartInterval</key>" in task_content
- assert "<integer>300</integer>" in task_content
-
-
-def test_render_windows_runner_writes_ps1_and_cmd_wrappers(tmp_path: Path) -> None:
- ps1_path = tmp_path / "run-headroom.ps1"
- cmd_path = tmp_path / "run-headroom.cmd"
-
- records = _render_windows_runner(
- ps1_path,
- cmd_path,
- ["C:\\Program Files\\Python\\python.exe", "headroom", "install", "agent", "run"],
- )
-
- assert [record.path for record in records] == [str(ps1_path), str(cmd_path)]
- ps1_content = ps1_path.read_text(encoding="utf-8")
- cmd_content = cmd_path.read_text(encoding="utf-8")
- assert '& "C:\\Program Files\\Python\\python.exe" headroom install agent run' in ps1_content
- assert (
- '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", "-"]
+from __future__ import annotations
+
+from pathlib import Path
+
+import click
+import pytest
+
+from headroom.install.models import DeploymentManifest, SupervisorKind
+from headroom.install.supervisors import (
+ _command_for_script,
+ _linux_service_unit,
+ _linux_task_spec,
+ _macos_launchd_plist,
+ _render_unix_runner,
+ _render_windows_runner,
+ install_supervisor,
+ remove_supervisor,
+ render_runner_scripts,
+ start_supervisor,
+ stop_supervisor,
+)
+
+
+def _manifest(
+ *, profile: str = "default", scope: str = "user", supervisor: str = "service"
+) -> DeploymentManifest:
+ return DeploymentManifest(
+ profile=profile,
+ preset="persistent-service",
+ runtime_kind="python",
+ supervisor_kind=supervisor,
+ scope=scope,
+ provider_mode="manual",
+ targets=[],
+ port=8787,
+ host="127.0.0.1",
+ backend="anthropic",
+ service_name=f"headroom-{profile}",
+ )
+
+
+def test_linux_service_unit_uses_user_systemd_path(monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ manifest = _manifest()
+
+ unit_path, content = _linux_service_unit(manifest, tmp_path / "run-headroom.sh")
+
+ assert unit_path == tmp_path / ".config" / "systemd" / "user" / "headroom-default.service"
+ assert "ExecStart=" + str(tmp_path / "run-headroom.sh") in content
+ assert "Restart=on-failure" in content
+
+
+def test_command_for_script_and_unix_runner(monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(
+ "headroom.install.supervisors.resolve_headroom_command",
+ lambda: ["python", "-m", "headroom"],
+ )
+
+ assert _command_for_script("install", "agent", "run") == [
+ "python",
+ "-m",
+ "headroom",
+ "install",
+ "agent",
+ "run",
+ ]
+
+ record = _render_unix_runner(
+ tmp_path / "scripts" / "run-headroom.sh", ["headroom", "run", "--flag"]
+ )
+ assert record.kind == "script"
+ content = Path(record.path).read_text(encoding="utf-8")
+ assert content.startswith("#!/usr/bin/env bash")
+ assert "exec headroom run --flag" in content
+
+
+def test_linux_task_spec_for_user_scope_includes_crontab_markers(tmp_path: Path) -> None:
+ manifest = _manifest(profile="smoke", supervisor=SupervisorKind.TASK.value)
+
+ cron_path, content = _linux_task_spec(manifest, tmp_path / "ensure-headroom.sh")
+
+ assert cron_path is None
+ assert "# >>> headroom smoke >>>" in content
+ assert "# <<< headroom smoke <<<" in content
+ assert "@reboot" in content
+ assert "*/5 * * * *" in content
+
+
+def test_macos_launchd_plist_switches_between_keepalive_and_interval(
+ monkeypatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+
+ service_manifest = _manifest(supervisor=SupervisorKind.SERVICE.value)
+ service_path, service_content = _macos_launchd_plist(
+ service_manifest, tmp_path / "run-headroom.sh"
+ )
+ assert service_path == tmp_path / "Library" / "LaunchAgents" / "com.headroom.default.plist"
+ assert "<key>KeepAlive</key>" in service_content
+ assert "<key>StartInterval</key>" not in service_content
+
+ task_manifest = _manifest(profile="tasky", supervisor=SupervisorKind.TASK.value)
+ task_path, task_content = _macos_launchd_plist(
+ task_manifest, tmp_path / "ensure-headroom.sh", interval=300
+ )
+ assert task_path == tmp_path / "Library" / "LaunchAgents" / "com.headroom.tasky.plist"
+ assert "<key>StartInterval</key>" in task_content
+ assert "<integer>300</integer>" in task_content
+
+
+def test_render_windows_runner_writes_ps1_and_cmd_wrappers(tmp_path: Path) -> None:
+ ps1_path = tmp_path / "run-headroom.ps1"
+ cmd_path = tmp_path / "run-headroom.cmd"
+
+ records = _render_windows_runner(
+ ps1_path,
+ cmd_path,
+ ["C:\\Program Files\\Python\\python.exe", "headroom", "install", "agent", "run"],
+ )
+
+ assert [record.path for record in records] == [str(ps1_path), str(cmd_path)]
+ ps1_content = ps1_path.read_text(encoding="utf-8")
+ cmd_content = cmd_path.read_text(encoding="utf-8")
+ assert '& "C:\\Program Files\\Python\\python.exe" headroom install agent run' in ps1_content
+ assert (
+ '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_render_runner_scripts_writes_windows_scripts(monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setattr("headroom.install.supervisors.os.name", "nt")
+ monkeypatch.setattr(
+ "headroom.install.supervisors.resolve_headroom_command", lambda: ["headroom.exe"]
+ )
+ monkeypatch.setattr(
+ "headroom.install.supervisors.windows_run_script_path",
+ lambda profile: tmp_path / "run-headroom.ps1",
+ )
+ monkeypatch.setattr(
+ "headroom.install.supervisors.windows_run_cmd_path",
+ lambda profile: tmp_path / "run-headroom.cmd",
+ )
+ monkeypatch.setattr(
+ "headroom.install.supervisors.windows_ensure_script_path",
+ lambda profile: tmp_path / "ensure-headroom.ps1",
+ )
+ monkeypatch.setattr(
+ "headroom.install.supervisors.windows_ensure_cmd_path",
+ lambda profile: tmp_path / "ensure-headroom.cmd",
+ )
+
+ records = render_runner_scripts(_manifest(profile="win"))
+
+ assert [Path(record.path).name for record in records] == [
+ "run-headroom.ps1",
+ "run-headroom.cmd",
+ "ensure-headroom.ps1",
+ "ensure-headroom.cmd",
+ ]
+
+
+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_install_supervisor_linux_service_and_tasks(monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "linux")
+ monkeypatch.setattr("headroom.install.supervisors.os.name", "posix")
+ run_script = tmp_path / "run-headroom.sh"
+ ensure_script = tmp_path / "ensure-headroom.sh"
+ monkeypatch.setattr(
+ "headroom.install.supervisors.render_runner_scripts",
+ lambda manifest: [
+ type("Record", (), {"kind": "script", "path": run_script.as_posix()})(),
+ type("Record", (), {"kind": "script", "path": ensure_script.as_posix()})(),
+ ],
+ )
+ unit_path = tmp_path / "headroom-default.service"
+ monkeypatch.setattr(
+ "headroom.install.supervisors._linux_service_unit",
+ lambda manifest, script: (unit_path, "UNIT"),
+ )
+ calls: list[tuple[list[str], dict]] = []
+
+ def fake_run(command: list[str], **kwargs):
+ calls.append((command, kwargs))
+ return type("Result", (), {"returncode": 0, "stdout": "# old cron\n"})()
+
+ monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)
+
+ service_records = install_supervisor(_manifest(supervisor=SupervisorKind.SERVICE.value))
+ assert unit_path.read_text(encoding="utf-8") == "UNIT"
+ assert ["systemctl", "--user", "daemon-reload"] in [call[0] for call in calls]
+ assert ["systemctl", "--user", "enable", "headroom-default"] in [call[0] for call in calls]
+ assert service_records[-1].kind == "service-unit"
+
+ cron_path = tmp_path / "headroom-system"
+ monkeypatch.setattr(
+ "headroom.install.supervisors._linux_task_spec",
+ lambda manifest, script: (cron_path, "@reboot root ensure\n"),
+ )
+ system_task_records = install_supervisor(
+ _manifest(profile="system-task", scope="system", supervisor=SupervisorKind.TASK.value)
+ )
+ assert cron_path.read_text(encoding="utf-8") == "@reboot root ensure\n"
+ assert system_task_records[-1].kind == "cron"
+
+ monkeypatch.setattr(
+ "headroom.install.supervisors._linux_task_spec",
+ lambda manifest, script: (
+ None,
+ "# >>> headroom default >>>\n@reboot ensure\n# <<< headroom default <<<\n",
+ ),
+ )
+ user_task_records = install_supervisor(_manifest(supervisor=SupervisorKind.TASK.value))
+ assert user_task_records[-1].kind == "crontab"
+ assert calls[-1][0] == ["crontab", "-"]
+ assert "@reboot ensure" in calls[-1][1]["input"]
+
+
+def test_install_supervisor_darwin_windows_and_unsupported(monkeypatch, tmp_path: Path) -> None:
+ run_script = tmp_path / "run-headroom.sh"
+ ensure_script = tmp_path / "ensure-headroom.sh"
+ monkeypatch.setattr(
+ "headroom.install.supervisors.render_runner_scripts",
+ lambda manifest: [
+ type("Record", (), {"kind": "script", "path": run_script.as_posix()})(),
+ type("Record", (), {"kind": "script", "path": ensure_script.as_posix()})(),
+ ],
+ )
+ calls: list[list[str]] = []
+ monkeypatch.setattr(
+ "headroom.install.supervisors.subprocess.run",
+ lambda command, **kwargs: calls.append(command),
+ )
+ monkeypatch.setattr("headroom.install.supervisors.os.getuid", lambda: 123, raising=False)
+
+ plist_path = tmp_path / "com.headroom.default.plist"
+ monkeypatch.setattr(
+ "headroom.install.supervisors._macos_launchd_plist",
+ lambda manifest, script, interval=None: (plist_path, f"plist-{interval}"),
+ )
+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "darwin")
+ monkeypatch.setattr("headroom.install.supervisors.os.name", "posix")
+ service_records = install_supervisor(_manifest(supervisor=SupervisorKind.SERVICE.value))
+ task_records = install_supervisor(_manifest(supervisor=SupervisorKind.TASK.value))
+ assert plist_path.read_text(encoding="utf-8") == "plist-300"
+ assert service_records[-1].kind == "plist"
+ assert task_records[-1].kind == "plist"
+ assert ["launchctl", "bootstrap", "gui/123", str(plist_path)] in calls
+
+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "win32")
+ monkeypatch.setattr("headroom.install.supervisors.os.name", "nt")
+ monkeypatch.setattr(
+ "headroom.install.supervisors.windows_run_cmd_path",
+ lambda profile: Path(f"C:\\tmp\\{profile}\\run-headroom.cmd"),
+ )
+ monkeypatch.setattr(
+ "headroom.install.supervisors.windows_ensure_cmd_path",
+ lambda profile: Path(f"C:\\tmp\\{profile}\\ensure-headroom.cmd"),
+ )
+ win_service = install_supervisor(_manifest(supervisor=SupervisorKind.SERVICE.value))
+ win_task = install_supervisor(_manifest(supervisor=SupervisorKind.TASK.value))
+ assert win_service[-1].kind == "windows-service"
+ assert win_task[-2].path.endswith("-startup")
+ assert [
+ "sc.exe",
+ "create",
+ "headroom-default",
+ 'binPath= cmd.exe /c "C:\\tmp\\default\\run-headroom.cmd"',
+ "start= auto",
+ ] in calls
+ assert [
+ "schtasks",
+ "/Create",
+ "/TN",
+ "headroom-default-health",
+ "/TR",
+ "C:\\tmp\\default\\ensure-headroom.cmd",
+ "/SC",
+ "MINUTE",
+ "/MO",
+ "5",
+ "/F",
+ ] in calls
+
+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "plan9")
+ monkeypatch.setattr("headroom.install.supervisors.os.name", "posix")
+ with pytest.raises(click.ClickException, match="not supported"):
+ install_supervisor(_manifest(supervisor=SupervisorKind.SERVICE.value))
+
+
+def test_start_and_stop_supervisor_darwin_windows_and_none(monkeypatch) -> None:
+ calls: list[list[str]] = []
+ monkeypatch.setattr(
+ "headroom.install.supervisors.subprocess.run",
+ lambda command, **kwargs: calls.append(command),
+ )
+ monkeypatch.setattr("headroom.install.supervisors.os.getuid", lambda: 77, raising=False)
+
+ start_supervisor(_manifest(supervisor=SupervisorKind.NONE.value))
+ stop_supervisor(_manifest(supervisor=SupervisorKind.NONE.value))
+ assert calls == []
+
+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "darwin")
+ monkeypatch.setattr("headroom.install.supervisors.os.name", "posix")
+ start_supervisor(_manifest(supervisor=SupervisorKind.SERVICE.value))
+ stop_supervisor(_manifest(supervisor=SupervisorKind.SERVICE.value))
+ assert calls == [
+ ["launchctl", "kickstart", "-k", "gui/77/com.headroom.default"],
+ ["launchctl", "bootout", "gui/77/com.headroom.default"],
+ ]
+
+ calls.clear()
+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "win32")
+ monkeypatch.setattr("headroom.install.supervisors.os.name", "nt")
+ start_supervisor(_manifest(supervisor=SupervisorKind.SERVICE.value))
+ stop_supervisor(_manifest(supervisor=SupervisorKind.SERVICE.value))
+ assert calls == [
+ ["sc.exe", "start", "headroom-default"],
+ ["sc.exe", "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", "-"]
+
+
+def test_remove_supervisor_linux_service_cron_path_and_missing_crontab(
+ monkeypatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "linux")
+ calls: list[list[str]] = []
+
+ def fake_run(command: list[str], **kwargs):
+ calls.append(command)
+ return type("Result", (), {"returncode": 1, "stdout": ""})()
+
+ monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)
+ unit_path = tmp_path / "headroom-default.service"
+ unit_path.write_text("unit", encoding="utf-8")
+ monkeypatch.setattr(
+ "headroom.install.supervisors._linux_service_unit",
+ lambda manifest, script: (unit_path, "unit"),
+ )
+ remove_supervisor(_manifest(supervisor=SupervisorKind.SERVICE.value))
+ assert not unit_path.exists()
+ assert ["systemctl", "--user", "disable", "--now", "headroom-default"] in calls
+ assert ["systemctl", "--user", "daemon-reload"] in calls
+
+ cron_path = tmp_path / "headroom-task"
+ cron_path.write_text("cron", encoding="utf-8")
+ monkeypatch.setattr(
+ "headroom.install.supervisors._linux_task_spec",
+ lambda manifest, script: (cron_path, "cron"),
+ )
+ remove_supervisor(_manifest(supervisor=SupervisorKind.TASK.value))
+ assert not cron_path.exists()
+
+ monkeypatch.setattr(
+ "headroom.install.supervisors._linux_task_spec",
+ lambda manifest, script: (None, "cron"),
+ )
+ remove_supervisor(_manifest(supervisor=SupervisorKind.TASK.value))
+ assert calls[-1] == ["crontab", "-l"]
+
+
+def test_remove_supervisor_darwin_and_windows(monkeypatch, tmp_path: Path) -> None:
+ calls: list[list[str]] = []
+ monkeypatch.setattr(
+ "headroom.install.supervisors.subprocess.run",
+ lambda command, **kwargs: calls.append(command),
+ )
+ monkeypatch.setattr("headroom.install.supervisors.os.getuid", lambda: 55, raising=False)
+
+ plist_path = tmp_path / "com.headroom.default.plist"
+ plist_path.write_text("plist", encoding="utf-8")
+ monkeypatch.setattr(
+ "headroom.install.supervisors.unix_run_script_path",
+ lambda profile: tmp_path / "run-headroom.sh",
+ )
+ monkeypatch.setattr(
+ "headroom.install.supervisors.unix_ensure_script_path",
+ lambda profile: tmp_path / "ensure-headroom.sh",
+ )
+ monkeypatch.setattr(
+ "headroom.install.supervisors._macos_launchd_plist",
+ lambda manifest, script, interval=None: (plist_path, "plist"),
+ )
+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "darwin")
+ monkeypatch.setattr("headroom.install.supervisors.os.name", "posix")
+ remove_supervisor(_manifest(supervisor=SupervisorKind.SERVICE.value))
+ assert not plist_path.exists()
+ assert calls[0] == ["launchctl", "bootout", "gui/55/com.headroom.default"]
+
+ calls.clear()
+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "win32")
+ monkeypatch.setattr("headroom.install.supervisors.os.name", "nt")
+ remove_supervisor(_manifest(supervisor=SupervisorKind.SERVICE.value))
+ remove_supervisor(_manifest(supervisor=SupervisorKind.TASK.value))
+ assert calls == [
+ ["sc.exe", "stop", "headroom-default"],
+ ["sc.exe", "delete", "headroom-default"],
+ ["schtasks", "/Delete", "/TN", "headroom-default-startup", "/F"],
+ ["schtasks", "/Delete", "/TN", "headroom-default-health", "/F"],
+ ]
diff --git a/tests/test_memory_handler_native_ops.py b/tests/test_memory_handler_native_ops.py
new file mode 100644
index 000000000..e75ce3c04
--- /dev/null
+++ b/tests/test_memory_handler_native_ops.py
@@ -0,0 +1,1395 @@
+from __future__ import annotations
+
+import asyncio
+import json
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from headroom.proxy import memory_handler as memory_handler_module
+from headroom.proxy.memory_handler import MemoryConfig, MemoryHandler
+
+
+def handler(tmp_path: Path) -> MemoryHandler:
+ return MemoryHandler(
+ MemoryConfig(
+ enabled=False,
+ use_native_tool=True,
+ native_memory_dir=str(tmp_path / "native"),
+ ),
+ agent_type="codex",
+ )
+
+
+class FakeBackend:
+ def __init__(self) -> None:
+ self.search_results: list[object] = []
+ self.saved: list[dict[str, object]] = []
+ self.updated: list[dict[str, object]] = []
+ self.deleted: list[str] = []
+ self.raise_on: str | None = None
+
+ async def search_memories(self, **kwargs): # noqa: ANN003
+ if self.raise_on == "search":
+ raise RuntimeError("search failed")
+ return self.search_results
+
+ async def save_memory(self, **kwargs): # noqa: ANN003
+ if self.raise_on == "save":
+ raise RuntimeError("save failed")
+ self.saved.append(kwargs)
+ return SimpleNamespace(id=f"mem-{len(self.saved)}", content=kwargs["content"])
+
+ async def update_memory(self, **kwargs): # noqa: ANN003
+ if self.raise_on == "update":
+ raise RuntimeError("update failed")
+ self.updated.append(kwargs)
+ return SimpleNamespace(id=kwargs["memory_id"])
+
+ async def delete_memory(self, memory_id: str): # noqa: ANN201
+ if self.raise_on == "delete":
+ raise RuntimeError("delete failed")
+ self.deleted.append(memory_id)
+ return True
+
+
+def make_result(
+ memory_id: str,
+ content: str,
+ *,
+ score: float = 0.9,
+ metadata: dict[str, object] | None = None,
+ related_entities: list[str] | None = None,
+ created_at: str | None = None,
+ importance: float = 0.5,
+) -> object:
+ return SimpleNamespace(
+ memory=SimpleNamespace(
+ id=memory_id,
+ content=content,
+ metadata=metadata or {},
+ created_at=created_at,
+ importance=importance,
+ ),
+ score=score,
+ related_entities=related_entities or [],
+ )
+
+
+def test_resolve_native_path_blocks_traversal(handler: MemoryHandler) -> None:
+ resolved = handler._resolve_native_path("/memories/topic.txt", "u1")
+ assert resolved.name == "topic.txt"
+ assert "u1" in str(resolved)
+
+ with pytest.raises(ValueError, match="Path traversal detected"):
+ handler._resolve_native_path("/memories/../escape.txt", "u1")
+
+
+def test_native_view_lists_directory_and_reads_files(handler: MemoryHandler) -> None:
+ root = handler._resolve_native_path("/memories", "u1")
+ (root / "alpha.txt").write_text("line1\nline2\nline3", encoding="utf-8")
+ (root / "nested").mkdir()
+ (root / "nested" / "beta.txt").write_text("nested", encoding="utf-8")
+ (root / ".hidden").write_text("skip", encoding="utf-8")
+ (root / "node_modules").mkdir()
+
+ listing = handler._native_view({"path": "/memories"}, "u1")
+ assert "/memories/alpha.txt" in listing
+ assert "/memories/nested/beta.txt" in listing
+ assert ".hidden" not in listing
+ assert "/memories/node_modules" not in listing
+
+ file_view = handler._native_view({"path": "/memories/alpha.txt", "view_range": [2, 3]}, "u1")
+ assert "2\tline2" in file_view
+ assert "3\tline3" in file_view
+
+
+def test_native_view_handles_missing_paths_and_latin1(handler: MemoryHandler) -> None:
+ missing = handler._native_view({"path": "/memories/missing.txt"}, "u1")
+ assert "does not exist" in missing
+
+ latin_path = handler._resolve_native_path("/memories/latin.txt", "u1")
+ latin_path.write_bytes("caf\xe9".encode("latin-1"))
+ viewed = handler._native_view({"path": "/memories/latin.txt"}, "u1")
+ assert "cafe" not in viewed
+ assert "café" in viewed
+
+
+def test_native_create_insert_delete_and_rename(handler: MemoryHandler) -> None:
+ assert handler._native_create(
+ {"path": "/memories/note.txt", "file_text": "a\nb"}, "u1"
+ ).startswith("File created successfully")
+ assert handler._native_create(
+ {"path": "/memories/note.txt", "file_text": "dup"}, "u1"
+ ).startswith("Error: File /memories/note.txt already exists")
+
+ inserted = handler._native_insert(
+ {"path": "/memories/note.txt", "insert_line": 1, "insert_text": "middle"},
+ "u1",
+ )
+ assert inserted == "The file /memories/note.txt has been edited."
+ assert "middle" in handler._resolve_native_path("/memories/note.txt", "u1").read_text(
+ encoding="utf-8"
+ )
+
+ renamed = handler._native_rename(
+ {"old_path": "/memories/note.txt", "new_path": "/memories/archive/renamed.txt"},
+ "u1",
+ )
+ assert renamed == "Successfully renamed /memories/note.txt to /memories/archive/renamed.txt"
+
+ deleted = handler._native_delete_file({"path": "/memories/archive"}, "u1")
+ assert deleted == "Successfully deleted /memories/archive"
+
+
+def test_native_insert_validates_range_and_path(handler: MemoryHandler) -> None:
+ assert (
+ handler._native_insert({"insert_line": 0, "insert_text": "x"}, "u1")
+ == "Error: path is required"
+ )
+ assert "does not exist" in handler._native_insert(
+ {"path": "/memories/missing.txt", "insert_line": 0, "insert_text": "x"},
+ "u1",
+ )
+
+ note = handler._resolve_native_path("/memories/note.txt", "u1")
+ note.write_text("a\nb", encoding="utf-8")
+ invalid = handler._native_insert(
+ {"path": "/memories/note.txt", "insert_line": 4, "insert_text": "x"},
+ "u1",
+ )
+ assert "Invalid `insert_line` parameter: 4" in invalid
+
+
+def test_native_str_replace_covers_missing_multiple_and_success(handler: MemoryHandler) -> None:
+ note = handler._resolve_native_path("/memories/note.txt", "u1")
+ note.write_text("hello\nhello\nworld", encoding="utf-8")
+
+ assert (
+ handler._native_str_replace({"old_str": "hello", "new_str": "bye"}, "u1")
+ == "Error: path is required"
+ )
+ assert (
+ handler._native_str_replace({"path": "/memories/note.txt", "new_str": "bye"}, "u1")
+ == "Error: old_str is required"
+ )
+
+ multiple = handler._native_str_replace(
+ {"path": "/memories/note.txt", "old_str": "hello", "new_str": "bye"},
+ "u1",
+ )
+ assert "Multiple occurrences of old_str `hello` in lines: 1, 2" in multiple
+
+ note.write_text("hello\nworld", encoding="utf-8")
+ missing = handler._native_str_replace(
+ {"path": "/memories/note.txt", "old_str": "nope", "new_str": "bye"},
+ "u1",
+ )
+ assert "did not appear verbatim" in missing
+
+ success = handler._native_str_replace(
+ {"path": "/memories/note.txt", "old_str": "hello", "new_str": "bye"},
+ "u1",
+ )
+ assert "The memory file has been edited." in success
+ assert "bye" in note.read_text(encoding="utf-8")
+
+
+def test_native_delete_and_rename_validate_inputs(handler: MemoryHandler) -> None:
+ assert handler._native_delete_file({}, "u1") == "Error: path is required"
+ assert "does not exist" in handler._native_delete_file({"path": "/memories/missing.txt"}, "u1")
+
+ assert (
+ handler._native_rename({"new_path": "/memories/new.txt"}, "u1")
+ == "Error: old_path is required"
+ )
+ assert (
+ handler._native_rename({"old_path": "/memories/old.txt"}, "u1")
+ == "Error: new_path is required"
+ )
+ assert "does not exist" in handler._native_rename(
+ {"old_path": "/memories/old.txt", "new_path": "/memories/new.txt"},
+ "u1",
+ )
+
+ old = handler._resolve_native_path("/memories/old.txt", "u1")
+ new = handler._resolve_native_path("/memories/new.txt", "u1")
+ old.write_text("x", encoding="utf-8")
+ new.write_text("y", encoding="utf-8")
+ assert (
+ handler._native_rename(
+ {"old_path": "/memories/old.txt", "new_path": "/memories/new.txt"},
+ "u1",
+ )
+ == "Error: The destination /memories/new.txt already exists"
+ )
+
+
+async def test_execute_native_memory_tool_dispatches_and_wraps_errors(
+ handler: MemoryHandler, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ handler._backend = object()
+ called: list[tuple[str, dict[str, object], str]] = []
+
+ async def fake_ensure_initialized() -> None:
+ return None
+
+ async def fake_view(input_data, user_id): # noqa: ANN001
+ called.append(("view", input_data, user_id))
+ return "viewed"
+
+ async def fake_create(input_data, user_id): # noqa: ANN001
+ called.append(("create", input_data, user_id))
+ return "created"
+
+ monkeypatch.setattr(handler, "_ensure_initialized", fake_ensure_initialized)
+ monkeypatch.setattr(handler, "_native_view_semantic", fake_view)
+ monkeypatch.setattr(handler, "_native_create_semantic", fake_create)
+
+ assert await handler._execute_native_memory_tool({"command": "view"}, "u1") == "viewed"
+ assert await handler._execute_native_memory_tool({"command": "create"}, "u1") == "created"
+ assert (
+ await handler._execute_native_memory_tool({"command": "bad"}, "u1")
+ == "Error: Unknown command 'bad'"
+ )
+
+ async def boom(input_data, user_id): # noqa: ANN001
+ raise RuntimeError("oops")
+
+ monkeypatch.setattr(handler, "_native_view_semantic", boom)
+ assert await handler._execute_native_memory_tool({"command": "view"}, "u1") == "Error: oops"
+ assert [entry[0] for entry in called] == ["view", "create"]
+
+
+async def test_semantic_search_recent_all_and_overview(handler: MemoryHandler) -> None:
+ backend = FakeBackend()
+ handler._backend = backend
+ backend.search_results = [
+ make_result(
+ "m1",
+ "Alice likes pizza and pasta",
+ score=0.91,
+ related_entities=["Alice", "pizza"],
+ created_at="2026-04-22",
+ ),
+ make_result("m2", "Bob prefers ramen", score=0.83),
+ ]
+
+ search_text = await handler._semantic_search("pizza", "u1")
+ assert "Found 2 memories matching 'pizza'" in search_text
+ assert "[91% match] Alice likes pizza and pasta" in search_text
+ assert "Related: Alice, pizza" in search_text
+
+ recent_text = await handler._get_recent_memories("u1", limit=2)
+ assert "Recent memories:" in recent_text
+ assert "(2026-04-22)" in recent_text
+
+ all_text = await handler._list_all_memories("u1", limit=2)
+ assert "Showing up to 2 memories:" in all_text
+ assert "Showing first 2" in all_text
+
+ overview = await handler._get_memory_overview("u1")
+ assert "Memory System (2 memories stored)" in overview
+ assert "view /memories/search/<your query>" in overview
+
+
+async def test_semantic_helpers_handle_empty_backend_and_errors(handler: MemoryHandler) -> None:
+ assert await handler._semantic_search("x", "u1") == "Error: Memory backend not initialized"
+ assert await handler._get_recent_memories("u1") == "Error: Memory backend not initialized"
+ assert await handler._list_all_memories("u1") == "Error: Memory backend not initialized"
+ assert await handler._get_memory_overview("u1") == "Error: Memory backend not initialized"
+
+ backend = FakeBackend()
+ handler._backend = backend
+ assert "No memories found matching 'x'" in await handler._semantic_search("x", "u1")
+ assert "No memories stored yet." in await handler._list_all_memories("u1")
+ assert "No memories stored yet." in await handler._get_recent_memories("u1")
+
+ backend.raise_on = "search"
+ assert "Error searching memories: search failed" == await handler._semantic_search("x", "u1")
+ assert "Error getting recent memories: search failed" == await handler._get_recent_memories(
+ "u1"
+ )
+ assert "Error listing memories: search failed" == await handler._list_all_memories("u1")
+ overview = await handler._get_memory_overview("u1")
+ assert "📁 Memory System" in overview
+ assert "To SEARCH memories" in overview
+
+
+async def test_native_view_semantic_routes_paths(
+ handler: MemoryHandler, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ seen: list[tuple[str, object]] = []
+
+ async def fake_search(query, user_id, top_k=5): # noqa: ANN001
+ seen.append(("search", query))
+ return "search-result"
+
+ async def fake_recent(user_id, limit=10): # noqa: ANN001
+ seen.append(("recent", limit))
+ return "recent-result"
+
+ async def fake_all(user_id, limit=20): # noqa: ANN001
+ seen.append(("all", limit))
+ return "all-result"
+
+ async def fake_overview(user_id): # noqa: ANN001
+ seen.append(("overview", user_id))
+ return "overview-result"
+
+ monkeypatch.setattr(handler, "_semantic_search", fake_search)
+ monkeypatch.setattr(handler, "_get_recent_memories", fake_recent)
+ monkeypatch.setattr(handler, "_list_all_memories", fake_all)
+ monkeypatch.setattr(handler, "_get_memory_overview", fake_overview)
+
+ assert (
+ await handler._native_view_semantic({"path": "/memories/search/pizza"}, "u1")
+ == "search-result"
+ )
+ assert (
+ await handler._native_view_semantic({"path": "/memories/recent"}, "u1") == "recent-result"
+ )
+ assert await handler._native_view_semantic({"path": "/memories/all"}, "u1") == "all-result"
+ assert await handler._native_view_semantic({"path": "/memories"}, "u1") == "overview-result"
+ assert (
+ await handler._native_view_semantic({"path": "/memories/work/projects"}, "u1")
+ == "search-result"
+ )
+ assert (await handler._native_view_semantic({"path": "/memories/search/"}, "u1")).startswith(
+ "Error: Please provide a search query"
+ )
+ assert seen == [
+ ("search", "pizza"),
+ ("recent", 10),
+ ("all", 20),
+ ("overview", "u1"),
+ ("search", "work projects"),
+ ]
+
+
+async def test_native_semantic_create_append_delete_and_rename(handler: MemoryHandler) -> None:
+ backend = FakeBackend()
+ handler._backend = backend
+
+ assert await handler._native_create_semantic({}, "u1") == "Error: path is required"
+ assert (
+ await handler._native_create_semantic({"path": "/memories/topic.txt"}, "u1")
+ == "Error: file_text is required (the memory content)"
+ )
+
+ created = await handler._native_create_semantic(
+ {"path": "/memories/topic.txt", "file_text": "prefers pizza"},
+ "u1",
+ )
+ assert created == "File created successfully at: /memories/topic.txt"
+ assert backend.saved[-1]["metadata"] == {
+ "virtual_path": "/memories/topic.txt",
+ "topic": "topic",
+ }
+
+ assert await handler._native_append_semantic({}, "u1") == "Error: path is required"
+ assert (
+ await handler._native_append_semantic({"path": "/memories/topic.txt"}, "u1")
+ == "Error: insert_text is required"
+ )
+ appended = await handler._native_append_semantic(
+ {"path": "/memories/topic.txt", "insert_text": "and pasta"},
+ "u1",
+ )
+ assert appended == "The file /memories/topic.txt has been edited."
+ assert backend.saved[-1]["metadata"]["appended"] is True
+
+ backend.search_results = [
+ make_result(
+ "m1", "prefers pizza", metadata={"virtual_path": "/memories/topic.txt"}, score=0.6
+ ),
+ make_result("m2", "prefers pasta", metadata={}, score=0.91),
+ ]
+ deleted = await handler._native_delete_semantic({"path": "/memories/topic.txt"}, "u1")
+ assert deleted == "Successfully deleted /memories/topic.txt"
+ assert backend.deleted == ["m1", "m2"]
+
+ backend.search_results = [
+ make_result(
+ "m3", "old content", metadata={"virtual_path": "/memories/old.txt"}, importance=0.7
+ )
+ ]
+ renamed = await handler._native_rename_semantic(
+ {"old_path": "/memories/old.txt", "new_path": "/memories/new/topic.txt"},
+ "u1",
+ )
+ assert renamed == "Successfully renamed /memories/old.txt to /memories/new/topic.txt"
+ assert backend.deleted[-1] == "m3"
+ assert backend.saved[-1]["metadata"] == {
+ "virtual_path": "/memories/new/topic.txt",
+ "topic": "new_topic",
+ }
+
+
+async def test_native_semantic_update_delete_rename_and_backend_errors(
+ handler: MemoryHandler,
+) -> None:
+ backend = FakeBackend()
+ handler._backend = backend
+
+ assert await handler._native_update_semantic({}, "u1") == "Error: path is required"
+ assert (
+ await handler._native_update_semantic({"path": "/memories/t.txt"}, "u1")
+ == "Error: old_str is required"
+ )
+
+ backend.search_results = [
+ make_result("m1", "hello hello world", metadata={"virtual_path": "/memories/t.txt"})
+ ]
+ multi = await handler._native_update_semantic(
+ {"path": "/memories/t.txt", "old_str": "hello", "new_str": "bye"},
+ "u1",
+ )
+ assert "Multiple occurrences of old_str `hello`" in multi
+
+ backend.search_results = [
+ make_result("m1", "hello world", metadata={"virtual_path": "/memories/t.txt"})
+ ]
+ edited = await handler._native_update_semantic(
+ {"path": "/memories/t.txt", "old_str": "hello", "new_str": "bye"},
+ "u1",
+ )
+ assert "The memory file has been edited." in edited
+ assert backend.updated[-1]["new_content"] == "bye world"
+
+ class NoUpdateBackend:
+ def __init__(self) -> None:
+ self.search_results: list[object] = []
+ self.saved: list[dict[str, object]] = []
+ self.deleted: list[str] = []
+
+ async def search_memories(self, **kwargs): # noqa: ANN003
+ return self.search_results
+
+ async def delete_memory(self, memory_id: str): # noqa: ANN201
+ self.deleted.append(memory_id)
+ return True
+
+ async def save_memory(self, **kwargs): # noqa: ANN003
+ self.saved.append(kwargs)
+ return SimpleNamespace(id=f"mem-{len(self.saved)}")
+
+ no_update_backend = NoUpdateBackend()
+ no_update_backend.search_results = [
+ make_result("m2", "alpha beta", metadata={"virtual_path": "/memories/t.txt"})
+ ]
+ handler._backend = no_update_backend
+ fallback = await handler._native_update_semantic(
+ {"path": "/memories/t.txt", "old_str": "alpha", "new_str": "omega"},
+ "u1",
+ )
+ assert "The memory file has been edited." in fallback
+ assert no_update_backend.deleted[-1] == "m2"
+ assert no_update_backend.saved[-1]["content"] == "omega beta"
+
+ backend = FakeBackend()
+ handler._backend = backend
+ assert await handler._native_delete_semantic({}, "u1") == "Error: path is required"
+ assert await handler._native_rename_semantic({}, "u1") == "Error: old_path is required"
+ assert (
+ await handler._native_rename_semantic({"old_path": "/memories/a.txt"}, "u1")
+ == "Error: new_path is required"
+ )
+ assert (
+ await handler._native_delete_semantic({"path": "/memories/x.txt"}, "u1")
+ == "Error: The path /memories/x.txt does not exist"
+ )
+ assert (
+ await handler._native_rename_semantic(
+ {"old_path": "/memories/x.txt", "new_path": "/memories/y.txt"},
+ "u1",
+ )
+ == "Error: The path /memories/x.txt does not exist"
+ )
+
+ backend.search_results = [
+ make_result("m9", "content", metadata={"virtual_path": "/memories/other.txt"}, score=0.1)
+ ]
+ assert (
+ await handler._native_delete_semantic({"path": "/memories/x.txt"}, "u1")
+ == "Error: The path /memories/x.txt does not exist"
+ )
+ assert (
+ await handler._native_rename_semantic(
+ {"old_path": "/memories/x.txt", "new_path": "/memories/y.txt"},
+ "u1",
+ )
+ == "Error: The path /memories/x.txt does not exist"
+ )
+
+ backend.raise_on = "search"
+ assert (
+ await handler._native_create_semantic(
+ {"path": "/memories/topic.txt", "file_text": "content"},
+ "u1",
+ )
+ == "File created successfully at: /memories/topic.txt"
+ )
+ backend.raise_on = "save"
+ assert (
+ await handler._native_create_semantic(
+ {"path": "/memories/topic.txt", "file_text": "content"}, "u1"
+ )
+ ).startswith("Error: ")
+ assert (
+ await handler._native_append_semantic(
+ {"path": "/memories/topic.txt", "insert_text": "content"}, "u1"
+ )
+ ).startswith("Error: ")
+ backend.raise_on = "search"
+ assert (
+ await handler._native_update_semantic(
+ {"path": "/memories/t.txt", "old_str": "a", "new_str": "b"}, "u1"
+ )
+ ).startswith("Error: ")
+ assert (await handler._native_delete_semantic({"path": "/memories/x.txt"}, "u1")).startswith(
+ "Error: "
+ )
+ assert (
+ await handler._native_rename_semantic(
+ {"old_path": "/memories/x.txt", "new_path": "/memories/y.txt"},
+ "u1",
+ )
+ ).startswith("Error: ")
+
+
+async def test_execute_search_update_delete_and_handler_status(
+ handler: MemoryHandler, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ backend = FakeBackend()
+ handler._backend = backend
+
+ assert json.loads(await handler._execute_search({}, "u1")) == {
+ "status": "error",
+ "error": "query is required",
+ }
+
+ backend.search_results = [
+ make_result("m1", "pizza", score=0.9123, related_entities=["food", "italy"])
+ ]
+ search_payload = json.loads(
+ await handler._execute_search(
+ {"query": "pizza", "top_k": 3, "include_related": False, "entities": ["food"]},
+ "u1",
+ )
+ )
+ assert search_payload["status"] == "found"
+ assert search_payload["count"] == 1
+ assert search_payload["memories"][0] == {
+ "id": "m1",
+ "content": "pizza",
+ "score": 0.912,
+ "entities": ["food", "italy"],
+ }
+
+ assert json.loads(await handler._execute_update({}, "u1")) == {
+ "status": "error",
+ "error": "memory_id is required",
+ }
+ assert json.loads(await handler._execute_update({"memory_id": "m1"}, "u1")) == {
+ "status": "error",
+ "error": "new_content is required",
+ }
+
+ backend.search_results = [make_result("m1", "old content")]
+ update_payload = json.loads(
+ await handler._execute_update(
+ {"memory_id": "m1", "new_content": "new content", "reason": "cleanup"},
+ "u1",
+ provider="openai",
+ )
+ )
+ assert update_payload == {"status": "updated", "memory_id": "m1"}
+ assert backend.updated[-1]["new_content"] == "new content"
+
+ class NoUpdateBackend:
+ def __init__(self) -> None:
+ self.deleted: list[str] = []
+ self.saved: list[dict[str, object]] = []
+
+ async def delete_memory(self, memory_id: str): # noqa: ANN201
+ self.deleted.append(memory_id)
+ return True
+
+ async def save_memory(self, **kwargs): # noqa: ANN003
+ self.saved.append(kwargs)
+ return SimpleNamespace(id="m2")
+
+ no_update_backend = NoUpdateBackend()
+ handler._backend = no_update_backend
+ update_fallback = json.loads(
+ await handler._execute_update({"memory_id": "m1", "new_content": "replacement"}, "u1")
+ )
+ assert update_fallback == {
+ "status": "updated",
+ "memory_id": "m2",
+ "note": "Replaced via delete+save",
+ }
+ assert no_update_backend.deleted == ["m1"]
+
+ handler._backend = backend
+ assert json.loads(await handler._execute_delete({}, "u1")) == {
+ "status": "error",
+ "error": "memory_id is required",
+ }
+ delete_payload = json.loads(await handler._execute_delete({"memory_id": "m1"}, "u1"))
+ assert delete_payload == {"status": "deleted", "memory_id": "m1"}
+
+ assert handler.health_status() == {
+ "enabled": False,
+ "backend": "local",
+ "initialized": False,
+ "native_tool": True,
+ "bridge_enabled": False,
+ }
+
+ seen = {"count": 0}
+
+ async def fake_ensure_initialized() -> None:
+ seen["count"] += 1
+
+ monkeypatch.setattr(handler, "_ensure_initialized", fake_ensure_initialized)
+ await handler.ensure_initialized()
+ assert seen["count"] == 1
+
+
+async def test_warmup_embedder_and_close(handler: MemoryHandler) -> None:
+ assert await handler.warmup_embedder() is False
+
+ class FakeEmbedder:
+ def __init__(self) -> None:
+ self.calls: list[str] = []
+
+ async def embed(self, value: str) -> None:
+ self.calls.append(value)
+
+ embedder = FakeEmbedder()
+ handler._initialized = True
+ handler._backend = SimpleNamespace(_hierarchical_memory=SimpleNamespace(_embedder=embedder))
+ assert await handler.warmup_embedder() is True
+ assert embedder.calls == ["warmup"]
+
+ handler._backend = SimpleNamespace(
+ _hierarchical_memory=SimpleNamespace(_embedder=SimpleNamespace())
+ )
+ assert await handler.warmup_embedder() is False
+
+ handler._backend = SimpleNamespace(close=lambda: None)
+ await handler.close()
+ assert handler.backend is None
+ assert handler.initialized is False
+
+
+async def test_execute_memory_tool_save_and_background_dedup(
+ handler: MemoryHandler, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ backend = FakeBackend()
+ handler._backend = backend
+
+ assert json.loads(await handler._execute_memory_tool("unknown", {}, "u1")) == {
+ "error": "Unknown tool: unknown"
+ }
+ assert json.loads(await handler._execute_memory_tool("memory_save", {}, "u1")) == {
+ "status": "error",
+ "error": "content is required",
+ }
+
+ created_tasks: list[object] = []
+
+ def fake_create_task(coro): # noqa: ANN001
+ created_tasks.append(coro)
+ coro.close()
+ return SimpleNamespace()
+
+ monkeypatch.setattr("headroom.proxy.memory_handler.asyncio.create_task", fake_create_task)
+ backend.search_results = [
+ make_result(
+ "other",
+ "Very similar memory content " * 5,
+ score=0.8,
+ metadata={"source_agent": "claude"},
+ ),
+ make_result("mem-1", "self result", score=0.99),
+ ]
+
+ saved = json.loads(
+ await handler._execute_memory_tool(
+ "memory_save",
+ {
+ "content": "Useful fact",
+ "importance": 0.7,
+ "facts": ["fact"],
+ "entities": ["entity"],
+ "extracted_entities": ["entity"],
+ "relationships": ["rel"],
+ "extracted_relationships": ["rel"],
+ },
+ "u1",
+ provider="openai",
+ )
+ )
+ assert saved["status"] == "saved"
+ assert saved["memory_id"] == "mem-1"
+ assert "Similar memory exists" in saved["note"]
+ assert "saved by claude" in saved["note"]
+ assert backend.saved[-1]["metadata"]["source_provider"] == "openai"
+ assert len(created_tasks) == 1
+
+ backend.raise_on = "save"
+ errored = json.loads(await handler._execute_memory_tool("memory_save", {"content": "x"}, "u1"))
+ assert errored == {"status": "error", "error": "save failed"}
+
+
+async def test_execute_save_handles_search_failure_and_background_dedup_filters(
+ handler: MemoryHandler,
+) -> None:
+ backend = FakeBackend()
+ handler._backend = backend
+
+ backend.raise_on = "search"
+ saved = json.loads(await handler._execute_save({"content": "Useful fact"}, "u1"))
+ assert saved == {"status": "saved", "memory_id": "mem-1", "content": "Useful fact"}
+
+ backend.raise_on = None
+ similar = [
+ make_result("mem-1", "same", score=0.99),
+ make_result("old-1", "duplicate", score=0.95, metadata={}),
+ make_result("old-2", "already handled", score=0.99, metadata={"superseded_by": "new"}),
+ make_result("old-3", "too low", score=0.5, metadata={}),
+ ]
+ await handler._background_dedup("mem-1", similar, "u1")
+ assert backend.deleted == ["old-1"]
+
+ backend.raise_on = "delete"
+ await handler._background_dedup("mem-1", [make_result("old-4", "duplicate", score=0.95)], "u1")
+
+
+def test_inject_tools_extract_query_and_has_tool_calls(
+ handler: MemoryHandler, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(
+ handler,
+ "_get_memory_tools",
+ lambda: [
+ {
+ "function": {
+ "name": "memory_save",
+ "description": "save memory",
+ "parameters": {"type": "object"},
+ }
+ }
+ ],
+ )
+
+ anthropic_tools, injected = handler.inject_tools([], "anthropic")
+ assert injected is True
+ assert anthropic_tools == [{"type": "memory_20250818", "name": "memory"}]
+
+ custom_handler = MemoryHandler(
+ MemoryConfig(enabled=False, inject_tools=True), agent_type="codex"
+ )
+ monkeypatch.setattr(
+ custom_handler,
+ "_get_memory_tools",
+ lambda: [
+ {
+ "function": {
+ "name": "memory_save",
+ "description": "save memory",
+ "parameters": {"type": "object"},
+ }
+ }
+ ],
+ )
+ anthropic_custom, injected_custom = custom_handler.inject_tools([], "anthropic")
+ assert injected_custom is True
+ assert anthropic_custom == [
+ {"name": "memory_save", "description": "save memory", "input_schema": {"type": "object"}}
+ ]
+ openai_custom, _ = custom_handler.inject_tools([], "openai")
+ assert openai_custom == [
+ {
+ "function": {
+ "name": "memory_save",
+ "description": "save memory",
+ "parameters": {"type": "object"},
+ }
+ }
+ ]
+ existing, was_injected = custom_handler.inject_tools(
+ [{"function": {"name": "memory_save"}}],
+ "openai",
+ )
+ assert was_injected is False
+ assert existing == [{"function": {"name": "memory_save"}}]
+
+ assert handler._extract_user_query([{"role": "assistant", "content": "skip"}]) == ""
+ assert handler._extract_user_query([{"role": "user", "content": "x" * 600}]) == "x" * 500
+ assert (
+ handler._extract_user_query(
+ [{"role": "user", "content": [{"type": "text", "text": "hello"}, {"type": "image"}]}]
+ )
+ == "hello"
+ )
+
+ anthropic_response = {
+ "content": [{"type": "tool_use", "name": "memory_save", "id": "1", "input": {}}]
+ }
+ openai_response = {
+ "choices": [{"message": {"tool_calls": [{"id": "1", "function": {"name": "memory_save"}}]}}]
+ }
+ responses_api = {"output": [{"type": "function_call", "call_id": "2", "name": "memory"}]}
+ assert handler.has_memory_tool_calls(anthropic_response, "anthropic") is True
+ assert handler.has_memory_tool_calls(openai_response, "openai") is True
+ assert handler.has_memory_tool_calls(responses_api, "openai") is True
+ assert handler.has_memory_tool_calls({"content": []}, "anthropic") is False
+
+
+async def test_memory_handler_misc_helpers(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ handler = MemoryHandler(
+ MemoryConfig(
+ enabled=False,
+ use_native_tool=True,
+ inject_tools=True,
+ native_memory_dir=str(tmp_path / "native"),
+ ),
+ agent_type="codex",
+ )
+ first_lock = handler._get_init_lock()
+ assert handler._get_init_lock() is first_lock
+ assert handler.get_beta_headers() == {"anthropic-beta": "context-management-2025-06-27"}
+
+ disabled_headers = MemoryHandler(
+ MemoryConfig(enabled=False, use_native_tool=False), agent_type="codex"
+ )
+ assert disabled_headers.get_beta_headers() == {}
+
+ tools, injected = handler._inject_native_tool([])
+ assert injected is True
+ assert tools == [{"type": "memory_20250818", "name": "memory"}]
+ same_tools, same_injected = handler._inject_native_tool([{"name": "memory"}])
+ assert same_injected is False
+ assert same_tools == [{"name": "memory"}]
+
+ calls = {"count": 0}
+ monkeypatch.setitem(
+ __import__("sys").modules,
+ "headroom.memory.tools",
+ SimpleNamespace(
+ get_memory_tools_optimized=lambda: calls.__setitem__("count", calls["count"] + 1)
+ or [{"name": "tool"}]
+ ),
+ )
+ cache_handler = MemoryHandler(MemoryConfig(enabled=False), agent_type="codex")
+ assert cache_handler._get_memory_tools() == [{"name": "tool"}]
+ assert cache_handler._get_memory_tools() == [{"name": "tool"}]
+ assert calls["count"] == 1
+
+ assert cache_handler._extract_tool_calls(
+ {"content": [{"type": "tool_use", "id": "1"}]}, "anthropic"
+ ) == [{"type": "tool_use", "id": "1"}]
+ assert cache_handler._extract_tool_calls(
+ {"choices": [{"message": {"tool_calls": [{"id": "2"}]}}]},
+ "openai",
+ ) == [{"id": "2"}]
+ assert cache_handler._extract_tool_calls(
+ {"output": [{"type": "function_call", "call_id": "3"}]},
+ "openai",
+ ) == [{"type": "function_call", "call_id": "3"}]
+ assert cache_handler._extract_tool_calls({}, "other") == []
+
+ closed: list[str] = []
+
+ class Closable:
+ async def close(self) -> None:
+ closed.append("closed")
+
+ await cache_handler._close_backend_instance(Closable(), reason="test")
+ assert closed == ["closed"]
+ await cache_handler._close_backend_instance(SimpleNamespace(), reason="test")
+
+ class BrokenCloser:
+ def close(self) -> None:
+ raise RuntimeError("boom")
+
+ await cache_handler._close_backend_instance(BrokenCloser(), reason="test")
+
+
+async def test_search_and_format_context_and_handle_memory_tool_calls(
+ handler: MemoryHandler, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ backend = FakeBackend()
+ handler._backend = backend
+ handler._initialized = True
+ backend.search_results = [
+ make_result("m1", "Alice likes pizza", score=0.8, related_entities=["Alice", "pizza"]),
+ make_result("m2", "below threshold", score=0.2),
+ ]
+
+ inject_none = await handler.search_and_format_context(
+ "u1",
+ [{"role": "assistant", "content": "skip"}],
+ )
+ assert inject_none is None
+
+ context = await handler.search_and_format_context(
+ "u1",
+ [{"role": "user", "content": "What food does Alice like?"}],
+ )
+ assert "## Relevant Memories for This User" in context
+ assert "1. Alice likes pizza" in context
+ assert "(Related: Alice, pizza)" in context
+
+ backend.raise_on = "search"
+ assert (
+ await handler.search_and_format_context("u1", [{"role": "user", "content": "Question"}])
+ is None
+ )
+ backend.raise_on = None
+
+ async def fake_ensure_initialized() -> None:
+ return None
+
+ async def fake_execute_memory_tool(tool_name, input_data, user_id, provider="anthropic"): # noqa: ANN001
+ return f"ran:{tool_name}:{user_id}:{provider}:{input_data}"
+
+ async def fake_execute_native(input_data, user_id): # noqa: ANN001
+ return f"native:{user_id}:{input_data}"
+
+ monkeypatch.setattr(handler, "_ensure_initialized", fake_ensure_initialized)
+ monkeypatch.setattr(handler, "_execute_memory_tool", fake_execute_memory_tool)
+ monkeypatch.setattr(handler, "_execute_native_memory_tool", fake_execute_native)
+
+ anthropic_results = await handler.handle_memory_tool_calls(
+ {
+ "content": [
+ {"type": "tool_use", "name": "memory_save", "id": "a1", "input": {"content": "x"}},
+ {"type": "tool_use", "name": "memory", "id": "a2", "input": {"command": "view"}},
+ {"type": "tool_use", "name": "other", "id": "a3", "input": {}},
+ ]
+ },
+ "u1",
+ "anthropic",
+ )
+ assert anthropic_results == [
+ {
+ "type": "tool_result",
+ "tool_use_id": "a1",
+ "content": "ran:memory_save:u1:anthropic:{'content': 'x'}",
+ },
+ {"type": "tool_result", "tool_use_id": "a2", "content": "native:u1:{'command': 'view'}"},
+ ]
+
+ openai_results = await handler.handle_memory_tool_calls(
+ {
+ "choices": [
+ {
+ "message": {
+ "tool_calls": [
+ {
+ "id": "o1",
+ "function": {
+ "name": "memory_search",
+ "arguments": '{"query":"pizza"}',
+ },
+ },
+ {"id": "o2", "function": {"name": "other", "arguments": "{}"}},
+ ]
+ }
+ }
+ ]
+ },
+ "u1",
+ "openai",
+ )
+ assert openai_results == [
+ {
+ "role": "tool",
+ "tool_call_id": "o1",
+ "content": "ran:memory_search:u1:openai:{'query': 'pizza'}",
+ }
+ ]
+
+ handler._backend = None
+ skipped = await handler.handle_memory_tool_calls(
+ {
+ "choices": [
+ {
+ "message": {
+ "tool_calls": [
+ {
+ "id": "o3",
+ "function": {"name": "memory_delete", "arguments": "{}"},
+ }
+ ]
+ }
+ }
+ ]
+ },
+ "u1",
+ "openai",
+ )
+ assert skipped == []
+
+
+async def test_ensure_initialized_timeout_and_cancellation(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ handler = MemoryHandler(
+ MemoryConfig(
+ enabled=True, use_native_tool=True, native_memory_dir=str(tmp_path / "native")
+ ),
+ agent_type="codex",
+ )
+ closed: list[str] = []
+
+ class ClosableBackend:
+ async def close(self) -> None:
+ closed.append("closed")
+
+ async def fake_init_backend_locked() -> None:
+ handler._backend = ClosableBackend()
+
+ monkeypatch.setattr(handler, "_init_backend_locked", fake_init_backend_locked)
+
+ async def fake_wait_for_timeout(coro, timeout): # noqa: ANN001
+ await coro
+ raise asyncio.TimeoutError
+
+ monkeypatch.setattr(memory_handler_module.asyncio, "wait_for", fake_wait_for_timeout)
+ await handler._ensure_initialized()
+ assert handler.backend is None
+ assert handler.initialized is False
+ assert closed == ["closed"]
+
+ async def fake_wait_for_cancel(coro, timeout): # noqa: ANN001
+ await coro
+ raise asyncio.CancelledError
+
+ monkeypatch.setattr(memory_handler_module.asyncio, "wait_for", fake_wait_for_cancel)
+ with pytest.raises(asyncio.CancelledError):
+ await handler._ensure_initialized()
+ assert handler.backend is None
+ assert handler.initialized is False
+ assert closed == ["closed", "closed"]
+
+
+async def test_init_backend_locked_local_and_bridge_import(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ handler = MemoryHandler(
+ MemoryConfig(
+ enabled=True,
+ backend="local",
+ db_path=str(tmp_path / "memory.db"),
+ bridge_enabled=True,
+ bridge_auto_import=True,
+ bridge_md_paths=[str(tmp_path / "notes.md")],
+ bridge_md_format="auto",
+ bridge_export_path=str(tmp_path / "export"),
+ ),
+ agent_type="codex",
+ )
+ seen: dict[str, object] = {}
+
+ class FakeLocalBackendConfig:
+ def __init__(self, **kwargs): # noqa: ANN003
+ seen["config"] = kwargs
+ for key, value in kwargs.items():
+ setattr(self, key, value)
+
+ class FakeLocalBackend:
+ def __init__(self, config) -> None: # noqa: ANN001
+ seen["backend_config"] = config
+
+ async def _ensure_initialized(self) -> None:
+ seen["backend_initialized"] = True
+
+ async def fake_init_and_import_bridge() -> None:
+ seen["bridge_called"] = True
+
+ monkeypatch.setitem(
+ sys.modules,
+ "headroom.memory.backends.local",
+ SimpleNamespace(
+ LocalBackend=FakeLocalBackend,
+ LocalBackendConfig=FakeLocalBackendConfig,
+ ),
+ )
+ monkeypatch.setitem(sys.modules, "onnxruntime", SimpleNamespace())
+ monkeypatch.setattr(handler, "_init_and_import_bridge", fake_init_and_import_bridge)
+
+ await handler._init_backend_locked()
+
+ assert handler.initialized is True
+ assert seen["backend_initialized"] is True
+ assert seen["bridge_called"] is True
+ assert seen["config"] == {
+ "db_path": str(tmp_path / "memory.db"),
+ "embedder_backend": "onnx",
+ "embedder_model": "all-MiniLM-L6-v2",
+ "vector_dimension": 384,
+ }
+
+
+async def test_init_and_import_bridge_success_and_failure(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ handler = MemoryHandler(
+ MemoryConfig(
+ enabled=True,
+ bridge_enabled=True,
+ bridge_md_paths=[str(tmp_path / "notes.md")],
+ bridge_md_format="auto",
+ bridge_export_path=str(tmp_path / "export"),
+ ),
+ agent_type="codex",
+ )
+ handler._backend = object()
+ seen: dict[str, object] = {}
+
+ class FakeMarkdownFormat(str):
+ pass
+
+ class FakeBridgeConfig:
+ def __init__(self, **kwargs): # noqa: ANN003
+ seen["bridge_config"] = kwargs
+
+ class FakeMemoryBridge:
+ def __init__(self, config, backend) -> None: # noqa: ANN001
+ seen["bridge_backend"] = backend
+ self.config = config
+
+ async def import_from_markdown(self):
+ return SimpleNamespace(sections_imported=2, sections_skipped_duplicate=1)
+
+ monkeypatch.setitem(
+ sys.modules,
+ "headroom.memory.bridge",
+ SimpleNamespace(MemoryBridge=FakeMemoryBridge),
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "headroom.memory.bridge_config",
+ SimpleNamespace(
+ BridgeConfig=FakeBridgeConfig,
+ MarkdownFormat=FakeMarkdownFormat,
+ ),
+ )
+
+ await handler._init_and_import_bridge()
+ assert isinstance(handler._bridge, FakeMemoryBridge)
+ assert seen["bridge_backend"] is handler._backend
+ assert seen["bridge_config"] == {
+ "md_paths": [tmp_path / "notes.md"],
+ "md_format": "auto",
+ "auto_import_on_startup": True,
+ "export_path": tmp_path / "export",
+ }
+
+ class BrokenMemoryBridge(FakeMemoryBridge):
+ async def import_from_markdown(self):
+ raise RuntimeError("bridge failed")
+
+ handler._bridge = None
+ monkeypatch.setitem(
+ sys.modules,
+ "headroom.memory.bridge",
+ SimpleNamespace(MemoryBridge=BrokenMemoryBridge),
+ )
+ await handler._init_and_import_bridge()
+ assert isinstance(handler._bridge, BrokenMemoryBridge)
+
+
+def test_memory_handler_init_defaults_and_tool_injection_edges(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ native_dir = tmp_path / "workspace-memory"
+ monkeypatch.setattr(
+ "headroom.paths.native_memory_dir",
+ lambda: native_dir,
+ )
+ handler = MemoryHandler(MemoryConfig(enabled=False, use_native_tool=True), agent_type="codex")
+ assert handler._native_memory_dir == native_dir
+ assert native_dir.exists()
+
+ disabled_injection = MemoryHandler(
+ MemoryConfig(enabled=False, inject_tools=False, use_native_tool=False),
+ agent_type="codex",
+ )
+ assert disabled_injection.inject_tools(None, "openai") == ([], False)
+
+ same_type_tools, same_type_injected = handler._inject_native_tool(
+ [{"type": "memory_20250818", "name": "other"}]
+ )
+ assert same_type_injected is False
+ assert same_type_tools == [{"type": "memory_20250818", "name": "other"}]
+
+
+async def test_ensure_initialized_fast_paths_and_qdrant_variants(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ disabled = MemoryHandler(MemoryConfig(enabled=False), agent_type="codex")
+ await disabled._ensure_initialized()
+ assert disabled.initialized is False
+
+ initialized = MemoryHandler(MemoryConfig(enabled=True), agent_type="codex")
+ initialized._initialized = True
+ await initialized._ensure_initialized()
+ assert initialized.initialized is True
+
+ qdrant_handler = MemoryHandler(
+ MemoryConfig(enabled=True, backend="qdrant-neo4j"),
+ agent_type="codex",
+ )
+ seen: dict[str, object] = {}
+
+ class FakeMem0Config:
+ def __init__(self, **kwargs): # noqa: ANN003
+ seen["config"] = kwargs
+
+ class FakeAdapter:
+ def __init__(self, config) -> None: # noqa: ANN001
+ seen["adapter_config"] = config
+
+ async def ensure_initialized(self) -> None:
+ seen["initialized"] = True
+
+ monkeypatch.setitem(
+ sys.modules,
+ "headroom.memory.backends.direct_mem0",
+ SimpleNamespace(DirectMem0Adapter=FakeAdapter, Mem0Config=FakeMem0Config),
+ )
+ await qdrant_handler._init_backend_locked()
+ assert qdrant_handler.initialized is True
+ assert seen["initialized"] is True
+ assert seen["config"] == {
+ "qdrant_host": "localhost",
+ "qdrant_port": 6333,
+ "neo4j_uri": "neo4j://localhost:7687",
+ "neo4j_user": "neo4j",
+ "neo4j_password": "password",
+ "enable_graph": True,
+ }
+
+ monkeypatch.setitem(sys.modules, "headroom.memory.backends.direct_mem0", None)
+ import builtins
+
+ real_import = builtins.__import__
+
+ def fake_import(name, globals=None, locals=None, fromlist=(), level=0):
+ if name == "headroom.memory.backends.direct_mem0":
+ raise ImportError("missing mem0")
+ return real_import(name, globals, locals, fromlist, level)
+
+ monkeypatch.setattr(builtins, "__import__", fake_import)
+ broken_qdrant = MemoryHandler(
+ MemoryConfig(enabled=True, backend="qdrant-neo4j"),
+ agent_type="codex",
+ )
+ with pytest.raises(ImportError, match="missing mem0"):
+ await broken_qdrant._init_backend_locked()
+ monkeypatch.setattr(builtins, "__import__", real_import)
+
+ unknown = MemoryHandler(MemoryConfig(enabled=True, backend="local"), agent_type="codex")
+ unknown.config.backend = "mystery" # type: ignore[assignment]
+ with pytest.raises(ValueError, match="Unknown memory backend"):
+ await unknown._init_backend_locked()
+
+
+async def test_init_and_import_bridge_early_return_and_context_formatting_edges(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ handler = MemoryHandler(
+ MemoryConfig(
+ enabled=True, bridge_enabled=True, bridge_md_paths=[str(tmp_path / "notes.md")]
+ ),
+ agent_type="codex",
+ )
+ handler._bridge = object()
+ await handler._init_and_import_bridge()
+ assert handler._bridge is not None
+
+ handler.config.inject_context = False
+ assert (
+ await handler.search_and_format_context("u1", [{"role": "user", "content": "hello"}])
+ is None
+ )
+
+ handler.config.inject_context = True
+ handler._backend = FakeBackend()
+ handler._initialized = True
+ handler._backend.search_results = [make_result("m1", "too low", score=0.1)]
+ assert (
+ await handler.search_and_format_context(
+ "u1", [{"role": "user", "content": [{"type": "image"}]}]
+ )
+ is None
+ )
+ assert (
+ await handler.search_and_format_context("u1", [{"role": "user", "content": "hello"}])
+ is None
+ )
+
+
+async def test_extract_tool_calls_and_handle_tool_calls_parse_edges(
+ handler: MemoryHandler, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ assert handler._extract_tool_calls({"content": "bad"}, "anthropic") == []
+ assert handler._extract_tool_calls({"choices": []}, "openai") == []
+ assert handler._extract_tool_calls({"output": "bad"}, "openai") == []
+
+ backend = FakeBackend()
+ handler._backend = backend
+
+ async def fake_ensure_initialized() -> None:
+ return None
+
+ async def fake_execute(tool_name, input_data, user_id, provider="anthropic"): # noqa: ANN001
+ return f"ok:{tool_name}:{input_data}"
+
+ monkeypatch.setattr(handler, "_ensure_initialized", fake_ensure_initialized)
+ monkeypatch.setattr(handler, "_execute_memory_tool", fake_execute)
+
+ results = await handler.handle_memory_tool_calls(
+ {
+ "output": [
+ {
+ "type": "function_call",
+ "call_id": "fc1",
+ "name": "memory_search",
+ "arguments": "{bad",
+ },
+ {"type": "function_call", "call_id": "fc2", "name": "other", "arguments": "{}"},
+ ]
+ },
+ "u1",
+ "openai",
+ )
+ assert results == [{"role": "tool", "tool_call_id": "fc1", "content": "ok:memory_search:{}"}]
diff --git a/tests/test_memory_wrapper.py b/tests/test_memory_wrapper.py
new file mode 100644
index 000000000..8f2bb41a8
--- /dev/null
+++ b/tests/test_memory_wrapper.py
@@ -0,0 +1,206 @@
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from headroom.memory.config import EmbedderBackend
+from headroom.memory.wrapper import MemoryWrapper, _MemoryAPI, with_memory
+
+
+class FakeMemory:
+ def __init__(self) -> None:
+ self.search_results: list[object] = []
+ self.add_calls: list[dict[str, object]] = []
+ self.query_results: list[object] = []
+ self.clear_result = 0
+
+ async def search(self, **kwargs): # noqa: ANN003
+ self.last_search = kwargs
+ return self.search_results
+
+ async def add(self, **kwargs): # noqa: ANN003
+ self.add_calls.append(kwargs)
+ return SimpleNamespace(id=f"mem-{len(self.add_calls)}", **kwargs)
+
+ async def query(self, filter_value): # noqa: ANN001, ANN201
+ self.last_filter = filter_value
+ return self.query_results
+
+ async def clear_scope(self, **kwargs): # noqa: ANN003
+ self.last_clear = kwargs
+ return self.clear_result
+
+
+def make_client(content: str = "raw response") -> tuple[object, object]:
+ response = SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=content))])
+
+ def create(**kwargs): # noqa: ANN003, ANN202
+ create.kwargs = kwargs
+ return response
+
+ client = SimpleNamespace(chat=SimpleNamespace(completions=SimpleNamespace(create=create)))
+ return client, response
+
+
+def test_memory_wrapper_lazy_initialization_and_factory(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, _response = make_client()
+ fake_memory = FakeMemory()
+ seen: dict[str, object] = {}
+
+ async def fake_create(config): # noqa: ANN001
+ seen["config"] = config
+ return fake_memory
+
+ monkeypatch.setattr("headroom.memory.wrapper.HierarchicalMemory.create", fake_create)
+
+ wrapper = MemoryWrapper(
+ client,
+ user_id="alice",
+ db_path="memory.db",
+ top_k=7,
+ session_id="session-1",
+ agent_id="agent-1",
+ embedder_backend=EmbedderBackend.OPENAI,
+ openai_api_key="sk-test",
+ )
+
+ assert wrapper.chat.completions._wrapper is wrapper
+ assert wrapper._initialized is False
+
+ api = wrapper.memory
+ assert isinstance(api, _MemoryAPI)
+ assert wrapper._initialized is True
+ assert wrapper._memory is fake_memory
+ assert seen["config"].db_path == Path("memory.db")
+ assert seen["config"].embedder_backend == EmbedderBackend.OPENAI
+ assert seen["config"].openai_api_key == "sk-test"
+
+ wrapped = with_memory(client, user_id="bob", session_id="s2", agent_id="a2", top_k=3)
+ assert isinstance(wrapped, MemoryWrapper)
+ assert wrapped._client is client
+ assert wrapped._user_id == "bob"
+ assert wrapped._session_id == "s2"
+ assert wrapped._agent_id == "a2"
+ assert wrapped._top_k == 3
+
+
+def test_inject_memories_handles_empty_and_inserts_context() -> None:
+ client, _response = make_client()
+ fake_memory = FakeMemory()
+ wrapper = MemoryWrapper(client, user_id="alice", _memory=fake_memory)
+
+ no_user = [{"role": "assistant", "content": "skip"}]
+ assert wrapper._inject_memories(no_user) == no_user
+
+ messages = [{"role": "user", "content": "Question?"}]
+ assert wrapper._inject_memories(messages) == messages
+
+ fake_memory.search_results = [
+ SimpleNamespace(memory=SimpleNamespace(content="Prefers Python")),
+ SimpleNamespace(memory=SimpleNamespace(content="Works on APIs")),
+ ]
+ original = [
+ {"role": "system", "content": "System"},
+ {"role": "user", "content": "Question?"},
+ {"role": "user", "content": "Follow-up"},
+ ]
+ injected = wrapper._inject_memories(original)
+
+ assert original[1]["content"] == "Question?"
+ assert injected[1]["content"].startswith(
+ "<context>\n- Prefers Python\n- Works on APIs\n</context>\n\n"
+ )
+ assert injected[2]["content"] == "Follow-up"
+ assert fake_memory.last_search == {
+ "query": "Follow-up",
+ "user_id": "alice",
+ "session_id": None,
+ "top_k": 5,
+ }
+
+
+def test_store_memories_persists_only_nonempty_content() -> None:
+ client, _response = make_client()
+ fake_memory = FakeMemory()
+ wrapper = MemoryWrapper(
+ client,
+ user_id="alice",
+ session_id="session-1",
+ agent_id="agent-1",
+ _memory=fake_memory,
+ )
+
+ wrapper._store_memories([{"content": "Remember this"}, {"content": ""}, {}])
+
+ assert fake_memory.add_calls == [
+ {
+ "content": "Remember this",
+ "user_id": "alice",
+ "session_id": "session-1",
+ "agent_id": "agent-1",
+ "importance": 0.7,
+ }
+ ]
+
+
+def test_wrapped_completions_create_injects_parses_and_stores(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ client, response = make_client("raw completion")
+ wrapper = MemoryWrapper(client, user_id="alice", _memory=FakeMemory())
+ stored: list[list[dict[str, str]]] = []
+
+ monkeypatch.setattr(
+ wrapper,
+ "_inject_memories",
+ lambda messages: [{"role": "user", "content": "enhanced"}],
+ )
+ monkeypatch.setattr(
+ "headroom.memory.wrapper.inject_memory_instruction",
+ lambda messages, short=True: messages
+ + [{"role": "system", "content": "memory-instruction"}],
+ )
+ monkeypatch.setattr(
+ "headroom.memory.wrapper.parse_response_with_memory",
+ lambda content: SimpleNamespace(
+ content="clean response",
+ memories=[{"content": "saved memory"}],
+ ),
+ )
+ monkeypatch.setattr(wrapper, "_store_memories", lambda memories: stored.append(memories))
+
+ result = wrapper.chat.completions.create(
+ messages=[{"role": "user", "content": "hello"}], model="x"
+ )
+
+ assert result is response
+ assert response.choices[0].message.content == "clean response"
+ assert client.chat.completions.create.kwargs["messages"] == [
+ {"role": "user", "content": "enhanced"},
+ {"role": "system", "content": "memory-instruction"},
+ ]
+ assert stored == [[{"content": "saved memory"}]]
+
+
+def test_memory_api_methods_delegate_to_underlying_memory() -> None:
+ fake_memory = FakeMemory()
+ memory_one = SimpleNamespace(id="m1", content="alpha")
+ memory_two = SimpleNamespace(id="m2", content="beta")
+ fake_memory.search_results = [
+ SimpleNamespace(memory=memory_one),
+ SimpleNamespace(memory=memory_two),
+ ]
+ fake_memory.query_results = [memory_one, memory_two]
+ fake_memory.clear_result = 2
+
+ api = _MemoryAPI(fake_memory, user_id="alice", session_id="session-1", agent_id="agent-1")
+
+ assert api.search("alpha", top_k=3) == [memory_one, memory_two]
+ added = api.add("new memory", importance=0.9)
+ assert added.content == "new memory"
+ assert api.get_all() == [memory_one, memory_two]
+ assert api.clear() == 2
+ assert api.stats() == {"total": 2}
+ assert fake_memory.last_clear == {"user_id": "alice"}
diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py
new file mode 100644
index 000000000..f6229a02e
--- /dev/null
+++ b/tests/test_pipeline.py
@@ -0,0 +1,130 @@
+from __future__ import annotations
+
+import importlib.metadata
+from dataclasses import dataclass
+
+from headroom.pipeline import (
+ CANONICAL_PIPELINE_STAGES,
+ ENTRY_POINT_GROUP,
+ PipelineEvent,
+ PipelineExtensionManager,
+ PipelineStage,
+ discover_pipeline_extensions,
+ summarize_routing_markers,
+)
+
+
+@dataclass
+class FakeEntryPoint:
+ name: str
+ value: object
+
+ def load(self):
+ if isinstance(self.value, Exception):
+ raise self.value
+ return self.value
+
+
+def test_discover_pipeline_extensions_handles_load_and_init_failures(
+ monkeypatch,
+) -> None:
+ class WorkingExtension:
+ def on_pipeline_event(self, event: PipelineEvent): # noqa: ANN001, ANN201
+ return event
+
+ class NeedsInit:
+ def __init__(self) -> None:
+ raise RuntimeError("bad init")
+
+ monkeypatch.setattr(
+ importlib.metadata,
+ "entry_points",
+ lambda group=None: [
+ FakeEntryPoint("working-instance", WorkingExtension()),
+ FakeEntryPoint("working-class", WorkingExtension),
+ FakeEntryPoint("bad-load", RuntimeError("bad load")),
+ FakeEntryPoint("bad-init", NeedsInit),
+ ]
+ if group == ENTRY_POINT_GROUP
+ else [],
+ )
+
+ discovered = discover_pipeline_extensions()
+ assert len(discovered) == 2
+ assert all(callable(getattr(ext, "on_pipeline_event", None)) for ext in discovered)
+
+
+def test_discover_pipeline_extensions_handles_enumeration_failure(monkeypatch) -> None:
+ monkeypatch.setattr(
+ importlib.metadata,
+ "entry_points",
+ lambda group=None: (_ for _ in ()).throw(RuntimeError("boom")),
+ )
+ assert discover_pipeline_extensions() == []
+
+
+def test_pipeline_manager_emit_and_summary(monkeypatch) -> None:
+ class Hook:
+ def __init__(self) -> None:
+ self.seen: list[str] = []
+
+ def on_pipeline_event(self, event: PipelineEvent): # noqa: ANN001, ANN201
+ self.seen.append(event.stage.value)
+ event.metadata["hook"] = True
+ return event
+
+ class ReplacingExtension:
+ def on_pipeline_event(self, event: PipelineEvent): # noqa: ANN001, ANN201
+ return PipelineEvent(
+ stage=event.stage,
+ operation=event.operation,
+ request_id=event.request_id,
+ provider=event.provider,
+ model=event.model,
+ messages=event.messages,
+ tools=event.tools,
+ headers=event.headers,
+ response=event.response,
+ metadata={**event.metadata, "replaced": True},
+ )
+
+ class BrokenExtension:
+ def on_pipeline_event(self, event: PipelineEvent): # noqa: ANN001, ANN201
+ raise RuntimeError("boom")
+
+ hook = Hook()
+ monkeypatch.setattr(
+ "headroom.pipeline.discover_pipeline_extensions",
+ lambda: [BrokenExtension()],
+ )
+
+ manager = PipelineExtensionManager(
+ hooks=hook,
+ extensions=[object(), ReplacingExtension()],
+ discover=True,
+ )
+
+ assert manager.enabled is True
+ event = manager.emit(
+ PipelineStage.INPUT_RECEIVED,
+ operation="compress",
+ request_id="req-1",
+ provider="openai",
+ model="gpt-4o",
+ messages=[{"role": "user", "content": "hello"}],
+ metadata={"start": True},
+ )
+
+ assert hook.seen == ["input_received"]
+ assert event.metadata == {"start": True, "hook": True, "replaced": True}
+ assert event.request_id == "req-1"
+
+ disabled = PipelineExtensionManager(discover=False)
+ assert disabled.enabled is False
+
+ assert summarize_routing_markers(["router:smart", "other", "router:cheap"]) == [
+ "router:smart",
+ "router:cheap",
+ ]
+ assert PipelineStage.SETUP in CANONICAL_PIPELINE_STAGES
+ assert PipelineStage.RESPONSE_RECEIVED in CANONICAL_PIPELINE_STAGES
diff --git a/tests/test_pricing.py b/tests/test_pricing.py
new file mode 100644
index 000000000..b3b94d3d1
--- /dev/null
+++ b/tests/test_pricing.py
@@ -0,0 +1,130 @@
+from __future__ import annotations
+
+from dataclasses import FrozenInstanceError
+from datetime import date, timedelta
+
+import pytest
+
+import headroom.pricing as pricing
+from headroom.pricing.anthropic_prices import ANTHROPIC_PRICES, get_anthropic_registry
+from headroom.pricing.openai_prices import OPENAI_PRICES, get_openai_registry
+from headroom.pricing.registry import ModelPricing, PricingRegistry
+
+
+def test_pricing_public_exports_and_provider_registries() -> None:
+ assert pricing.ModelPricing is ModelPricing
+ assert pricing.PricingRegistry is PricingRegistry
+ assert "get_openai_registry" in pricing.__all__
+ assert "get_anthropic_registry" in pricing.__all__
+ assert "estimate_cost" in pricing.__all__
+
+ openai_registry = get_openai_registry()
+ anthropic_registry = get_anthropic_registry()
+ assert openai_registry.source_url == "https://openai.com/api/pricing/"
+ assert anthropic_registry.source_url == "https://www.anthropic.com/pricing"
+ assert openai_registry.prices["gpt-4o"] == OPENAI_PRICES["gpt-4o"]
+ assert (
+ anthropic_registry.prices["claude-3-5-sonnet-20241022"]
+ == ANTHROPIC_PRICES["claude-3-5-sonnet-20241022"]
+ )
+
+ openai_registry.prices.pop("gpt-4o")
+ anthropic_registry.prices.pop("claude-3-5-sonnet-20241022")
+ assert "gpt-4o" in OPENAI_PRICES
+ assert "claude-3-5-sonnet-20241022" in ANTHROPIC_PRICES
+
+
+def test_model_pricing_is_frozen() -> None:
+ model = ModelPricing(model="demo", provider="test", input_per_1m=1.5, output_per_1m=2.5)
+ with pytest.raises(FrozenInstanceError):
+ model.model = "other" # type: ignore[misc]
+
+
+def test_registry_staleness_and_warning() -> None:
+ fresh = PricingRegistry(last_updated=date.today() - timedelta(days=30))
+ assert fresh.is_stale() is False
+ assert fresh.staleness_warning() is None
+
+ stale = PricingRegistry(
+ last_updated=date.today() - timedelta(days=31),
+ source_url="https://example.test/pricing",
+ )
+ assert stale.is_stale() is True
+ assert stale.staleness_warning() == (
+ f"Pricing data is 31 days old (last updated: {stale.last_updated})."
+ " Please verify at: https://example.test/pricing"
+ )
+
+
+def test_registry_estimate_cost_with_all_token_types() -> None:
+ registry = PricingRegistry(
+ last_updated=date.today() - timedelta(days=31),
+ prices={
+ "demo": ModelPricing(
+ model="demo",
+ provider="test",
+ input_per_1m=2.0,
+ output_per_1m=4.0,
+ cached_input_per_1m=1.0,
+ batch_input_per_1m=0.5,
+ batch_output_per_1m=0.25,
+ )
+ },
+ )
+
+ estimate = registry.estimate_cost(
+ "demo",
+ input_tokens=1_000_000,
+ output_tokens=500_000,
+ cached_input_tokens=250_000,
+ batch_input_tokens=200_000,
+ batch_output_tokens=100_000,
+ )
+
+ assert estimate.cost_usd == pytest.approx(4.375)
+ assert estimate.breakdown == {
+ "input": {"tokens": 1_000_000, "rate_per_1m": 2.0, "cost_usd": 2.0},
+ "output": {"tokens": 500_000, "rate_per_1m": 4.0, "cost_usd": 2.0},
+ "cached_input": {"tokens": 250_000, "rate_per_1m": 1.0, "cost_usd": 0.25},
+ "batch_input": {"tokens": 200_000, "rate_per_1m": 0.5, "cost_usd": 0.1},
+ "batch_output": {"tokens": 100_000, "rate_per_1m": 0.25, "cost_usd": 0.025},
+ }
+ assert estimate.pricing_date == registry.last_updated
+ assert estimate.is_stale is True
+ assert estimate.warning == (
+ f"Pricing data is 31 days old (last updated: {registry.last_updated})."
+ )
+
+
+def test_registry_estimate_cost_zero_usage_returns_empty_breakdown() -> None:
+ registry = PricingRegistry(
+ last_updated=date.today(),
+ prices={
+ "demo": ModelPricing(model="demo", provider="test", input_per_1m=1.0, output_per_1m=2.0)
+ },
+ )
+ estimate = registry.estimate_cost("demo")
+ assert estimate.cost_usd == 0.0
+ assert estimate.breakdown == {}
+ assert estimate.is_stale is False
+ assert estimate.warning is None
+
+
+ ("kwargs", "message"),
+ [
+ ({}, "Model 'missing' not found in registry"),
+ ({"cached_input_tokens": 1}, "Model 'demo' does not have cached input pricing"),
+ ({"batch_input_tokens": 1}, "Model 'demo' does not have batch input pricing"),
+ ({"batch_output_tokens": 1}, "Model 'demo' does not have batch output pricing"),
+ ],
+)
+def test_registry_estimate_cost_error_paths(kwargs: dict[str, int], message: str) -> None:
+ registry = PricingRegistry(
+ last_updated=date.today(),
+ prices={
+ "demo": ModelPricing(model="demo", provider="test", input_per_1m=1.0, output_per_1m=2.0)
+ },
+ )
+ with pytest.raises(ValueError, match=message):
+ registry.estimate_cost("missing" if not kwargs else "demo", **kwargs)
diff --git a/tests/test_pricing_litellm.py b/tests/test_pricing_litellm.py
new file mode 100644
index 000000000..1abde321d
--- /dev/null
+++ b/tests/test_pricing_litellm.py
@@ -0,0 +1,97 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from headroom.pricing import litellm_pricing
+
+
+def test_litellm_helpers_when_dependency_is_unavailable(monkeypatch) -> None:
+ monkeypatch.setattr(litellm_pricing, "LITELLM_AVAILABLE", False)
+ monkeypatch.setattr(litellm_pricing, "litellm", None)
+
+ assert litellm_pricing.get_litellm_model_cost() == {}
+ assert litellm_pricing.get_model_pricing("gpt-4o") is None
+ assert litellm_pricing.estimate_cost("gpt-4o", input_tokens=1, output_tokens=1) is None
+ assert litellm_pricing.list_available_models() == []
+
+
+def test_litellm_model_pricing_exact_match_and_defaults(monkeypatch) -> None:
+ fake_litellm = SimpleNamespace(
+ model_cost={
+ "gpt-4o": {
+ "input_cost_per_token": 0.0000025,
+ "output_cost_per_token": 0.00001,
+ "max_tokens": 128000,
+ }
+ }
+ )
+ monkeypatch.setattr(litellm_pricing, "LITELLM_AVAILABLE", True)
+ monkeypatch.setattr(litellm_pricing, "litellm", fake_litellm)
+
+ assert litellm_pricing.get_litellm_model_cost() == fake_litellm.model_cost
+ pricing = litellm_pricing.get_model_pricing("gpt-4o")
+ assert pricing is not None
+ assert pricing.model == "gpt-4o"
+ assert pricing.input_cost_per_1m == 2.5
+ assert pricing.output_cost_per_1m == 10.0
+ assert pricing.max_tokens == 128000
+ assert pricing.max_input_tokens is None
+ assert pricing.max_output_tokens is None
+ assert pricing.supports_vision is False
+ assert pricing.supports_function_calling is False
+ assert (
+ litellm_pricing.estimate_cost("gpt-4o", input_tokens=200_000, output_tokens=300_000) == 3.5
+ )
+ assert litellm_pricing.list_available_models() == ["gpt-4o"]
+
+
+def test_litellm_model_pricing_uses_provider_prefixes(monkeypatch) -> None:
+ fake_litellm = SimpleNamespace(
+ model_cost={
+ "openai/gpt-4o-mini": {
+ "input_cost_per_token": 0.00000015,
+ "output_cost_per_token": 0.0000006,
+ "supports_vision": True,
+ "supports_function_calling": True,
+ "max_input_tokens": 64000,
+ "max_output_tokens": 16000,
+ }
+ }
+ )
+ monkeypatch.setattr(litellm_pricing, "LITELLM_AVAILABLE", True)
+ monkeypatch.setattr(litellm_pricing, "litellm", fake_litellm)
+
+ pricing = litellm_pricing.get_model_pricing("gpt-4o-mini")
+ assert pricing is not None
+ assert pricing.input_cost_per_1m == 0.15
+ assert pricing.output_cost_per_1m == 0.6
+ assert pricing.max_input_tokens == 64000
+ assert pricing.max_output_tokens == 16000
+ assert pricing.supports_vision is True
+ assert pricing.supports_function_calling is True
+
+
+def test_litellm_model_pricing_uses_aliases_and_zero_cost_defaults(monkeypatch) -> None:
+ fake_litellm = SimpleNamespace(
+ model_cost={
+ "claude-sonnet-4-20250514": {
+ "input_cost_per_token": None,
+ "output_cost_per_token": None,
+ }
+ }
+ )
+ monkeypatch.setattr(litellm_pricing, "LITELLM_AVAILABLE", True)
+ monkeypatch.setattr(litellm_pricing, "litellm", fake_litellm)
+
+ pricing = litellm_pricing.get_model_pricing("claude-3-5-sonnet-20241022")
+ assert pricing is not None
+ assert pricing.model == "claude-3-5-sonnet-20241022"
+ assert pricing.input_cost_per_1m == 0
+ assert pricing.output_cost_per_1m == 0
+ assert litellm_pricing.estimate_cost("claude-3-5-sonnet-20241022", input_tokens=1) == 0
+
+
+def test_litellm_model_pricing_returns_none_for_unknown_models(monkeypatch) -> None:
+ monkeypatch.setattr(litellm_pricing, "LITELLM_AVAILABLE", True)
+ monkeypatch.setattr(litellm_pricing, "litellm", SimpleNamespace(model_cost={}))
+ assert litellm_pricing.get_model_pricing("missing") is None
diff --git a/tests/test_proxy_handlers_batch.py b/tests/test_proxy_handlers_batch.py
new file mode 100644
index 000000000..f082d2755
--- /dev/null
+++ b/tests/test_proxy_handlers_batch.py
@@ -0,0 +1,1047 @@
+from __future__ import annotations
+
+import json
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+from headroom.proxy.handlers import batch as batch_module
+
+
+class FakeResponse:
+ def __init__(
+ self,
+ *,
+ status_code: int = 200,
+ content: bytes = b"{}",
+ headers: dict[str, str] | None = None,
+ text: str | None = None,
+ json_data=None, # noqa: ANN001
+ ) -> None:
+ self.status_code = status_code
+ self.content = content
+ self.headers = headers or {}
+ self.text = text if text is not None else content.decode("utf-8", errors="ignore")
+ self._json_data = json_data
+
+ def json(self): # noqa: ANN201
+ if self._json_data is not None:
+ return self._json_data
+ return json.loads(self.text)
+
+
+class FakeHttpClient:
+ def __init__(self) -> None:
+ self.posts: list[dict[str, object]] = []
+ self.gets: list[dict[str, object]] = []
+ self.requests: list[dict[str, object]] = []
+ self.post_response = FakeResponse()
+ self.get_response = FakeResponse()
+ self.raise_post: Exception | None = None
+ self.raise_get: Exception | None = None
+
+ async def post(self, url: str, **kwargs): # noqa: ANN003, ANN201
+ self.posts.append({"url": url, **kwargs})
+ if self.raise_post is not None:
+ raise self.raise_post
+ return self.post_response
+
+ async def get(self, url: str, **kwargs): # noqa: ANN003, ANN201
+ self.gets.append({"url": url, **kwargs})
+ if self.raise_get is not None:
+ raise self.raise_get
+ return self.get_response
+
+ async def request(self, method: str, url: str, **kwargs): # noqa: ANN003, ANN201
+ self.requests.append({"method": method, "url": url, **kwargs})
+ if self.raise_get is not None:
+ raise self.raise_get
+ return self.get_response
+
+
+class FakeMetrics:
+ def __init__(self) -> None:
+ self.record_calls: list[dict[str, object]] = []
+ self.failed_calls: list[dict[str, object]] = []
+
+ async def record_request(self, **kwargs) -> None: # noqa: ANN003
+ self.record_calls.append(kwargs)
+
+ async def record_failed(self, **kwargs) -> None: # noqa: ANN003
+ self.failed_calls.append(kwargs)
+
+
+class DummyBatchHandler(batch_module.BatchHandlerMixin):
+ OPENAI_API_URL = "https://openai.example"
+ GEMINI_API_URL = "https://gemini.example"
+
+ def __init__(self) -> None:
+ self.http_client = FakeHttpClient()
+ self.metrics = FakeMetrics()
+ self.config = SimpleNamespace(
+ optimize=False,
+ ccr_inject_tool=False,
+ ccr_inject_system_instructions=False,
+ )
+ self.openai_provider = SimpleNamespace(get_context_limit=lambda model: 8192)
+ self.openai_pipeline = SimpleNamespace(apply=lambda **kwargs: None)
+ self._request_counter = 0
+ self._retry_response = FakeResponse()
+
+ async def _next_request_id(self) -> str:
+ self._request_counter += 1
+ return f"req-{self._request_counter}"
+
+ async def handle_passthrough(self, request, base_url): # noqa: ANN001, ANN201
+ return {"request": request, "base_url": base_url}
+
+ async def _retry_request(self, method, url, headers, body): # noqa: ANN001, ANN201
+ return self._retry_response
+
+ def _gemini_contents_to_messages(self, contents, system_instruction): # noqa: ANN001, ANN201
+ messages = [{"role": "user", "content": part["parts"][0]["text"]} for part in contents]
+ return messages, []
+
+ def _messages_to_gemini_contents(self, messages): # noqa: ANN001, ANN201
+ return ([{"parts": [{"text": message["content"]}]} for message in messages], None)
+
+
+class FakeRequest:
+ def __init__(
+ self,
+ body: bytes | str,
+ *,
+ headers: dict[str, str] | None = None,
+ method: str = "POST",
+ path: str = "/v1/batches",
+ query: str = "",
+ ) -> None:
+ self._body = body.encode("utf-8") if isinstance(body, str) else body
+ self.headers = headers or {}
+ self.method = method
+ self.url = SimpleNamespace(path=path, query=query)
+
+ async def body(self) -> bytes:
+ return self._body
+
+
+def install_batch_support_modules(
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ injector_result=None, # noqa: ANN001
+ tokenizer_count: int = 10,
+) -> None:
+ class FakeInjector:
+ def __init__(self, **kwargs) -> None: # noqa: ANN003
+ self.kwargs = kwargs
+
+ def process_request(self, messages, tools): # noqa: ANN001, ANN201
+ if injector_result is not None:
+ return injector_result
+ return messages, tools, False
+
+ class FakeTokenizer:
+ def count_messages(self, messages) -> int: # noqa: ANN001
+ return tokenizer_count
+
+ monkeypatch.setitem(sys.modules, "headroom.ccr", SimpleNamespace(CCRToolInjector=FakeInjector))
+ monkeypatch.setitem(
+ sys.modules,
+ "headroom.tokenizers",
+ SimpleNamespace(get_tokenizer=lambda model: FakeTokenizer()),
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "headroom.utils",
+ SimpleNamespace(extract_user_query=lambda messages: "query"),
+ )
+
+
+async def test_compress_batch_jsonl_without_optimization_handles_invalid_lines(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ install_batch_support_modules(monkeypatch, tokenizer_count=12)
+ handler = DummyBatchHandler()
+ content = "\n".join(
+ [
+ json.dumps(
+ {"body": {"model": "gpt-4o", "messages": [{"role": "user", "content": "hi"}]}}
+ ),
+ json.dumps({"body": {"model": "gpt-4o", "messages": []}}),
+ "not-json",
+ ]
+ )
+
+ lines, stats = await handler._compress_batch_jsonl(content, "req-1")
+
+ assert len(lines) == 3
+ assert json.loads(lines[0])["body"]["messages"][0]["content"] == "hi"
+ assert lines[2] == "not-json"
+ assert stats == {
+ "total_requests": 3,
+ "total_original_tokens": 12,
+ "total_compressed_tokens": 12,
+ "total_tokens_saved": 0,
+ "savings_percent": 0.0,
+ "errors": 1,
+ }
+
+
+async def test_compress_batch_jsonl_uses_pipeline_and_ccr_injection(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ install_batch_support_modules(
+ monkeypatch,
+ injector_result=(
+ [{"role": "system", "content": "compressed"}],
+ [{"name": "retrieval"}],
+ True,
+ ),
+ )
+ handler = DummyBatchHandler()
+ handler.config.optimize = True
+ handler.config.ccr_inject_tool = True
+ handler.openai_pipeline = SimpleNamespace(
+ apply=lambda **kwargs: SimpleNamespace(
+ messages=[{"role": "assistant", "content": "short"}],
+ tokens_before=100,
+ tokens_after=40,
+ )
+ )
+
+ lines, stats = await handler._compress_batch_jsonl(
+ json.dumps(
+ {
+ "body": {
+ "model": "gpt-4o-mini",
+ "messages": [{"role": "user", "content": "hello"}],
+ "tools": [{"name": "existing"}],
+ }
+ }
+ ),
+ "req-2",
+ )
+
+ body = json.loads(lines[0])["body"]
+ assert body["messages"] == [{"role": "system", "content": "compressed"}]
+ assert body["tools"] == [{"name": "retrieval"}]
+ assert stats["total_tokens_saved"] == 60
+ assert stats["savings_percent"] == 60.0
+
+
+async def test_compress_batch_jsonl_falls_back_when_pipeline_raises(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ install_batch_support_modules(monkeypatch, tokenizer_count=33)
+ handler = DummyBatchHandler()
+ handler.config.optimize = True
+ handler.openai_pipeline = SimpleNamespace(
+ apply=lambda **kwargs: (_ for _ in ()).throw(RuntimeError("boom"))
+ )
+
+ lines, stats = await handler._compress_batch_jsonl(
+ json.dumps({"body": {"messages": [{"role": "user", "content": "hello"}]}}),
+ "req-3",
+ )
+
+ assert json.loads(lines[0])["body"]["messages"][0]["content"] == "hello"
+ assert stats["total_original_tokens"] == 33
+ assert stats["total_compressed_tokens"] == 33
+
+
+async def test_batch_passthrough_forwards_request_and_strips_response_headers() -> None:
+ handler = DummyBatchHandler()
+ handler.http_client.post_response = FakeResponse(
+ content=b'{"ok":true}',
+ headers={"content-encoding": "gzip", "content-length": "20", "x-kept": "1"},
+ )
+
+ response = await handler._batch_passthrough(
+ FakeRequest(
+ '{"input_file_id":"file-1"}', headers={"host": "example", "content-length": "10"}
+ ),
+ {"input_file_id": "file-1"},
+ )
+
+ assert response.status_code == 200
+ assert dict(response.headers)["x-kept"] == "1"
+ assert "content-encoding" not in dict(response.headers)
+ assert handler.http_client.posts[0]["url"] == "https://openai.example/v1/batches"
+
+
+async def test_handle_batch_create_validates_json_and_required_fields(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ handler = DummyBatchHandler()
+
+ async def raise_bad_json(request): # noqa: ANN001
+ raise ValueError("bad json")
+
+ monkeypatch.setattr("headroom.proxy.helpers._read_request_json", raise_bad_json)
+
+ bad = await handler.handle_batch_create(FakeRequest("{}"))
+ assert bad.status_code == 400
+ assert bad.body.decode().find("invalid_json") > 0
+
+ async def missing_file_payload(request): # noqa: ANN001
+ return {"endpoint": "/v1/chat/completions"}
+
+ monkeypatch.setattr("headroom.proxy.helpers._read_request_json", missing_file_payload)
+ missing_file = await handler.handle_batch_create(FakeRequest("{}"))
+ assert missing_file.status_code == 400
+ assert missing_file.body.decode().find("input_file_id is required") > 0
+
+ async def missing_endpoint_payload(request): # noqa: ANN001
+ return {"input_file_id": "file-1"}
+
+ monkeypatch.setattr("headroom.proxy.helpers._read_request_json", missing_endpoint_payload)
+ missing_endpoint = await handler.handle_batch_create(FakeRequest("{}"))
+ assert missing_endpoint.status_code == 400
+ assert missing_endpoint.body.decode().find("endpoint is required") > 0
+
+
+async def test_handle_batch_create_passthrough_and_download_failure(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ handler = DummyBatchHandler()
+ passthrough_response = SimpleNamespace(marker="passthrough")
+
+ async def fake_passthrough(request, body): # noqa: ANN001
+ return passthrough_response
+
+ monkeypatch.setattr(handler, "_batch_passthrough", fake_passthrough)
+
+ async def passthrough_payload(request): # noqa: ANN001
+ return {"input_file_id": "file-1", "endpoint": "/v1/responses"}
+
+ monkeypatch.setattr("headroom.proxy.helpers._read_request_json", passthrough_payload)
+ assert await handler.handle_batch_create(FakeRequest("{}")) is passthrough_response
+
+ async def download_missing_payload(request): # noqa: ANN001
+ return {"input_file_id": "file-1", "endpoint": "/v1/chat/completions"}
+
+ async def missing_download(file_id, headers): # noqa: ANN001
+ return None
+
+ monkeypatch.setattr("headroom.proxy.helpers._read_request_json", download_missing_payload)
+ monkeypatch.setattr(handler, "_download_openai_file", missing_download)
+ missing = await handler.handle_batch_create(FakeRequest("{}"))
+ assert missing.status_code == 404
+ assert missing.body.decode().find("file_not_found") > 0
+
+
+async def test_handle_batch_create_handles_empty_upload_failure_and_success(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ handler = DummyBatchHandler()
+
+ async def request_payload(request): # noqa: ANN001
+ return {
+ "input_file_id": "file-1",
+ "endpoint": "/v1/chat/completions",
+ "completion_window": "12h",
+ "metadata": {"source": "test"},
+ }
+
+ monkeypatch.setattr("headroom.proxy.helpers._read_request_json", request_payload)
+
+ async def fake_download(file_id, headers): # noqa: ANN001
+ return "downloaded"
+
+ monkeypatch.setattr(handler, "_download_openai_file", fake_download)
+
+ async def empty_compress(content, request_id): # noqa: ANN001
+ return [], {
+ "total_requests": 0,
+ "total_original_tokens": 0,
+ "total_compressed_tokens": 0,
+ "total_tokens_saved": 0,
+ "savings_percent": 0.0,
+ "errors": 0,
+ }
+
+ monkeypatch.setattr(handler, "_compress_batch_jsonl", empty_compress)
+ empty = await handler.handle_batch_create(FakeRequest("{}"))
+ assert empty.status_code == 400
+ assert empty.body.decode().find("empty_file") > 0
+
+ async def compressed(content, request_id): # noqa: ANN001
+ return ['{"body":{}}'], {
+ "total_requests": 1,
+ "total_original_tokens": 20,
+ "total_compressed_tokens": 10,
+ "total_tokens_saved": 10,
+ "savings_percent": 50.0,
+ "errors": 0,
+ }
+
+ monkeypatch.setattr(handler, "_compress_batch_jsonl", compressed)
+
+ async def upload_failed_file(content, filename, headers): # noqa: ANN001
+ return None
+
+ monkeypatch.setattr(handler, "_upload_openai_file", upload_failed_file)
+ upload_failed = await handler.handle_batch_create(FakeRequest("{}"))
+ assert upload_failed.status_code == 500
+ assert upload_failed.body.decode().find("upload_failed") > 0
+
+ handler.http_client.post_response = FakeResponse(
+ content=b'{"id":"batch_123","object":"batch"}',
+ headers={"content-encoding": "gzip", "content-length": "12", "x-openai": "1"},
+ )
+
+ async def upload_success(content, filename, headers): # noqa: ANN001
+ return "file-compressed"
+
+ monkeypatch.setattr(handler, "_upload_openai_file", upload_success)
+ success = await handler.handle_batch_create(
+ FakeRequest(
+ "{}", headers={"host": "proxy", "content-length": "4", "authorization": "Bearer test"}
+ )
+ )
+
+ assert success.status_code == 200
+ success_headers = dict(success.headers)
+ assert success_headers["x-headroom-tokens-saved"] == "10"
+ assert success_headers["x-headroom-savings-percent"] == "50.0"
+ assert success_headers["x-openai"] == "1"
+ sent_body = handler.http_client.posts[-1]["json"]
+ assert sent_body["metadata"]["headroom_compressed"] == "true"
+ assert sent_body["metadata"]["headroom_original_file_id"] == "file-1"
+ assert handler.metrics.record_calls[-1]["provider"] == "openai"
+
+
+async def test_handle_batch_create_records_failure_on_exception(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ handler = DummyBatchHandler()
+
+ async def request_payload(request): # noqa: ANN001
+ return {"input_file_id": "file-1", "endpoint": "/v1/chat/completions"}
+
+ async def boom(file_id, headers): # noqa: ANN001
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr("headroom.proxy.helpers._read_request_json", request_payload)
+ monkeypatch.setattr(handler, "_download_openai_file", boom)
+
+ response = await handler.handle_batch_create(FakeRequest("{}"))
+
+ assert response.status_code == 500
+ assert handler.metrics.failed_calls == [{"provider": "batch"}]
+
+
+async def test_download_and_upload_openai_file_helpers() -> None:
+ handler = DummyBatchHandler()
+ handler.http_client.get_response = FakeResponse(status_code=200, text="jsonl-content")
+ downloaded = await handler._download_openai_file("file-1", {"authorization": "Bearer token"})
+ assert downloaded == "jsonl-content"
+ assert handler.http_client.gets[0]["url"] == "https://openai.example/v1/files/file-1/content"
+
+ handler.http_client.get_response = FakeResponse(status_code=404, text="missing")
+ assert await handler._download_openai_file("file-2", {}) is None
+
+ handler.http_client.post_response = FakeResponse(
+ status_code=200,
+ json_data={"id": "file-uploaded"},
+ headers={"content-type": "application/json"},
+ )
+ file_id = await handler._upload_openai_file(
+ '{"body":{}}',
+ "compressed.jsonl",
+ {"authorization": "Bearer token", "content-type": "application/json"},
+ )
+ assert file_id == "file-uploaded"
+ post_call = handler.http_client.posts[-1]
+ assert post_call["headers"] == {"authorization": "Bearer token"}
+ assert post_call["files"]["file"][0] == "compressed.jsonl"
+
+ handler.http_client.post_response = FakeResponse(status_code=500, text="fail")
+ assert await handler._upload_openai_file("{}", "bad.jsonl", {}) is None
+ handler.http_client.raise_post = RuntimeError("network")
+ assert await handler._upload_openai_file("{}", "bad.jsonl", {}) is None
+
+
+async def test_store_google_batch_context_persists_transformed_requests(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ stored_contexts: list[object] = []
+
+ class FakeBatchContext:
+ def __init__(self, **kwargs) -> None: # noqa: ANN003
+ self.kwargs = kwargs
+ self.requests: list[object] = []
+
+ def add_request(self, request) -> None: # noqa: ANN001
+ self.requests.append(request)
+
+ class FakeBatchRequestContext:
+ def __init__(self, **kwargs) -> None: # noqa: ANN003
+ self.kwargs = kwargs
+
+ class FakeStore:
+ async def store(self, context) -> None: # noqa: ANN001
+ stored_contexts.append(context)
+
+ monkeypatch.setitem(
+ sys.modules,
+ "headroom.ccr",
+ SimpleNamespace(
+ BatchContext=FakeBatchContext,
+ BatchRequestContext=FakeBatchRequestContext,
+ get_batch_context_store=lambda: FakeStore(),
+ ),
+ )
+
+ handler = DummyBatchHandler()
+ await handler._store_google_batch_context(
+ "batches/123",
+ [
+ {
+ "metadata": {"key": "req-1"},
+ "request": {
+ "contents": [{"parts": [{"text": "hello"}]}],
+ "systemInstruction": {"parts": [{"text": "system"}]},
+ "tools": [{"name": "tool"}],
+ },
+ }
+ ],
+ "gemini-2.0",
+ "api-key",
+ )
+
+ context = stored_contexts[0]
+ assert context.kwargs["batch_id"] == "batches/123"
+ assert context.requests[0].kwargs["custom_id"] == "req-1"
+ assert context.requests[0].kwargs["messages"] == [{"role": "user", "content": "hello"}]
+ assert context.requests[0].kwargs["system_instruction"] == "system"
+
+
+async def test_handle_google_batch_results_passes_through_early_exit_cases(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class FakeStore:
+ async def get(self, batch_name): # noqa: ANN001
+ return None
+
+ monkeypatch.setitem(
+ sys.modules,
+ "headroom.ccr",
+ SimpleNamespace(
+ BatchResultProcessor=lambda http_client: None,
+ get_batch_context_store=lambda: FakeStore(),
+ ),
+ )
+
+ handler = DummyBatchHandler()
+ request = FakeRequest(
+ "{}", headers={"x-goog-api-key": "secret"}, method="GET", path="/v1beta/batches/b1"
+ )
+
+ handler.http_client.get_response = FakeResponse(
+ status_code=500, content=b"bad", headers={"x-upstream": "1"}
+ )
+ error_response = await handler.handle_google_batch_results(request, "batches/b1")
+ assert error_response.status_code == 500
+ assert dict(error_response.headers)["x-upstream"] == "1"
+
+ class BadJsonResponse(FakeResponse):
+ def json(self): # noqa: ANN201
+ raise json.JSONDecodeError("bad", "x", 0)
+
+ handler.http_client.get_response = BadJsonResponse(
+ status_code=200, content=b"plain", headers={"x-upstream": "2"}
+ )
+ non_json = await handler.handle_google_batch_results(request, "batches/b1")
+ assert non_json.status_code == 200
+ assert dict(non_json.headers)["x-upstream"] == "2"
+
+ handler.http_client.get_response = FakeResponse(
+ status_code=200,
+ content=b"{}",
+ json_data={"metadata": {"state": "RUNNING"}},
+ )
+ running = await handler.handle_google_batch_results(request, "batches/b1")
+ assert running.status_code == 200
+
+ handler.http_client.get_response = FakeResponse(
+ status_code=200,
+ content=b"{}",
+ json_data={"metadata": {"state": "SUCCEEDED"}, "response": {"responses": []}},
+ )
+ no_results = await handler.handle_google_batch_results(request, "batches/b1")
+ assert no_results.status_code == 200
+
+ handler.http_client.get_response = FakeResponse(
+ status_code=200,
+ content=b"{}",
+ json_data={"metadata": {"state": "SUCCEEDED"}, "response": {"responses": [{"id": 1}]}},
+ )
+ handler.config.ccr_inject_tool = False
+ no_ccr = await handler.handle_google_batch_results(request, "batches/b1")
+ assert no_ccr.status_code == 200
+ assert "key=secret" in handler.http_client.gets[-1]["url"]
+
+
+async def test_handle_google_batch_results_processes_completed_results(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ processed_calls: list[tuple[str, list[object], str]] = []
+
+ class FakeProcessed:
+ def __init__(
+ self, result, custom_id: str, was_processed: bool, continuation_rounds: int
+ ) -> None: # noqa: ANN001
+ self.result = result
+ self.custom_id = custom_id
+ self.was_processed = was_processed
+ self.continuation_rounds = continuation_rounds
+
+ class FakeProcessor:
+ def __init__(self, http_client) -> None: # noqa: ANN001
+ self.http_client = http_client
+
+ async def process_results(self, batch_name, results, provider): # noqa: ANN001
+ processed_calls.append((batch_name, results, provider))
+ return [
+ FakeProcessed({"id": "processed"}, "req-1", True, 2),
+ FakeProcessed({"id": "unchanged"}, "req-2", False, 0),
+ ]
+
+ class FakeStore:
+ async def get(self, batch_name): # noqa: ANN001
+ return SimpleNamespace(batch_name=batch_name)
+
+ monkeypatch.setitem(
+ sys.modules,
+ "headroom.ccr",
+ SimpleNamespace(
+ BatchResultProcessor=FakeProcessor,
+ get_batch_context_store=lambda: FakeStore(),
+ ),
+ )
+
+ handler = DummyBatchHandler()
+ handler.config.ccr_inject_tool = True
+ handler.http_client.get_response = FakeResponse(
+ status_code=200,
+ content=b"{}",
+ json_data={
+ "metadata": {"state": "SUCCEEDED"},
+ "response": {"responses": [{"id": "raw-1"}, {"id": "raw-2"}]},
+ },
+ )
+
+ response = await handler.handle_google_batch_results(
+ FakeRequest("{}", method="GET", path="/v1beta/batches/b1"),
+ "batches/b1",
+ )
+
+ payload = json.loads(response.body)
+ assert payload["response"]["responses"] == [{"id": "processed"}, {"id": "unchanged"}]
+ assert processed_calls == [("batches/b1", [{"id": "raw-1"}, {"id": "raw-2"}], "google")]
+ assert handler.metrics.record_calls[-1]["model"] == "batch:ccr-processed"
+
+
+async def test_google_batch_passthrough_helpers_forward_and_track_metrics() -> None:
+ handler = DummyBatchHandler()
+ handler.http_client.post_response = FakeResponse(
+ content=b'{"ok":true}',
+ headers={"content-encoding": "gzip", "content-length": "10", "x-kept": "1"},
+ )
+ handler.http_client.post_response = FakeResponse(
+ content=b'{"ok":true}',
+ headers={"content-encoding": "gzip", "content-length": "10", "x-kept": "1"},
+ )
+
+ passthrough = await handler._google_batch_passthrough(
+ FakeRequest(
+ "body", headers={"host": "proxy", "content-length": "4", "x-goog-api-key": "secret"}
+ ),
+ "gemini-pro",
+ {"batch": {}},
+ )
+ assert passthrough.status_code == 200
+ assert dict(passthrough.headers)["x-kept"] == "1"
+ assert "key=secret" in handler.http_client.posts[-1]["url"]
+ assert handler.metrics.record_calls[-1]["model"] == "passthrough:batch:gemini-pro"
+
+ handler.http_client.get_response = FakeResponse(
+ content=b'{"state":"ok"}',
+ headers={"content-encoding": "gzip", "content-length": "10", "x-kept": "2"},
+ )
+ response = await handler.handle_google_batch_passthrough(
+ FakeRequest(
+ "ping",
+ headers={"host": "proxy", "x-goog-api-key": "secret"},
+ method="DELETE",
+ path="/v1beta/batches/b1",
+ query="alt=json",
+ ),
+ "b1",
+ )
+ assert response.status_code == 200
+ assert dict(response.headers)["x-kept"] == "2"
+ get_call = handler.http_client.requests[-1]
+ assert get_call["url"] == "https://gemini.example/v1beta/batches/b1?alt=json&key=secret"
+ assert handler.metrics.record_calls[-1]["model"] == "passthrough:batches"
+
+
+async def test_handle_google_batch_create_validates_and_passthroughs(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ install_batch_support_modules(monkeypatch)
+ handler = DummyBatchHandler()
+
+ too_large = await handler.handle_google_batch_create(
+ FakeRequest("{}", headers={"content-length": str(200 * 1024 * 1024)}),
+ "gemini-pro",
+ )
+ assert too_large.status_code == 413
+
+ async def bad_json(request): # noqa: ANN001
+ raise ValueError("bad json")
+
+ monkeypatch.setattr("headroom.proxy.helpers._read_request_json", bad_json)
+ invalid = await handler.handle_google_batch_create(FakeRequest("{}"), "gemini-pro")
+ assert invalid.status_code == 400
+
+ passthrough_response = SimpleNamespace(kind="passthrough")
+
+ async def fake_google_passthrough(request, model, body=None): # noqa: ANN001
+ return passthrough_response
+
+ async def no_inline(request): # noqa: ANN001
+ return {"batch": {"input_config": {"requests": {"requests": []}}}}
+
+ monkeypatch.setattr("headroom.proxy.helpers._read_request_json", no_inline)
+ monkeypatch.setattr(handler, "_google_batch_passthrough", fake_google_passthrough)
+ assert (
+ await handler.handle_google_batch_create(FakeRequest("{}"), "gemini-pro")
+ is passthrough_response
+ )
+
+
+async def test_handle_google_batch_create_success_and_failure_paths(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ install_batch_support_modules(monkeypatch)
+ handler = DummyBatchHandler()
+ handler.config.optimize = True
+ handler.config.ccr_inject_tool = True
+ handler.openai_pipeline = SimpleNamespace(
+ apply=lambda **kwargs: SimpleNamespace(
+ messages=[{"role": "user", "content": "compressed"}],
+ timing={"compress": 1.2},
+ tokens_before=100,
+ tokens_after=40,
+ )
+ )
+
+ class FakeInjector:
+ def __init__(self, **kwargs) -> None: # noqa: ANN003
+ pass
+
+ def process_request(self, messages, tools): # noqa: ANN001, ANN201
+ return (
+ messages + [{"role": "system", "content": "retrieval"}],
+ [{"name": "retrieval"}],
+ True,
+ )
+
+ monkeypatch.setitem(sys.modules, "headroom.ccr", SimpleNamespace(CCRToolInjector=FakeInjector))
+
+ stored: list[tuple[str, list[dict[str, object]], str, str | None]] = []
+
+ async def fake_store(batch_name, requests_list, model, api_key): # noqa: ANN001
+ stored.append((batch_name, requests_list, model, api_key))
+
+ async def fake_retry(method, url, headers, body): # noqa: ANN001
+ return FakeResponse(
+ status_code=200,
+ content=b'{"name":"batches/123"}',
+ headers={"content-encoding": "gzip", "content-length": "10", "x-upstream": "1"},
+ json_data={"name": "batches/123"},
+ )
+
+ async def good_payload(request): # noqa: ANN001
+ return {
+ "batch": {
+ "input_config": {
+ "requests": {
+ "requests": [
+ {
+ "request": {
+ "contents": [{"parts": [{"text": "hello"}]}],
+ "tools": [{"functionDeclarations": [{"name": "existing"}]}],
+ },
+ "metadata": {"key": "req-1"},
+ }
+ ]
+ }
+ }
+ }
+ }
+
+ monkeypatch.setattr("headroom.proxy.helpers._read_request_json", good_payload)
+ monkeypatch.setattr(handler, "_retry_request", fake_retry)
+ monkeypatch.setattr(handler, "_store_google_batch_context", fake_store)
+
+ response = await handler.handle_google_batch_create(
+ FakeRequest("{}", headers={"x-goog-api-key": "secret"}),
+ "gemini-pro",
+ )
+ assert response.status_code == 200
+ assert dict(response.headers)["x-upstream"] == "1"
+ assert handler.metrics.record_calls[-1]["provider"] == "google"
+ assert handler.metrics.record_calls[-1]["tokens_saved"] == 60
+ assert stored[0][0] == "batches/123"
+ assert stored[0][2:] == ("gemini-pro", "secret")
+ assert stored[0][1][0]["metadata"] == {"key": "req-1"}
+
+ async def broken_retry(method, url, headers, body): # noqa: ANN001
+ raise RuntimeError("forward failed")
+
+ monkeypatch.setattr(handler, "_retry_request", broken_retry)
+ failed = await handler.handle_google_batch_create(FakeRequest("{}"), "gemini-pro")
+ assert failed.status_code == 500
+
+
+async def test_handle_google_batch_create_covers_passthrough_revert_and_store_failures(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ install_batch_support_modules(
+ monkeypatch, injector_result=([{"role": "user", "content": "kept"}], None, False)
+ )
+ handler = DummyBatchHandler()
+ handler.config.optimize = True
+ handler.config.ccr_inject_tool = True
+
+ pipeline_calls: list[dict[str, object]] = []
+ handler.openai_pipeline = SimpleNamespace(
+ apply=lambda **kwargs: pipeline_calls.append(kwargs)
+ or SimpleNamespace(
+ messages=[{"role": "user", "content": "inflated"}],
+ timing={},
+ tokens_before=40,
+ tokens_after=80,
+ )
+ )
+
+ def fake_to_messages(contents, system_instruction): # noqa: ANN001, ANN201
+ if contents and "inlineData" in contents[0]["parts"][0]:
+ return ([{"role": "user", "content": "binary"}], [0])
+ return ([{"role": "user", "content": "compress"}], [])
+
+ def fake_to_gemini(messages): # noqa: ANN001, ANN201
+ return ([{"parts": [{"text": "new"}]}], {"parts": [{"text": "sys"}]})
+
+ async def payload(request): # noqa: ANN001
+ return {
+ "batch": {
+ "input_config": {
+ "requests": {
+ "requests": [
+ {"request": {"contents": []}, "metadata": {"key": "empty"}},
+ {
+ "request": {"contents": [{"parts": [{"inlineData": "x"}]}]},
+ "metadata": {"key": "preserved"},
+ },
+ {
+ "request": {
+ "contents": [{"parts": [{"text": "hello"}]}],
+ "tools": [
+ {"other": True},
+ {"functionDeclarations": [{"name": "existing"}]},
+ ],
+ },
+ "metadata": {"key": "optimized"},
+ },
+ ]
+ }
+ }
+ }
+ }
+
+ seen_bodies: list[dict[str, object]] = []
+
+ async def retry(method, url, headers, body): # noqa: ANN001
+ seen_bodies.append(body)
+ return FakeResponse(status_code=200, content=b"{}", json_data={"name": "batches/123"})
+
+ async def broken_store(batch_name, requests_list, model, api_key): # noqa: ANN001
+ raise RuntimeError("store failed")
+
+ monkeypatch.setattr("headroom.proxy.helpers._read_request_json", payload)
+ monkeypatch.setattr(handler, "_gemini_contents_to_messages", fake_to_messages)
+ monkeypatch.setattr(handler, "_messages_to_gemini_contents", fake_to_gemini)
+ monkeypatch.setattr(handler, "_retry_request", retry)
+ monkeypatch.setattr(handler, "_store_google_batch_context", broken_store)
+
+ response = await handler.handle_google_batch_create(FakeRequest("{}"), "gemini-pro")
+ assert response.status_code == 200
+ assert len(pipeline_calls) == 1
+ assert handler.metrics.record_calls[-1]["tokens_saved"] == 0
+ assert (
+ seen_bodies[0]["batch"]["input_config"]["requests"]["requests"][0]["metadata"]["key"]
+ == "empty"
+ )
+ optimized = seen_bodies[0]["batch"]["input_config"]["requests"]["requests"][2]["request"]
+ assert optimized["contents"][0] == {"parts": [{"text": "new"}]}
+ assert optimized["systemInstruction"] == {"parts": [{"text": "sys"}]}
+
+
+async def test_google_batch_passthrough_without_body_and_query_variants() -> None:
+ handler = DummyBatchHandler()
+ handler.http_client.post_response = FakeResponse(content=b"ok", headers={"x-upstream": "1"})
+
+ response = await handler._google_batch_passthrough(
+ FakeRequest("raw-body", headers={"host": "proxy"}, method="POST"),
+ "gemini-pro",
+ )
+ assert response.status_code == 200
+ assert handler.http_client.posts[-1]["content"] == b"raw-body"
+
+ handler.http_client.get_response = FakeResponse(content=b"{}", headers={"x-upstream": "2"})
+ passthrough = await handler.handle_google_batch_passthrough(
+ FakeRequest(
+ "{}",
+ headers={"host": "proxy", "x-goog-api-key": "secret"},
+ method="GET",
+ path="/v1beta/batches/b1",
+ ),
+ "b1",
+ )
+ assert passthrough.status_code == 200
+ assert (
+ handler.http_client.requests[-1]["url"]
+ == "https://gemini.example/v1beta/batches/b1?key=secret"
+ )
+
+
+async def test_batch_helper_methods_and_openai_file_error_branches() -> None:
+ handler = DummyBatchHandler()
+ marker = object()
+
+ async def fake_passthrough(request, base_url): # noqa: ANN001
+ return marker
+
+ handler.handle_passthrough = fake_passthrough
+ request = FakeRequest("{}")
+ assert await handler.handle_batch_list(request) is marker
+ assert await handler.handle_batch_get(request, "b1") is marker
+ assert await handler.handle_batch_cancel(request, "b1") is marker
+
+ handler.http_client.raise_get = RuntimeError("download boom")
+ assert await handler._download_openai_file("file-1", {}) is None
+
+ handler.http_client.raise_get = None
+ handler.http_client.post_response = FakeResponse(status_code=200, json_data={})
+ assert await handler._upload_openai_file("{}", "missing-id.jsonl", {}) is None
+
+
+async def test_store_google_batch_context_without_system_text() -> None:
+ stored_contexts: list[object] = []
+
+ class FakeBatchContext:
+ def __init__(self, **kwargs) -> None: # noqa: ANN003
+ self.kwargs = kwargs
+ self.requests: list[object] = []
+
+ def add_request(self, request) -> None: # noqa: ANN001
+ self.requests.append(request)
+
+ class FakeBatchRequestContext:
+ def __init__(self, **kwargs) -> None: # noqa: ANN003
+ self.kwargs = kwargs
+
+ class FakeStore:
+ async def store(self, context) -> None: # noqa: ANN001
+ stored_contexts.append(context)
+
+ handler = DummyBatchHandler()
+ sys.modules["headroom.ccr"] = SimpleNamespace(
+ BatchContext=FakeBatchContext,
+ BatchRequestContext=FakeBatchRequestContext,
+ get_batch_context_store=lambda: FakeStore(),
+ )
+
+ await handler._store_google_batch_context(
+ "batches/456",
+ [
+ {
+ "request": {
+ "contents": [{"parts": [{"text": "hello"}]}],
+ "systemInstruction": {"parts": ["bad"]},
+ }
+ }
+ ],
+ "gemini-2.0",
+ None,
+ )
+
+ context = stored_contexts[0]
+ assert context.kwargs["api_key"] is None
+ assert context.requests[0].kwargs["custom_id"] == ""
+ assert context.requests[0].kwargs["system_instruction"] is None
+
+
+async def test_compress_batch_jsonl_skips_blank_lines_and_preserves_tools_when_not_injected(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ install_batch_support_modules(
+ monkeypatch,
+ injector_result=([{"role": "assistant", "content": "short"}], [{"name": "orig"}], False),
+ )
+ handler = DummyBatchHandler()
+ handler.config.optimize = True
+ handler.config.ccr_inject_tool = True
+ handler.openai_pipeline = SimpleNamespace(
+ apply=lambda **kwargs: SimpleNamespace(
+ messages=[{"role": "assistant", "content": "short"}],
+ tokens_before=50,
+ tokens_after=10,
+ )
+ )
+
+ lines, stats = await handler._compress_batch_jsonl(
+ "\n"
+ + json.dumps(
+ {
+ "body": {
+ "model": "gpt-4o",
+ "messages": [{"role": "user", "content": "hello"}],
+ "tools": [{"name": "orig"}],
+ }
+ }
+ )
+ + "\n",
+ "req-extra",
+ )
+
+ assert len(lines) == 1
+ body = json.loads(lines[0])["body"]
+ assert body["tools"] == [{"name": "orig"}]
+ assert stats["total_requests"] == 1
+ assert stats["errors"] == 0
diff --git a/tests/test_relevance_extra.py b/tests/test_relevance_extra.py
new file mode 100644
index 000000000..e5c705a5e
--- /dev/null
+++ b/tests/test_relevance_extra.py
@@ -0,0 +1,181 @@
+from __future__ import annotations
+
+import builtins
+from dataclasses import dataclass
+from types import SimpleNamespace
+
+import pytest
+
+import headroom.relevance as relevance_mod
+from headroom.relevance import (
+ BM25Scorer,
+ EmbeddingScorer,
+ HybridScorer,
+ create_scorer,
+ embedding,
+ hybrid,
+)
+from headroom.relevance.base import RelevanceScore, RelevanceScorer, default_batch_score
+
+
+@dataclass
+class DummyRelevanceScorer(RelevanceScorer):
+ def score(self, item: str, context: str) -> RelevanceScore:
+ return RelevanceScore(score=0.4, reason=f"{item}:{context}")
+
+ def score_batch(self, items: list[str], context: str) -> list[RelevanceScore]:
+ return [RelevanceScore(score=0.2, reason=context) for _ in items]
+
+
+def test_base_default_batch_and_abstract_methods() -> None:
+ scorer = DummyRelevanceScorer()
+ batch = default_batch_score(scorer, ["a", "b"], "ctx")
+ assert [item.reason for item in batch] == ["a:ctx", "b:ctx"]
+
+ assert RelevanceScorer.score(scorer, "a", "ctx") is None
+ assert RelevanceScorer.score_batch(scorer, ["a"], "ctx") is None
+ assert RelevanceScorer.is_available() is True
+
+
+def test_create_scorer_embedding_unavailable_branch(monkeypatch) -> None:
+ monkeypatch.setattr(
+ relevance_mod.EmbeddingScorer, "is_available", classmethod(lambda cls: False)
+ )
+ with pytest.raises(RuntimeError, match="sentence-transformers"):
+ create_scorer("embedding")
+
+
+def test_bm25_internal_paths_and_non_normalized_mode() -> None:
+ scorer = BM25Scorer(normalize_score=False)
+ assert scorer._tokenize("") == []
+ assert scorer._compute_idf("x", doc_count=1, doc_freq=0) == 0.0
+ assert scorer._compute_idf("x", doc_count=1, doc_freq=1) > 0
+ assert scorer._bm25_score([], ["a"]) == (0.0, [])
+ assert scorer._bm25_score(["a"], []) == (0.0, [])
+
+ no_match = scorer.score("hello world", "missing")
+ assert no_match.reason == "BM25: no term matches"
+
+ one_match = scorer.score("find alice", "alice")
+ assert one_match.reason == "BM25: matched 'alice'"
+ assert one_match.score > 0
+
+ many_match = scorer.score("alpha beta gamma delta", "alpha beta gamma delta")
+ assert many_match.reason.startswith("BM25: matched 4 terms")
+
+ batch = scorer.score_batch(["alpha", "alpha beta"], "alpha beta")
+ assert [item.reason for item in batch] == ["BM25: 1 terms", "BM25: 2 terms"]
+
+
+def test_embedding_numpy_and_model_error_paths(monkeypatch) -> None:
+ embedding._numpy = None
+ real_import = builtins.__import__
+
+ def fake_import(name, globals=None, locals=None, fromlist=(), level=0):
+ if name == "numpy":
+ raise ImportError("missing")
+ return real_import(name, globals, locals, fromlist, level)
+
+ monkeypatch.setattr(builtins, "__import__", fake_import)
+ with pytest.raises(ImportError, match="numpy is required"):
+ embedding._get_numpy()
+
+ monkeypatch.setattr(builtins, "__import__", real_import)
+ fake_np = SimpleNamespace(
+ linalg=SimpleNamespace(norm=lambda value: 0 if value == [0, 0] else 1),
+ dot=lambda a, b: -1,
+ )
+ monkeypatch.setattr(embedding, "_numpy", fake_np)
+ assert embedding._cosine_similarity([0, 0], [1, 0]) == 0.0
+ assert embedding._cosine_similarity([1, 0], [0, 1]) == 0.0
+
+ monkeypatch.setattr(EmbeddingScorer, "is_available", classmethod(lambda cls: False))
+ with pytest.raises(RuntimeError, match="requires sentence-transformers"):
+ EmbeddingScorer()._get_model()
+
+
+def test_embedding_score_empty_and_batch_shortcuts() -> None:
+ scorer = EmbeddingScorer()
+ assert scorer.score("", "ctx").reason == "Embedding: empty input"
+ assert scorer.score("item", "").reason == "Embedding: empty input"
+ assert scorer.score_batch([], "ctx") == []
+ assert scorer.score_batch(["item"], "")[0].reason == "Embedding: empty context"
+
+
+def test_embedding_score_and_batch_with_fake_model(monkeypatch) -> None:
+ scorer = EmbeddingScorer()
+ monkeypatch.setattr(
+ scorer,
+ "_encode",
+ lambda texts: [[1.0, 0.0], [0.5, 0.5]]
+ if len(texts) == 2
+ else [[1.0, 0.0], [0.0, 1.0], [1.0, 0.0]],
+ )
+ monkeypatch.setattr(
+ embedding, "_cosine_similarity", lambda a, b: 0.75 if a == [1.0, 0.0] else 0.25
+ )
+
+ single = scorer.score("item", "ctx")
+ assert single.score == 0.75
+ assert single.reason == "Embedding: semantic similarity 0.75"
+
+ batch = scorer.score_batch(["first", "second"], "ctx")
+ assert [item.score for item in batch] == [0.75, 0.25]
+ assert [item.reason for item in batch] == ["Embedding: 0.75", "Embedding: 0.25"]
+
+
+def test_hybrid_constructor_alpha_variants_and_single_score_paths(monkeypatch) -> None:
+ bm25_result = RelevanceScore(score=0.1, reason="bm25", matched_terms=["term"])
+ emb_result = RelevanceScore(score=0.9, reason="emb", matched_terms=[])
+
+ class FakeBM25:
+ def score(self, item: str, context: str) -> RelevanceScore:
+ return bm25_result
+
+ def score_batch(self, items: list[str], context: str) -> list[RelevanceScore]:
+ return [bm25_result for _ in items]
+
+ class FakeEmbedding:
+ def score(self, item: str, context: str) -> RelevanceScore:
+ return emb_result
+
+ def score_batch(self, items: list[str], context: str) -> list[RelevanceScore]:
+ return [emb_result for _ in items]
+
+ scorer = HybridScorer(
+ alpha=0.4, adaptive=True, bm25_scorer=FakeBM25(), embedding_scorer=FakeEmbedding()
+ )
+ assert scorer.has_embedding_support() is True
+ assert scorer._compute_alpha("find id 1234") == 0.65
+ assert scorer._compute_alpha("find host api.example.com") == 0.6
+ assert scorer._compute_alpha("find email [email protected]") == 0.6
+
+ single = scorer.score("item", "show me errors")
+ assert single.score == pytest.approx(0.58)
+ assert "Hybrid (α=0.40): BM25=0.10, Semantic=0.90" == single.reason
+
+ batch = scorer.score_batch(["a", "b"], "show me errors")
+ assert len(batch) == 2
+ assert batch[0].reason == "Hybrid (α=0.40): BM25=0.10, Emb=0.90"
+
+
+def test_hybrid_fallback_and_empty_batch(monkeypatch) -> None:
+ scorer = HybridScorer(bm25_scorer=BM25Scorer())
+ scorer._embedding_available = False
+ scorer.embedding = None
+
+ empty = scorer.score_batch([], "ctx")
+ assert empty == []
+
+ boosted = scorer.score('{"id":"123","name":"alice"}', "alice")
+ assert boosted.score >= 0.3
+ assert "BM25 only, boosted" in boosted.reason
+
+ boosted_batch = scorer.score_batch(['{"id":"123"}', '{"id":"456"}'], "123 456")
+ assert all("BM25 only, boosted" in item.reason for item in boosted_batch)
+
+
+def test_hybrid_auto_fallback_when_embeddings_unavailable(monkeypatch) -> None:
+ monkeypatch.setattr(hybrid.EmbeddingScorer, "is_available", classmethod(lambda cls: False))
+ scorer = HybridScorer()
+ assert scorer.has_embedding_support() is False
diff --git a/tests/test_reporting.py b/tests/test_reporting.py
new file mode 100644
index 000000000..8a9f150c2
--- /dev/null
+++ b/tests/test_reporting.py
@@ -0,0 +1,305 @@
+from __future__ import annotations
+
+import builtins
+import sys
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+from types import SimpleNamespace
+
+import pytest
+
+import headroom.reporting as reporting
+from headroom.reporting import generator
+
+
+@dataclass
+class FakeMetrics:
+ request_id: str
+ model: str
+ mode: str
+ timestamp: datetime
+ tokens_input_before: int
+ tokens_input_after: int
+ cache_alignment_score: float
+ waste_signals: dict[str, int]
+
+
+class FakeStorage:
+ def __init__(self, stats: dict, items: list[FakeMetrics]) -> None:
+ self._stats = stats
+ self._items = items
+ self.closed = False
+
+ def get_summary_stats(self, start_time, end_time):
+ return dict(self._stats)
+
+ def iter_all(self):
+ return iter(self._items)
+
+ def close(self) -> None:
+ self.closed = True
+
+
+def test_reporting_public_export() -> None:
+ assert reporting.generate_report is generator.generate_report
+ assert reporting.__all__ == ["generate_report"]
+
+
+def test_get_jinja2_template_success_with_stub(monkeypatch) -> None:
+ class FakeTemplate:
+ def __init__(self, template_str: str) -> None:
+ self.template_str = template_str
+
+ def render(self, **kwargs) -> str:
+ return f"{self.template_str}:{kwargs['name']}"
+
+ monkeypatch.setitem(sys.modules, "jinja2", SimpleNamespace(Template=FakeTemplate))
+ template = generator._get_jinja2_template("hello")
+ assert template.render(name="world") == "hello:world"
+
+
+def test_get_jinja2_template_raises_helpful_error(monkeypatch) -> None:
+ real_import = builtins.__import__
+
+ def fake_import(name, globals=None, locals=None, fromlist=(), level=0):
+ if name == "jinja2":
+ raise ImportError("missing")
+ return real_import(name, globals, locals, fromlist, level)
+
+ monkeypatch.setattr(builtins, "__import__", fake_import)
+ with pytest.raises(ImportError, match="jinja2 is required for report generation"):
+ generator._get_jinja2_template("ignored")
+
+
+def test_build_waste_histogram_empty_and_filtered_data() -> None:
+ now = datetime(2026, 4, 23, 12, 0, 0)
+ metrics = [
+ FakeMetrics(
+ request_id="before",
+ model="gpt-4o",
+ mode="audit",
+ timestamp=now - timedelta(days=2),
+ tokens_input_before=100,
+ tokens_input_after=90,
+ cache_alignment_score=10,
+ waste_signals={"json_bloat": 5},
+ ),
+ FakeMetrics(
+ request_id="inside",
+ model="gpt-4o",
+ mode="optimize",
+ timestamp=now,
+ tokens_input_before=200,
+ tokens_input_after=100,
+ cache_alignment_score=70,
+ waste_signals={"json_bloat": 30, "html_noise": 10, "dynamic_date": 5},
+ ),
+ FakeMetrics(
+ request_id="flat",
+ model="gpt-4o",
+ mode="audit",
+ timestamp=now,
+ tokens_input_before=50,
+ tokens_input_after=50,
+ cache_alignment_score=50,
+ waste_signals={"whitespace": 4},
+ ),
+ FakeMetrics(
+ request_id="after",
+ model="gpt-4o",
+ mode="audit",
+ timestamp=now + timedelta(days=2),
+ tokens_input_before=100,
+ tokens_input_after=20,
+ cache_alignment_score=20,
+ waste_signals={"base64": 50},
+ ),
+ ]
+ histogram = generator._build_waste_histogram(
+ FakeStorage({}, metrics),
+ start_time=now - timedelta(hours=1),
+ end_time=now + timedelta(hours=1),
+ )
+
+ assert histogram[0] == {"label": "History Bloat", "tokens": 55, "percentage": 100.0}
+ assert histogram[1] == pytest.approx(
+ {"label": "Tool JSON Bloat", "tokens": 30, "percentage": 54.54545454545454}
+ )
+ assert any(item["label"] == "HTML Noise" and item["tokens"] == 10 for item in histogram)
+ assert any(item["label"] == "Dynamic Dates" and item["tokens"] == 5 for item in histogram)
+ assert any(item["label"] == "Base64 Blobs" and item["tokens"] == 0 for item in histogram)
+
+ empty = generator._build_waste_histogram(FakeStorage({}, []), None, None)
+ assert all(item["tokens"] == 0 and item["percentage"] == 0 for item in empty)
+
+
+def test_get_top_waste_requests_sorts_filters_and_limits() -> None:
+ now = datetime(2026, 4, 23, 12, 0, 0)
+ metrics = [
+ FakeMetrics("one", "gpt-4o", "audit", now, 400, 100, 80, {}),
+ FakeMetrics("two", "gpt-4o-mini", "optimize", now, 350, 330, 70, {}),
+ FakeMetrics("three", "claude", "audit", now - timedelta(days=3), 1000, 10, 50, {}),
+ FakeMetrics("four", "claude", "audit", now + timedelta(days=3), 1000, 200, 40, {}),
+ ]
+ top_requests = generator._get_top_waste_requests(
+ FakeStorage({}, metrics),
+ start_time=now - timedelta(hours=1),
+ end_time=now + timedelta(hours=1),
+ limit=1,
+ )
+ assert top_requests == [
+ {
+ "request_id": "one",
+ "model": "gpt-4o",
+ "mode": "audit",
+ "tokens_before": 400,
+ "tokens_saved": 300,
+ "cache_alignment": 80,
+ }
+ ]
+
+
+def test_generate_recommendations_for_heavy_waste_and_for_getting_started() -> None:
+ stats = {
+ "avg_cache_alignment": 40,
+ "audit_count": 7,
+ "optimize_count": 3,
+ "total_tokens_saved": 120000,
+ "estimated_savings": "$1.23",
+ }
+ histogram = [
+ {"label": "Tool JSON Bloat", "tokens": 15000, "percentage": 100},
+ {"label": "History Bloat", "tokens": 60000, "percentage": 50},
+ ]
+ recommendations = generator._generate_recommendations(stats, histogram, top_requests=[{}])
+ titles = [item["title"] for item in recommendations]
+ assert titles == [
+ "Improve Cache Alignment",
+ "Enable Tool Output Compression",
+ "Review Rolling Window Settings",
+ "Switch to Optimize Mode",
+ "Continue Monitoring",
+ ]
+ assert "15,000" in recommendations[1]["description"]
+ assert "60,000" in recommendations[2]["description"]
+
+ starter = generator._generate_recommendations(
+ {
+ "avg_cache_alignment": 90,
+ "audit_count": 1,
+ "optimize_count": 1,
+ "total_tokens_saved": 0,
+ "estimated_savings": "$0.00",
+ },
+ [{"label": "Tool JSON Bloat", "tokens": 1, "percentage": 100}],
+ top_requests=[],
+ )
+ assert starter == [
+ {
+ "title": "Get Started",
+ "description": "No optimizations applied yet. Try setting headroom_mode='optimize' "
+ "on your next request to start seeing token savings.",
+ }
+ ]
+
+
+ ("start_time", "end_time", "expected_period"),
+ [
+ (
+ datetime(2026, 4, 20, 8, 0, 0),
+ datetime(2026, 4, 23, 18, 0, 0),
+ "2026-04-20 to 2026-04-23",
+ ),
+ (datetime(2026, 4, 20, 8, 0, 0), None, "Since 2026-04-20"),
+ (None, datetime(2026, 4, 23, 18, 0, 0), "Until 2026-04-23"),
+ (None, None, "All time"),
+ ],
+)
+def test_generate_report_writes_output_and_closes_storage(
+ monkeypatch, tmp_path, start_time, end_time, expected_period
+) -> None:
+ storage = FakeStorage(
+ {
+ "total_requests": 3,
+ "total_tokens_saved": 50,
+ "avg_tokens_saved": 16.6,
+ "total_tokens_before": 100,
+ "total_tokens_after": 0,
+ "avg_cache_alignment": 82,
+ "audit_count": 1,
+ "optimize_count": 2,
+ },
+ [],
+ )
+ render_calls: list[dict] = []
+
+ class FakeTemplate:
+ def render(self, **kwargs) -> str:
+ render_calls.append(kwargs)
+ return "<html>report</html>"
+
+ monkeypatch.setattr(generator, "create_storage", lambda store_url: storage)
+ monkeypatch.setattr(
+ generator, "_build_waste_histogram", lambda *args: [{"label": "x", "tokens": 1}]
+ )
+ monkeypatch.setattr(
+ generator, "_get_top_waste_requests", lambda *args, **kwargs: [{"request_id": "abc"}]
+ )
+ monkeypatch.setattr(
+ generator, "_generate_recommendations", lambda *args: [{"title": "Keep going"}]
+ )
+ monkeypatch.setattr(generator, "_get_jinja2_template", lambda template_str: FakeTemplate())
+ monkeypatch.setattr(
+ generator,
+ "estimate_cost",
+ lambda tokens, output_tokens, model: {100: 2.0, 0: None}[tokens],
+ )
+ monkeypatch.setattr(generator, "format_cost", lambda cost: f"${cost:.2f}")
+
+ output_path = tmp_path / "report.html"
+ result = generator.generate_report(
+ "sqlite:///demo.db",
+ output_path=str(output_path),
+ start_time=start_time,
+ end_time=end_time,
+ )
+
+ assert result == str(output_path)
+ assert output_path.read_text() == "<html>report</html>"
+ assert render_calls[0]["period"] == expected_period
+ assert render_calls[0]["stats"]["tpm_multiplier"] == 100.0
+ assert render_calls[0]["stats"]["estimated_savings"] == "$2.00"
+ assert storage.closed is True
+
+
+def test_generate_report_closes_storage_when_render_fails(monkeypatch, tmp_path) -> None:
+ storage = FakeStorage(
+ {
+ "total_requests": 0,
+ "total_tokens_saved": 0,
+ "avg_tokens_saved": 0,
+ "total_tokens_before": 0,
+ "total_tokens_after": 0,
+ "avg_cache_alignment": 0,
+ "audit_count": 0,
+ "optimize_count": 0,
+ },
+ [],
+ )
+
+ class FakeTemplate:
+ def render(self, **kwargs) -> str:
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr(generator, "create_storage", lambda store_url: storage)
+ monkeypatch.setattr(generator, "_build_waste_histogram", lambda *args: [])
+ monkeypatch.setattr(generator, "_get_top_waste_requests", lambda *args, **kwargs: [])
+ monkeypatch.setattr(generator, "_generate_recommendations", lambda *args: [])
+ monkeypatch.setattr(generator, "_get_jinja2_template", lambda template_str: FakeTemplate())
+ monkeypatch.setattr(generator, "estimate_cost", lambda *args: 0.0)
+ monkeypatch.setattr(generator, "format_cost", lambda cost: "$0.00")
+
+ with pytest.raises(RuntimeError, match="boom"):
+ generator.generate_report("sqlite:///demo.db", output_path=str(tmp_path / "report.html"))
+ assert storage.closed is True
diff --git a/tests/test_storage_backends.py b/tests/test_storage_backends.py
new file mode 100644
index 000000000..7800fb133
--- /dev/null
+++ b/tests/test_storage_backends.py
@@ -0,0 +1,294 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+from pathlib import Path
+from types import SimpleNamespace
+
+from headroom.config import RequestMetrics
+from headroom.storage import JSONLStorage, SQLiteStorage, Storage, create_storage
+
+
+def _metrics(
+ request_id: str,
+ timestamp: datetime,
+ model: str = "gpt-4o",
+ mode: str = "audit",
+ before: int = 100,
+ after: int = 80,
+) -> RequestMetrics:
+ return RequestMetrics(
+ request_id=request_id,
+ timestamp=timestamp,
+ model=model,
+ stream=False,
+ mode=mode,
+ tokens_input_before=before,
+ tokens_input_after=after,
+ tokens_output=25,
+ block_breakdown={"system": 10},
+ waste_signals={"json_bloat": 3},
+ stable_prefix_hash="prefix",
+ cache_alignment_score=75.0,
+ cached_tokens=12,
+ transforms_applied=["compress"],
+ tool_units_dropped=1,
+ turns_dropped=2,
+ messages_hash="messages",
+ error=None,
+ )
+
+
+@dataclass
+class DummyStorage(Storage):
+ closed: bool = False
+
+ def save(self, metrics: RequestMetrics) -> None:
+ return None
+
+ def get(self, request_id: str) -> RequestMetrics | None:
+ return None
+
+ def query(self, **kwargs) -> list[RequestMetrics]:
+ return []
+
+ def count(self, **kwargs) -> int:
+ return 0
+
+ def iter_all(self):
+ return iter(())
+
+ def get_summary_stats(self, **kwargs) -> dict[str, int]:
+ return {}
+
+ def close(self) -> None:
+ self.closed = True
+
+
+def test_storage_base_context_manager_calls_close() -> None:
+ storage = DummyStorage()
+ with storage as managed:
+ assert managed is storage
+ assert storage.closed is False
+ assert storage.closed is True
+
+ assert Storage.save(storage, _metrics("x", datetime(2026, 4, 23, 12, 0, 0))) is None
+ assert Storage.get(storage, "x") is None
+ assert Storage.query(storage) is None
+ assert Storage.count(storage) is None
+ assert Storage.iter_all(storage) is None
+ assert Storage.get_summary_stats(storage) is None
+ assert Storage.close(storage) is None
+
+
+def test_create_storage_builtin_entrypoint_and_fallback(monkeypatch, tmp_path: Path) -> None:
+ sqlite_storage = create_storage(f"sqlite://{tmp_path}\\metrics.db")
+ jsonl_storage = create_storage(f"jsonl://{tmp_path}\\metrics.jsonl")
+ assert isinstance(sqlite_storage, SQLiteStorage)
+ assert isinstance(jsonl_storage, JSONLStorage)
+ sqlite_storage.close()
+ jsonl_storage.close()
+
+ absolute_sqlite = create_storage("sqlite:///tmp/demo.db")
+ absolute_jsonl = create_storage("jsonl:///tmp/demo.jsonl")
+ assert isinstance(absolute_sqlite, SQLiteStorage)
+ assert isinstance(absolute_jsonl, JSONLStorage)
+ absolute_sqlite.close()
+ absolute_jsonl.close()
+
+ created = DummyStorage()
+
+ class FakeEntryPoint:
+ name = "custom"
+
+ def load(self):
+ return lambda store_url: created
+
+ monkeypatch.setattr(
+ "importlib.metadata.entry_points",
+ lambda group: [FakeEntryPoint()] if group == "headroom.storage_backend" else [],
+ )
+ assert create_storage("custom://memory") is created
+
+ monkeypatch.setattr(
+ "importlib.metadata.entry_points", lambda group: (_ for _ in ()).throw(RuntimeError("boom"))
+ )
+ created_fallback: list[str] = []
+
+ class FakeSQLiteStorage:
+ def __init__(self, db_path: str) -> None:
+ created_fallback.append(db_path)
+
+ def close(self) -> None:
+ return None
+
+ monkeypatch.setattr("headroom.storage.SQLiteStorage", FakeSQLiteStorage)
+ fallback = create_storage("custom://fallback.db")
+ assert isinstance(fallback, FakeSQLiteStorage)
+ assert created_fallback == ["custom://fallback.db"]
+ fallback.close()
+
+ monkeypatch.setattr(
+ "importlib.metadata.entry_points",
+ lambda group: [SimpleNamespace(name="other", load=lambda: (lambda url: created))],
+ )
+ missing_ep = create_storage("custom://missing.db")
+ assert isinstance(missing_ep, FakeSQLiteStorage)
+ assert created_fallback == ["custom://fallback.db", "custom://missing.db"]
+ missing_ep.close()
+
+ plain = create_storage("metrics.db")
+ assert isinstance(plain, FakeSQLiteStorage)
+ assert created_fallback == ["custom://fallback.db", "custom://missing.db", "metrics.db"]
+ plain.close()
+
+
+def test_jsonl_storage_round_trip_query_count_and_summary(tmp_path: Path) -> None:
+ storage = JSONLStorage(str(tmp_path / "metrics.jsonl"))
+ now = datetime(2026, 4, 23, 12, 0, 0)
+ first = _metrics("one", now - timedelta(hours=2), mode="audit", before=120, after=100)
+ second = _metrics(
+ "two", now - timedelta(hours=1), model="claude", mode="optimize", before=90, after=30
+ )
+ third = _metrics("three", now, mode="audit", before=60, after=50)
+
+ storage.save(first)
+ storage.save(second)
+ storage.save(third)
+
+ assert storage.get("two") == second
+ assert storage.get("missing") is None
+
+ results = storage.query(start_time=now - timedelta(hours=1, minutes=30), offset=1, limit=1)
+ assert [item.request_id for item in results] == ["three"]
+ assert storage.query(model="claude")[0].request_id == "two"
+ assert storage.query(mode="optimize")[0].request_id == "two"
+ assert storage.query(end_time=now - timedelta(hours=1, minutes=30))[0].request_id == "one"
+ assert storage.count(mode="audit") == 2
+ assert storage.count(end_time=now - timedelta(hours=1, minutes=30)) == 1
+ assert storage.count(start_time=now + timedelta(days=1)) == 0
+
+ summary = storage.get_summary_stats(start_time=now - timedelta(hours=3), end_time=now)
+ assert summary == {
+ "total_requests": 3,
+ "total_tokens_before": 270,
+ "total_tokens_after": 180,
+ "total_tokens_saved": 90,
+ "avg_tokens_saved": 30.0,
+ "avg_cache_alignment": 75.0,
+ "audit_count": 2,
+ "optimize_count": 1,
+ }
+
+ storage.close()
+
+
+def test_jsonl_storage_handles_missing_file_malformed_lines_and_defaults(tmp_path: Path) -> None:
+ path = tmp_path / "events.jsonl"
+ storage = JSONLStorage(str(path))
+ path.unlink()
+ assert list(storage.iter_all()) == []
+
+ path.write_text(
+ "\n".join(
+ [
+ "",
+ "not-json",
+ '{"id":"x","timestamp":"2026-04-23T12:00:00Z","model":"gpt-4o","stream":true,"mode":"simulate","tokens_input_before":5,"tokens_input_after":3}',
+ ]
+ )
+ )
+ loaded = list(storage.iter_all())
+ assert len(loaded) == 1
+ assert loaded[0].request_id == "x"
+ assert loaded[0].tokens_output is None
+ assert loaded[0].block_breakdown == {}
+ assert loaded[0].waste_signals == {}
+ assert loaded[0].stable_prefix_hash == ""
+ assert loaded[0].cache_alignment_score == 0.0
+ assert loaded[0].transforms_applied == []
+ assert loaded[0].tool_units_dropped == 0
+ assert loaded[0].turns_dropped == 0
+ assert loaded[0].messages_hash == ""
+ assert loaded[0].error is None
+
+
+def test_sqlite_storage_round_trip_filters_summary_and_defaults(tmp_path: Path) -> None:
+ storage = SQLiteStorage(str(tmp_path / "metrics.db"))
+ now = datetime(2026, 4, 23, 12, 0, 0)
+ first = _metrics("one", now - timedelta(hours=2), mode="audit", before=100, after=70)
+ second = _metrics(
+ "two", now - timedelta(hours=1), model="claude", mode="optimize", before=90, after=20
+ )
+ third = _metrics("three", now, before=50, after=50)
+ third.stable_prefix_hash = ""
+ third.cache_alignment_score = 0.0
+ third.cached_tokens = None
+ third.transforms_applied = []
+ third.tool_units_dropped = 0
+ third.turns_dropped = 0
+ third.messages_hash = ""
+
+ storage.save(first)
+ storage.save(second)
+ storage.save(third)
+ replacement = _metrics("one", now + timedelta(minutes=1), before=111, after=11)
+ storage.save(replacement)
+
+ assert storage.get("one") == replacement
+ assert storage.get("missing") is None
+
+ results = storage.query(start_time=now - timedelta(hours=2), end_time=now, limit=2, offset=1)
+ assert [item.request_id for item in results] == ["two"]
+ assert storage.query(model="claude")[0].request_id == "two"
+ assert storage.query(mode="optimize")[0].request_id == "two"
+ assert storage.count(mode="audit") == 2
+ assert storage.count(start_time=now - timedelta(hours=1, minutes=30), end_time=now) == 2
+ assert storage.count(model="missing") == 0
+ assert [item.request_id for item in storage.iter_all()] == ["two", "three", "one"]
+
+ summary = storage.get_summary_stats(
+ start_time=now - timedelta(hours=3), end_time=now + timedelta(hours=1)
+ )
+ assert summary == {
+ "total_requests": 3,
+ "total_tokens_before": 251,
+ "total_tokens_after": 81,
+ "total_tokens_saved": 170,
+ "avg_tokens_saved": 56.666666666666664,
+ "avg_cache_alignment": 50.0,
+ "audit_count": 2,
+ "optimize_count": 1,
+ }
+
+ empty = storage.get_summary_stats(start_time=now + timedelta(days=1))
+ assert empty == {
+ "total_requests": 0,
+ "total_tokens_before": 0,
+ "total_tokens_after": 0,
+ "total_tokens_saved": 0,
+ "avg_tokens_saved": 0,
+ "avg_cache_alignment": 0,
+ "audit_count": 0,
+ "optimize_count": 0,
+ }
+
+ storage.close()
+ assert storage._conn is None
+
+
+def test_sqlite_storage_get_conn_reuses_connection_and_create_storage_entrypoint(
+ monkeypatch, tmp_path: Path
+) -> None:
+ storage = SQLiteStorage(str(tmp_path / "metrics.db"))
+ first = storage._get_conn()
+ second = storage._get_conn()
+ assert first is second
+ storage.close()
+
+ created = DummyStorage()
+ monkeypatch.setattr(
+ "importlib.metadata.entry_points",
+ lambda group: [SimpleNamespace(name="custom", load=lambda: (lambda url: created))],
+ )
+ assert create_storage("custom://db") is created
diff --git a/tests/test_subscription_base.py b/tests/test_subscription_base.py
new file mode 100644
index 000000000..ae73952af
--- /dev/null
+++ b/tests/test_subscription_base.py
@@ -0,0 +1,140 @@
+from __future__ import annotations
+
+import pytest
+
+import headroom.subscription.base as base_module
+from headroom.subscription.base import (
+ QuotaTracker,
+ QuotaTrackerRegistry,
+ get_quota_registry,
+ reset_quota_registry,
+)
+
+
+class DummyTracker(QuotaTracker):
+ def __init__(
+ self,
+ key: str,
+ *,
+ label: str = "Dummy",
+ available: bool = True,
+ stats: dict | None = None,
+ stop_error: Exception | None = None,
+ ) -> None:
+ self._key = key
+ self._label = label
+ self._available = available
+ self._stats = stats
+ self._stop_error = stop_error
+ self.started = 0
+ self.stopped = 0
+
+ @property
+ def key(self) -> str:
+ return self._key
+
+ @property
+ def label(self) -> str:
+ return self._label
+
+ def is_available(self) -> bool:
+ return self._available
+
+ async def start(self) -> None:
+ self.started += 1
+
+ async def stop(self) -> None:
+ self.stopped += 1
+ if self._stop_error:
+ raise self._stop_error
+
+ def get_stats(self) -> dict | None:
+ return self._stats
+
+
+class PassiveTracker(QuotaTracker):
+ @property
+ def key(self) -> str:
+ return "passive"
+
+ @property
+ def label(self) -> str:
+ return "Passive"
+
+ def get_stats(self) -> dict | None:
+ return {"passive": True}
+
+
+def test_register_get_trackers_and_duplicate_keys() -> None:
+ registry = QuotaTrackerRegistry()
+ tracker = DummyTracker("alpha", stats={"ok": True})
+ registry.register(tracker)
+
+ assert registry.get("alpha") is tracker
+ assert registry.get("missing") is None
+ assert registry.trackers == [tracker]
+ assert registry.get_stats("alpha") == {"ok": True}
+ assert registry.get_stats("missing") is None
+
+ snapshot = registry.trackers
+ snapshot.clear()
+ assert registry.trackers == [tracker]
+
+ with pytest.raises(ValueError, match="already registered"):
+ registry.register(DummyTracker("alpha"))
+
+
+async def test_start_all_stop_all_and_stats_filtering() -> None:
+ registry = QuotaTrackerRegistry()
+ enabled = DummyTracker("enabled", label="Enabled", stats={"value": 1})
+ disabled = DummyTracker("disabled", label="Disabled", available=False, stats={"skip": True})
+ empty = DummyTracker("empty", label="Empty", stats=None)
+ broken = DummyTracker(
+ "broken", label="Broken", stats={"value": 2}, stop_error=RuntimeError("boom")
+ )
+
+ for tracker in (enabled, disabled, empty, broken):
+ registry.register(tracker)
+
+ await registry.start_all()
+ assert enabled.started == 1
+ assert disabled.started == 0
+ assert empty.started == 1
+ assert broken.started == 1
+
+ assert registry.get_all_stats() == {
+ "enabled": {"value": 1},
+ "broken": {"value": 2},
+ }
+
+ await registry.stop_all()
+ assert enabled.stopped == 1
+ assert disabled.stopped == 1
+ assert empty.stopped == 1
+ assert broken.stopped == 1
+
+
+def test_quota_registry_singleton_reset() -> None:
+ reset_quota_registry()
+ base_module._registry = None
+ first = get_quota_registry()
+ second = get_quota_registry()
+ assert first is second
+
+ first.register(DummyTracker("singleton"))
+ assert get_quota_registry().get("singleton") is not None
+
+ reset_quota_registry()
+ refreshed = get_quota_registry()
+ assert refreshed is not first
+ assert refreshed.trackers == []
+
+
+async def test_quota_tracker_default_methods() -> None:
+ tracker = PassiveTracker()
+ assert tracker.is_available() is True
+ await tracker.start()
+ await tracker.stop()
+ assert tracker.get_stats() == {"passive": True}
diff --git a/tests/test_subscription_client.py b/tests/test_subscription_client.py
new file mode 100644
index 000000000..f8056d719
--- /dev/null
+++ b/tests/test_subscription_client.py
@@ -0,0 +1,179 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import httpx
+import pytest
+
+from headroom.subscription.client import (
+ _BETA_HEADER,
+ _USAGE_URL,
+ SubscriptionClient,
+ _credentials_path,
+ _load_credentials_file,
+ read_cached_oauth_token,
+)
+
+
+class DummyResponse:
+ def __init__(self, status_code: int, data: dict | None = None) -> None:
+ self.status_code = status_code
+ self._data = data or {}
+
+ def json(self) -> dict:
+ return self._data
+
+
+class AsyncClientStub:
+ def __init__(
+ self,
+ *,
+ response=None,
+ error: Exception | None = None,
+ record: dict | None = None,
+ timeout=None,
+ ):
+ self._response = response
+ self._error = error
+ self._record = record if record is not None else {}
+ self._record["timeout"] = timeout
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb):
+ return False
+
+ async def get(self, url: str, headers: dict[str, str]):
+ self._record["url"] = url
+ self._record["headers"] = headers
+ if self._error:
+ raise self._error
+ return self._response
+
+
+def test_credentials_path_uses_env_override(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path))
+ assert _credentials_path() == tmp_path / ".credentials.json"
+
+
+def test_load_credentials_file_handles_missing_invalid_and_valid(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path))
+ assert _load_credentials_file() is None
+
+ creds_path = tmp_path / ".credentials.json"
+ creds_path.write_text("{invalid", encoding="utf-8")
+ assert _load_credentials_file() is None
+
+ payload = {"claudeAiOauth": {"accessToken": "token-from-file"}}
+ creds_path.write_text(json.dumps(payload), encoding="utf-8")
+ assert _load_credentials_file() == payload
+
+
+def test_read_cached_oauth_token_prefers_env_and_checks_expiry(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("CLAUDE_CODE_OAUTH_TOKEN", " env-token ")
+ monkeypatch.setattr("headroom.subscription.client._load_credentials_file", lambda: None)
+ assert read_cached_oauth_token() == "env-token"
+
+ monkeypatch.delenv("CLAUDE_CODE_OAUTH_TOKEN", raising=False)
+ monkeypatch.setattr(
+ "headroom.subscription.client._load_credentials_file",
+ lambda: {"claudeAiOauth": {"accessToken": "cached-token"}},
+ )
+ assert read_cached_oauth_token() == "cached-token"
+
+ monkeypatch.setattr(
+ "headroom.subscription.client._load_credentials_file",
+ lambda: {
+ "claudeAiOauth": {
+ "accessToken": "expired-token",
+ "expiresAt": 59_000,
+ }
+ },
+ )
+ monkeypatch.setattr("time.time", lambda: 60)
+ assert read_cached_oauth_token() is None
+
+ monkeypatch.setattr(
+ "headroom.subscription.client._load_credentials_file",
+ lambda: {"claudeAiOauth": {"accessToken": ""}},
+ )
+ assert read_cached_oauth_token() is None
+
+ monkeypatch.setattr(
+ "headroom.subscription.client._load_credentials_file",
+ lambda: None,
+ )
+ assert read_cached_oauth_token() is None
+
+
+async def test_subscription_client_fetch_handles_success_and_status_codes(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ record: dict = {}
+ monkeypatch.setattr(
+ "headroom.subscription.client.httpx.AsyncClient",
+ lambda timeout: AsyncClientStub(
+ response=DummyResponse(200, {"five_hour": {"total": 1}}),
+ record=record,
+ timeout=timeout,
+ ),
+ )
+ monkeypatch.setattr(
+ "headroom.subscription.client.SubscriptionSnapshot.from_api_response",
+ lambda data, token="": {"data": data, "token": token},
+ )
+
+ client = SubscriptionClient(timeout=3.5)
+ result = await client.fetch(" explicit-token ")
+ assert result == {"data": {"five_hour": {"total": 1}}, "token": "explicit-token"}
+ assert record["timeout"] == 3.5
+ assert record["url"] == _USAGE_URL
+ assert record["headers"] == {
+ "Authorization": "Bearer explicit-token",
+ "anthropic-beta": _BETA_HEADER,
+ "Content-Type": "application/json",
+ }
+
+ for status_code in (401, 404, 500):
+ monkeypatch.setattr(
+ "headroom.subscription.client.httpx.AsyncClient",
+ lambda timeout, status_code=status_code: AsyncClientStub(
+ response=DummyResponse(status_code), timeout=timeout
+ ),
+ )
+ assert await client.fetch("explicit-token") is None
+
+
+async def test_subscription_client_fetch_uses_cached_token_and_handles_exceptions(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ client = SubscriptionClient()
+
+ monkeypatch.setattr("headroom.subscription.client.read_cached_oauth_token", lambda: None)
+ assert await client.fetch() is None
+
+ monkeypatch.setattr(
+ "headroom.subscription.client.read_cached_oauth_token",
+ lambda: "cached-token",
+ )
+ monkeypatch.setattr(
+ "headroom.subscription.client.httpx.AsyncClient",
+ lambda timeout: AsyncClientStub(error=httpx.TimeoutException("slow"), timeout=timeout),
+ )
+ assert await client.fetch() is None
+
+ monkeypatch.setattr(
+ "headroom.subscription.client.httpx.AsyncClient",
+ lambda timeout: AsyncClientStub(error=RuntimeError("boom"), timeout=timeout),
+ )
+ assert await client.fetch() is None
diff --git a/tests/test_subscription_tracker.py b/tests/test_subscription_tracker.py
index be58eb9b7..6b274a6f9 100644
--- a/tests/test_subscription_tracker.py
+++ b/tests/test_subscription_tracker.py
@@ -1,496 +1,201 @@
-"""Tests for the Anthropic subscription window tracking feature."""
-
from __future__ import annotations
-from datetime import datetime, timedelta, timezone
+import sys
+from datetime import timedelta
from pathlib import Path
-from unittest.mock import AsyncMock, MagicMock, patch
+from types import SimpleNamespace
import pytest
+import headroom.subscription.tracker as tracker_module
from headroom.subscription.models import (
- ExtraUsage,
HeadroomContribution,
RateLimitWindow,
SubscriptionSnapshot,
- SubscriptionState,
WindowDiscrepancy,
WindowTokens,
+ _utc_now,
)
-
-# ---------------------------------------------------------------------------
-# RateLimitWindow
-# ---------------------------------------------------------------------------
-
-
-class TestRateLimitWindow:
- def test_from_api_dict_full(self):
- now = datetime.now(timezone.utc)
- resets = (now + timedelta(hours=3)).isoformat()
- w = RateLimitWindow.from_api_dict(
- {"utilization": 42.5, "resets_at": resets, "used": 100, "limit": 235}
- )
- assert w.utilization_pct == pytest.approx(42.5)
- assert w.used == 100
- assert w.limit == 235
- assert w.resets_at is not None
-
- def test_from_api_dict_minimal(self):
- # Real API responses only include utilization + resets_at
- w = RateLimitWindow.from_api_dict({"utilization": 0.0, "resets_at": None})
- assert w.utilization_pct == 0.0
- assert w.resets_at is None
- assert w.used == 0
- assert w.limit == 0
-
- def test_seconds_to_reset(self):
- now = datetime.now(timezone.utc)
- future = now + timedelta(hours=2, minutes=30)
- w = RateLimitWindow(resets_at=future)
- secs = w.seconds_to_reset(now=now)
- assert secs is not None
- assert 9000 <= secs <= 9001
-
- def test_seconds_to_reset_none_when_no_reset(self):
- w = RateLimitWindow()
- assert w.seconds_to_reset() is None
-
- def test_to_dict_contains_expected_keys(self):
- w = RateLimitWindow(utilization_pct=55.0)
- d = w.to_dict()
- assert "utilization_pct" in d
- assert "resets_at" in d
- assert "seconds_to_reset" in d
-
-
-# ---------------------------------------------------------------------------
-# ExtraUsage
-# ---------------------------------------------------------------------------
-
-
-class TestExtraUsage:
- def test_from_api_dict_with_cents(self):
- eu = ExtraUsage.from_api_dict(
- {
- "is_enabled": True,
- "monthly_limit": 5000, # $50.00
- "used_credits": 123, # $1.23
- "utilization": 2.46,
- }
- )
- assert eu.is_enabled is True
- assert eu.monthly_limit_cents == 5000
- assert eu.used_credits_cents == 123
- assert eu.monthly_limit_usd == pytest.approx(50.0)
- assert eu.used_credits_usd == pytest.approx(1.23)
- assert eu.utilization_pct == pytest.approx(2.46)
-
- def test_from_api_dict_disabled(self):
- eu = ExtraUsage.from_api_dict({"is_enabled": False})
- assert eu.is_enabled is False
- assert eu.monthly_limit_cents is None
- assert eu.used_credits_cents is None
- assert eu.monthly_limit_usd is None
-
- def test_to_dict_converts_to_usd(self):
- eu = ExtraUsage(is_enabled=True, monthly_limit_cents=10000, used_credits_cents=499)
- d = eu.to_dict()
- assert d["monthly_limit_usd"] == pytest.approx(100.0, abs=0.01)
- assert d["used_credits_usd"] == pytest.approx(4.99, abs=0.001)
-
-
-# ---------------------------------------------------------------------------
-# SubscriptionSnapshot
-# ---------------------------------------------------------------------------
-
-
-class TestSubscriptionSnapshot:
- def test_from_api_response_all_fields(self):
- now = datetime.now(timezone.utc)
- data = {
- "five_hour": {"utilization": 30.0, "resets_at": (now + timedelta(hours=2)).isoformat()},
- "seven_day": {"utilization": 10.0, "resets_at": (now + timedelta(days=3)).isoformat()},
- "seven_day_opus": {"utilization": 5.0, "resets_at": None},
- "seven_day_sonnet": {"utilization": 8.0, "resets_at": None},
- "extra_usage": {
- "is_enabled": True,
- "monthly_limit": 5000,
- "used_credits": 250,
- "utilization": 5.0,
- },
- }
- snap = SubscriptionSnapshot.from_api_response(data, token="tok_test_abc")
- assert snap.five_hour.utilization_pct == pytest.approx(30.0)
- assert snap.seven_day.utilization_pct == pytest.approx(10.0)
- assert snap.seven_day_opus is not None
- assert snap.seven_day_sonnet is not None
- assert snap.extra_usage.is_enabled is True
- assert snap.extra_usage.used_credits_usd == pytest.approx(2.50)
- assert snap.token_prefix == "tok_test"
-
- def test_from_api_response_missing_optional_fields(self):
- snap = SubscriptionSnapshot.from_api_response(
- {"five_hour": {"utilization": 0.0, "resets_at": None}}
- )
- assert snap.seven_day_opus is None
- assert snap.seven_day_sonnet is None
- assert snap.extra_usage.is_enabled is False
-
- def test_to_dict_round_trip(self):
- snap = SubscriptionSnapshot.from_api_response(
- {
- "five_hour": {"utilization": 42.0, "resets_at": None},
- "seven_day": {"utilization": 15.0, "resets_at": None},
- "extra_usage": {"is_enabled": False},
- }
- )
- d = snap.to_dict()
- assert d["five_hour"]["utilization_pct"] == pytest.approx(42.0)
- assert d["seven_day"]["utilization_pct"] == pytest.approx(15.0)
- assert "seven_day_opus" not in d # absent when None
-
-
-# ---------------------------------------------------------------------------
-# HeadroomContribution
-# ---------------------------------------------------------------------------
-
-
-class TestHeadroomContribution:
- def test_efficiency_pct_no_savings(self):
- c = HeadroomContribution(tokens_submitted=100)
- assert c.efficiency_pct() == 0.0
-
- def test_efficiency_pct_with_savings(self):
- c = HeadroomContribution(
- tokens_submitted=70,
- tokens_saved_compression=20,
- tokens_saved_rtk=10,
- )
- # raw_without_headroom = 70 + 20 + 10 = 100
- # total_saved = 30
- assert c.efficiency_pct() == pytest.approx(30.0)
-
- def test_total_savings_usd(self):
- c = HeadroomContribution(compression_savings_usd=1.5, cache_savings_usd=0.75)
- assert c.total_savings_usd() == pytest.approx(2.25)
-
- def test_to_dict_structure(self):
- c = HeadroomContribution(
- tokens_submitted=200,
- tokens_saved_compression=50,
- compression_savings_usd=0.10,
- )
- d = c.to_dict()
- assert d["tokens_submitted"] == 200
- assert d["tokens_saved"]["compression"] == 50
- assert d["savings_usd"]["compression"] == pytest.approx(0.10)
-
-
-# ---------------------------------------------------------------------------
-# SubscriptionState
-# ---------------------------------------------------------------------------
-
-
-class TestSubscriptionState:
- def test_is_active_recent(self):
- state = SubscriptionState()
- state.last_active_at = datetime.now(timezone.utc)
- assert state.is_active(active_window_s=60.0) is True
-
- def test_is_active_stale(self):
- state = SubscriptionState()
- state.last_active_at = datetime.now(timezone.utc) - timedelta(minutes=5)
- assert state.is_active(active_window_s=60.0) is False
-
- def test_is_active_none(self):
- state = SubscriptionState()
- assert state.is_active() is False
-
- def test_add_snapshot_caps_history(self):
- state = SubscriptionState()
- state._MAX_HISTORY = 3
- for _ in range(5):
- state.add_snapshot(SubscriptionSnapshot.from_api_response({}))
- assert len(state.history) == 3
- assert state.poll_count == 5
-
- def test_add_discrepancy_caps_list(self):
- state = SubscriptionState()
- state._MAX_DISCREPANCIES = 2
- for i in range(4):
- state.add_discrepancy(WindowDiscrepancy(kind=f"kind_{i}"))
- assert len(state.discrepancies) == 2
-
-
-# ---------------------------------------------------------------------------
-# SubscriptionTracker — unit tests with mocked client
-# ---------------------------------------------------------------------------
-
-
-class TestSubscriptionTrackerNotifyActive:
- def _make_tracker(self, tmp_path: Path):
- from headroom.subscription.tracker import SubscriptionTracker
-
- return SubscriptionTracker(
- poll_interval_s=30,
- active_window_s=60,
- persist_path=tmp_path / "state.json",
- client=MagicMock(),
- )
-
- def test_notify_active_oauth_token(self, tmp_path):
- t = self._make_tracker(tmp_path)
- t.notify_active("Bearer sk-ant-oat01-sometoken")
- assert t.is_active() is True
- assert t._current_token == "sk-ant-oat01-sometoken"
-
- def test_notify_active_ignores_api_key(self, tmp_path):
- t = self._make_tracker(tmp_path)
- t.notify_active("Bearer sk-ant-api03-key")
- assert t.is_active() is False
- assert t._current_token is None
-
- def test_notify_active_ignores_non_bearer(self, tmp_path):
- t = self._make_tracker(tmp_path)
- t.notify_active("x-api-key somevalue")
- assert t.is_active() is False
-
- def test_update_contribution(self, tmp_path):
- t = self._make_tracker(tmp_path)
- t.update_contribution(
- tokens_submitted=500,
- tokens_saved_compression=100,
- tokens_saved_cache_reads=50,
- )
- c = t._state.contribution
- assert c.tokens_submitted == 500
- assert c.tokens_saved_compression == 100
- assert c.tokens_saved_cache_reads == 50
-
- def test_update_contribution_accumulates(self, tmp_path):
- t = self._make_tracker(tmp_path)
- t.update_contribution(tokens_submitted=100)
- t.update_contribution(tokens_submitted=200)
- assert t._state.contribution.tokens_submitted == 300
-
- def test_state_dict_structure(self, tmp_path):
- t = self._make_tracker(tmp_path)
- d = t.state
- assert "latest" in d
- assert "contribution" in d
- assert "poll_count" in d
- assert "last_active_at" in d
-
-
-# ---------------------------------------------------------------------------
-# SubscriptionTracker — poll loop integration test
-# ---------------------------------------------------------------------------
-
-
-class TestSubscriptionTrackerPollLoop:
- @pytest.mark.asyncio
- async def test_poll_called_when_active(self, tmp_path):
- """When notify_active is called, the poll loop should fetch a snapshot."""
- from headroom.subscription.tracker import SubscriptionTracker
-
- mock_snapshot = SubscriptionSnapshot.from_api_response(
- {
- "five_hour": {"utilization": 25.0, "resets_at": None},
- "seven_day": {"utilization": 5.0, "resets_at": None},
- }
- )
- mock_client = MagicMock()
- mock_client.fetch = AsyncMock(return_value=mock_snapshot)
-
- tracker = SubscriptionTracker(
- poll_interval_s=1,
- active_window_s=60,
- persist_path=tmp_path / "state.json",
- client=mock_client,
- )
-
- # Mark active so the poll proceeds
- tracker.notify_active("Bearer sk-ant-oat01-testtoken")
-
- # Run poll once directly (bypasses loop timing)
- await tracker._maybe_poll()
-
- assert tracker.latest_snapshot is not None
- assert tracker.latest_snapshot.five_hour.utilization_pct == pytest.approx(25.0)
- mock_client.fetch.assert_called_once()
-
- @pytest.mark.asyncio
- async def test_poll_skipped_when_no_token_and_inactive(self, tmp_path):
- """When not active and no credentials file token, poll should skip."""
- from headroom.subscription.tracker import SubscriptionTracker
-
- mock_client = MagicMock()
- mock_client.fetch = AsyncMock(return_value=None)
-
- tracker = SubscriptionTracker(
- poll_interval_s=1,
- active_window_s=60,
- persist_path=tmp_path / "state.json",
- client=mock_client,
- )
-
- with patch("headroom.subscription.client.read_cached_oauth_token", return_value=None):
- await tracker._maybe_poll()
-
- mock_client.fetch.assert_not_called()
-
- @pytest.mark.asyncio
- async def test_poll_loop_does_not_leak_event_wait_tasks(self, tmp_path):
- """The poll loop must not accumulate idle Event.wait waiters.
-
- Regression for the ``asyncio.shield(event.wait())`` pattern:
- ``shield`` prevents the inner wait from being cancelled when
- ``wait_for`` times out, leaking one Task per poll interval.
- Observed as the "aged proxy degradation" in 2026-04-17 runtime
- analysis — over hours the accumulated idle waiters bog down the
- event-loop scheduler.
- """
- import asyncio
-
- from headroom.subscription.tracker import SubscriptionTracker
-
- mock_client = MagicMock()
- mock_client.fetch = AsyncMock(return_value=None)
-
- tracker = SubscriptionTracker(
- poll_interval_s=0.05, # short so many iterations fit in the test window
- active_window_s=60,
- persist_path=tmp_path / "state.json",
- client=mock_client,
- )
-
- def _count_event_wait_tasks() -> int:
- return sum(
- 1
- for t in asyncio.all_tasks()
- if (t.get_coro().__qualname__ if t.get_coro() else "") == "Event.wait"
+from headroom.subscription.tracker import SubscriptionTracker
+
+
+def _make_snapshot(
+ *, token_prefix: str = "token123", reset_offset_hours: int = 5
+) -> SubscriptionSnapshot:
+ return SubscriptionSnapshot(
+ five_hour=RateLimitWindow(
+ used=10,
+ limit=100,
+ utilization_pct=10.0,
+ resets_at=_utc_now() + timedelta(hours=reset_offset_hours),
+ ),
+ seven_day=RateLimitWindow(used=20, limit=200, utilization_pct=10.0),
+ token_prefix=token_prefix,
+ )
+
+
+def test_tracker_notify_active_update_and_basic_state(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(SubscriptionTracker, "_load_persisted_state", lambda self: None)
+ tracker = SubscriptionTracker(enabled=False)
+
+ assert tracker.is_available() is False
+ assert tracker.latest_snapshot is None
+ assert tracker.is_active() is False
+ assert isinstance(tracker.get_stats(), dict)
+
+ tracker.notify_active("")
+ tracker.notify_active("Basic token")
+ tracker.notify_active("Bearer sk-ant-api-key")
+ assert tracker._current_token is None
+
+ tracker.notify_active("Bearer oauth-token-123")
+ assert tracker._current_token == "oauth-token-123"
+ assert tracker._full_tokens["oauth-to"] == 1
+ assert tracker.is_active() is True
+
+ tracker.update_contribution(
+ tokens_submitted=10,
+ tokens_saved_compression=5,
+ tokens_saved_rtk=-1,
+ tokens_saved_cache_reads=3,
+ compression_savings_usd=1.25,
+ cache_savings_usd=-2.0,
+ )
+ contribution = tracker._state.contribution
+ assert contribution.tokens_submitted == 10
+ assert contribution.tokens_saved_compression == 5
+ assert contribution.tokens_saved_rtk == 0
+ assert contribution.tokens_saved_cache_reads == 3
+ assert contribution.compression_savings_usd == 1.25
+ assert contribution.cache_savings_usd == 0.0
+
+
+async def test_tracker_start_stop_and_rollover_reset(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr(SubscriptionTracker, "_load_persisted_state", lambda self: None)
+ tracker = SubscriptionTracker(persist_path=tmp_path / "state.json")
+
+ async def fake_poll_loop() -> None:
+ assert tracker._stop_event is not None
+ await tracker._stop_event.wait()
+
+ tracker._poll_loop = fake_poll_loop # type: ignore[method-assign]
+ await tracker.start()
+ first_task = tracker._poll_task
+ assert first_task is not None
+
+ await tracker.start()
+ assert tracker._poll_task is first_task
+
+ await tracker.stop()
+ assert tracker._stop_event is not None and tracker._stop_event.is_set()
+ assert tracker._persist_path.exists()
+
+ tracker._state.history = [
+ _make_snapshot(reset_offset_hours=5),
+ _make_snapshot(reset_offset_hours=6),
+ ]
+ tracker._state.contribution = HeadroomContribution(tokens_submitted=99)
+ tracker._maybe_reset_contribution(tracker._state.history[-1])
+ assert tracker._state.contribution.tokens_submitted == 0
+
+
+async def test_maybe_poll_handles_inactive_and_none_snapshot(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(SubscriptionTracker, "_load_persisted_state", lambda self: None)
+ tracker = SubscriptionTracker()
+
+ monkeypatch.setattr("headroom.subscription.client.read_cached_oauth_token", lambda: None)
+ await tracker._maybe_poll()
+ assert tracker._state.poll_count == 0
+
+ monkeypatch.setattr(
+ "headroom.subscription.client.read_cached_oauth_token", lambda: "cached-token"
+ )
+
+ async def fetch_none(token: str | None):
+ return None
+
+ tracker._client = SimpleNamespace(fetch=fetch_none)
+ await tracker._maybe_poll()
+ assert tracker._state.last_error == "fetch returned None"
+ assert tracker._state.poll_errors == 1
+
+
+async def test_maybe_poll_success_updates_state_and_metrics(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(SubscriptionTracker, "_load_persisted_state", lambda self: None)
+ tracker = SubscriptionTracker()
+ tracker.notify_active("Bearer live-oauth-token")
+
+ snapshot = _make_snapshot()
+ discrepancies = [WindowDiscrepancy(kind="cache_miss", description="miss", severity="warning")]
+ metrics_calls: list[dict] = []
+
+ async def fetch_snapshot(token: str | None):
+ assert token == "live-oauth-token"
+ return snapshot
+
+ tracker._client = SimpleNamespace(fetch=fetch_snapshot)
+ monkeypatch.setattr(
+ tracker_module, "_compute_window_tokens_for_snapshot", lambda snap: WindowTokens(input=7)
+ )
+ monkeypatch.setattr(tracker_module, "_detect_discrepancies", lambda snap, tokens: discrepancies)
+ monkeypatch.setattr(
+ tracker, "_persist_state", lambda: metrics_calls.append({"persisted": True})
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "headroom.observability.metrics",
+ SimpleNamespace(
+ get_otel_metrics=lambda: SimpleNamespace(
+ record_subscription_window=lambda state: metrics_calls.append(state)
)
-
- baseline = _count_event_wait_tasks()
- await tracker.start()
- try:
- # Let the loop run through ~6 iterations. Each iteration would
- # previously leak one Event.wait waiter.
- await asyncio.sleep(0.3)
- peak = _count_event_wait_tasks()
- finally:
- await tracker.stop()
-
- # After stop the loop task has exited; anything above baseline + 1
- # (the single live wait that was in-flight before stop set the event)
- # indicates leaked waiters.
- await asyncio.sleep(0.05) # let stop()'s awaited tasks settle
- residual = _count_event_wait_tasks()
-
- # Peak growth during polling should be at most one (the one currently
- # awaiting inside the loop); anything more is a leak.
- assert peak - baseline <= 1, (
- f"poll loop leaked Event.wait waiters: baseline={baseline} peak={peak}"
- )
- assert residual <= baseline, (
- f"poll loop left residual Event.wait waiters: baseline={baseline} residual={residual}"
- )
-
-
-# ---------------------------------------------------------------------------
-# Anomaly detection
-# ---------------------------------------------------------------------------
-
-
-class TestAnomalyDetection:
- def test_surge_pricing_detection(self):
- from headroom.subscription.tracker import _detect_discrepancies
-
- snap = SubscriptionSnapshot.from_api_response(
- {
- "five_hour": {"utilization": 80.0, "resets_at": None},
- "seven_day": {"utilization": 20.0, "resets_at": None},
- }
- )
- # Simulate API limit known; weighted tokens imply only 50% should be used
- snap.five_hour.limit = 1000
- window_tokens = WindowTokens(input=300, output=100, weighted_token_equivalent=500.0)
-
- discrepancies = _detect_discrepancies(snap, window_tokens)
- kinds = [d.kind for d in discrepancies]
- assert "surge_pricing" in kinds
-
- def test_no_surge_when_limit_unknown(self):
- from headroom.subscription.tracker import _detect_discrepancies
-
- snap = SubscriptionSnapshot.from_api_response(
- {"five_hour": {"utilization": 90.0, "resets_at": None}}
- )
- snap.five_hour.limit = 0 # Unknown
- window_tokens = WindowTokens(weighted_token_equivalent=500.0)
-
- discrepancies = _detect_discrepancies(snap, window_tokens)
- assert not any(d.kind == "surge_pricing" for d in discrepancies)
-
- def test_cache_miss_detection(self):
- from headroom.subscription.tracker import _detect_discrepancies
-
- snap = SubscriptionSnapshot.from_api_response(
- {"five_hour": {"utilization": 40.0, "resets_at": None}}
- )
- # High input, very few cache reads
- window_tokens = WindowTokens(input=100_000, cache_reads=500)
-
- discrepancies = _detect_discrepancies(snap, window_tokens)
- kinds = [d.kind for d in discrepancies]
- assert "cache_miss" in kinds
-
- def test_no_cache_miss_below_threshold(self):
- from headroom.subscription.tracker import _detect_discrepancies
-
- snap = SubscriptionSnapshot.from_api_response(
- {"five_hour": {"utilization": 30.0, "resets_at": None}}
- )
- # Low input total — doesn't trigger cache miss check
- window_tokens = WindowTokens(input=30_000, cache_reads=0)
-
- discrepancies = _detect_discrepancies(snap, window_tokens)
- assert not any(d.kind == "cache_miss" for d in discrepancies)
-
-
-# ---------------------------------------------------------------------------
-# Persistence round-trip
-# ---------------------------------------------------------------------------
-
-
-class TestPersistence:
- @pytest.mark.asyncio
- async def test_persist_and_reload(self, tmp_path):
- from headroom.subscription.tracker import SubscriptionTracker
-
- persist_file = tmp_path / "sub_state.json"
-
- mock_client = MagicMock()
- snap = SubscriptionSnapshot.from_api_response(
- {"five_hour": {"utilization": 55.0, "resets_at": None}}
- )
- mock_client.fetch = AsyncMock(return_value=snap)
-
- t1 = SubscriptionTracker(
- persist_path=persist_file,
- client=mock_client,
- )
- t1.notify_active("Bearer sk-ant-oat01-tok")
- t1.update_contribution(tokens_submitted=1000, tokens_saved_compression=200)
- await t1._maybe_poll()
- t1._persist_state()
-
- assert persist_file.exists()
-
- # Load a new tracker from the same file
- t2 = SubscriptionTracker(
- persist_path=persist_file,
- client=MagicMock(),
- )
- assert t2._state.contribution.tokens_submitted == 1000
- assert t2._state.contribution.tokens_saved_compression == 200
+ ),
+ )
+
+ await tracker._maybe_poll()
+ assert tracker.latest_snapshot is snapshot
+ assert tracker._state.window_tokens.input == 7
+ assert tracker._state.discrepancies[-1].kind == "cache_miss"
+ assert tracker._state.last_error is None
+ assert tracker._state.poll_count == 1
+ assert metrics_calls[0] == {"persisted": True}
+ assert isinstance(metrics_calls[1], dict)
+
+
+def test_persist_and_load_state_round_trip(tmp_path: Path) -> None:
+ persist_path = tmp_path / "tracker-state.json"
+ tracker = SubscriptionTracker(persist_path=persist_path)
+ tracker.update_contribution(
+ tokens_submitted=11,
+ tokens_saved_compression=2,
+ tokens_saved_rtk=3,
+ tokens_saved_cache_reads=4,
+ compression_savings_usd=1.5,
+ cache_savings_usd=2.5,
+ )
+ tracker._state.poll_count = 7
+ tracker._persist_state()
+
+ loader = SubscriptionTracker(persist_path=persist_path)
+ assert loader._state.contribution.tokens_submitted == 11
+ assert loader._state.contribution.tokens_saved_compression == 2
+ assert loader._state.contribution.tokens_saved_rtk == 3
+ assert loader._state.contribution.tokens_saved_cache_reads == 4
+ assert loader._state.contribution.compression_savings_usd == 1.5
+ assert loader._state.contribution.cache_savings_usd == 2.5
+ assert loader._state.poll_count == 7
+
+ persist_path.write_text("{invalid", encoding="utf-8")
+ broken = SubscriptionTracker(persist_path=persist_path)
+ assert broken._state.poll_count == 0
+
+ missing = SubscriptionTracker(persist_path=tmp_path / "missing.json")
+ assert missing._state.poll_count == 0
diff --git a/tests/test_tokenizer.py b/tests/test_tokenizer.py
new file mode 100644
index 000000000..030aeb56f
--- /dev/null
+++ b/tests/test_tokenizer.py
@@ -0,0 +1,50 @@
+from __future__ import annotations
+
+from typing import Any
+
+from headroom.tokenizer import Tokenizer, count_tokens_messages, count_tokens_text
+
+
+class FakeTokenCounter:
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, Any]] = []
+
+ def count_text(self, text: str) -> int:
+ self.calls.append(("text", text))
+ return len(text.split())
+
+ def count_message(self, message: dict[str, Any]) -> int:
+ self.calls.append(("message", message))
+ return len(str(message.get("content", "")).split())
+
+ def count_messages(self, messages: list[dict[str, Any]]) -> int:
+ self.calls.append(("messages", messages))
+ return sum(len(str(msg.get("content", "")).split()) for msg in messages)
+
+
+def test_tokenizer_delegates_to_counter() -> None:
+ counter = FakeTokenCounter()
+ tokenizer = Tokenizer(counter, model="gpt-4o")
+
+ assert tokenizer.model == "gpt-4o"
+ assert tokenizer.available is True
+ assert tokenizer.count_text("hello world") == 2
+ assert tokenizer.count_message({"role": "user", "content": "three word text"}) == 3
+ assert tokenizer.count_messages([{"content": "one two"}, {"content": "three"}]) == 3
+ assert counter.calls == [
+ ("text", "hello world"),
+ ("message", {"role": "user", "content": "three word text"}),
+ ("messages", [{"content": "one two"}, {"content": "three"}]),
+ ]
+
+
+def test_tokenizer_convenience_functions() -> None:
+ counter = FakeTokenCounter()
+ messages = [{"content": "one"}, {"content": "two three"}]
+
+ assert count_tokens_text("alpha beta gamma", counter) == 3
+ assert count_tokens_messages(messages, counter) == 3
+ assert counter.calls == [
+ ("text", "alpha beta gamma"),
+ ("messages", messages),
+ ]
diff --git a/tests/test_transforms_content_detection.py b/tests/test_transforms_content_detection.py
new file mode 100644
index 000000000..1ca9de7ea
--- /dev/null
+++ b/tests/test_transforms_content_detection.py
@@ -0,0 +1,202 @@
+from __future__ import annotations
+
+from headroom.transforms.content_detector import (
+ ContentType,
+ _try_detect_code,
+ _try_detect_diff,
+ _try_detect_html,
+ _try_detect_json,
+ _try_detect_log,
+ _try_detect_search,
+ detect_content_type,
+ is_json_array_of_dicts,
+)
+from headroom.transforms.error_detection import (
+ ERROR_INDICATOR_KEYWORDS,
+ ERROR_KEYWORDS,
+ ERROR_PATTERN,
+ IMPORTANCE_KEYWORDS,
+ IMPORTANCE_PATTERN,
+ PRIORITY_PATTERNS_DIFF,
+ PRIORITY_PATTERNS_SEARCH,
+ PRIORITY_PATTERNS_TEXT,
+ SECURITY_KEYWORDS,
+ SECURITY_PATTERN,
+ WARNING_PATTERN,
+ content_has_error_indicators,
+)
+
+
+def test_detect_content_type_handles_empty_and_plain_text() -> None:
+ empty = detect_content_type(" ")
+ assert empty.content_type is ContentType.PLAIN_TEXT
+ assert empty.confidence == 0.0
+
+ plain = detect_content_type("just a normal paragraph with no strong patterns")
+ assert plain.content_type is ContentType.PLAIN_TEXT
+ assert plain.confidence == 0.5
+
+
+def test_json_detection_distinguishes_dict_arrays_and_other_lists() -> None:
+ dict_result = _try_detect_json('[{"id": 1}, {"id": 2}]')
+ assert dict_result is not None
+ assert dict_result.content_type is ContentType.JSON_ARRAY
+ assert dict_result.confidence == 1.0
+ assert dict_result.metadata == {"item_count": 2, "is_dict_array": True}
+
+ scalar_result = _try_detect_json("[1, 2, 3]")
+ assert scalar_result is not None
+ assert scalar_result.confidence == 0.8
+ assert scalar_result.metadata == {"item_count": 3, "is_dict_array": False}
+
+ empty_result = _try_detect_json("[]")
+ assert empty_result is not None
+ assert empty_result.metadata == {"item_count": 0, "is_dict_array": False}
+
+ assert _try_detect_json('{"id": 1}') is None
+ assert _try_detect_json("[not valid json") is None
+ assert is_json_array_of_dicts('[{"id": 1}]') is True
+ assert is_json_array_of_dicts('["value"]') is False
+
+
+def test_diff_detection_tracks_headers_and_changes() -> None:
+ diff = "\n".join(
+ [
+ "diff --git a/app.py b/app.py",
+ "--- a/app.py",
+ "@@ -1,2 +1,2 @@",
+ "-old line",
+ "+new line",
+ ]
+ )
+ result = _try_detect_diff(diff)
+ assert result is not None
+ assert result.content_type is ContentType.GIT_DIFF
+ assert result.metadata["header_matches"] == 3
+ assert result.metadata["change_lines"] == 2
+ assert result.confidence == 1.0
+ assert detect_content_type(diff).content_type is ContentType.GIT_DIFF
+
+ assert _try_detect_diff("+not enough by itself") is None
+
+
+def test_html_detection_requires_real_structure() -> None:
+ html = """
+ <!DOCTYPE html>
+ <html>
+ <head><meta charset="utf-8"></head>
+ <body><main><section><div>Hello</div><nav>Links</nav></section></main></body>
+ </html>
+ """
+ result = _try_detect_html(html)
+ assert result is not None
+ assert result.content_type is ContentType.HTML
+ assert result.metadata["has_doctype"] is True
+ assert result.metadata["has_html_tag"] is True
+ assert result.metadata["structural_tags"] >= 3
+ assert detect_content_type(html).content_type is ContentType.HTML
+
+ assert _try_detect_html("<div>only one tag</div>") is None
+ assert _try_detect_html("<html><title>too sparse</title></html>") is None
+
+
+def test_search_detection_uses_match_ratio() -> None:
+ search_output = "\n".join(
+ [
+ "src/app.py:10:def main():",
+ "src/app.py:20:print('hello')",
+ "README.md:5:usage docs",
+ "plain text footer",
+ ]
+ )
+ result = _try_detect_search(search_output)
+ assert result is not None
+ assert result.content_type is ContentType.SEARCH_RESULTS
+ assert result.metadata == {"matching_lines": 3, "total_lines": 4}
+ assert result.confidence == 0.85
+ assert detect_content_type(search_output).content_type is ContentType.SEARCH_RESULTS
+
+ assert _try_detect_search("one:1:match\nplain\nplain\nplain") is None
+ assert _try_detect_search("\n\n") is None
+
+
+def test_log_detection_prefers_build_output_patterns() -> None:
+ log_output = "\n".join(
+ [
+ "2025-01-01 Starting run",
+ "ERROR failed to compile",
+ "WARNING retrying build",
+ "PASSED unit test",
+ "Traceback (most recent call last)",
+ "plain footer",
+ ]
+ )
+ result = _try_detect_log(log_output)
+ assert result is not None
+ assert result.content_type is ContentType.BUILD_OUTPUT
+ assert result.metadata == {"pattern_matches": 5, "error_matches": 2, "total_lines": 6}
+ assert result.confidence == 0.8166666666666667
+ assert detect_content_type(log_output).content_type is ContentType.BUILD_OUTPUT
+
+ assert _try_detect_log("plain\ntext\nonly") is None
+ assert _try_detect_log("\n\n") is None
+ assert _try_detect_log("\n".join(["ERROR one", *["plain"] * 15])) is None
+
+
+def test_code_detection_identifies_language_and_thresholds() -> None:
+ python_code = "\n".join(
+ [
+ "import os",
+ "from pathlib import Path",
+ "",
+ "@cached",
+ "class App:",
+ " pass",
+ "def main():",
+ ' """Run."""',
+ ]
+ )
+ result = _try_detect_code(python_code)
+ assert result is not None
+ assert result.content_type is ContentType.SOURCE_CODE
+ assert result.metadata == {"language": "python", "pattern_matches": 6}
+ assert result.confidence == 0.8628571428571429
+ assert detect_content_type(python_code).content_type is ContentType.SOURCE_CODE
+
+ assert _try_detect_code("function maybe() {}\nplain text") is None
+ assert _try_detect_code("import os\ndef main():") is None
+ assert _try_detect_code("\n\n") is None
+
+
+def test_detect_content_type_respects_priority_order() -> None:
+ diff_like_search = "\n".join(
+ [
+ "diff --git a/src/app.py b/src/app.py",
+ "@@ -1,1 +1,1 @@",
+ "+src/app.py:10:def still_diff_first()",
+ ]
+ )
+ assert detect_content_type(diff_like_search).content_type is ContentType.GIT_DIFF
+
+
+def test_error_detection_keywords_patterns_and_indicator_helper() -> None:
+ assert {"error", "failed", "critical"} <= ERROR_KEYWORDS
+ assert {"warning", "todo", "fix"} <= IMPORTANCE_KEYWORDS
+ assert {"security", "password", "token"} <= SECURITY_KEYWORDS
+ assert ERROR_INDICATOR_KEYWORDS[0] == "error"
+
+ assert ERROR_PATTERN.search("Fatal error occurred")
+ assert WARNING_PATTERN.search("warning: be careful")
+ assert IMPORTANCE_PATTERN.search("TODO fix this hack")
+ assert SECURITY_PATTERN.search("rotate the auth token")
+
+ assert PRIORITY_PATTERNS_SEARCH[:3] == [ERROR_PATTERN, WARNING_PATTERN, IMPORTANCE_PATTERN]
+ assert PRIORITY_PATTERNS_DIFF == [ERROR_PATTERN, IMPORTANCE_PATTERN, SECURITY_PATTERN]
+ assert PRIORITY_PATTERNS_TEXT[0] is ERROR_PATTERN
+ assert PRIORITY_PATTERNS_TEXT[1] is IMPORTANCE_PATTERN
+ assert PRIORITY_PATTERNS_TEXT[2].match("## Header")
+ assert PRIORITY_PATTERNS_TEXT[3].match("**Bold")
+ assert PRIORITY_PATTERNS_TEXT[4].match("> quote")
+
+ assert content_has_error_indicators("TRACEBACK: Fatal crash in worker") is True
+ assert content_has_error_indicators("Everything completed successfully") is False
diff --git a/tests/test_transforms_content_router.py b/tests/test_transforms_content_router.py
new file mode 100644
index 000000000..7969bb152
--- /dev/null
+++ b/tests/test_transforms_content_router.py
@@ -0,0 +1,294 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+import headroom.transforms.content_router as content_router_module
+from headroom.transforms.content_detector import ContentType, DetectionResult
+from headroom.transforms.content_router import (
+ CompressionCache,
+ CompressionStrategy,
+ ContentRouter,
+ ContentRouterConfig,
+ RouterCompressionResult,
+ RoutingDecision,
+ _create_content_signature,
+ _detect_content,
+ _extract_json_block,
+ is_mixed_content,
+ split_into_sections,
+)
+
+
+def test_compression_cache_handles_hits_skips_evictions_and_clear(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ times = iter([100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 112.0, 112.0])
+ monkeypatch.setattr(content_router_module.time, "time", lambda: next(times))
+ monkeypatch.setattr(content_router_module.time, "perf_counter_ns", lambda: 50)
+
+ cache = CompressionCache(ttl_seconds=10)
+ cache.put(1, "compressed", 0.4, "text")
+ cache.mark_skip(2)
+
+ assert cache.get(1) == ("compressed", 0.4, "text")
+ assert cache.is_skipped(2) is True
+ assert cache.size == 1
+ assert cache.skip_size == 1
+
+ cache.move_to_skip(1)
+ assert cache.get(1) is None
+ assert cache.is_skipped(1) is True
+
+ # Expire both skip entries
+ assert cache.is_skipped(2) is False
+ assert cache.is_skipped(1) is False
+
+ assert cache.stats["cache_hits"] == 1
+ assert cache.stats["cache_skip_hits"] == 2
+ assert cache.stats["cache_misses"] == 1
+ assert cache.stats["cache_evictions"] >= 2
+
+ cache.clear()
+ assert cache.size == 0
+ assert cache.skip_size == 0
+
+
+def test_router_result_helpers_and_summary() -> None:
+ pure = RouterCompressionResult(
+ compressed="small",
+ original="very large",
+ strategy_used=CompressionStrategy.TEXT,
+ routing_log=[
+ RoutingDecision(
+ content_type=ContentType.PLAIN_TEXT,
+ strategy=CompressionStrategy.TEXT,
+ original_tokens=10,
+ compressed_tokens=4,
+ )
+ ],
+ )
+ assert pure.total_original_tokens == 10
+ assert pure.total_compressed_tokens == 4
+ assert pure.compression_ratio == 0.4
+ assert pure.tokens_saved == 6
+ assert pure.savings_percentage == 60.0
+ assert pure.summary() == "Pure text: 10→4 tokens (60% saved)"
+
+ mixed = RouterCompressionResult(
+ compressed="joined",
+ original="original",
+ strategy_used=CompressionStrategy.MIXED,
+ sections_processed=2,
+ routing_log=[
+ RoutingDecision(
+ content_type=ContentType.PLAIN_TEXT,
+ strategy=CompressionStrategy.TEXT,
+ original_tokens=0,
+ compressed_tokens=0,
+ ),
+ RoutingDecision(
+ content_type=ContentType.SEARCH_RESULTS,
+ strategy=CompressionStrategy.SEARCH,
+ original_tokens=8,
+ compressed_tokens=2,
+ ),
+ ],
+ )
+ assert mixed.routing_log[0].compression_ratio == 1.0
+ assert mixed.summary().startswith("Mixed content: 2 sections, routed to ")
+
+
+def test_content_signature_and_detection_helpers(monkeypatch: pytest.MonkeyPatch) -> None:
+ signature = _create_content_signature("search", "file.py:10:match", language="python")
+ assert signature is not None
+ assert len(signature.structure_hash) == 24
+
+ fake_detector = SimpleNamespace(
+ detect=lambda content: SimpleNamespace(
+ content_type=SimpleNamespace(value="code"),
+ confidence=0.91,
+ language="python",
+ raw_label="python",
+ )
+ )
+ monkeypatch.setattr(content_router_module, "_get_magika_detector", lambda: fake_detector)
+ magika_result = _detect_content("def main(): pass")
+ assert magika_result == DetectionResult(
+ content_type=ContentType.SOURCE_CODE,
+ confidence=0.91,
+ metadata={"language": "python", "raw_label": "python"},
+ )
+
+ fallback = DetectionResult(ContentType.PLAIN_TEXT, 0.6, {"kind": "fallback"})
+ monkeypatch.setattr(content_router_module, "_get_magika_detector", lambda: None)
+ monkeypatch.setattr(content_router_module, "detect_content_type", lambda content: fallback)
+ assert _detect_content("plain") is fallback
+
+
+def test_mixed_content_section_splitting_and_json_extraction() -> None:
+ content = "\n".join(
+ [
+ "Intro paragraph with Several words included for prose detection.",
+ "Another line with enough words to read as normal prose today.",
+ "Third line adds more prose so the detector sees real text content.",
+ "Fourth sentence keeps the count moving higher for prose patterns.",
+ "Fifth sentence does the same for mixed content identification.",
+ "Sixth sentence seals the prose threshold for the helper.",
+ "```python",
+ "def main():",
+ " return 1",
+ "```",
+ '[{"id": 1}]',
+ "src/app.py:10:def main():",
+ "src/app.py:11:return 1",
+ ]
+ )
+ assert is_mixed_content(content) is True
+
+ sections = split_into_sections(content)
+ assert [section.content_type for section in sections] == [
+ ContentType.PLAIN_TEXT,
+ ContentType.SOURCE_CODE,
+ ContentType.JSON_ARRAY,
+ ContentType.SEARCH_RESULTS,
+ ]
+ assert sections[1].language == "python"
+ assert sections[1].is_code_fence is True
+ assert sections[2].content == '[{"id": 1}]'
+ assert sections[3].end_line == 12
+
+ json_block, end_idx = _extract_json_block(["[", '{"id": 1}', "]"], 0)
+ assert json_block == '[\n{"id": 1}\n]'
+ assert end_idx == 2
+ assert _extract_json_block(["{", '"a": 1'], 0) == (None, 0)
+
+
+def test_content_router_strategy_and_compress_paths(monkeypatch: pytest.MonkeyPatch) -> None:
+ router = ContentRouter(ContentRouterConfig(prefer_code_aware_for_code=False))
+
+ monkeypatch.setattr(content_router_module, "is_mixed_content", lambda content: False)
+ monkeypatch.setattr(
+ content_router_module,
+ "_detect_content",
+ lambda content: DetectionResult(ContentType.SOURCE_CODE, 1.0, {}),
+ )
+ assert router._determine_strategy("code") is CompressionStrategy.KOMPRESS
+ assert (
+ router._strategy_from_detection(DetectionResult(ContentType.SEARCH_RESULTS, 1.0, {}))
+ is CompressionStrategy.SEARCH
+ )
+ assert router._strategy_from_detection_type(ContentType.GIT_DIFF) is CompressionStrategy.DIFF
+ assert (
+ router._content_type_from_strategy(CompressionStrategy.PASSTHROUGH)
+ is ContentType.PLAIN_TEXT
+ )
+
+ mixed_result = RouterCompressionResult(
+ compressed="mixed",
+ original="mixed",
+ strategy_used=CompressionStrategy.MIXED,
+ )
+ pure_result = RouterCompressionResult(
+ compressed="pure",
+ original="pure",
+ strategy_used=CompressionStrategy.TEXT,
+ )
+ monkeypatch.setattr(router, "_compress_mixed", lambda *args, **kwargs: mixed_result)
+ monkeypatch.setattr(router, "_compress_pure", lambda *args, **kwargs: pure_result)
+
+ monkeypatch.setattr(router, "_determine_strategy", lambda content: CompressionStrategy.MIXED)
+ assert router.compress("mixed") is mixed_result
+
+ monkeypatch.setattr(router, "_determine_strategy", lambda content: CompressionStrategy.TEXT)
+ assert router.compress("pure") is pure_result
+ assert router.compress(" ").strategy_used is CompressionStrategy.PASSTHROUGH
+
+
+def test_content_router_mixed_pure_apply_and_toin(monkeypatch: pytest.MonkeyPatch) -> None:
+ router = ContentRouter()
+ mixed_content = "\n".join(["before", "```python", "print('x')", "```", "after"])
+ monkeypatch.setattr(
+ content_router_module,
+ "split_into_sections",
+ lambda content: [
+ SimpleNamespace(
+ content="print('x')",
+ content_type=ContentType.SOURCE_CODE,
+ language="python",
+ is_code_fence=True,
+ ),
+ SimpleNamespace(
+ content="after text",
+ content_type=ContentType.PLAIN_TEXT,
+ language=None,
+ is_code_fence=False,
+ ),
+ ],
+ )
+ monkeypatch.setattr(
+ router,
+ "_apply_strategy_to_content",
+ lambda content, strategy, context, language=None, question=None, bias=1.0: (
+ f"{strategy.value}:{content}",
+ len(content.split()) - 1,
+ ),
+ )
+ result = router._compress_mixed(mixed_content, "ctx")
+ assert result.strategy_used is CompressionStrategy.MIXED
+ assert result.sections_processed == 2
+ assert "```python\ncode_aware:print('x')\n```" in result.compressed
+
+ monkeypatch.setattr(
+ router,
+ "_apply_strategy_to_content",
+ lambda content, strategy, context, language=None, question=None, bias=1.0: (
+ "shrunk",
+ 1,
+ ),
+ )
+ pure = router._compress_pure("some plain text", CompressionStrategy.TEXT, "ctx")
+ assert pure.routing_log[0].content_type is ContentType.PLAIN_TEXT
+ assert pure.total_original_tokens == 3
+ assert pure.total_compressed_tokens == 1
+
+ calls: list[dict] = []
+ router._toin = SimpleNamespace(record_compression=lambda **kwargs: calls.append(kwargs))
+ monkeypatch.setattr(content_router_module, "_create_content_signature", lambda **kwargs: "sig")
+ router._record_to_toin(
+ CompressionStrategy.TEXT,
+ "original content",
+ "small",
+ original_tokens=10,
+ compressed_tokens=4,
+ language="python",
+ context="question",
+ )
+ assert calls[0]["tool_signature"] == "sig"
+ assert calls[0]["strategy"] == "text"
+ assert calls[0]["query_context"] == "question"
+
+ router._record_to_toin(
+ CompressionStrategy.SMART_CRUSHER,
+ "x",
+ "x",
+ original_tokens=10,
+ compressed_tokens=4,
+ )
+ router._record_to_toin(
+ CompressionStrategy.TEXT,
+ "x",
+ "x",
+ original_tokens=2,
+ compressed_tokens=2,
+ )
+ monkeypatch.setattr(content_router_module, "_create_content_signature", lambda **kwargs: None)
+ router._record_to_toin(
+ CompressionStrategy.TEXT,
+ "x",
+ "y",
+ original_tokens=5,
+ compressed_tokens=1,
+ )
+ assert len(calls) == 1
diff --git a/tests/test_transforms_package.py b/tests/test_transforms_package.py
new file mode 100644
index 000000000..95b604a8b
--- /dev/null
+++ b/tests/test_transforms_package.py
@@ -0,0 +1,26 @@
+from __future__ import annotations
+
+import pytest
+
+import headroom.transforms as transforms
+
+
+def test_transforms_getattr_and_dir(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(transforms, "_HTML_EXTRACTOR_AVAILABLE", True)
+ monkeypatch.setattr(
+ transforms,
+ "_LAZY_EXPORTS",
+ {"FakeExport": ("fake.module", "VALUE")},
+ )
+ monkeypatch.setattr(transforms, "import_module", lambda name: type("M", (), {"VALUE": 123})())
+
+ assert transforms.__getattr__("_HTML_EXTRACTOR_AVAILABLE") is True
+ assert transforms.__getattr__("FakeExport") == 123
+ assert transforms.FakeExport == 123
+ assert "FakeExport" in transforms.__dir__()
+
+ with pytest.raises(AttributeError, match="__path__"):
+ transforms.__getattr__("__path__")
+
+ with pytest.raises(AttributeError, match="MissingExport"):
+ transforms.__getattr__("MissingExport")
diff --git a/tests/test_transforms_search_compressor.py b/tests/test_transforms_search_compressor.py
new file mode 100644
index 000000000..a2473347e
--- /dev/null
+++ b/tests/test_transforms_search_compressor.py
@@ -0,0 +1,143 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from headroom.transforms.search_compressor import (
+ FileMatches,
+ SearchCompressionResult,
+ SearchCompressor,
+ SearchCompressorConfig,
+ SearchMatch,
+)
+
+
+def test_parse_score_select_and_format_search_results(monkeypatch: pytest.MonkeyPatch) -> None:
+ compressor = SearchCompressor(
+ SearchCompressorConfig(
+ max_matches_per_file=3,
+ max_total_matches=4,
+ max_files=2,
+ context_keywords=["auth"],
+ )
+ )
+ content = "\n".join(
+ [
+ "src/auth.py:10:ERROR auth failed",
+ "src/auth.py-11-warning auth retry",
+ "src/auth.py:12:plain auth line",
+ "src/db.py:2:warning token expired",
+ "not a match",
+ ]
+ )
+ parsed = compressor._parse_search_results(content)
+ assert set(parsed) == {"src/auth.py", "src/db.py"}
+ assert parsed["src/auth.py"].first == SearchMatch(
+ file="src/auth.py", line_number=10, content="ERROR auth failed"
+ )
+ assert parsed["src/auth.py"].last.line_number == 12
+
+ compressor._score_matches(parsed, "find auth error")
+ assert parsed["src/auth.py"].matches[0].score == 1.0
+ assert parsed["src/db.py"].matches[0].score > 0
+
+ monkeypatch.setitem(
+ __import__("sys").modules,
+ "headroom.transforms.adaptive_sizer",
+ SimpleNamespace(compute_optimal_k=lambda items, **kwargs: 4),
+ )
+ selected = compressor._select_matches(parsed, bias=1.2)
+ assert list(selected) == ["src/auth.py", "src/db.py"]
+ assert [m.line_number for m in selected["src/auth.py"].matches] == [10, 11, 12]
+
+ formatted, summaries = compressor._format_output(
+ selected,
+ {
+ **parsed,
+ "src/db.py": FileMatches(
+ file="src/db.py",
+ matches=[
+ SearchMatch(file="src/db.py", line_number=2, content="warning token expired"),
+ SearchMatch(file="src/db.py", line_number=3, content="another line"),
+ ],
+ ),
+ },
+ )
+ assert "src/auth.py:10:ERROR auth failed" in formatted
+ assert summaries["src/db.py"] == "[... and 1 more matches in src/db.py]"
+
+
+def test_search_compressor_compress_paths_and_ccr(monkeypatch: pytest.MonkeyPatch) -> None:
+ compressor = SearchCompressor(
+ SearchCompressorConfig(enable_ccr=True, min_matches_for_ccr=2, context_keywords=["auth"])
+ )
+ no_match = compressor.compress("plain text only")
+ assert no_match.original_match_count == 0
+ assert no_match.compressed == "plain text only"
+
+ parsed = {
+ "src/auth.py": FileMatches(
+ file="src/auth.py",
+ matches=[
+ SearchMatch(file="src/auth.py", line_number=1, content="auth error"),
+ SearchMatch(file="src/auth.py", line_number=2, content="auth ok"),
+ ],
+ )
+ }
+ monkeypatch.setattr(compressor, "_parse_search_results", lambda content: parsed)
+ monkeypatch.setattr(compressor, "_score_matches", lambda file_matches, context: None)
+ monkeypatch.setattr(compressor, "_select_matches", lambda file_matches, bias=1.0: parsed)
+ monkeypatch.setattr(
+ compressor,
+ "_format_output",
+ lambda selected, original: ("short", {"src/auth.py": "summary"}),
+ )
+ monkeypatch.setattr(compressor, "_store_in_ccr", lambda original, compressed, count: "abc123")
+
+ result = compressor.compress("raw search", context="auth", bias=0.8)
+ assert result.original_match_count == 2
+ assert result.compressed_match_count == 2
+ assert result.cache_key == "abc123"
+ assert result.summaries == {"src/auth.py": "summary"}
+ assert result.compressed.endswith("[2 matches compressed to 2. Retrieve more: hash=abc123]")
+
+ monkeypatch.setattr(compressor, "_store_in_ccr", lambda original, compressed, count: None)
+ no_cache = compressor.compress("raw search", context="auth")
+ assert no_cache.cache_key is None
+ assert no_cache.compressed == "short"
+
+
+def test_store_in_ccr_and_result_properties(monkeypatch: pytest.MonkeyPatch) -> None:
+ compressor = SearchCompressor()
+ monkeypatch.setitem(
+ __import__("sys").modules,
+ "headroom.cache.compression_store",
+ SimpleNamespace(
+ get_compression_store=lambda: SimpleNamespace(
+ store=lambda original, compressed, original_item_count=0: "stored-key"
+ )
+ ),
+ )
+ assert compressor._store_in_ccr("orig", "comp", 5) == "stored-key"
+
+ def broken_store():
+ raise RuntimeError("boom")
+
+ monkeypatch.setitem(
+ __import__("sys").modules,
+ "headroom.cache.compression_store",
+ SimpleNamespace(get_compression_store=broken_store),
+ )
+ assert compressor._store_in_ccr("orig", "comp", 5) is None
+
+ result = SearchCompressionResult(
+ compressed="tiny",
+ original="this is a much longer original string",
+ original_match_count=10,
+ compressed_match_count=4,
+ files_affected=2,
+ compression_ratio=0.3,
+ )
+ assert result.tokens_saved_estimate > 0
+ assert result.matches_omitted == 6
diff --git a/tests/test_utils.py b/tests/test_utils.py
new file mode 100644
index 000000000..5e6b6bbf0
--- /dev/null
+++ b/tests/test_utils.py
@@ -0,0 +1,122 @@
+from __future__ import annotations
+
+from datetime import datetime
+
+from headroom import utils
+
+
+class FakeProvider:
+ def __init__(self, result):
+ self.result = result
+ self.calls: list[tuple[int, int, str, int]] = []
+
+ def estimate_cost(
+ self, input_tokens: int, output_tokens: int, model: str, cached_tokens: int = 0
+ ):
+ self.calls.append((input_tokens, output_tokens, model, cached_tokens))
+ return self.result
+
+
+def test_hash_helpers_and_request_id() -> None:
+ request_id = utils.generate_request_id()
+ assert len(request_id) == 36
+ assert request_id.count("-") == 4
+
+ assert (
+ utils.compute_hash("hello")
+ == "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
+ )
+ assert utils.compute_hash("hi\ud800") == utils.compute_hash(
+ "hi\ud800".encode("utf-8", "surrogatepass")
+ )
+ assert utils.compute_short_hash("hello", length=8) == "2cf24dba"
+ assert utils.fast_hash("hello", length=8) == "5d41402a"
+
+
+def test_extract_user_query_and_message_hashes() -> None:
+ messages = [
+ {"role": "system", "content": "rules"},
+ {"role": "user", "content": " "},
+ {"role": "assistant", "content": "skip"},
+ {
+ "role": "user",
+ "content": [{"type": "image"}, {"type": "text", "text": " latest question "}],
+ },
+ ]
+ assert utils.extract_user_query(messages) == "latest question"
+ assert utils.extract_user_query([{"role": "assistant", "content": "skip"}]) == ""
+
+ hash_one = utils.compute_messages_hash(messages)
+ hash_two = utils.compute_messages_hash(list(messages))
+ assert hash_one == hash_two
+ assert len(hash_one) == 16
+
+ prefix_default = utils.compute_prefix_hash(
+ [
+ {"role": "system", "content": "a"},
+ {"role": "system", "content": "b"},
+ {"role": "user", "content": "c"},
+ {"role": "assistant", "content": "d"},
+ ]
+ )
+ prefix_explicit = utils.compute_prefix_hash(
+ [
+ {"role": "system", "content": "a"},
+ {"role": "system", "content": "b"},
+ {"role": "user", "content": "c"},
+ {"role": "assistant", "content": "d"},
+ ],
+ prefix_count=3,
+ )
+ assert prefix_default == prefix_explicit
+ assert utils.compute_prefix_hash([]) == utils.compute_short_hash("")
+
+
+def test_timestamp_marker_and_json_helpers() -> None:
+ ts = utils.format_timestamp(datetime(2026, 4, 23, 6, 0, 0))
+ assert ts == "2026-04-23T06:00:00Z"
+ assert utils.parse_timestamp(ts) == datetime(2026, 4, 23, 6, 0, 0)
+ assert utils.parse_timestamp("2026-04-23T06:00:00") == datetime(2026, 4, 23, 6, 0, 0)
+
+ marker = utils.create_marker("tool_digest", sha256="abc", count="2")
+ assert marker == '<headroom:tool_digest sha256="abc" count="2">'
+ assert utils.create_tool_digest_marker("abc") == '<headroom:tool_digest sha256="abc">'
+ assert utils.create_dropped_context_marker("budget") == (
+ '<headroom:dropped_context reason="budget">'
+ )
+ assert utils.create_dropped_context_marker("budget", count=4) == (
+ '<headroom:dropped_context reason="budget" count="4">'
+ )
+ assert utils.create_truncated_marker(100, 25) == (
+ '<headroom:truncated original="100" truncated_to="25">'
+ )
+
+ extracted = utils.extract_markers(
+ 'x <headroom:tool_digest sha256="abc"> y <headroom:dropped_context reason="budget" count="2">'
+ )
+ assert extracted == [
+ {"type": "tool_digest", "attributes": {"sha256": "abc"}},
+ {"type": "dropped_context", "attributes": {"reason": "budget", "count": "2"}},
+ ]
+
+ assert utils.safe_json_loads('{"ok": true}') == ({"ok": True}, True)
+ assert utils.safe_json_loads("{bad") == (None, False)
+ assert utils.safe_json_dumps({"emoji": "café"}) == '{"emoji":"café"}'
+
+
+def test_cost_formatting_and_deep_copy() -> None:
+ provider = FakeProvider("1.25")
+ assert utils.estimate_cost(100, 50, "gpt-4o", cached_tokens=10, provider=provider) == 1.25
+ assert provider.calls == [(100, 50, "gpt-4o", 10)]
+ assert utils.estimate_cost(1, 1, "gpt-4o", provider=None) is None
+
+ none_provider = FakeProvider(None)
+ assert utils.estimate_cost(1, 1, "gpt-4o", provider=none_provider) is None
+
+ assert utils.format_cost(0.0099) == "$0.0099"
+ assert utils.format_cost(1.234) == "$1.23"
+
+ messages = [{"role": "user", "content": {"nested": ["a"]}}]
+ copied = utils.deep_copy_messages(messages)
+ copied[0]["content"]["nested"].append("b")
+ assert messages == [{"role": "user", "content": {"nested": ["a"]}}]