bindery-cli 0.30.0__tar.gz → 0.32.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/CLAUDE.md +16 -5
  2. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/PKG-INFO +8 -8
  3. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/README.md +6 -6
  4. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/patchnotes.md +122 -0
  5. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/pyproject.toml +2 -2
  6. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/roadmap.md +414 -2
  7. bindery_cli-0.32.0/scripts/FastSweepExtract.java +44 -0
  8. bindery_cli-0.32.0/scripts/sweep.sh +34 -0
  9. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/spec.md +43 -7
  10. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/src/bindery/__init__.py +1 -1
  11. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/src/bindery/audit.py +13 -3
  12. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/src/bindery/cli.py +25 -0
  13. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/src/bindery/epub.py +135 -34
  14. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/src/bindery/library.py +69 -11
  15. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/src/bindery/pagination.py +16 -4
  16. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/src/bindery/reserialize.py +18 -4
  17. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/src/bindery/transforms.py +122 -32
  18. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/src/bindery/watermark.py +67 -17
  19. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/tests/test_audit.py +12 -0
  20. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/tests/test_cli.py +34 -1
  21. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/tests/test_epub.py +194 -1
  22. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/tests/test_library.py +55 -4
  23. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/tests/test_pagination.py +52 -0
  24. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/tests/test_reserialize.py +13 -0
  25. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/tests/test_transforms.py +126 -0
  26. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/tests/test_watermark.py +100 -17
  27. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/uv.lock +5 -5
  28. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/.github/workflows/ci.yml +0 -0
  29. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/.github/workflows/publish.yml +0 -0
  30. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/.gitignore +0 -0
  31. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/AGENTS.md +0 -0
  32. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/LICENSE +0 -0
  33. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/docs/screenshots/library-sweep.png +0 -0
  34. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/logo.svg +0 -0
  35. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/run_tests.sh +0 -0
  36. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/scripts/FastSweep.java +0 -0
  37. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/scripts/fast_sweep.py +0 -0
  38. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/scripts/find_block_in_inline.py +0 -0
  39. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/scripts/find_css_illegal_tags.py +0 -0
  40. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/scripts/find_duplicate_playorder.py +0 -0
  41. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/scripts/find_empty_body.py +0 -0
  42. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/scripts/find_illegal_tags.py +0 -0
  43. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/scripts/find_invalid_ids.py +0 -0
  44. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/scripts/find_invalid_st_tag.py +0 -0
  45. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/scripts/find_invalid_value_attr.py +0 -0
  46. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/scripts/find_missing_images.py +0 -0
  47. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/scripts/find_missing_title.py +0 -0
  48. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/src/bindery/__main__.py +0 -0
  49. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/src/bindery/validate.py +0 -0
  50. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/agda.epub +0 -0
  51. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/agda_fixed.epub +0 -0
  52. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/last_man_out.epub +0 -0
  53. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/last_man_out_fixed.epub +0 -0
  54. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/leaves_of_grass.epub +0 -0
  55. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/leaves_of_grass_fixed.epub +0 -0
  56. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/leaves_of_grass_st_fixed.epub +0 -0
  57. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/leaves_of_grass_tags_fixed.epub +0 -0
  58. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/muse_of_nightmares.epub +0 -0
  59. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/muse_of_nightmares_fixed.epub +0 -0
  60. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/poor_mans_fight.epub +0 -0
  61. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/poor_mans_fight_fixed.epub +0 -0
  62. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/test_block_in_inline.py +0 -0
  63. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/test_duplicate_playorder.py +0 -0
  64. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/test_empty_body.py +0 -0
  65. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/test_illegal_tags.py +0 -0
  66. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/test_invalid_ids.py +0 -0
  67. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/test_invalid_value.py +0 -0
  68. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/test_missing_title.py +0 -0
  69. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/unworthy_gods.epub +0 -0
  70. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/test_facility/unworthy_gods_fixed.epub +0 -0
  71. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/testing_facility/books_to_fix/.gitkeep +0 -0
  72. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/testing_facility/top500candidates/REPORT.md +0 -0
  73. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/tests/test_validate.py +0 -0
  74. {bindery_cli-0.30.0 → bindery_cli-0.32.0}/tests/test_version.py +0 -0
