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.

fix(learn): decode sanitized pattern-id markers and keep visible-text dedup keys (#3956)

Zhibo Zhang (Amur)ec1ba70c974f
diff --git a/headroom/learn/writer.py b/headroom/learn/writer.py
index cc77a0704..19ce1f152 100644
--- a/headroom/learn/writer.py
+++ b/headroom/learn/writer.py
@@ -6,6 +6,7 @@ injection mechanism for each agent system (CLAUDE.md, .cursorrules, etc.).
from __future__ import annotations
+import html
import re
import subprocess
from abc import ABC, abstractmethod
@@ -124,6 +125,18 @@ _PATTERN_ID_PATTERN = re.compile(
)
+def _tagged_pattern_id(line: str) -> str | None:
+ """Return the id inside a bullet's pattern-id comment, if any.
+
+ ``_build_section`` sanitizes block content, so on disk the comment reads
+ ``<!-- ... -->``; match against the decoded line so carried-forward
+ sections are still recognized as lifecycle-tracked. Callers keep the
+ original (still-sanitized) line when the bullet survives.
+ """
+ match = _PATTERN_ID_PATTERN.search(html.unescape(line))
+ return match.group(1) if match else None
+
+
def _merge_markdown_items(
new_content: str,
prior_content: str,
@@ -152,8 +165,7 @@ def _merge_markdown_items(
return None
items: list[tuple[str | None, str, str]] = []
for line in lines:
- id_match = _PATTERN_ID_PATTERN.search(line)
- pattern_id = id_match.group(1) if id_match else None
+ pattern_id = _tagged_pattern_id(line)
visible = _PATTERN_ID_PATTERN.sub("", line).strip().casefold()
items.append((pattern_id, visible, line))
return items
@@ -227,12 +239,12 @@ def _prune_carried_section(
kept: list[str] = []
saw_tracked_item = False
for line in lines:
- id_match = _PATTERN_ID_PATTERN.search(line)
- if id_match is None:
+ pattern_id = _tagged_pattern_id(line)
+ if pattern_id is None:
kept.append(line)
continue
saw_tracked_item = True
- if id_match.group(1) in active_item_ids:
+ if pattern_id in active_item_ids:
kept.append(line)
if not saw_tracked_item:
return None
diff --git a/tests/test_learn/test_section_lifecycle.py b/tests/test_learn/test_section_lifecycle.py
index 4836aaa45..398a174ae 100644
--- a/tests/test_learn/test_section_lifecycle.py
+++ b/tests/test_learn/test_section_lifecycle.py
@@ -15,7 +15,7 @@ because it asserts on writer behaviour; it drives the real, unmodified
import pytest
from headroom.learn.models import Recommendation, RecommendationTarget
-from headroom.learn.writer import _merge_into_file
+from headroom.learn.writer import _merge_into_file, _merge_markdown_items, _prune_carried_section
from headroom.memory.traffic_learner import (
ExtractedPattern,
PatternCategory,
@@ -262,3 +262,37 @@ class TestTrafficLearnerCategoryLifecycle:
assert "User prefers terse output" in final
assert "### Learned: architecture" not in final
assert "Handlers live under headroom/proxy/handlers" not in final
+
+
+class TestSanitizedPatternIdHandling:
+ """The persisted form of a pattern-id comment is HTML-sanitized."""
+
+ def test_prune_decodes_sanitized_pattern_ids(self):
+ """A carried bullet whose id comment is sanitized still expires.
+
+ On disk the comment reads ``<!-- ... -->``; the prune path must
+ treat it as a tracked item, not as untagged content to keep forever.
+ """
+ sanitized = (
+ "- Handlers live under headroom/proxy/handlers"
+ " <!-- headroom:pattern-id:abc123 -->"
+ )
+
+ assert _prune_carried_section(sanitized, frozenset()) == ""
+ assert _prune_carried_section(sanitized, frozenset({"abc123"})) == sanitized
+
+ def test_merge_keeps_entity_and_literal_ampersand_bullets_distinct(self):
+ """Two live bullets differing only in ``&`` vs ``&`` both survive.
+
+ The visible-text dedup key must stay on the bullet text as written:
+ decoding it before comparing would collapse suggestions that render
+ the same but are literally different advice.
+ """
+ new_content = "- Prefer `a &amp; b` in configs <!-- headroom:pattern-id:hash2 -->"
+ prior_content = "- Prefer `a & b` in configs <!-- headroom:pattern-id:hash1 -->"
+
+ merged = _merge_markdown_items(new_content, prior_content, frozenset({"hash1", "hash2"}))
+
+ assert merged is not None
+ assert "`a &amp; b`" in merged
+ assert "`a & b`" in merged