[bug] Chapter detection counts prose cross-references and diff lines as chapters

Author: wgm66Created Sep 20, 2026Updated Sep 22, 2026
Labelsbug

Problem

detect_structure()'s docstring states it counts "explicit "Chapter N"/"Capítulo N" headings, rejecting prose cross-references and numbered list items" (utils.py:670), and PR #161's body repeats the claim — "Prose cross-references like Chapter 6 explores... are still rejected." That rejection is incomplete in two ways, both reachable without any exotic input.

1. A wrapped sentence that ends in Chapter N. is counted

When the extractor wraps prose, a cross-reference can start a line. _HEADING_TAIL (utils.py:117) accepts a punctuation tail that is immediately followed by end-of-line:

python
_HEADING_TAIL = re.compile(r"^\s*$|^\s*[.:\-—–]|^\s+(?![a-z])")

so Chapter 6. — a sentence ending — reads as a heading. Minimal cases, each a single short string:

input line _chapter_number() counted as a chapter?
# Chapter 6 6 yes (correct)
Chapter 6 6 yes (correct)
# Chapter 6: Enums 6 yes (correct)
Chapter 6. (prose wraps here) 6 yes — wrong
Chapter 13. Closures and iterators create types that only the 13 yes — wrong
Chapter 4. References are indicated by the & symbol and borrow the 4 yes — wrong

The second and third are ordinary wrapped sentences: ...we cover in\nChapter 13. Closures and iterators.... The capitalized word after the period defeats the lowercase guard at utils.py:117, and the lowercase guard was the only prose test.

2. A unified-diff line is counted

The plain matcher (utils.py:579) accepts "number + 2 or more spaces + non-space":

python
plain = re.match(r"^([1-9]\d{0,2})\s{2,}\S", s)

A diff hunk line satisfies it exactly:

1  + use crate::trpl::StreamExt;      ->  _chapter_number(...) == 1

Unlike _structural_chapter_count(), which skips fenced lines via _closed_fence_line_numbers() (utils.py:460), the numeric scan iterates every line (utils.py:676-682) with no fence awareness — so a code sample containing a diff is scanned as prose.

Real-book measurement

The Rust Book (rust-lang/book, MIT OR Apache-2.0 — real Markdown source, not a fixture). To be precise about the input: the extractor was given the repository's src/*.md as a multi-file corpus, so it saw 112 sources. Counting only that repository's top-level ch*-00-*.md chapter files gives 22 real chapters; the number the extractor reported is compared against that:

reported chapters_detected : 8      (chapters_method = numeric)
distinct numbers matched   : 8
REAL top-level chapters    : 22

every one of the 13 lines the numeric scan matched, classified:
  ATX Markdown headings : 0
  prose / code lines    : 13

The sample the extractor reported is entirely prose — 'Chapter 6.', 'Chapter 13. Closures and iterators create types that only the compiler knows or', 'Chapter 4. References are indicated by the & symbol and borrow the value they', '1 + use crate::trpl::StreamExt;', 'Chapter 17.) We have seen a solution to this problem a few times now: We can' — so the number is not just wrong, it is unverifiable at a glance, and because numeric_count >= 2 the correct structural count is never consulted (utils.py:693).

