Files
headroom/tests/test_graph.py
Tejas ChopraandClaude Opus 5.5 30d23fb799 refactor(graph): drop the bespoke codebase-memory-mcp downloader nothing calls (#4102)
## Description

`headroom/graph/installer.py` had its own downloader for the
codebase-memory-mcp binary: `download_cbm` and `ensure_cbm`, plus
platform, asset-name and zip helpers. `headroom wrap` stopped calling
`ensure_cbm()` in dca9853e (#1230), when tokensave and Serena replaced
codebase-memory-mcp in wrap. Since then the only product user of the
module is the `--code-graph` watcher (`graph/watcher.py:121`). It calls
only `get_cbm_path()`. The downloader duplicated `headroom.binaries`
(the same `tools.json` pin, the same verification), and only its tests
kept it alive.

This PR keeps `get_cbm_path`, `_installed_name`, `CBM_BIN_DIR` and
`CBM_BIN_NAME`, and removes the rest.

Evidence:
- `grep -rnw` for `download_cbm`, `ensure_cbm`, `_detect_platform`,
`_asset_filename`, `_extract_from_zip`, `CBM_VERSION`, `CBM_REPO` and
`GITHUB_RELEASE_URL` found only `installer.py` and tests. The search
covered `headroom crates plugins sdk docs wiki scripts benchmarks
examples e2e .github` and the consumer repos.
- `git show dca9853e` shows the removed `from headroom.graph.installer
import ensure_cbm, get_cbm_path` in `cli/wrap.py`.
- `installer.py` has no `__all__`. `headroom/graph/__init__.py`
re-exports nothing. Neither is documented.

**`binaries.resolve` vs `get_cbm_path` check (requested before
deleting).**
- `binaries.resolve("codebase-memory-mcp")` installs to
`binaries.cache_dir()/codebase-memory-mcp-<version>-<platform>/codebase-memory-mcp`.
The same goes for `headroom tools install` and `ensure_tools()` at proxy
startup with `--intercept-tool-results`. On macOS that is
`~/Library/Caches/headroom/bin/...`; elsewhere it is the platform cache
dir or `HEADROOM_BINARIES_CACHE`.
- `get_cbm_path()` looks on `PATH` and then in `~/.local/bin` only.
- So a binary installed through `headroom.binaries` is **not** found by
the watcher unless that cache dir is on `PATH`. This gap already exists
on main and this PR does not change it.
- The removed `download_cbm` did install into `~/.local/bin`, but
nothing has called it since #1230.
- A follow-up could make `get_cbm_path()` also try
`binaries.which("codebase-memory-mcp")`. I left that out because it is a
behaviour change.

Refs #4136

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [x] Code refactoring (no functional changes)

## Changes Made

- `headroom/graph/installer.py`:
- Remove `download_cbm`, `ensure_cbm`, `_detect_platform`,
`_asset_filename` and `_extract_from_zip`.
- Remove the constants `CBM_VERSION`, `CBM_REPO` and
`GITHUB_RELEASE_URL`, and the imports only they used.
- The module docstring now says what the module does: it locates the
binary.
- `headroom/offline.py`: the docstring lists codebase-memory-mcp under
release-binary downloads.
- Tests:
  - `tests/test_graph.py`: drop the platform, download and ensure tests.
- `tests/test_graph_installer.py`: rewrite the real-PATH-lookup test so
it creates the binary directly instead of through `download_cbm`, and
keep the off-PATH test.
- `tests/test_binaries_refusal_reaches_callers.py`: drop the two
`ensure_cbm` tests.
- `tests/test_offline_egress_chokepoint.py`: drop
`test_cbm_download_opens_no_socket`.
  - The watcher tests are unchanged.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [ ] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ pytest -q -p no:cacheprovider tests/test_graph.py tests/test_graph_installer.py tests/test_binaries_refusal_reaches_callers.py tests/test_offline_egress_chokepoint.py tests/test_litellm_optional.py tests/test_binaries.py
FAILED tests/test_offline_egress_chokepoint.py::TestHeadroomCloudCompressionOffline::test_asgi_middleware_opens_no_socket
FAILED tests/test_offline_egress_chokepoint.py::TestHeadroomCloudCompressionOffline::test_litellm_callback_opens_no_socket
======================== 2 failed, 188 passed in 16.14s ========================
# The same two fail on a clean origin/main (2 failed, 141 passed for that file), so they are pre-existing and unrelated.
$ mypy headroom/graph/installer.py headroom/graph/watcher.py --ignore-missing-imports
Success: no issues found in 2 source files
$ uvx ruff@0.16.8 check <changed files>
All checks passed!
```

## Real Behavior Proof

- Environment: macOS, Python 3.12.13, repo .venv, branch checkout at
0cbd67d6 (base a9815bbb), temp HOME / HEADROOM_WORKSPACE_DIR /
CODEX_HOME, offline.
- Exact command / steps:
- Ran the shared smoke harness with `--code-graph`. It starts a real
proxy from this checkout against a local fake upstream and sends one
Anthropic and one OpenAI request with a compressible tool result.
- Ran a direct script with a stub `codebase-memory-mcp` in the temp
`~/.local/bin`. It calls `get_cbm_path` and starts the real
`CodeGraphWatcher`, then repeats both with the binary removed.
  - Ran the graph, installer, binaries and offline-egress tests.
- Observed result:
- With `--code-graph`, the proxy starts and both requests return HTTP
200 with savings. The temp HOME has no binary, so the watcher stays off,
which is unchanged and logged at DEBUG only.
- With the stub present, `get_cbm_path` finds it and the watcher starts.
Without it, both return None/False.
  - 188 tests pass. The 2 failures are pre-existing on main.
- Not tested: Indexing with a real codebase-memory-mcp binary.
`get_cbm_path` and the watcher are unchanged.

```text
$ bash smoke.sh <worktree> --code-graph
branch: cleanup/memory-cache-graph-downloader @ 0cbd67d6
health: 200
POST /v1/messages        -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines:
   2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you 
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection.

$ HOME=$TMP/home HEADROOM_WORKSPACE_DIR=$TMP/ws CODEX_HOME=$TMP/codex python -u -c "<get_cbm_path(); CodeGraphWatcher(project_dir).start(); remove stub; repeat>"
get_cbm_path() -> $TMP/home/.local/bin/codebase-memory-mcp
watcher.start() -> True
without binary: get_cbm_path() -> None ; start() -> False
```

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: N/A; dead-code removal.
- Stable/default behavior changed: No. Nothing called the removed
downloader.
- Kill switch / disable path: N/A.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert this commit.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

N/A.

## Additional Notes

Part of maintainer-requested cleanup #4136 (dead code, duplication,
debuggability), split into small PRs for review.

Follow-ups, out of scope here:
- the install-location gap described above;
- `binaries.verify_download_bytes`, whose only product caller was the
removed `download_cbm`. It is now used only by `tests/test_binaries.py`,
and its docstring still names codebase-memory-mcp.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 08:59:18 -07:00

227 lines
7.5 KiB
Python

from __future__ import annotations
import json
import subprocess
from pathlib import Path
from types import ModuleType, SimpleNamespace
from headroom.graph import installer, watcher
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.platform, "system", lambda: "Linux")
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_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()