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.

Add live code graph watcher, remove --code-aware flag

chopratejas95ce5ee7610a
diff --git a/headroom/cli/proxy.py b/headroom/cli/proxy.py
index 2ff99e099..84c66db01 100644
--- a/headroom/cli/proxy.py
+++ b/headroom/cli/proxy.py
@@ -67,8 +67,12 @@ from .main import main
envvar="HEADROOM_BUDGET",
help="Daily budget limit in USD (env: HEADROOM_BUDGET)",
)
-# Code-aware compression (ON by default if installed)
[email protected]("--no-code-aware", is_flag=True, help="Disable AST-based code compression")
+# Code graph: indexes project + watches files for live reindex via codebase-memory-mcp
+ "--code-graph",
+ is_flag=True,
+ help="Enable code graph intelligence (indexes project, watches files for live reindex via codebase-memory-mcp)",
+)
# Read lifecycle (ON by default: compresses stale/superseded Read outputs)
@click.option(
"--no-read-lifecycle",
@@ -188,7 +192,7 @@ def proxy(
connect_timeout_seconds: int | None,
log_file: str | None,
budget: float | None,
- no_code_aware: bool,
+ code_graph: bool,
no_read_lifecycle: bool,
no_intelligent_context: bool,
no_intelligent_scoring: bool,
@@ -270,8 +274,8 @@ def proxy(
else 10,
log_file=log_file,
budget_limit_usd=budget,
- # Code-aware: ON by default (use --no-code-aware to disable)
- code_aware_enabled=not no_code_aware,
+ # Code graph: live file watcher for incremental reindexing
+ code_graph_watcher=code_graph,
# Read lifecycle: ON by default (use --no-read-lifecycle to disable)
read_lifecycle=not no_read_lifecycle,
# Intelligent Context: ON by default (use --no-intelligent-context to disable)
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.py
index a89c48a32..e388cf4df 100644
--- a/headroom/cli/wrap.py
+++ b/headroom/cli/wrap.py
@@ -78,6 +78,7 @@ def _start_proxy(
*,
learn: bool = False,
agent_type: str = "unknown",
+ code_graph: bool = False,
backend: str | None = None,
anyllm_provider: str | None = None,
region: str | None = None,
@@ -99,6 +100,10 @@ def _start_proxy(
if learn:
cmd.append("--learn")
+ # Forward --code-graph flag to proxy subprocess (live file watcher)
+ if code_graph:
+ cmd.append("--code-graph")
+
# Forward backend configuration to proxy subprocess
_backend = backend or os.environ.get("HEADROOM_BACKEND")
if _backend:
@@ -508,6 +513,7 @@ def _ensure_proxy(
*,
learn: bool = False,
agent_type: str = "unknown",
+ code_graph: bool = False,
backend: str | None = None,
anyllm_provider: str | None = None,
region: str | None = None,
@@ -537,6 +543,7 @@ def _ensure_proxy(
port,
learn=learn,
agent_type=agent_type,
+ code_graph=code_graph,
backend=backend,
anyllm_provider=anyllm_provider,
region=region,
@@ -626,6 +633,7 @@ def _launch_tool(
no_proxy,
learn=learn,
agent_type=agent_type,
+ code_graph=code_graph,
backend=backend,
anyllm_provider=anyllm_provider,
region=region,
@@ -981,7 +989,9 @@ def claude(
click.echo(" ╚═══════════════════════════════════════════════╝")
click.echo()
- proxy_holder[0] = _ensure_proxy(port, no_proxy, learn=learn, agent_type="claude")
+ proxy_holder[0] = _ensure_proxy(
+ port, no_proxy, learn=learn, agent_type="claude", code_graph=code_graph
+ )
if not no_rtk:
click.echo(" Setting up rtk...")
diff --git a/headroom/graph/__init__.py b/headroom/graph/__init__.py
new file mode 100644
index 000000000..8a69d5f37
--- /dev/null
+++ b/headroom/graph/__init__.py
@@ -0,0 +1,5 @@
+"""Code graph intelligence for headroom.
+
+Provides live code graph reindexing via file watching, with
+codebase-memory-mcp as the graph backend.
+"""
diff --git a/headroom/graph/watcher.py b/headroom/graph/watcher.py
new file mode 100644
index 000000000..ae5ddaa75
--- /dev/null
+++ b/headroom/graph/watcher.py
@@ -0,0 +1,268 @@
+"""File watcher for live code graph reindexing.
+
+Monitors the project directory for source file changes and triggers
+incremental reindexing via codebase-memory-mcp. Runs as a background
+thread in the proxy process.
+
+Cross-platform: uses watchdog (FSEvents on macOS, inotify on Linux,
+ReadDirectoryChangesW on Windows).
+
+Usage:
+ watcher = CodeGraphWatcher(project_dir="/path/to/project")
+ watcher.start() # Non-blocking, runs in background thread
+ ...
+ watcher.stop() # Clean shutdown
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import shutil
+import subprocess
+import threading
+import time
+from pathlib import Path
+
+logger = logging.getLogger(__name__)
+
+# Source file extensions worth reindexing for
+_SOURCE_EXTENSIONS = frozenset(
+ {
+ ".py",
+ ".js",
+ ".jsx",
+ ".ts",
+ ".tsx",
+ ".go",
+ ".rs",
+ ".java",
+ ".c",
+ ".cpp",
+ ".cc",
+ ".h",
+ ".hpp",
+ ".cs",
+ ".kt",
+ ".scala",
+ ".rb",
+ ".php",
+ ".swift",
+ ".lua",
+ ".zig",
+ ".ex",
+ ".exs",
+ ".m",
+ ".mm",
+ ".jl",
+ ".r",
+ ".R",
+ ".sql",
+ # Config/docs that affect graph
+ ".md",
+ ".rst",
+ ".toml",
+ ".yaml",
+ ".yml",
+ ".json",
+ }
+)
+
+# Directories to ignore
+_IGNORE_DIRS = frozenset(
+ {
+ ".git",
+ ".hg",
+ ".svn",
+ "node_modules",
+ "__pycache__",
+ ".venv",
+ "venv",
+ ".tox",
+ ".mypy_cache",
+ ".pytest_cache",
+ ".ruff_cache",
+ "dist",
+ "build",
+ ".eggs",
+ "*.egg-info",
+ ".headroom",
+ "target", # Rust/Java
+ }
+)
+
+
+class CodeGraphWatcher:
+ """Watches project files and triggers incremental graph reindex.
+
+ Uses a debounce strategy: after a file change, waits for a quiet
+ period (no more changes) before triggering reindex. This handles
+ rapid multi-file edits efficiently.
+
+ Args:
+ project_dir: Root directory to watch.
+ debounce_seconds: Wait this long after last change before reindexing.
+ cbm_binary: Path to codebase-memory-mcp binary. Auto-detected if None.
+ """
+
+ def __init__(
+ self,
+ project_dir: str | Path,
+ debounce_seconds: float = 2.0,
+ cbm_binary: str | None = None,
+ ) -> None:
+ self.project_dir = str(project_dir)
+ self.debounce_seconds = debounce_seconds
+ self.cbm_binary = cbm_binary or shutil.which("codebase-memory-mcp")
+ self._observer: object | None = None
+ self._debounce_timer: threading.Timer | None = None
+ self._lock = threading.Lock()
+ self._running = False
+ self._reindex_count = 0
+ self._last_reindex: float = 0
+
+ def start(self) -> bool:
+ """Start watching in a background thread. Returns True if started."""
+ if not self.cbm_binary:
+ logger.debug("Code graph watcher: codebase-memory-mcp not found, not starting")
+ return False
+
+ try:
+ from watchdog.events import FileSystemEventHandler
+ from watchdog.observers import Observer
+ except ImportError:
+ logger.debug("Code graph watcher: watchdog not installed, not starting")
+ return False
+
+ class _Handler(FileSystemEventHandler):
+ def __init__(self, watcher: CodeGraphWatcher):
+ self._watcher = watcher
+
+ def on_any_event(self, event: object) -> None:
+ # watchdog event has src_path attribute
+ src_path = getattr(event, "src_path", "")
+ if not src_path:
+ return
+
+ path = Path(src_path)
+
+ # Skip ignored directories
+ for part in path.parts:
+ if part in _IGNORE_DIRS:
+ return
+
+ # Only react to source file changes
+ if path.suffix.lower() not in _SOURCE_EXTENSIONS:
+ return
+
+ # Skip temporary/swap files
+ if path.name.startswith(".") or path.name.endswith("~"):
+ return
+
+ self._watcher._schedule_reindex()
+
+ observer = Observer()
+ observer.schedule(_Handler(self), self.project_dir, recursive=True)
+ observer.daemon = True
+ observer.start()
+ self._observer = observer
+ self._running = True
+
+ logger.info(
+ "Code graph watcher: monitoring %s (debounce=%.1fs)",
+ self.project_dir,
+ self.debounce_seconds,
+ )
+ return True
+
+ def stop(self) -> None:
+ """Stop watching and clean up."""
+ self._running = False
+ with self._lock:
+ if self._debounce_timer:
+ self._debounce_timer.cancel()
+ self._debounce_timer = None
+
+ if self._observer:
+ observer = self._observer
+ self._observer = None
+ # watchdog Observer has stop() and join()
+ if hasattr(observer, "stop"):
+ observer.stop() # type: ignore[union-attr]
+ if hasattr(observer, "join"):
+ observer.join(timeout=3) # type: ignore[union-attr]
+
+ if self._reindex_count > 0:
+ logger.info("Code graph watcher: stopped after %d reindexes", self._reindex_count)
+
+ def _schedule_reindex(self) -> None:
+ """Schedule a debounced reindex. Resets timer on each call."""
+ with self._lock:
+ if self._debounce_timer:
+ self._debounce_timer.cancel()
+ self._debounce_timer = threading.Timer(self.debounce_seconds, self._do_reindex)
+ self._debounce_timer.daemon = True
+ self._debounce_timer.start()
+
+ def _do_reindex(self) -> None:
+ """Trigger incremental reindex via codebase-memory-mcp."""
+ if not self._running or not self.cbm_binary:
+ return
+
+ try:
+ start = time.monotonic()
+ result = subprocess.run(
+ [
+ self.cbm_binary,
+ "cli",
+ "index_repository",
+ json.dumps({"repo_path": self.project_dir, "mode": "fast"}),
+ ],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ )
+
+ elapsed = time.monotonic() - start
+ self._reindex_count += 1
+ self._last_reindex = time.time()
+
+ if result.returncode == 0:
+ # Check if incremental (look for "changed=N" in output)
+ changed = "?"
+ for line in result.stderr.splitlines():
+ if "changed=" in line:
+ import re
+
+ m = re.search(r"changed=(\d+)", line)
+ if m:
+ changed = m.group(1)
+ break
+
+ logger.info(
+ "Code graph: reindexed (%s files changed, %.1fs)",
+ changed,
+ elapsed,
+ )
+ else:
+ logger.debug(
+ "Code graph: reindex failed (exit=%d, %.1fs)",
+ result.returncode,
+ elapsed,
+ )
+
+ except subprocess.TimeoutExpired:
+ logger.warning("Code graph: reindex timed out after 30s")
+ except Exception as e:
+ logger.debug("Code graph: reindex error: %s", e)
+
+ @property
+ def stats(self) -> dict:
+ """Return watcher statistics."""
+ return {
+ "running": self._running,
+ "project_dir": self.project_dir,
+ "reindex_count": self._reindex_count,
+ "last_reindex": self._last_reindex,
+ "debounce_seconds": self.debounce_seconds,
+ }
diff --git a/headroom/proxy/models.py b/headroom/proxy/models.py
index cb9f37834..cdfb5b6e9 100644
--- a/headroom/proxy/models.py
+++ b/headroom/proxy/models.py
@@ -113,6 +113,9 @@ class ProxyConfig:
# Code-aware compression (disabled by default — use code graph tools instead)
code_aware_enabled: bool = False
+ # Code graph live watcher (triggers incremental reindex on file changes)
+ code_graph_watcher: bool = False
+
# Per-tool compression profiles
tool_profiles: dict[str, Any] | None = None
diff --git a/headroom/proxy/server.py b/headroom/proxy/server.py
index 0a7452332..269602d35 100644
--- a/headroom/proxy/server.py
+++ b/headroom/proxy/server.py
@@ -511,6 +511,17 @@ class HeadroomProxy(
agent_type=config.traffic_learning_agent_type,
)
+ # Code graph file watcher (live reindex on file changes)
+ self.code_graph_watcher: CodeGraphWatcher | None = None # type: ignore[annotation-unchecked]
+ if config.code_graph_watcher:
+ from headroom.graph.watcher import CodeGraphWatcher
+
+ self.code_graph_watcher = CodeGraphWatcher(project_dir=Path.cwd())
+ if self.code_graph_watcher.start():
+ logger.info("Code graph: file watcher started")
+ else:
+ self.code_graph_watcher = None
+
def _get_compression_cache(self, session_id: str) -> CompressionCache:
"""Get or create a CompressionCache for a session."""
if session_id not in self._compression_caches:
@@ -1006,6 +1017,8 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
await proxy.usage_reporter.stop()
if proxy.traffic_learner:
await proxy.traffic_learner.stop()
+ if proxy.code_graph_watcher:
+ proxy.code_graph_watcher.stop()
await proxy.shutdown()
shutdown_headroom_tracing()
shutdown_otel_metrics()