(The 8-vs-22 gap is not claimed to be solely this defect — a 112-source corpus also hits the depth-selection problem in #236. What this issue establishes is narrower and unambiguous: every one of the 13 lines that produced the numeric count is a prose or code line, not a heading.)

Proposed change

Two independent loosenesses, two independent fixes; neither needs a new dependency.

  1. Tighten _HEADING_TAIL. A tail introduced by sentence punctuation must introduce a word, and the tail should be capped to a heading-sized word count — which keeps Chapter 6: Enums and Unit 1 — How to Write an Introduction while rejecting Chapter 6. and Chapter 4. References are indicated by the & symbol....
  2. Make the numeric scan fence-aware, mirroring _structural_chapter_count(): skip lines inside closed fences in detect_structure()'s loop.

Note the third case (a bare diff line not inside a fence) is fixed by neither of the above and needs the plain matcher narrowed — I would rather flag it than pretend the two changes are complete.

I have changed no code on the branch — this is a report. I prototyped (1) and (2) on a copy of upstream/master only to produce the measurements below.

How would we know it's better?

Prototype applied to a copy of upstream/master (526f362), measured on Linux (py3.9.5):

probe before after prototype expected
Chapter 6. (wrapped prose) counted not counted not counted
Chapter 13. Closures and iterators … counted not counted not counted
Chapter 4. References are indicated by … counted not counted not counted
fake diff line, bare (no fence) counted still counted not counted — not fixed by this prototype
# Chapter 6 / Chapter 6 / # Chapter 6: Enums counted counted counted (unchanged)

On the real Rust Book corpus, the numeric path stops winning entirely: chapters_method moves from numeric (8) to structural, and the reported count moves from 8 → 26. (26 is still not the 22 real chapters — that residual gap is the depth-selection problem in #236, reached because the corpus has 112 sources each contributing an H1. The two defects are separable and I have kept them separate.)

  • No regression: pytest tests/ -q is 679 passed, 1 skipped both before and after the prototype (pytest-only venv = CI parity). ruff check . clean.
  • Tests to add: the three prose strings above as "not a chapter", the three real heading forms as "is a chapter" (so the fix cannot be tightened into false negatives), and a diff line inside a fence. tests/test_book_to_skill.py already has test_stray_roman_numeral_does_not_suppress_structural_count and the Roman cross-reference tests at tests/test_book_to_skill.py:937; those are the closest homes.

The prototype, so the numbers above are reproducible

Applied to book_to_skill/utils.py at 526f362 (git cat-file blob 441934ee92c7e1ad9d5c4a73523b24888229fbc8, sha256 2eb30781f74a74838aaf166d6a78ecb11ffbcb1889c22a8d02b5170fda586d2c). 3 hunks:

diff
--- a/book_to_skill/utils.py
+++ b/book_to_skill/utils.py
@@ -114,7 +114,15 @@
 # Capitalized title word. A lowercase continuation (“Chapter 6 explores...”,
 # “Chapter 8 are relevant...”) is prose / a cross-reference, not a heading.
 # The uppercase class is À-Þ so titles starting with Ü/Û (common in German, e.g. “Überblick”) are recognized.
-_HEADING_TAIL = re.compile(r"^\s*$|^\s*[.:\-—–]|^\s+(?![a-z])")
+# A heading tail after punctuation must actually introduce a word: a bare
+# "Chapter 6." is a sentence ending, not a heading. The word cap rejects a
+# prose tail that happens to start with a capital ("Chapter 4. References are
+# indicated by ...") while leaving real headings ("Chapter 6: Enums",
+# "Unit 1 - How to Write an Introduction") intact.
+_MAX_HEADING_TAIL_WORDS = 8
+_HEADING_TAIL = re.compile(
+    r"^\s*$|^\s*[.:\-\u2014\u2013]\s*\S|^\s+(?![a-z])"
+)
 
 # Roman-numeral chapter heading: "I: Loomings", "II. The Carpet-Bag".
 # Uppercase alone at line start is safe — no common English word is a valid
@@ -581,7 +589,11 @@
         return int(plain.group(1))
 
     m = _EXPLICIT_CHAPTER.match(s)
-    if m and _HEADING_TAIL.match(m.group("rest")):
+    if (
+        m
+        and _HEADING_TAIL.match(m.group("rest"))
+        and len(m.group("rest").split()) <= _MAX_HEADING_TAIL_WORDS
+    ):
         if m.group(1):
             return int(m.group(1))
         return _roman_to_int(m.group("roman").upper())
@@ -675,7 +687,13 @@
 
     headings = []
     numbers = set()
-    for line in lines:
+    # A fenced block is code, not prose: a diff excerpt line
+    # ("1  + use crate::...") otherwise satisfies the plain-number
+    # matcher. The structural collector already skips these.
+    fenced = _closed_fence_line_numbers(lines)
+    for index, line in enumerate(lines):
+        if index in fenced:
+            continue
         num = _chapter_number(line)
         if num is not None:
             numbers.add(num)

Note the third hunk does not fix the bare (unfenced) diff line — that needs the plain matcher itself narrowed, which I left open on purpose. The 8 → 26 figure moves the failure from "prose counted as chapters" to "counted by the wrong rule" (#236), it does not make the count correct. This is offered as evidence, not as a finished patch, and I have not opened a PR.

Alternatives considered

  • Reject by body size (a heading has a short line). The len(s) > 80 guard at utils.py:571 is already this idea and is too coarse — 'Chapter 13. Closures and iterators create types that only the compiler knows or' is 76 characters and passes.
  • Reject when the tail is a full sentence (trailing period plus a verb). Fragile and hard to test; the word cap is the cheaper boundary.
  • Require an ATX/Markdown prefix for every match. Would break the documented bare-line forms (Chapter 5, Capítulo 5: ...) that the matchers exist to support.
  • Fix it inside the source parser instead. The wrapped sentence is produced by extraction, but a plain .txt or OCR'd source has the same shape, so the matcher is the right layer.
  • Rely on chapters_method being reported (#148/#150). It was, and it is what let me find this — but it reports the branch, not the matched lines; chapter_headings_sample did that, and here it was populated with prose, which is how the defect became visible at all.

Environment

  • upstream/master 526f362552562d88c1a8bbf8012d2cee93f831d5 (v1.4.0), clean Linux checkout.
  • Ubuntu 20.04.6 LTS, Python 3.9.5, pytest 8.4.2, ruff 0.16.8.
  • --mode text. The Rust Book was fetched from codeload.github.com/rust-lang/book (MIT OR Apache-2.0); no copyrighted text is reproduced here, and the quoted lines are the extractor's own output of a permissively-licensed source.
  • Related: #236 covers the structural path (_structural_chapter_count, back matter, multi-source depth selection). This issue is the numeric path (_match_chapter_number, _HEADING_TAIL, plain) — different functions, different fix, kept separate on purpose.

Source: virgiliojr94/book-to-skill