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.

refactor(memory,learn,cache): remove unreferenced classes, methods and constants (#4112)

Tejas Chopraabbf36f052fc
diff --git a/headroom/cache/compression_feedback.py b/headroom/cache/compression_feedback.py
index dbb8d5bd8..9032d3886 100644
--- a/headroom/cache/compression_feedback.py
+++ b/headroom/cache/compression_feedback.py
@@ -344,13 +344,6 @@ class CompressionFeedback:
# Extract potential field names from query
self._extract_field_hints(pattern, event.query)
- def _truncate_strategy_dicts(self, pattern: LocalToolPattern) -> None:
- """Truncate strategy counters using the shared strategy outcome domain."""
- outcomes = pattern.strategy_outcomes
- outcomes.prune()
- pattern.strategy_compressions = outcomes.compressions
- pattern.strategy_retrievals = outcomes.retrievals
-
def _extract_field_hints(self, pattern: LocalToolPattern, query: str) -> None:
"""Extract potential field names from search queries.
diff --git a/headroom/learn/analyzer.py b/headroom/learn/analyzer.py
index 9ce974579..dd8fe0939 100644
--- a/headroom/learn/analyzer.py
+++ b/headroom/learn/analyzer.py
@@ -1162,18 +1162,3 @@ def _safe_int(val: object) -> int:
except (ValueError, TypeError):
return 0
return 0
-
-
-# =============================================================================
-# Legacy compatibility alias
-# =============================================================================
-
-
-class FailureAnalyzer:
- """Legacy alias for SessionAnalyzer — used by existing CLI code."""
-
- def __init__(self) -> None:
- self._analyzer = SessionAnalyzer()
-
- def analyze(self, project: ProjectInfo, sessions: list[SessionData]) -> AnalysisResult:
- return self._analyzer.analyze(project, sessions)
diff --git a/headroom/memory/core.py b/headroom/memory/core.py
index 776d5152c..0b7131b54 100644
--- a/headroom/memory/core.py
+++ b/headroom/memory/core.py
@@ -894,15 +894,6 @@ class HierarchicalMemory:
f"Bubbled memory {memory.id} from {current_scope.value} to {target_scope.value}"
)
- def _scope_level_value(self, level: ScopeLevel) -> int:
- """Get numeric value for scope level (lower = broader scope)."""
- return {
- ScopeLevel.USER: 0,
- ScopeLevel.SESSION: 1,
- ScopeLevel.AGENT: 2,
- ScopeLevel.TURN: 3,
- }[level]
-
# =========================================================================
# Properties
# =========================================================================
diff --git a/headroom/memory/inline_extractor.py b/headroom/memory/inline_extractor.py
index d04b9ae63..aef53a466 100644
--- a/headroom/memory/inline_extractor.py
+++ b/headroom/memory/inline_extractor.py
@@ -173,95 +173,3 @@ def parse_response_with_memory(response_text: str | None) -> ParsedResponse:
memories=memories,
raw=response_text,
)
-
-
-class InlineMemoryWrapper:
- """Wrapper that extracts memories from LLM responses inline.
-
- This is the zero-latency approach - memories are extracted
- as part of the response, not in a separate call.
-
- Usage:
- wrapper = InlineMemoryWrapper(openai_client)
- response, memories = wrapper.chat(
- messages=[{"role": "user", "content": "I prefer Python"}],
- model="gpt-4o-mini"
- )
- # response = "Great choice! Python is excellent..."
- # memories = [{"content": "User prefers Python"}]
- """
-
- def __init__(self, client: Any):
- """Initialize wrapper.
-
- Args:
- client: OpenAI-compatible client
- """
- self.client = client
-
- def chat(
- self,
- messages: list[dict[str, Any]],
- model: str = "gpt-4o-mini",
- short_instruction: bool = True,
- **kwargs: Any,
- ) -> tuple[str | None, list[dict[str, Any]]]:
- """Send chat request and extract memories inline.
-
- Args:
- messages: Chat messages
- model: Model to use
- short_instruction: Use shorter memory instruction
- **kwargs: Additional args for chat completion
-
- Returns:
- Tuple of (response_content, extracted_memories)
- """
- # Inject memory instruction
- modified_messages = inject_memory_instruction(messages, short=short_instruction)
-
- # Call LLM
- response = self.client.chat.completions.create(
- model=model,
- messages=modified_messages,
- **kwargs,
- )
-
- raw_content = response.choices[0].message.content
-
- # Parse response and extract memories
- parsed = parse_response_with_memory(raw_content)
-
- return parsed.content, parsed.memories
-
- def chat_with_response(
- self,
- messages: list[dict[str, Any]],
- model: str = "gpt-4o-mini",
- **kwargs: Any,
- ) -> tuple[Any, str | None, list[dict[str, Any]]]:
- """Send chat request and return full response object.
-
- Args:
- messages: Chat messages
- model: Model to use
- **kwargs: Additional args for chat completion
-
- Returns:
- Tuple of (response_object, content, memories)
- """
- modified_messages = inject_memory_instruction(messages)
-
- response = self.client.chat.completions.create(
- model=model,
- messages=modified_messages,
- **kwargs,
- )
-
- raw_content = response.choices[0].message.content
- parsed = parse_response_with_memory(raw_content)
-
- # Modify response to have clean content
- response.choices[0].message.content = parsed.content
-
- return response, parsed.content, parsed.memories
diff --git a/headroom/memory/traffic_learner.py b/headroom/memory/traffic_learner.py
index 468071369..2939b06a9 100644
--- a/headroom/memory/traffic_learner.py
+++ b/headroom/memory/traffic_learner.py
@@ -125,17 +125,6 @@ class PatternCategory(str, Enum):
ARCHITECTURE = "architecture" # File structure, dependencies, conventions
-class AgentType(str, Enum):
- """Supported coding agent types."""
-
- CLAUDE = "claude"
- CURSOR = "cursor"
- CODEX = "codex"
- AIDER = "aider"
- GEMINI = "gemini"
- UNKNOWN = "unknown"
-
-
# =============================================================================
# Extracted Pattern Model
# =============================================================================
@@ -258,11 +247,6 @@ def _is_error(content: str) -> bool:
# Tool Call Extractors
# =============================================================================
-# Extract command from Bash tool calls
-_COMMAND_RE = re.compile(r"^(?:source\s+\S+\s*&&\s*)?(.+)", re.I)
-
-# Extract file paths
-_FILE_PATH_RE = re.compile(r"(?:/[\w./-]+(?:\.\w+)?)")
# Extract package/module names from errors
_MODULE_RE = re.compile(r"No module named ['\"]?(\w[\w.]*)['\"]?")
@@ -758,14 +742,6 @@ class TrafficLearner:
return list(by_hash.values())
- def get_learned_patterns(self) -> list[ExtractedPattern]:
- """Return patterns from the in-memory accumulator.
-
- Retained for backwards compatibility. Reads only the accumulator;
- does not consult persisted rows. Use flush_to_file() for full data.
- """
- return [pattern for pattern, count in self._pattern_counts.values() if count >= 1]
-
async def on_tool_result(
self,
tool_name: str,
diff --git a/tests/test_learn/test_analyzer.py b/tests/test_learn/test_analyzer.py
index abd6b0e1c..d4a6d6498 100644
--- a/tests/test_learn/test_analyzer.py
+++ b/tests/test_learn/test_analyzer.py
@@ -21,7 +21,6 @@ from headroom.learn.analyzer import (
_strip_fenced_json,
)
from headroom.learn.models import (
- AnalysisResult,
ErrorCategory,
ProjectInfo,
RecommendationTarget,
@@ -1445,20 +1444,3 @@ class TestCallLlmRouting:
mock_cli.return_value = {}
_call_llm("digest", "codex-cli")
mock_cli.assert_called_once_with("digest", "codex-cli", on_progress=None)
-
-
-# =============================================================================
-# Legacy Compatibility
-# =============================================================================
-
-
-class TestFailureAnalyzerCompat:
- @patch("headroom.learn.analyzer._call_llm")
- def test_legacy_alias_works(self, mock_call_llm: MagicMock):
- from headroom.learn.analyzer import FailureAnalyzer
-
- mock_call_llm.return_value = {"context_file_rules": [], "memory_file_rules": []}
-
- analyzer = FailureAnalyzer()
- result = analyzer.analyze(_project(), [])
- assert isinstance(result, AnalysisResult)