@@ -34,11 +34,22 @@ Born from the 2026 library audit (see the user memory `calibre-library-epubcheck
34
34
  minimal content. v0.14–v0.16 ran these unconditionally, which broke this rule;
35
35
  v0.17.0 restored it. `--unwrap-illegal-tags` additionally protects any illegal-tag
36
36
  name that an EPUB stylesheet styles as an element selector (`css_protected_tags`,
37
- book-wide, inline `<style>` blocks included).
37
+ book-wide, inline `<style>` blocks included). The two EPUB2-targeted fixes
38
+ (`--strip-epub3-attrs`, `--downgrade-epub3-tags`) are additionally gated on the
39
+ package version in the OPF (`package_version()`): inert on EPUB 3 books and when
40
+ no version can be read, since their target defects only exist below EPUB 3; the
41
+ attribute scrub is anchored to real start tags via
42
+ `transforms.strip_attrs_in_start_tags` (prose mentioning the attributes and
43
+ CDATA/comment content are preserved), and `strip_invalid_value` matches the
44
+ attribute name with a `(?<![\w:.-])value` lookbehind so `data-value` survives.
38
45
  * **Lossy strips** (`--strip-pagination`, `--strip-broken-tags`, `--strip-watermarks`;
39
46
  pagination.py, watermark.py): remove only what a converter injected (page numbers,
40
47
  running headers, leaked tags, watermarks), fenced behind character conservation, tag
41
- balance, and the epubcheck no-regression bar.
48
+ balance, and the epubcheck no-regression bar. The watermark anchored pass's
49
+ whole-match fallback only fires when the match holds nothing but the stamp; a
50
+ larger match (an unclosed stamp anchor that swallowed prose) is refused, counted
51
+ in `RepairReport.watermark_refusals`, and surfaced as a `manual_watermark_repair`
52
+ decision by `run phase1` on both the read-only and apply paths.
42
53
  Do not let any NEW fix touch content without its own flag; if a candidate repair cannot
43
54
  be made deterministically safe, it does not belong here — report it for manual repair
44
55
  instead.
@@ -58,15 +69,15 @@ Born from the 2026 library audit (see the user memory `calibre-library-epubcheck
58
69
 
59
70
  ## Layout
60
71
 
61
- - `src/bindery/transforms.py`: pure `str -> (str, int)` text transforms (including `strip_broken_tags`).
72
+ - `src/bindery/transforms.py`: pure `str -> (str, int)` text transforms (including `strip_broken_tags`). Since v0.32.0: `strip_attrs_in_start_tags` anchors attribute edits on the quote-aware start-tag matcher, `_outside_protected` forwards arguments (context-carrying transforms can be decorated), `fix_id_colons` matches only the bare `id` attribute and only internal fragments (`fix_ncx_src_fragments` carries renames into the NCX), `fix_ncx_playorder` is anchored to `<navPoint>` start tags, and the css selector boundary covers namespaced and functional selector forms.
62
73
  - `src/bindery/pagination.py`: the opt-in lossy page-number strip (runhead detection, page-layer decision, block-centric removal/merge, safety nets).
63
74
  - `src/bindery/watermark.py`: the opt-in lossy watermark strip (anchored and anchorless signature removal).
64
75
  - `src/bindery/reserialize.py`: structural repair via `html5lib`.
65
76
  - `src/bindery/audit.py`: read-only body-text audits (`content`, `pagenumbers`, `emptytext`, `ocr`, and `monolithic` since v0.21.0, `--max-doc-chars N`) behind the `audit` subcommand (v0.15.0). Since v0.18.0 library mode resolves EPUB paths through `cquarry.get_format_path()` and can apply a tag to flagged books via `cquarry.write.WritableCalibreDB` (only with explicit `--tag`; the only sanctioned write path). Since v0.19.0 `audit --id BOOK_ID` audits a single library book through cquarry's single-entity `get_book()` fetch (no library-wide cache; supports `--tag`; incompatible with the directory argument; comma lists since v0.23.0). Since v0.22.0 every archive entry is fully read (CRC + decompression) before analysis — a damaged entry reports its own CORRUPT verdict instead of feeding emptytext — and manifest/NCX references to absent files classify as `convention` (bloated ToC, consecutive span) or `fragment` (broken span). Hazard: the scan loop reuses `tag` as its per-book display column, so the `--tag` argument is captured as `audit_tag` at function entry — do not collapse them again. Since v0.29.0 `audit --json FILE` writes per-file analyzer verdicts in the `library --json` shape (directory, library, and single-book modes; with `--id`, exactly one id; emptytext omitted from a record when the archive verdict owns the body-text story).
66
77
  - `src/bindery/epub.py`: archive rewrite, NCX uid sync, RepairReport, mismatch detection, and the opt-in structural-repair plumbing (including the CSS precondition scan).
67
78
  - `src/bindery/validate.py`: epubcheck wrapper, the `gate` (improvement) and `no_worse` (no-regression, for the lossy strips) acceptance bars.
68
- - `src/bindery/library.py`: Calibre walk, atomic replace, backups, and native format installation. Since v0.19.0 `CalibreIdResolver` resolves the book id from `metadata.db` through cquarry (one lazy path→id map per run; since v0.20.0 the map comes from `CalibreDB.format_path_index()`, re-normalized with `resolve().lower()` for the resolver's symlinked-directory and case-insensitive matching) — the `(id)` directory-name regex is only the no-catalog fallback. Since v0.24.0 `install_format()` places the repaired file atomically and updates the `data` row through `cquarry.write.WritableCalibreDB` (remove+add in one `batch()`; `add_format` refuses duplicates); the external `calibredb` CLI is gone. Never reintroduce directory-name guessing as the primary source: renamed/mismatched directories would replace the wrong book.
69
- - `src/bindery/cli.py`: `repair` and `library` subcommands, including `--all` and `--install-to-calibre`; since v0.29.0 also the `run` verbs — `phase1` (pre-import vetting over loose files: the audit battery composed with one gated repair sweep; read-only until `--apply-lossy`, which IS the lossy-strip consent) and `phase3` (the scoped post-import apply step: `library --id --sweep --only all --apply --all --install-to-calibre` plus a pre/post summary; mechanically refuses unscoped sweeps with exit 2). Both take `--non-interactive` and surface open questions as `decisions_needed` in their JSON, never prompts. They drive the shipped `run_library` through the real parser, so no flag can drift between the verb and the subcommand it wraps. `library --workers N` (v0.30.0) parallelizes only the sweep's candidate pass, in windows of N consumed in order so `--limit` stays lazy; the repair phase is never parallel (shared workdir, atomic-replacement contract).
79
+ - `src/bindery/library.py`: Calibre walk, atomic replace, backups, and native format installation. Since v0.19.0 `CalibreIdResolver` resolves the book id from `metadata.db` through cquarry (one lazy path→id map per run; since v0.20.0 the map comes from `CalibreDB.format_path_index()`, re-normalized with `resolve().lower()` for the resolver's symlinked-directory and case-insensitive matching) — the `(id)` directory-name regex is only the no-catalog fallback. Since v0.24.0 `install_format()` places the repaired file atomically and updates the `data` row through `cquarry.write.WritableCalibreDB` (since v0.31.0 via `set_format`, cquarry 1.17's sanctioned remove+add in one transaction); the external `calibredb` CLI is gone. Since v0.32.0 a guessed id drives a row update only when metadata.db corroborates it (`_verify_guess`: books row exists, file in the book's own directory, catalogued `data.name` when a row exists); anything else saves in place and leaves the catalog untouched — never reintroduce directory-name guessing as the primary source: renamed/mismatched directories would replace the wrong book.
80
+ - `src/bindery/cli.py`: `repair` and `library` subcommands, including `--all` and `--install-to-calibre`; since v0.29.0 also the `run` verbs: `phase1` (pre-import vetting over loose files: the audit battery composed with one gated repair sweep; read-only until `--apply-lossy`, which IS the lossy-strip consent) and `phase3` (the scoped post-import apply step: `library --id --sweep --only all --apply --all --install-to-calibre` plus a pre/post summary; mechanically refuses unscoped sweeps with exit 2). Both take `--non-interactive` and surface open questions as `decisions_needed` in their JSON, never prompts. They drive the shipped `run_library` through the real parser, so no flag can drift between the verb and the subcommand it wraps. `library --workers N` (v0.30.0) parallelizes only the sweep's candidate pass, in windows of N consumed in order so `--limit` stays lazy; the repair phase is never parallel (shared workdir, atomic-replacement contract).
70
81
  - `tests/`: transforms, end-to-end repair, atomic replace, pagination, watermarks, the audit analyzers (content/pagenumbers/emptytext/ocr/monolithic, archive integrity, spine classification), the library sweep and `CalibreIdResolver`, validate, reserialize, CLI wiring, and the version pin.
71
82
 
72
83
  ## Conventions
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bindery-cli
3
- Version: 0.30.0
3
+ Version: 0.32.0
4
4
  Summary: Audit EPUB body text and repair broken EPUBs with deterministic, epubcheck-gated fixes; atomic in-place replacement in a Calibre library.
5
5
  Author: vrnvctss
6
6
  License: MIT
@@ -13,7 +13,7 @@ Classifier: License :: OSI Approved :: MIT License
13
13
  Classifier: Programming Language :: Python :: 3.14
14
14
  Classifier: Topic :: Utilities
15
15
  Requires-Python: >=3.14
16
- Requires-Dist: cquarry>=1.9.0
16
+ Requires-Dist: cquarry>=1.17.0
17
17
  Requires-Dist: tqdm
18
18
  Requires-Dist: vir-tui>=2.2.0
19
19
  Provides-Extra: reserialize
@@ -51,14 +51,14 @@ Everything below is off until its flag is passed (or all at once via `--all`). T
51
51
  - **`--reserialize`**: rebuild content documents that are still malformed by re-parsing them with html5lib and re-emitting XHTML, closing unclosed `<p>`/`<div>`/`<span>`/`<blockquote>` that the regex transforms cannot. Runs only on documents that are not already well-formed, so good files are untouched.
52
52
  - **`--strip-bad-attrs`**: drop attributes that are invalid XML (a name starting with a digit, or a namespaced name whose prefix is never declared, like Office VML `v:shapes`). Surgical and a no-op on well-formed files.
53
53
  - **`--escape-unknown-entities`**: escape entity names that are not in the HTML5 table (`&foo;` becomes `&amp;foo;`), which renders exactly as browsers already render an unknown entity. Documents whose DOCTYPE carries an internal subset are skipped wholesale, since a subset can declare custom entities.
54
- - **`--fix-id-colons`**: translates illegal colons in `id="X:Y"` and their matching `#X:Y` fragment references to valid underscores.
54
+ - **`--fix-id-colons`**: translates illegal colons in `id="X:Y"` and their matching internal `#X:Y` fragment references to valid underscores. External URL fragments are left verbatim (they name positions in other documents), `data-id` values are never touched, and the NCX's `content src` fragments follow the rename so the table of contents never dangles against the ids it references.
55
55
  - **`--fix-empty-body`**: appends a non-breaking space `&nbsp;` to strictly empty body tags to satisfy parser requirements.
56
56
  - **`--fix-missing-title`**: injects a `<title>Unknown</title>` fallback in the `<head>` if missing, handling both empty `<title/>` self-closing tags and entirely absent tags.
57
57
  - **`--unwrap-block-in-inline`**: safely unwraps `<span>` tags that illegally contain a block-level element (e.g. `<div>` or `<p>`), leaving the block element intact.
58
58
  - **`--strip-invalid-value`**: systematically strips invalid `value="..."` attributes from elements like `<div>`, `<span>`, `<p>`, etc.
59
59
  - **`--fix-page-map`**: normalizes legacy page-map markup — drops the non-standard `page-map="..."` attribute from the OPF `<spine>` and adds `class="pages"` to classless NCX `<pageList>` elements (epubcheck rejects both on older HarperCollins / Anna's Archive conversions).
60
- - **`--strip-epub3-attrs`**: scrubs the EPUB3-only attributes epubcheck rejects on an EPUB2 package — `page-progression-direction`, `epub:type`, `aria-label` (a fixed, documented set; rendering is unchanged, and lookalikes like `type` or the wider aria family survive).
61
- - **`--downgrade-epub3-tags`**: downgrades EPUB3/HTML5 semantic elements to their EPUB2 equivalents — `figure`/`section` to `div`, `figcaption` to `p` — keeping existing classes and appending the semantic name (`class="figure"`) as the styling hook. Tag names a stylesheet styles as an element selector are protected book-wide, so styled formatting is never destroyed.
60
+ - **`--strip-epub3-attrs`**: scrubs the EPUB3-only attributes epubcheck rejects on an EPUB2 package — `page-progression-direction`, `epub:type`, `aria-label` (a fixed, documented set; rendering is unchanged, and lookalikes like `type` or the wider aria family survive). The edit is anchored to real start tags, so prose that merely mentions `epub:type="chapter"` is preserved.
61
+ - **`--downgrade-epub3-tags`**: downgrades EPUB3/HTML5 semantic elements to their EPUB2 equivalents — `figure`/`section` to `div`, `figcaption` to `p` — keeping existing classes and appending the semantic name (`class="figure"`) as the styling hook. Tag names a stylesheet styles as an element selector are protected book-wide, so styled formatting is never destroyed. Both EPUB2-targeted fixes are gated on the package version declared in the OPF: on an EPUB 3 book they do nothing, because their target defects only exist below EPUB 3.
62
62
  - **`--unwrap-illegal-tags`**: strips completely invalid or deprecated HTML tags that break EPUB3 validation (`<st>`, `<sentence>`, `<o>`, `<w>`, `<pagebreak>`) while retaining their inner text. Any of those names styled as an *element selector* by an EPUB stylesheet (`.css` entries and inline `<style>` blocks alike; class/id selectors like `.st`/`#w` don't count) is protected for the whole book, guaranteeing format preservation.
63
63
  - **`--prune-missing-resources`**: removes references to files the archive does not contain (RSC-007/PKG-010): dead `<link>` elements, anchors' `href` to absent files (anchor text preserved), absent `<img>` sources (replaced by their alt text when they carry one), and orphaned non-spine OPF manifest items. Spine documents are never pruned: a missing spine document is reported as a damaged fragment, not silently dropped.
64
64
  - **`--strip-broken-anchors`**: strips href attributes that cannot resolve, keeping the anchor text byte-for-byte: a `#fragment` the target document does not define (RSC-020/RSC-012; NCX navTargets fall back to the document target, so chapter navigation survives) and unresolvable URI schemes (`kindle:`, `file:`).
@@ -67,9 +67,9 @@ Everything below is off until its flag is passed (or all at once via `--all`). T
67
67
 
68
68
  Three opt-in fixes are **lossy** and stand apart from the semantics-preserving rest:
69
69
 
70
- - **`--strip-pagination`**: remove print page numbers and running headers that a PDF/OCR conversion baked into the body text as literal paragraphs (so they reflow into the middle of a sentence: "where the hay cart **16** was taking him"). It removes only that injected furniture, never the author's prose: where a number split a sentence it rejoins the two paragraphs (closing up a word split like `compli-` / `mentary`), and it preserves roman chapter numbers, page-list nav anchors, and years. A book is only treated as paginated when it has both a dense run of arabic numbers and several confident mid-sentence interrupts, so a merely chapter-numbered book is left alone. Three safety nets guard every edit (character conservation, tag balance, and an epubcheck no-regression check); any failure leaves the document untouched.
70
+ - **`--strip-pagination`**: remove print page numbers and running headers that a PDF/OCR conversion baked into the body text as literal paragraphs (so they reflow into the middle of a sentence: "where the hay cart **16** was taking him"). It removes only that injected furniture, never the author's prose: where a number split a sentence it rejoins the two paragraphs (closing up a word split like `compli-` / `mentary`), and it preserves roman chapter numbers, page-list nav anchors, and years. A roman numeral counts as a page number only when it is well-formed and under 100, so ordinary words (`mid`, `mix`, `civil`) are never mistaken for pages. A book is only treated as paginated when it has both a dense run of arabic numbers and several confident mid-sentence interrupts, so a merely chapter-numbered book is left alone. Three safety nets guard every edit (character conservation, tag balance, and an epubcheck no-regression check); any failure leaves the document untouched.
71
71
  - **`--strip-broken-tags`**: remove leaked HTML closing tags missing their open brackets (e.g. `</p>`) that render as raw text.
72
- - **`--strip-watermarks`**: remove known producer and distributor watermarks (e.g. OceanofPDF, ABC Amber LIT Converter) and stray marker files. It locates the stamp and deletes the outermost wrapper whose entire visible text is the watermark, ensuring prose that merely mentions the URL is preserved.
72
+ - **`--strip-watermarks`**: remove known producer and distributor watermarks (e.g. OceanofPDF, ABC Amber LIT Converter) and stray marker files. It locates the stamp and deletes the outermost wrapper whose entire visible text is the watermark, ensuring prose that merely mentions the URL is preserved. An inline stamp link is deleted only when it holds nothing but the stamp; a match too large to be safe (an unclosed stamp anchor that swallowed prose) is refused and reported for manual repair rather than deleted.
73
73
 
74
74
  All lossy edits are invisible to epubcheck, so they are accepted when the result is *no worse* rather than measurably better.
75
75
 
@@ -200,7 +200,7 @@ bindery library ~/docs/Calibre\ Library --only all --apply --all --install-to-ca
200
200
  - `--json FILE` writes a machine-readable report of the whole run (per-book status, before/after counts, applied flag, summary totals). `--manual-list FILE` writes the paths of every book that was not auto-repaired, one per line, ready for manual follow-up.
201
201
  - `--apply` is required to write; the default is a dry run. `--backup DIR` mirrors originals before replacing; `--backup-inplace` writes `.epub.bak` beside each file.
202
202
  - `--install-to-calibre` resolves the Calibre book id from `metadata.db` via cquarry (one read-only path→id map per run), so a hand-renamed `Author/Title (id)/` directory can never send the repaired file to the wrong book. The directory-name regex is only a no-catalog fallback; with neither, the file is saved atomically in place.
203
- - `--install-to-calibre` installs the repaired EPUB through cquarry's write module: the file is placed atomically at the catalogued path (same filename, Calibre's layout never changes) and the format row is re-registered in one transaction, so the stored size stays truthful and the book lands in `metadata_dirtied` — Calibre regenerates its sidecar .opf on next start. No external `calibredb` call is involved. It falls back to atomic file replacement if the Calibre database ID cannot be resolved, and a database failure degrades to the in-place save with a warning.
203
+ - `--install-to-calibre` installs the repaired EPUB through cquarry's write module: the file is placed atomically at the catalogued path (same filename, Calibre's layout never changes) and the format row is re-registered in one transaction, so the stored size stays truthful and the book lands in `metadata_dirtied` — Calibre regenerates its sidecar .opf on next start. No external `calibredb` call is involved. It falls back to atomic file replacement if the Calibre database ID cannot be resolved, and a database failure degrades to the in-place save with a warning. A directory-name-guessed id is trusted only when `metadata.db` corroborates it (the book exists and the file is that book's catalogued EPUB); an uncatalogued stray file inside a book directory is saved in place and the catalog row is left untouched.
204
204
  - `--all` automatically turns on all opt-in non-fatal fixes and lossy strips (pagination, watermarks, bad attributes, unknown entities, image alt tags, etc.) in a single run.
205
205
  - Only the `.epub` is replaced. `metadata.opf`, `cover.jpg`, and `metadata.db` are left for Calibre's Quality Check sync to reconcile.
206
206
  - A per-book progress line goes to stderr (stdout stays a clean report); `--quiet` suppresses it. A corrupt or unreadable book is reported and skipped, never aborting the sweep.
@@ -29,14 +29,14 @@ Everything below is off until its flag is passed (or all at once via `--all`). T
29
29
  - **`--reserialize`**: rebuild content documents that are still malformed by re-parsing them with html5lib and re-emitting XHTML, closing unclosed `<p>`/`<div>`/`<span>`/`<blockquote>` that the regex transforms cannot. Runs only on documents that are not already well-formed, so good files are untouched.
30
30
  - **`--strip-bad-attrs`**: drop attributes that are invalid XML (a name starting with a digit, or a namespaced name whose prefix is never declared, like Office VML `v:shapes`). Surgical and a no-op on well-formed files.
31
31
  - **`--escape-unknown-entities`**: escape entity names that are not in the HTML5 table (`&foo;` becomes `&amp;foo;`), which renders exactly as browsers already render an unknown entity. Documents whose DOCTYPE carries an internal subset are skipped wholesale, since a subset can declare custom entities.
32
- - **`--fix-id-colons`**: translates illegal colons in `id="X:Y"` and their matching `#X:Y` fragment references to valid underscores.
32
+ - **`--fix-id-colons`**: translates illegal colons in `id="X:Y"` and their matching internal `#X:Y` fragment references to valid underscores. External URL fragments are left verbatim (they name positions in other documents), `data-id` values are never touched, and the NCX's `content src` fragments follow the rename so the table of contents never dangles against the ids it references.
33
33
  - **`--fix-empty-body`**: appends a non-breaking space `&nbsp;` to strictly empty body tags to satisfy parser requirements.
34
34
  - **`--fix-missing-title`**: injects a `<title>Unknown</title>` fallback in the `<head>` if missing, handling both empty `<title/>` self-closing tags and entirely absent tags.
35
35
  - **`--unwrap-block-in-inline`**: safely unwraps `<span>` tags that illegally contain a block-level element (e.g. `<div>` or `<p>`), leaving the block element intact.
36
36
  - **`--strip-invalid-value`**: systematically strips invalid `value="..."` attributes from elements like `<div>`, `<span>`, `<p>`, etc.
37
37
  - **`--fix-page-map`**: normalizes legacy page-map markup — drops the non-standard `page-map="..."` attribute from the OPF `<spine>` and adds `class="pages"` to classless NCX `<pageList>` elements (epubcheck rejects both on older HarperCollins / Anna's Archive conversions).
38
- - **`--strip-epub3-attrs`**: scrubs the EPUB3-only attributes epubcheck rejects on an EPUB2 package — `page-progression-direction`, `epub:type`, `aria-label` (a fixed, documented set; rendering is unchanged, and lookalikes like `type` or the wider aria family survive).
39
- - **`--downgrade-epub3-tags`**: downgrades EPUB3/HTML5 semantic elements to their EPUB2 equivalents — `figure`/`section` to `div`, `figcaption` to `p` — keeping existing classes and appending the semantic name (`class="figure"`) as the styling hook. Tag names a stylesheet styles as an element selector are protected book-wide, so styled formatting is never destroyed.
38
+ - **`--strip-epub3-attrs`**: scrubs the EPUB3-only attributes epubcheck rejects on an EPUB2 package — `page-progression-direction`, `epub:type`, `aria-label` (a fixed, documented set; rendering is unchanged, and lookalikes like `type` or the wider aria family survive). The edit is anchored to real start tags, so prose that merely mentions `epub:type="chapter"` is preserved.
39
+ - **`--downgrade-epub3-tags`**: downgrades EPUB3/HTML5 semantic elements to their EPUB2 equivalents — `figure`/`section` to `div`, `figcaption` to `p` — keeping existing classes and appending the semantic name (`class="figure"`) as the styling hook. Tag names a stylesheet styles as an element selector are protected book-wide, so styled formatting is never destroyed. Both EPUB2-targeted fixes are gated on the package version declared in the OPF: on an EPUB 3 book they do nothing, because their target defects only exist below EPUB 3.
40
40
  - **`--unwrap-illegal-tags`**: strips completely invalid or deprecated HTML tags that break EPUB3 validation (`<st>`, `<sentence>`, `<o>`, `<w>`, `<pagebreak>`) while retaining their inner text. Any of those names styled as an *element selector* by an EPUB stylesheet (`.css` entries and inline `<style>` blocks alike; class/id selectors like `.st`/`#w` don't count) is protected for the whole book, guaranteeing format preservation.
41
41
  - **`--prune-missing-resources`**: removes references to files the archive does not contain (RSC-007/PKG-010): dead `<link>` elements, anchors' `href` to absent files (anchor text preserved), absent `<img>` sources (replaced by their alt text when they carry one), and orphaned non-spine OPF manifest items. Spine documents are never pruned: a missing spine document is reported as a damaged fragment, not silently dropped.
42
42
  - **`--strip-broken-anchors`**: strips href attributes that cannot resolve, keeping the anchor text byte-for-byte: a `#fragment` the target document does not define (RSC-020/RSC-012; NCX navTargets fall back to the document target, so chapter navigation survives) and unresolvable URI schemes (`kindle:`, `file:`).
@@ -45,9 +45,9 @@ Everything below is off until its flag is passed (or all at once via `--all`). T
45
45
 
46
46
  Three opt-in fixes are **lossy** and stand apart from the semantics-preserving rest:
47
47
 
48
- - **`--strip-pagination`**: remove print page numbers and running headers that a PDF/OCR conversion baked into the body text as literal paragraphs (so they reflow into the middle of a sentence: "where the hay cart **16** was taking him"). It removes only that injected furniture, never the author's prose: where a number split a sentence it rejoins the two paragraphs (closing up a word split like `compli-` / `mentary`), and it preserves roman chapter numbers, page-list nav anchors, and years. A book is only treated as paginated when it has both a dense run of arabic numbers and several confident mid-sentence interrupts, so a merely chapter-numbered book is left alone. Three safety nets guard every edit (character conservation, tag balance, and an epubcheck no-regression check); any failure leaves the document untouched.
48
+ - **`--strip-pagination`**: remove print page numbers and running headers that a PDF/OCR conversion baked into the body text as literal paragraphs (so they reflow into the middle of a sentence: "where the hay cart **16** was taking him"). It removes only that injected furniture, never the author's prose: where a number split a sentence it rejoins the two paragraphs (closing up a word split like `compli-` / `mentary`), and it preserves roman chapter numbers, page-list nav anchors, and years. A roman numeral counts as a page number only when it is well-formed and under 100, so ordinary words (`mid`, `mix`, `civil`) are never mistaken for pages. A book is only treated as paginated when it has both a dense run of arabic numbers and several confident mid-sentence interrupts, so a merely chapter-numbered book is left alone. Three safety nets guard every edit (character conservation, tag balance, and an epubcheck no-regression check); any failure leaves the document untouched.
49
49
  - **`--strip-broken-tags`**: remove leaked HTML closing tags missing their open brackets (e.g. `</p>`) that render as raw text.
50
- - **`--strip-watermarks`**: remove known producer and distributor watermarks (e.g. OceanofPDF, ABC Amber LIT Converter) and stray marker files. It locates the stamp and deletes the outermost wrapper whose entire visible text is the watermark, ensuring prose that merely mentions the URL is preserved.
50
+ - **`--strip-watermarks`**: remove known producer and distributor watermarks (e.g. OceanofPDF, ABC Amber LIT Converter) and stray marker files. It locates the stamp and deletes the outermost wrapper whose entire visible text is the watermark, ensuring prose that merely mentions the URL is preserved. An inline stamp link is deleted only when it holds nothing but the stamp; a match too large to be safe (an unclosed stamp anchor that swallowed prose) is refused and reported for manual repair rather than deleted.
51
51
 
52
52
  All lossy edits are invisible to epubcheck, so they are accepted when the result is *no worse* rather than measurably better.
53
53
 
@@ -178,7 +178,7 @@ bindery library ~/docs/Calibre\ Library --only all --apply --all --install-to-ca
178
178
  - `--json FILE` writes a machine-readable report of the whole run (per-book status, before/after counts, applied flag, summary totals). `--manual-list FILE` writes the paths of every book that was not auto-repaired, one per line, ready for manual follow-up.
179
179
  - `--apply` is required to write; the default is a dry run. `--backup DIR` mirrors originals before replacing; `--backup-inplace` writes `.epub.bak` beside each file.
180
180
  - `--install-to-calibre` resolves the Calibre book id from `metadata.db` via cquarry (one read-only path→id map per run), so a hand-renamed `Author/Title (id)/` directory can never send the repaired file to the wrong book. The directory-name regex is only a no-catalog fallback; with neither, the file is saved atomically in place.
181
- - `--install-to-calibre` installs the repaired EPUB through cquarry's write module: the file is placed atomically at the catalogued path (same filename, Calibre's layout never changes) and the format row is re-registered in one transaction, so the stored size stays truthful and the book lands in `metadata_dirtied` — Calibre regenerates its sidecar .opf on next start. No external `calibredb` call is involved. It falls back to atomic file replacement if the Calibre database ID cannot be resolved, and a database failure degrades to the in-place save with a warning.
181
+ - `--install-to-calibre` installs the repaired EPUB through cquarry's write module: the file is placed atomically at the catalogued path (same filename, Calibre's layout never changes) and the format row is re-registered in one transaction, so the stored size stays truthful and the book lands in `metadata_dirtied` — Calibre regenerates its sidecar .opf on next start. No external `calibredb` call is involved. It falls back to atomic file replacement if the Calibre database ID cannot be resolved, and a database failure degrades to the in-place save with a warning. A directory-name-guessed id is trusted only when `metadata.db` corroborates it (the book exists and the file is that book's catalogued EPUB); an uncatalogued stray file inside a book directory is saved in place and the catalog row is left untouched.
182
182
  - `--all` automatically turns on all opt-in non-fatal fixes and lossy strips (pagination, watermarks, bad attributes, unknown entities, image alt tags, etc.) in a single run.
183
183
  - Only the `.epub` is replaced. `metadata.opf`, `cover.jpg`, and `metadata.db` are left for Calibre's Quality Check sync to reconcile.
184
184
  - A per-book progress line goes to stderr (stdout stays a clean report); `--quiet` suppresses it. A corrupt or unreadable book is reported and skipped, never aborting the sweep.
@@ -1,4 +1,126 @@
1
1
  # bindery-cli Patch Notes
2
+ ## v0.32.0 (2026-09-10)
3
+
4
+ ### The four Bug Reports fixes (2026-09-08 sweep) and the anchored-attribute cluster
5
+
6
+ - **`--strip-watermarks` refuses anchored matches larger than the stamp**
7
+ (the sweep demonstrated two paragraphs of real prose vanishing with
8
+ count 1). The anchored stamp regex is DOTALL with no tag budget, so an
9
+ unclosed stamp `<a>` matched through real prose to the next unrelated
10
+ `</a>`, and the whole-match fallback deleted everything in between;
11
+ epubcheck cannot see deleted text, so the no-regression bar accepted the
12
+ loss. The fallback now fires only when the match demonstrably holds
13
+ nothing but the stamp (a tag-free body within stamp length, or visible
14
+ text exactly the watermark), a second `<a>` opening inside the match
15
+ refuses it outright, and anything larger stays in place, counted in the
16
+ new `RepairReport.watermark_refusals` and surfaced by `run phase1` as a
17
+ `manual_watermark_repair` decision on both the read-only and apply paths.
18
+ Safe shapes (pure wrappers, inline stamp-only links) are byte-identical
19
+ to before.
20
+ - **Roman page-number detection reads well-formed numerals only**, in both
21
+ `--strip-pagination` and the audit pagenumbers analyzer. The old
22
+ `[ivxlcdm]{2,7}` character set read ordinary English words as page
23
+ numbers (`mid` = 1499), and a standalone `<p>mid</p>` before a
24
+ lowercase-starting paragraph is exactly the confident interrupt shape,
25
+ so real words were deleted and merged away. A roman counts only when
26
+ well-formed (explicit subtractive pairs) and valued under 100, where
27
+ front-matter page numbers live and words do not (`mix` = M+IX = 1009).
28
+ Lowercase front-matter romans keep working; the audit copy's deliberately
29
+ different year handling is untouched.
30
+ - **`install_format` verifies directory-guessed ids against metadata.db.**
31
+ In directory mode, an uncatalogued stray `.epub` inside a book directory
32
+ made the `(id)` directory guess fire, and the row update re-registered
33
+ the catalogued format name with the stray file's size: the catalogued
34
+ 999-byte file untouched on disk while `data` recorded 8123 bytes. A
35
+ stale `(N)` directory for a deleted book crashed the sweep instead. A
36
+ guessed id now drives a row update only when metadata.db corroborates it
37
+ (the books row exists, the file sits in that book's own directory, and
38
+ when an EPUB row exists it carries the row's stored name); anything else
39
+ saves the repair in place with a warning and leaves the catalog
40
+ untouched. The resolver path needs no verification: its id comes from
41
+ the catalog's own path map.
42
+ - **The EPUB2-targeted fixes are gated on the package version.** Neither
43
+ `--strip-epub3-attrs` nor `--downgrade-epub3-tags` checked what the
44
+ package declared, so under `--all` every EPUB3 book in a sweep took the
45
+ EPUB2 cure: a repairable EPUB3 book gained a net-new error from a
46
+ stripped nav `epub:type` (whole repair rejected), and a legal
47
+ `epub:type="chapter"` was silently removed because the gate only sees
48
+ epubcheck counts. Both fixes now fire only on EPUB 2 packages (major
49
+ version 1 or 2) and are inert on EPUB 3 packages and when no version can
50
+ be read, where their target defects do not exist.
51
+ - **The anchored-attribute regex cluster closes with the gate** (the same
52
+ sweep's sharpest repair-pipeline finding): the attribute scrub runs
53
+ anchored on real start tags through the new
54
+ `transforms.strip_attrs_in_start_tags`, with CDATA sections and comments
55
+ protected, so prose mentioning `epub:type="chapter"` is no longer
56
+ deleted down to `Use here`; `strip_invalid_value` matches its attribute
57
+ name behind a `(?<![\w:.-])value` lookbehind, so `data-value="42"`
58
+ survives instead of becoming a malformed `<span data->`.
59
+
60
+ ### Repair-pipeline correctness (Phase 14, the 2026-09-08 sweep's backlog)
61
+
62
+ - **`--fix-id-colons` is consistent and honest.** Only the bare `id`
63
+ attribute is in scope (a lookbehind keeps `data-id` and `xml:id` values
64
+ untouched), the fragment of an external URL survives verbatim (it names a
65
+ position in another document), the NCX's `content src` fragments follow
66
+ the rename through the new `fix_ncx_src_fragments` so a ToC never dangles
67
+ against the ids it references, and only actual colons replaced are
68
+ counted (byte-identical reruns report 0 and no longer trigger the
69
+ re-encode the untouched-file guard exists to prevent).
70
+ - **The anchor pass runs last.** `strip_broken_anchors`' id snapshot used
71
+ to predate the unwrap fixes, so an id they deleted still counted as
72
+ present and fragments pointing at it survived dangling. The anchor pass
73
+ now runs after every content fix, against a snapshot that replicates
74
+ each id-moving fix ahead of it.
75
+ - **CDATA sections and comments are protected everywhere.**
76
+ `strip_broken_tags` and `unwrap_illegal_tags` joined the module's
77
+ protected-span machinery (the wrapper now forwards arguments, so the
78
+ protected_tags-carrying unwrap could be decorated); a leaked-looking tag
79
+ inside either is literal rendered text, not markup.
80
+ - **Non-UTF-8 documents are skipped verbatim.** A fix firing on a
81
+ windows-1252 or UTF-16 document used to decode with U+FFFD substitutes
82
+ and re-encode UTF-8 under a declaration still naming the old encoding:
83
+ usually well-formed, so the gate could not see the corruption. The write
84
+ loop strict-decodes first; failures are copied byte-for-byte, counted in
85
+ the new `non_utf8_docs_skipped` entry, and left for manual repair.
86
+ - **`--reserialize` requires an html root.** A broken non-HTML `.xml`
87
+ sidecar used to come back html/body-wrapped with `ns0:` prefixes,
88
+ structurally rewritten while staying well-formed; it is now returned
89
+ untouched.
90
+ - **Seven papercuts.** `fix_ncx_playorder` is anchored to `<navPoint>`
91
+ start tags (nav-label text is untouchable); mimetype fixes increment
92
+ `files_changed`; `fix_manifest_ids` and its reference rewrites are
93
+ quote-agnostic (a single-quoting OPF used to be a silent count-0 no-op;
94
+ the two shadowed `_IDREF_ATTR_RE` definitions collapsed into one);
95
+ the css selector boundary recognizes `svg|st`, `:is(st, w)`, and
96
+ `:where(...)` forms and the stylesheet scan collects `.xpgt` page
97
+ templates, so styled tags keep their unwrap protection; watermark
98
+ normalization decodes entities (`OceanofPDF.com&nbsp;` stamps now
99
+ match); the prolog and duplicate-xmlns fixes run under the
100
+ protected-span wrapper; and the archive comment field rides the rewrite.
101
+
102
+ Dry-run validation for this release: the 14 staged top500candidates plus
103
+ the 3 books_to_fix fixtures swept clean (9 accepted, 2 gate-refused
104
+ regressions, 0 errors), and a 200-candidate sample of the real library
105
+ (5,228 EPUBs) under `--all --workers 4` matched the documented verdict
106
+ mix (94 accepted, 84 equal, 16 gate-refused, 0 partial, 0 epubcheck
107
+ errors, 0 unreadable) with zero crashes. Read-only throughout; the
108
+ gate-refused books are the safety contract declining marginal repairs,
109
+ left untouched for manual work.
110
+
111
+ ## v0.31.0 (2026-09-09)
112
+
113
+ ### Cascade: install through cquarry 1.17's set_format
114
+
115
+ - **`--install-to-calibre` replaces the format row through
116
+ `WritableCalibreDB.set_format`** (cquarry 1.17's sanctioned remove+add
117
+ in one transaction) instead of composing `remove_format` + `add_format`
118
+ in a `batch()` by hand. Same contract as before: same `data.name`,
119
+ truthful size, OPF-resync queue, and a database failure still degrades
120
+ to the in-place save with a warning. The cquarry floor moves from
121
+ >=1.9.0 to **>=1.17.0** (`uv.lock` re-resolved), and the failure-mode
122
+ test now injects through `set_format`.
123
+
2
124
  ## v0.30.0 (2026-09-06)
3
125
 
4
126
  ### Phase 8 stretch: concurrent sweep workers
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "bindery-cli"
7
- version = "0.30.0"
7
+ version = "0.32.0"
8
8
  description = "Audit EPUB body text and repair broken EPUBs with deterministic, epubcheck-gated fixes; atomic in-place replacement in a Calibre library."
9
9
  readme = "README.md"
10
10
  classifiers = [
@@ -27,7 +27,7 @@ authors = [
27
27
  dependencies = [
28
28
  "tqdm",
29
29
  "vir-tui>=2.2.0",
30
- "cquarry>=1.9.0",
30
+ "cquarry>=1.17.0",
31
31
  ]
32
32
 
33
33
  [project.optional-dependencies]