Files
headroom/tests/test_learn
45dacc1f94 fix(learn): anchor the managed block on its last start marker, append when no end marker (#4342)
## Description

`_merge_into_file` (`headroom/learn/writer.py`) located the managed
block with `block_pattern` (first occurrence of the start marker to the
nearest end marker) whenever `_MARKER_START in existing`. Two
consequences, both reported in #4339:

1. Hand-written prose that quotes the start-marker string became the
start of the match, so `--apply` replaced everything from that mention
through the real block's end marker, deleting the hand-written text in
between.
2. A file holding the start marker but no end marker matched nothing:
`sub()` returned the file unchanged and every recommendation of the run
was silently dropped while the CLI still printed `[WROTE]`.

The block is now identified by the shape `_build_section` writes: a line
that is **exactly** the start marker through the next line that is
**exactly** the end marker. A marker quoted inside prose (sharing its
line with other text, or indented) or inside a fenced code block (a
Markdown example) is not a boundary, and a start marker with no end
marker before the next start marker is skipped. One helper,
`_find_managed_block()`, is used by every reader and writer of the block
in this module, so the block that is parsed is the block that is
replaced.

The first commit (2c6853ea) used "the last start marker that has an end
marker after it"; review showed that only moved the problem to prose
after the block, and left `_parse_prior_recommendations` reading a
different span. The second commit (eba6458b) replaces it with the
line-based rule above, and the third (40880d1e, after review) skips
marker lines inside fenced code blocks.

Closes #4339

## Type of Change

- [x] 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
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/learn/writer.py`: new `_find_managed_block(text) -> (start,
end) | None` (linear scan of lines; whole-line markers only; marker
lines inside ``` / ~~~ fences ignored, CommonMark-style open/close
rules; first complete block). `extract_marker_block`,
`_parse_prior_recommendations`, `_merge_into_file`,
`_strip_marker_block` and the two legacy-migration presence checks in
`_migrate_legacy_block` use it. With no block (including a dangling
start marker), `_merge_into_file` appends a fresh section as for a file
with no markers. `_MARKER_PATTERN` and the `block_pattern` import are
removed from this module; `managed_block.block_pattern` and
`sanitize_block_text` are unchanged.
- `tests/test_learn/test_writer.py` (`TestClaudeCodeWriter`), four
tests:
- `test_merge_keeps_prose_that_quotes_the_start_marker_above_the_block`
and `test_merge_appends_a_block_when_the_end_marker_is_missing` (the two
cases in #4339; both fail on `main`);
- `test_merge_keeps_prose_quoting_both_markers_after_the_block` and
`test_prior_sections_come_from_the_block_not_from_quoting_prose` (the
two layouts from the first review; both fail on the first commit);
- `test_merge_leaves_a_fenced_example_of_the_block_untouched` (the
fenced-example layout from the second review; fails on
eba6458b/35cf4a98) and
`test_fenced_code_inside_the_block_does_not_hide_its_end_marker` (a
closed code fence in a recommendation body).

Behaviour notes: a file holding two complete blocks used to have both
replaced by `sub()`; the merge now rewrites the first one and leaves the
second as text, and `_strip_marker_block` (legacy migration) still
removes every complete block. An unclosed code fence inside the managed
block would hide its end marker (the merge then appends a fresh block);
recommendation bodies with balanced fences are covered by a test.

## Testing

- [x] Unit tests pass (`pytest`) — `tests/test_learn/`,
`tests/test_managed_block_injection.py`,
`tests/test_memory/test_traffic_learner.py`: 617 passed, 10 skipped (on
40880d1e)
- [x] Linting passes (`ruff check .`) — on the two changed files, plus
`ruff format --check`
- [x] Type checking passes (`mypy headroom`) — run on
`headroom/learn/writer.py`; the single reported error is in
`headroom/providers/model_metadata.py:79` and is identical on `main`
- [x] New tests added for new functionality
- [ ] Manual testing performed

### Test Output

```text
# the four tests against the FIRST commit 2c6853ea (fail-before for the two review layouts)
$ pytest tests/test_learn/test_writer.py -q -k "quotes_the_start_marker or end_marker_is_missing or both_markers_after or quoting_prose" --tb=line
tests/test_learn/test_writer.py:379: AssertionError: assert 2 == 1          # "### Manual policy" copied into the block
FAILED tests/test_learn/test_writer.py::TestClaudeCodeWriter::test_merge_keeps_prose_quoting_both_markers_after_the_block
FAILED tests/test_learn/test_writer.py::TestClaudeCodeWriter::test_prior_sections_come_from_the_block_not_from_quoting_prose
2 failed, 2 passed, 44 deselected in 1.82s

# with eba6458b (pass-after)
4 passed, 44 deselected in 0.99s

# fenced-example case (second review) on 35cf4a98, then on 40880d1e
FAILED tests/test_learn/test_writer.py::TestClaudeCodeWriter::test_merge_leaves_a_fenced_example_of_the_block_untouched
1 failed, 1 passed, 48 deselected
2 passed, 48 deselected in 1.14s

# the #4339 cases against main 4c7acba5 (from the first round)
2 failed (hand-written rule line deleted; file returned unchanged)

$ pytest tests/test_learn tests/test_managed_block_injection.py tests/test_memory/test_traffic_learner.py -q
617 passed, 10 skipped, 1 warning in 10.90s

$ ruff check headroom/learn/writer.py tests/test_learn/test_writer.py && ruff format --check headroom/learn/writer.py tests/test_learn/test_writer.py
All checks passed!
2 files already formatted
```

## Real Behavior Proof

- Environment: WSL2 Ubuntu, Python 3.12.15, pytest 9.1.1, ruff 0.17.1,
mypy 2.4.0; a clone of this fork with the core runtime dependencies only
- Exact command / steps: on the PR branch at the first commit, apply
only the two new tests and run the four `-k` tests above (the two review
layouts fail, the two #4339 cases pass); apply the source change and run
them again (all pass); then the learn, managed-block and traffic-learner
suites, ruff and mypy as pasted
- Observed result: prose that quotes the start marker above the block,
prose that quotes both markers below it, and headings inside such prose
all stay hand-written text: the managed block is the one rebuilt, its
prior sections are read from that same block, and a dangling start
marker gets a fresh section appended instead of losing the run's
recommendations
- Not tested: `headroom learn --apply` end to end through the CLI (only
`_merge_into_file`, the parser and the writer tests); the memory
writers, which share `block_pattern` but are not changed here

## Runtime Rollout Safety

- Rollout-managed feature(s): none (`headroom learn` is not behind a
rollout flag)
- Minimum rollout channel: n/a (not rollout-managed)
- Stable/default behavior changed: only for files with marker strings
quoted in prose, a dangling start marker, or two complete blocks (see
Behaviour notes); a file the writer produced merges exactly as before
- Kill switch / disable path: none added; `headroom learn` without
`--apply` never writes
- Unsafe override required: no
- Qualification impact: none known; no `CHANGELOG.md` edit
(release-please)
- Rollback path: revert the two commits

## 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
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation (none
needed)
- [x] My changes generate no new warnings
- [x] 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)

## Additional Notes

Produced with AI assistance (Claude Code) operated by me (HetCreep); the
test runs above were executed on my machine on a clone of this fork.
Related: #3850 (introduced `managed_block.py` and the nearest-end-marker
rule).

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

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-10-24 08:45:10 -07:00
..