fix(learn): locate the managed block by whole-line markers, one span for every reader

The previous commit picked the last start marker that had an end marker
after it. Review showed that only moved the problem: prose AFTER the
block that quotes both markers was selected instead of the block, and
_parse_prior_recommendations still read from the first start marker, so
headings in prose that quotes the start marker above the block were
carried into the rebuilt block as generated sections.

Add _find_managed_block(): the block is a line that is exactly the start
marker through the next line that is exactly the end marker (the shape
_build_section writes). A marker quoted inside prose or indented is not
a boundary, and a start marker with no end marker before the next start
marker is skipped. extract_marker_block, _parse_prior_recommendations,
_merge_into_file, _strip_marker_block and the legacy-migration presence
checks all use this one span, so the block that is parsed is the block
that is replaced. _MARKER_PATTERN is no longer needed here.

Two more tests pin the reviewer's layouts (both markers quoted after the
block; a heading inside prose quoting the start marker); both fail on
the previous commit.

Refs #4339

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
HetCreep
2026-10-22 03:20:51 +07:00
co-authored by Claude Opus 5.5
parent 2c6853ea52
commit eba6458b43
2 changed files with 88 additions and 18 deletions
+41 -18
View File
@@ -16,7 +16,7 @@ from pathlib import Path
from headroom._subprocess import run
from ..managed_block import block_pattern, sanitize_block_text
from ..managed_block import sanitize_block_text
from ._shared import claude_config_dir
from .models import (
ProjectInfo,
@@ -29,7 +29,30 @@ from .models import (
# cannot close the block early (see headroom.managed_block).
_MARKER_START = "<!-- headroom:learn:start -->"
_MARKER_END = "<!-- headroom:learn:end -->"
_MARKER_PATTERN = block_pattern(_MARKER_START, _MARKER_END)
def _find_managed_block(text: str) -> tuple[int, int] | None:
"""Return the ``(start, end)`` offsets of the managed block, or None.
The block is a line that is exactly the start marker through the next line
that is exactly the end marker -- the shape ``_build_section`` writes. A
marker quoted inside prose (sharing its line with other text, or indented)
is not a block boundary, and a start marker with no end marker before the
next start marker is not a block. Every reader and writer of the block in
this module uses this one span, so the block that is parsed is the block
that is replaced (#4339). ``end`` stops after the end marker, before its
line break.
"""
offset = 0
start: int | None = None
for line in text.splitlines(keepends=True):
bare = line.rstrip()
if bare == _MARKER_START:
start = offset
elif bare == _MARKER_END and start is not None:
return start, offset + len(bare)
offset += len(line)
return None
def _read_text_tolerant(file_path: Path) -> str:
@@ -258,8 +281,8 @@ def extract_marker_block(file_content: str) -> str | None:
(including the start/end markers) so it can be fed back to an LLM as
context without losing formatting. Returns None if no block is present.
"""
match = _MARKER_PATTERN.search(file_content)
return match.group(0) if match else None
span = _find_managed_block(file_content)
return file_content[span[0] : span[1]] if span else None
def _parse_prior_recommendations(existing: str) -> list[Recommendation]:
@@ -270,10 +293,10 @@ def _parse_prior_recommendations(existing: str) -> list[Recommendation]:
_build_section — target is set to a placeholder since the marker block
itself doesn't record it (blocks are always per-file and per-target).
"""
match = _MARKER_PATTERN.search(existing)
if not match:
span = _find_managed_block(existing)
if not span:
return []
inner = match.group(0)[len(_MARKER_START) : -len(_MARKER_END)]
inner = existing[span[0] + len(_MARKER_START) : span[1] - len(_MARKER_END)]
recs: list[Recommendation] = []
for part in re.split(r"\n### ", "\n" + inner)[1:]:
@@ -364,14 +387,12 @@ def _merge_into_file(file_path: Path, new_recommendations: list[Recommendation])
section = _build_section(merged)
if file_path.exists():
existing = _read_text_tolerant(file_path)
# The block is the LAST start marker that still has an end marker after
# it: prose above the block may quote the start marker, and a start
# marker with no end marker is not a block to rewrite (#4339).
last_end = existing.rfind(_MARKER_END)
start = existing.rfind(_MARKER_START, 0, last_end) if last_end >= 0 else -1
if start >= 0:
end = existing.index(_MARKER_END, start) + len(_MARKER_END)
return existing[:start] + section + existing[end:]
# Replace only the managed block itself; marker strings quoted in
# prose on either side are hand-written text. No block (including a
# start marker without its end marker) -> append a fresh one (#4339).
span = _find_managed_block(existing)
if span:
return existing[: span[0]] + section + existing[span[1] :]
return existing.rstrip() + "\n\n" + section + "\n"
return section + "\n"
@@ -382,7 +403,9 @@ def _strip_marker_block(content: str) -> str:
Used when migrating a stale block out of the team-shared CLAUDE.md into the
personal CLAUDE.local.md. Returns "" if nothing but the block remained.
"""
cleaned = _MARKER_PATTERN.sub("", content)
cleaned = content
while span := _find_managed_block(cleaned):
cleaned = cleaned[: span[0]] + cleaned[span[1] :]
cleaned = re.sub(r"\n{3,}", "\n\n", cleaned).strip()
return cleaned + "\n" if cleaned else ""
@@ -568,11 +591,11 @@ class ClaudeCodeWriter(ContextWriter):
if target_path == legacy_path or not legacy_path.exists():
return []
legacy_text = _read_text_tolerant(legacy_path)
if _MARKER_START not in legacy_text:
if _find_managed_block(legacy_text) is None:
return []
# If the target already owns a block, it is the source of truth -- don't
# double-migrate or clobber accumulated learnings.
if target_path.exists() and _MARKER_START in _read_text_tolerant(target_path):
if target_path.exists() and _find_managed_block(_read_text_tolerant(target_path)):
return []
migrated = _parse_prior_recommendations(legacy_text)
+47
View File
@@ -335,6 +335,53 @@ class TestClaudeCodeWriter:
assert "- Use uv" in final
assert "- Hand-written rule: never force-push" in final
def test_merge_keeps_prose_quoting_both_markers_after_the_block(self, tmp_path):
"""Marker quotes in prose below the block are hand-written text, not a second block."""
context_file = tmp_path / "CLAUDE.local.md"
context_file.write_text(
f"{_MARKER_START}\n"
"## Headroom Learned Patterns\n\n"
"### Environment\n"
"- old bullet\n\n"
f"{_MARKER_END}\n\n"
f"Example: {_MARKER_START}\n"
"- Hand-written rule: never force-push\n"
f"{_MARKER_END}\n"
)
recommendation = _rec(RecommendationTarget.CONTEXT_FILE, "Tooling", "- Use uv")
final = _merge_into_file(context_file, [recommendation])
assert "- Hand-written rule: never force-push" in final
assert final.startswith(f"{_MARKER_START}\n## Headroom Learned Patterns")
block = final[: final.index(_MARKER_END)]
assert "- Use uv" in block
assert "- old bullet" in block
assert final.count(f"Example: {_MARKER_START}") == 1
def test_prior_sections_come_from_the_block_not_from_quoting_prose(self, tmp_path):
"""Headings in prose that quotes the start marker must not become generated sections."""
context_file = tmp_path / "CLAUDE.local.md"
context_file.write_text(
f"Example: {_MARKER_START}\n"
"### Manual policy\n"
"- Hand-written rule: never force-push\n\n"
f"{_MARKER_START}\n"
"## Headroom Learned Patterns\n\n"
"### Environment\n"
"- old bullet\n\n"
f"{_MARKER_END}\n"
)
recommendation = _rec(RecommendationTarget.CONTEXT_FILE, "Tooling", "- Use uv")
final = _merge_into_file(context_file, [recommendation])
assert final.count("### Manual policy") == 1
block = final[final.index(f"\n{_MARKER_START}\n") :]
assert "### Manual policy" not in block
assert "### Environment" in block
assert "- Use uv" in block
def test_memory_md_carry_forward(self, tmp_path):
"""Carry-forward also works for MEMORY.md."""
proj = _project(tmp_path)