[bug] Front and back matter are counted as chapters on the structural path (and two 'Part' headings collapse the count)
Problem
book_to_skill/utils.py::_structural_chapter_count() decides a chapter count by returning len(levels[depth]) for the shallowest heading depth that has at least two distinct titles (utils.py:509). It has no concept of front matter or back matter, so every framing heading at that depth is counted as a teaching chapter.
Measured on upstream/master (526f362, v1.4.0) with a synthetic fixture (no copyrighted text) shaped like a real book — 20 titled chapters plus the front matter and back matter a book actually carries:
| headings | role |
|---|---|
## Preface, ## Acknowledgements, ## Table of Contents |
front matter |
## Chapter Title 1 … ## Chapter Title 20 |
the 20 real chapters |
## Appendix A: Notation, ## Appendix B: Datasets, ## Glossary, ## Bibliography, ## Index |
back matter |
$ python3 scripts/extract.py synthetic-book.md --mode text --install-missing no
chapters: 28 (structural)
Extraction complete:
Chapters: 28 detected overall (structural)
ToC : yesmetadata.json from that same run:
"chapters_detected": 28,
"chapters_method": "structural",
"chapter_headings_sample": [],
"has_toc": trueA 5-chapter version of the same fixture reports 13 — exactly the 5 real chapters plus all 8 framing headings (Preface, Acknowledgements, Table of Contents, Appendix A: Notation, Appendix B: Datasets, Glossary, Bibliography, Index).
Two things keep this out of sight:
chapter_headings_sampleis always empty on this path.detect_structurebuilds it only from numeric matches (utils.py:679-682), and a titled heading never matches_chapter_number, so the list an operator would audit the count against is[].chapters_method(from #148/#150) says how the count was produced; nothing says what was counted.- The same object is inconsistent with itself.
has_toc: trueshows the detector matched a table-of-contents indicator — evidence that framing pages are present — whilechapters_detectedsilently includes them. (Strictly,has_tocis a text match on the ToC heading, not proof of front-matter identification; the point is that the run already knows a ToC is there and still counts it as a chapter.)
This is not cosmetic: SKILL.md Step 3 turns the number into the "Chapters Detected" plan and Step 7 writes one chapters/chNN-*.md per detected chapter, so the 8 framing sections become 8 generated chapter files, each paid for at generation time.
A second, separate cause: two Part headings collapse the count
The same entry point short-circuits to the numeric count when two or more numeric headings exist (utils.py:693). _chapter_number('# Part I') == 1 and ('# Part II') == 2 — PR #161 deliberately added part to that alternation — so a book whose parts contain chapters reports the parts:
_chapter_number('# Part I') -> 1
_chapter_number('# Part II') -> 2
detect_structure() on 2 Parts + 10 chapters:
chapters_detected : 2
chapters_method : numeric
headings_sample : ['# Part I', '# Part II']
real chapters : 10 # 5x undercountPR #161's own comment anticipates this shape — "a single stray number (e.g. a Roman numeral inside an example paper reproduced in the book, or a lone 'Part 1') is not enough to suppress the structural heading count" — but the guard only handles one Part heading. Two of them satisfy numeric_count >= 2, so the numeric branch answers with 2.
Asking the structural counter directly on the same pristine tree does not rescue it either: it returns 3, not 10, because the two Part headings and the book's own H1 title sit at depth 1 and win the shallowest-depth test (if len(levels[depth]) >= 2, utils.py:509). So both branches are wrong for one underlying reason — the depth-selection rule, not the number of matches. Excluding Part-prefixed titles drops depth 1 below the >= 2 floor, the loop falls through to depth 2, and the count becomes the correct 10; the prototype below measures exactly that (_structural_chapter_count(): 3 → 10).
Correction, added after filing. An earlier revision of this issue claimed the structural counter "returns the correct
10when asked directly". That was wrong:10was a post-prototype figure quoted against pristine code. Re-run onupstream/master526f362, the pristine value is 3 (_structural_chapter_count(), depth 1 ={'the book', 'part i', 'part ii'}). The rest of the measurement stands; only that one sentence was wrong, and it is corrected here rather than silently edited.
I have changed no code — this is a report, not a PR.
Proposed change
Deferential on shape; three separable pieces.
- A non-chapter classifier, in the file's existing style.
_TOC_HEADERS(utils.py:343) is already a lowercase, whole-line, multilingual tuple consumed by_TOC_PATTERN. An analogous_BACK_MATTER_HEADERS/_FRONT_MATTER_HEADERS(plus anappendix/appendices/partprefix rule, since the real heading carries a label — "Appendix A: Notation") applied in both heading-collection branches of_structural_chapter_count()would drop the framing headings. Whole-title matching is deliberate: 6 probe headings that merely contain a back-matter word (## Indexing Strategies,## Glossary of Terms,## Building an Index,## Bibliography Management, …) must stay counted. - Populate
chapter_headings_sampleon the structural path, so a wrong count is auditable. This is the same argument #148 made, one layer deeper: the method is now reported, but the evidence is not. - The
Partshort-circuit is a distinct fix and I would keep it out of (1). Making_structural_chapter_count()Part-aware does not help whileutils.py:693never calls it. This one may deserve its own issue.
How would we know it's better?
Mechanical before/after on the same fixture, prototype applied to a copy of upstream/master:
| probe | before | after | expected |
|---|---|---|---|
| 5 chapters + 3 front + 5 back | 13 | 5 | 5 |
| 20 chapters + 3 front + 5 back | 28 | 20 | 20 |
3 chapters + a heading exactly Appendix |
4 | 3 | 3 |
2 Parts (#) + 10 titled chapters (##) — _structural_chapter_count() called directly |
3 | 10 | 10 |
| 6 chapters whose titles contain back-matter words | 6 | 6 | 6 (unchanged) |
| 5 titled chapters, no front/back matter | 5 | 5 | unchanged |
| 5 numbered sections | 5 | 5 | unchanged |
| 3 unnumbered sections | 3 | 3 | unchanged |
End to end through the real CLI after the change: chapters: 20 (structural), metadata.json chapters_detected = 20.
- No regression:
pytest tests/ -qon Linux (py3.9.5) is 679 passed, 1 skipped both before and after the prototype (~/bts/venv, pytest-only = CI parity).ruff check .clean;tools/validate_skill.py SKILL.mdexit 0. - Tests to add: the 5-chapter and 20-chapter shapes (count == real chapter count), the bare
Appendixheading, and the containment cases above as the false-positive guard.tests/test_numbered_headings.pyandtests/test_chapter_method_reported.pyare the closest existing homes. - Nothing currently pins the old behaviour:
grep -riE 'appendix|bibliograph|back.?matter' tests/finds no counting test, so this is additive.
The prototype, so the numbers above are reproducible
Applied to book_to_skill/utils.py at 526f362 (git cat-file blob 441934ee92c7e1ad9d5c4a73523b24888229fbc8, sha256 2eb30781f74a74838aaf166d6a78ecb11ffbcb1889c22a8d02b5170fda586d2c). 31 added lines, 3 changed:
--- a/book_to_skill/utils.py
+++ b/book_to_skill/utils.py
@@ -355,6 +355,37 @@
+ r")\s*$",
re.IGNORECASE | re.MULTILINE,
)
+
+# Headings that FRAME a book rather than teach inside it. A structural heading
+# that matches one of these is not a chapter and must not be counted as one.
+# Same shape as _TOC_HEADERS above: lowercase, whole-title, deterministic, no
+# new dependency. "appendix" matches by prefix because the real heading carries
+# a label ("Appendix A: Notation", "Appendix B - Datasets").
+_BACK_MATTER_HEADERS = (
+ "bibliography", "references", "works cited", "further reading",
+ "index", "glossary", "notes", "endnotes", "footnotes",
+ "colophon", "about the author", "about the authors",
+)
+_FRONT_MATTER_HEADERS = (
+ "preface", "foreword", "acknowledgements", "acknowledgments",
+ "dedication", "copyright", "epigraph", "prologue",
+)
+_BACK_MATTER_PREFIX = re.compile(r"^(?:appendix|appendices|part)\b", re.IGNORECASE)
+
+
+def _is_non_chapter_section(title: str) -> bool:
+ """True when a heading frames the book instead of teaching in it.
+
+ ``title`` is already lowercased and stripped. The ToC heading is covered by
+ ``_TOC_HEADERS``/``_TOC_PATTERN``; this adds the front matter that precedes
+ it, the back matter that follows the last chapter, and Part-level wrappers
+ (which are containers of chapters, never chapters themselves).
+ """
+ if title in _BACK_MATTER_HEADERS or title in _FRONT_MATTER_HEADERS:
+ return True
+ if _TOC_PATTERN.match(title):
+ return True
+ return bool(_BACK_MATTER_PREFIX.match(title))
# ATX-style heading: "# Title", "## Section", AsciiDoc "= Title", "== Section".
# The required space after the marker distinguishes an AsciiDoc "== X" from a
@@ -480,7 +511,8 @@
and re.search(r"\w", prev)
):
depth = 1 if s[0] == "=" else 2
- levels.setdefault(depth, set()).add(prev.lower())
+ if not _is_non_chapter_section(prev.lower()):
+ levels.setdefault(depth, set()).add(prev.lower())
heading_lines.append(index)
prev = ""
continue
@@ -494,7 +526,7 @@
heading_lines.append(index)
if title[0].isdigit():
numbered.setdefault(depth, []).append((title, index))
- else:
+ elif not _is_non_chapter_section(title):
levels.setdefault(depth, set()).add(title)
# An ATX heading line is not a setext title for the next line.
prev = ""This is offered as evidence, not as a finished patch — I deliberately did not resolve the Introduction false-negative above, and I have not opened a PR.
Alternatives considered
- Treat appendices as chapters on purpose. Defensible for a book whose appendices teach. But then
Index,Bibliography, and the ToC heading are also chapters, which they are not, and the count silently becomes "headings at one depth" rather than "chapters". - Substring matching instead of whole-title. Rejected — it would delete
## Building an Indexand## Glossary of Termsfrom the count. The containment probes above exist to pin that. - Position-based ("everything after the last numeric chapter is back matter"). More state and more ways to be wrong; it also cannot help titled-chapter books that have no numeric headings at all, which is exactly the population that reaches this path.
- Fix only the
chapter_headings_samplereporting and leave the count. Makes the error visible without making it correct. - Do nothing / document it. The number feeds the generated skill's structure; documenting a wrong count does not stop the 8 phantom chapter files.
Environment
upstream/master526f362552562d88c1a8bbf8012d2cee93f831d5(v1.4.0), clean Linux checkout.- Ubuntu 20.04.6 LTS (kernel 5.4.0-216), Python 3.9.5, pytest 8.4.2, ruff 0.16.8.
--mode text; no optional extractors were needed (the fixture is Markdown, so no dependency is involved in the reproduction).- The structural path is reached only when fewer than two numeric
Chapter Nheadings exist (utils.py:693), so numbered books are unaffected; the exposure is titled-chapter books, internal docs, runbooks and collections — exactly the "Beyond books" inputs the README promotes.
Source: virgiliojr94/book-to-skill