The second half of #70's deepening, on the maintainer's discrete charter
approval: four narrowly-bounded opt-in OPF repairs, the Nook cover
attribute swap riding --fix-cover, the advisory a11y analyzer, and a
--diff preview on the repair verb.
- The OPF-hygiene four (#70 item 4). Each targets one bounded defect
and rides the no-worse bar, because none is a schema finding epubcheck
scores.
--fix-ncx-refwires a spine that carries notocattribute onto the manifest's single NCX (exactly one is required; a spine that already carries the reference is never touched).--dedupe-opf-entriesremoves duplicate manifest hrefs and duplicate spine idrefs, all but the first in document order, self-closing items only, with the gate and the spine veto guarding the edges.--strip-empty-identifiersremoves emptydc:identifiershells in both shapes, never the element theunique-identifiernames, and never an identifier's value (the dc: metadata carve-out stands).--fix-spine-mimesnormalizes spine-carried HTML documents' media-type toapplication/xhtml+xml, narrowed to HTML-shaped targets so a genuinely non-HTML spine item is never mislabeled. - The Nook cover swap rides
--fix-cover. A cover meta whosecontentattribute is spelled before itsnamehas the two moved wherenamecomes first; some readers only recognize the cover in that order. - The
a11yanalyzer (#70 item 5). Advisory by contract like completeness and the shell: images missing alt (decorative roles excluded), documents whose root carries no language, the EPUB accessibility metadata's absence, and the link-hygiene shapes a string check can name. It never flags a book and never moves an exit code. --diffpreviews the candidate (#70 item 6). The repair verb prints a unified diff of every text entry the candidate changed, probe or written run alike, per-entry output capped so a reserialized monolith cannot flood the terminal. Display material; the gate never sees it.
Suite: 1220 tests.
The resource graph sees the whole book, and a renamed id stops stranding its accessibility references
The first half of the polish-parity deepening (#70's part 1): four pieces, all behind existing flags, plus the migration lane's first deterministic ports.
- A renamed id keeps its IDREF attributes (#70 item 1).
--fix-id-colonsrenamed ids and their fragment references but leftaria-labelledby,aria-describedby, the tableheaderslist, and label/outputforpointing at the old spelling: a dangling accessibility reference the oracle never names. The rename now syncs those attributes in the same document, token by token; a token naming no renamed id survives verbatim, anddata-aria-*spellings are not the ARIA attributes. - The reference census and the prune see the media elements (#70 item
2).
audio/video/sourcesrc, videoposter,objectdata, and SVGimagehref/xlink:hrefreference archive files exactly the way animg srcdoes, and every pass that reads references missed them:--declare-missing-items' census never saw the files (the RSC-008 repair never fired), the rename and encode rewrites never repointed them (a renamed entry's old references dangled), and--prune-missing-resourcesnever stripped them. The census and the reference passes now cover the kinds, in markup and in.svgfiles, and the prune takes the attribute while the element stays: video and object fallback content is text the author wrote. - Bare CSS imports join the graph (#70 item 2).
@import "sheet.css"without aurl()wrapper rode outside the stylesheet scans; the census and the stylesheet-side rewrite and encodes read it now. mathmlandswitchproperties declare themselves (#70 item 3a). The whole-book census behind--fix-item-propertiesdetectedscripted,svg, andremote-resourcesbut not the<math>element or anepub:switch, so a book carrying either read OPF-014 (the property is required when the feature is present). Both tokens ride the existing EPUB 3 gate.- The 2.0 migration's first ports land (#70 item 3b).
bindery.upgradecarries the OPF guide to landmarkepub:typemapping (the one Calibre's upgrade ships,notesmapping to no landmark) and the rootxml:langtolangsync, as pure functions with their tests. No flag consumes them yet; the 2.0-C flags inherit green paths when they land.
Suite: 1187 tests.
The first minor release of the 2026-12-01 issue sweep's second half: a new verb, a new flag, and the performance work from the vir-tui adoption audit (#66, #67).
bindery fast-sweep(#67). The multi-core JVM census folded out ofscripts/into the installed package, so a PyPI user gets minutes-scale full-library sweeps without a checkout. The harness launches through the same JEP 330 single-file source launcher as the oracle daemon: the JVM compiles the embedded source in memory from a tempdir, so there is no javac step, no--release 25requirement, and no write into site-packages. Path collection rides the library walker, so.caltrashis never swept.--mode audit(the default) prints the CSV thatbindery library --auditconsumes;--mode extract --summaryprints the per-code profile. The retired scripts were removed;build_plugin.pyandrender_repairs_doc.pystay as maintainer tooling.- One styling surface (#66). Every ANSI code bindery emits now comes
from
bindery._ui: the constants areNO_COLOR-aware (any non-empty value disables color everywhere; previously the audit console ignored it), cli.py's direct tqdm import routes through the adapter, and the new tool-level--themeflag pins vir-tui's theme preset (hackerincluded;VIR_TUI_THEMEselects the same way when the flag is absent) for the styled surfaces. On 3.12/3.13 the adapter degrades to local shapes under the same gate. The vir-tui floor moves 2.5.4 to 2.6.0 in this batch: the theme verbs it needs shipped there. - The hot loops stop rescanning (#66). The watermark strip's ancestor walk ran a fresh tag scan from offset 0 per stamp occurrence; on a monolithic document with hundreds of per-page stamps that was quadratic. The scan now runs once per pass and snapshots the open-element stack at each stamp's position, with the same covered-match skip rule the lazy scan's advance carried. The watermark close-tag scanner and the pagination balance net compile their patterns once per name instead of once per call.
- The oracle budget stops reopening archives (#66). The gate computes
its epubcheck budget twice per book (before and after), and each
computation opened the file once more just to count entries. The repair
now reports the totals its own archives already held, and
oracle_timeout_foraccepts them; budgets are unchanged, and a count of 0 (an unreadable archive) earns no entry term exactly as the failed open always did.
Suite: 1154 tests.
Diagnosed from the sweep's five rejecting books (issue #74): every candidate
that renamed a space-bearing entry whose name also carries a literal &
manufactured exactly one fatal and was rejected for the regression.
- The rebuilt reference is attribute text again (#74). The space-rename
rewrite resolves each reference the way the XML parser does (entities
decoded), matches the renamed spelling, and writes the rebuilt path into
the attribute. A filename can carry a literal
&alongside the space the rename targets (Title B&W.png; the Designers & Dragons series' image and chapter names, Thieves' World's spine documents), and the author's original value escaped it. Writing the renamed entry's raw spelling emitted&W.png, which epubcheck parses as an unterminated entity reference (RSC-016 fatal): five books went from 0f/Xe to 1f/0e and the gate correctly rejected every one, leaving them safely unrepaired. The writer's side now escapes the rebuilt path (&,<), the same shape the author's value already carried; the CSS url() variant stays raw because a stylesheet entry is not XML. All five books now accept: the three Dragons volumes land at 0f/1e/0w or better, the 80s volume fully clean, and Thieves' World at 0f/5e/0w.
Suite: 1134 tests.
Three changes from the 2026-12-01 issue sweep's fourth batch: one false verdict on a real book shape, and the two dependency floors the shared libraries earned since the last wave.
- The audit loader no longer reads an extensionless spine as an empty
book (#75). The raw cache keyed on filename suffixes alone, so a spine
document whose archive name carries no extension (the
html_split_000converter shape, declaredapplication/xhtml+xmlin the manifest) was fully decompressed in the CRC sweep and then dropped:emptytextcounted 5 characters on a book with about 830,000, andcompletenessreported 39 blank spine documents on a 40-document spine. Spine and manifest-declared content documents are now cached by membership as well as suffix, and the contamination corpus picks up non-spine declared content the same way. The fix is loader-only: the analyzers' contracts were already correct, they had just been handed empty text. - cquarry floor 1.19.0 to 1.31.0 (#57, #73). The write path
(
--install-to-calibre,audit --tag) gains the batch commit-integrity fixes: a rejected batch commit now compensates like a failed batch (rollback, queue drop, directory cleanup, re-raise) instead of stranding copied format files with no catalog row, and a per-setter savepoint rollback discards the file operations that setter queued. The bump also carries the rename-collision preservation and theset_formatfollow-up fix, so a repair that swaps a file's bytes without changing its size no longer silently skips Calibre's rescan. One behavior change arrives with it: a database lock that outlasts cquarry's snapshot leash (10 seconds) now raises an actionable error instead of serving a snapshot that can read uncommitted rows. The closed-Calibre doors already guard every write path, so only a plain audit run against a busy library can see it. - vir-tui floor 2.5.0 to 2.5.4 (#72).
ui.infokeeps its ANSI color on plain interactive terminals (2.5.1 stopped counting import-time curses capability as TUI activity), and the descriptor-based TTY gate removes a closed-stdout import-crash class the doctor's stack probe could hit. The lock resolves 2.6.0; adopting the hacker theme is the next feature batch's floor move, deliberately not this one.
Suite: 1133 tests.
Six fixes from the 2026-12-01 issue sweep: no data loss in any of them, but a sweep's throughput, two detectors' honesty, and one reporting door were on the line.
- A daemon timeout no longer disables the warm pool for the rest of the
sweep (#63). A per-book roundtrip timeout tore its JVM down and marked
the pool exhausted, so one huge first book on a multi-thousand-book sweep
paid cold-subprocess startup for every book after it, and the stuck book's
budget was spent three times over (the daemon's roundtrip plus two full
subprocess attempts). A timeout now names the book, not the toolchain: the
pool re-arms and the next book gets a fresh warm daemon, and the daemon's
spent budget counts as the first attempt, so the subprocess oracle runs
once and a double timeout still raises the named
OracleTimeout. - The anchorless watermark sweep reads the document, not its lowercase
(#63). The text-signature search ran over
html.lower(), whose case folding can change the length (Turkish'İ'.lower()is two code points), shifting every later offset and slicing the wrong span, so a stamp after one such character survived every repair. The search runs on the document itself with a case-insensitive pattern, matching left to right and splicing right to left like the anchored sweep, which also retires the restart-from-zero rescan per removal. imagescanreads what a viewport actually declares (#71). Any<meta name="viewport">on an image carrier counted as fixed-layout packaging, so a reflowable book whose pages carry the responsivewidth=device-widthmarkup every HTML5 converter emits read as a FIXED-LAYOUT book with a low-resolution problem line. The meta must now declare explicit pixel dimensions, and the viewport spelling elevates only when the carriers dominate the spine and a majority of them declare it: one pixel-viewport cover plate in a reflowable book is neither a fixed layout nor a page scan. The OPF'srendition:layoutdeclaration works exactly as before.- JPEG fill bytes and truncated PNG headers (#61). The dimension
parser read the first
0xFFfill byte as the marker itself (legal before any marker per ITU-T T.81 B.1.1.2), misread the real segment length, and leapt past the SOF header, so encoders that pad markers answered "dimensions unknown" in the fixed-layout width line. The marker scan now skips fill runs, stops at EOI/SOS, and skips stuffed bytes; a truncated PNG header answers unknown instead of a short-read height. - The
--auditCSV's counts are the before measurements (#62). The audit-CSV door filtered candidates with the CSV rows but never handed their counts to the gate, so every candidate re-measured its before live (double oracle work) and a no-change book on that door still carried null counts. Found in this sweep's bar-change dry run over the real library, and the no-change reporting verified against it: 20 residual books surfaced with their census counts on this door. - An out-of-range
--idwarns and skips (#65). SQLite binds signed 64-bit integers; Python'sint()accepts wider decimals, and the binding's OverflowError aborted a whole scoped sweep with a traceback. The id now follows the same skip-and-warn policy as any other unresolvable id, and the rest of a mixed list stays eligible.
Suite: 1130 tests.
Two correctness fixes from the 2026-12-01 issue sweep, both in the verdict and reporting layer the batch consumers read.
- A no-change book keeps its sweep measurement (#62). A sweep candidate
whose findings no bindery fix targets (an unknown attribute, say) produced
no repair edits, and the no-change outcome dropped the measured counts:
before: null, after: null, exit 0. An operator or an automated intake reading the documented contract (0 = all clean) was told an unsupported finding was absent, and the evidence was unrecoverable from the JSON. The no-change outcome now carries the sweep measurement (the file is unchanged, so its before counts are its after counts), a measured error or fatal on such a book drives the trouble exit, and the JSON exposes the counts, and the per-book console output prints a NO-FIX line naming the book under its measurement.run phase1names such a bookproblem(a clean-labeled batch that still exits 2 would name nothing), and--help-json's exit contract carries the class. Warnings-only residuals stay clean. The standalonerepairprobe keeps its unmeasured nochange, andrepairnever exits 2. - The acceptance bars hold their order (#68). The
refs_delim_encodedbar ran last and unconditionally, so a firedno_worsebar's rejection (a lossy strip whose candidate regressed the error count) was silently overwritten toacceptwhenever the encode also fired on a fatal-free candidate. The delimiter bar's override now reaches exactly the gate's own error-rise rejection, which is the missing-file mask promotion it exists for; a strip bar's rejection stands. And the--strip-broken-anchorsid pre-pass now runs the same single content-doc pipeline as the repair loop, where it used to replicate a seven-transform subset by hand: five later transforms (the structural repairs' siblings, the watermark and pagination strips) could move or delete an id the snapshot still counted alive, leaving a dangling fragment the oracle never flagged. A new content-doc fix joins the pipeline once; both consumers pick it up.
Suite: 1120 tests.
Four correctness fixes from the 2026-12-01 issue sweep, three of them in paths that could touch bytes they should not.
- The prolog strip no longer deletes visible text (#58). The prolog
transform ran its "remove bytes before the first
<" rule on every span between comments and CDATA sections, so the words between a mid-document comment and the next tag were amputated as "prolog". A book with an independent repairable error (a bare&) passed epubcheck after the loss and could be applied. The scan is document-scoped now: prolog is only the bytes before the document's first markup token, and a leading comment or CDATA section counts as a token, never as junk. - An explicitly empty
--idis a usage error, never a whole-library apply (#64). The flag defaulted to"", so--id ''(an unset shell variable, a generated argument) was indistinguishable from an omitted flag, and a nominally scoped--applysilently expanded into the unscoped tree walk. Omission is the sentinel now; an empty, whitespace-only, or comma-only value exits 1 before any candidate is measured, and the empty value no longer bypasses the--id/--auditconflict check. - Backups are keyed by source file (#59). The mirror key was the book
directory name alone, so two same-named books in different subtrees shared
one rotation, and re-backing either up could delete the other's only
original. Slots now live under
DIR/<book directory>--<digest of the resolved source path>/: same-named books never share a rotation, a backup directory reused between input roots cannot confuse originals, and a symlinked library root keeps the same slots as its real path. Pre-1.3.1 layout directories are never adopted or deleted; an original that lives only under an old-layout directory must be recovered by hand. - A case-variant stray can no longer rewrite a catalog row (#60). The id
resolver's index keys are lowercased, so a stray EPUB whose name differed
only by case resolved to the catalogued book, and
--install-to-calibrewrote the stray's size over the catalogued row and queued the book for OPF regeneration. A catalog write now requires the repaired file to BE the catalogued file (samefile): two spellings of one file install normally, a case-distinct stray gets the ordinary in-place repair, and the row stands.
Suite: 1111 tests.
The first MINOR release since 1.0: two additive surfaces and one decision fix, all in the acquisition pipeline the run verbs serve.
imagescan: the page-scan and fixed-layout analyzer (#43). An AZW3 converted to EPUB as low-quality page images passedbindery auditandbindery run phase1as CLEAN and had to be found by hand after import. The new analyzer counts the spine documents that are full-page image carriers (an image carrying under 200 visible characters), reads the fixed-layout signals (rendition:layoutpre-paginated, a viewport meta), and parses image dimensions from bounded header reads (PNG IHDR, GIF screen descriptor, JPEG SOF; the bytes are never retained). A spine that is at least 60% image carriers over at least 8 documents is flagged IMAGE-PAGE BOOK; a declared fixed layout stays advisory, with the median page-image width as the quality line and a width under 800px flagging.- Honest phase1 apply decisions (#44). The dry run labeled every
pending book
apply_lossy, even when the queued repairs fired no lossy strip at all (image alt text, media types, the page-list class), and the documented follow-up command omitted--all, so it applied fewer fixes than the run previewed. The decision now splits:apply_lossyfor books a lossy strip touched (the consent flag exists for exactly those), andapplyfor the rest, advising the exact stage-2 command (library --sweep --only all --all --apply). CalibreQuarry's mirror is unaffected: it keys on the per-book fix data and the top-level consent flag, not the decision label. --fix-opf-scheme: the EPUB 3 identifier repair (#45).opf:schemeis EPUB 2 vocabulary; under the EPUB 3 rules epubcheck rejects it (RSC-005, attribute not allowed here), typically aftercalibredb embed_metadatarewrote the package. The flag drops the attribute from every<dc:identifier>, which keeps itsid; on an EPUB 2 package the attribute is legal and the flag removes nothing, and an unknown package version licenses nothing.
Suite: 1097 tests.
Issue #49's three defects were all the same disease: a pass reading one
layout while holding the other's existence set, under --encode-url-spaces
co-firing with the delimiter, bracket, stub, and declaration passes.
- The encodes run after the rewrite. The delimiter and bracket encodes
ran before the space-rename rewrite while checking the renamed layout, so
an entry named
Ch #01.xhtmlwas never delimiter-encoded (its raw-space spelling missed the renamed set), the rewrite then missed it too (the raw#split a phantom fragment), and the space encode broke the reference against the renamed entry. The encodes now run after the rewrite in all four branches (NCX, OPF, content, CSS), resolving against the output directory, and the rewrite itself retries the whole reference as a path when the fragment split misses: the reference ends upCh_%2301.xhtmlbeside the entryCh_#01.xhtml, and epubcheck agrees. - The stub subtraction reads renamed spellings.
anchor_presentand the ids-by-document map carry the renamed layout, but the dropped-stub set was subtracted in source spelling, so a stub namedstub 1.xhtmlsurvived the subtraction and its dangling links read live. The subtraction renames the set to match. - The undeclared census reads the pre-rename layout. The census
inspects the archive's source references, so its existence set is the
source layout: a percent-encoded reference (
img%201.jpg) now resolves against the raw-space entry it denotes and the declaration fires. The raw-space reference itself stays skipped: that is the encode family's repair target, never a guess, and membership compares percent-decoded spellings on both sides, never twice.
Suite: 1087 tests.
Three fixes in how the repair engine treats entries that are not plain XHTML, from the issue sweep.
- The strip reads documents by name (#46). The per-document numbering verdicts were consumed through a positional counter that never advanced when the copy loop skipped an entry early: a dropped stub, a replaced container, or a non-UTF-8 skip shifted every later document's verdict. The shift defeated the issue #38 guard and stripped the first canto's verse numbers (the fixture: two cantos with shared standalone numbers and a stale container). The lookup is by archive name now, exact however many entries the loop skips.
- Non-HTML
.xmlsidecars never receive the HTML transforms (#55). The defaultself_close_voidrewrote any element whose local name matches an HTML void tag, so apage-map.xmlcarrying<link>keep</link>became<link/>keep-- broken XML -- under the default flags. Content dispatch now runs through one predicate: a.xmlentry is a content document only when the manifest declares it XHTML or HTML, or its own bytes carry an<htmlroot;META-INF/entries are never content, and the strip's collection and the copy loop read the same predicate. --reserializeverifies its own round trip (#54). A broken XHTML page carrying inline SVG or MathML reserialized with the reserved namespace bound to a generated prefix (xmlns:ns1="http://www.w3.org/2000/xmlns/"), a fatal namespace error every strict parser rejects. The recorded xmlns attributes in the reserved namespace are dropped, the standard foreign prefixes (svg, math, xlink, epub) are kept readable, and the rebuilt document must parse before the repair is claimed: a rebuild that fails its own parse is refused, never written.
Suite: 1083 tests.
The last batch of the sweep's matching-integrity work closes every defect the v1.2.9 documentation pass had filed as a known limitation (#39, #40, #41) and two more of the same class the sweep found (#47, #48). The Known limitations section is gone from AGENTS.md because there is nothing left to list.
- Rewrites land inside real start tags only (#47). Three opt-in transforms
matched attributes over whole-document text:
--fix-id-colonsrenamed theid="sec:1"quoted in a paragraph of prose and inside escaped code samples;--fix-duplicate-ids(and the SVG half) read anid='c1'spelled inside another attribute's quoted value as the element's id and renamed the phantom;--strip-invalid-valuedeleted avalue="x"that lived inside a tooltip. All three now find attributes with one sequential walker (walk_attrs), which consumes a tag's attributes in order and can never read inside a preceding quoted value. The NCXcontent srchalf of--fix-id-colonsuses the same walker. - A self-closed script no longer derails the stray-close scan (#48).
fix_stray_closechecked the raw-text rule before the self-closing rule, so a legal<script src="a.js"/>sent the walk leaping to a later</script>: every start tag in between was never pushed, and their closers (a real</body>included) were deleted as stray. The self-closing check runs first now. - The double-colon match stops at its own escaped bracket (#39). The
tail ran to the first raw
>, so a pseudo-tag whose closing bracket was entity-escaped (<b::c ...>) ran past it and escaped the next real tag too. The tail now terminates at the construct's own bracket, raw or escaped, and keeps the 120-character runaway budget. - A headless document keeps its SVG titles (#41). The empty-title fill
was scoped to the
<head>only when a head existed; a document without one was filled document-wide, and an empty SVG<title>(the image's accessibility name) received "Unknown". The no-head path still fills document-wide but skips every closed SVG span. - The watermark fallback demands the stamp's own text (#40). The inline fallback deleted any tag-free body of at most 120 normalized characters when the href looked like a stamp, so a short sentence that merely sat inside a stamp link died with it. The body must now carry the stamp's own text; anything else is refused and counted for manual repair, exactly like an oversized match.
Suite: 1076 tests.
Three fixes in the audit surface, from the issue sweep. bindery audit stays
read-only; what changed is which books print, fail the run, and take the tag.
- A shell advisory no longer crashes the run (#50). The library report
appends four-element rows (book id, title, tag, analyzer result) for every
advisory, and
_shell_sectionsunpacked three of them, so one shell book in the library raisedValueErrorafter the whole scan and lost every report and tag behind it. It unpacks four now, exactly like its four sibling advisory sections. - A DRM-encrypted or broken-obfuscated-font book fails a library audit
(#51). The archive verdict already said
problemand the JSON record carried it, but the console collection keyed on the corrupt count alone, so a book whose unreadable entries are all encryption declared read asarchive CLEAN, exited 0, and never took--tag. Collection is verdict-driven now, and each hit carries the verdict's own lines, so an encrypted book prints its ENCRYPTED story instead of a corrupt count. The readable-obfuscation OBFUSCATED advisory stays benign. - An entry refused at the size cap is archive damage, not empty text
(#52). The 32 MiB refusal was recorded into a local list that nothing
ever read: the book reported
archive CLEANand its oversized spine document read as empty text (EMPTY). The refusal lands inbook.corruptnow, so the archive verdict names it. The read itself is bounded at the cap (a lying central-directory size cannot buy an unbounded decompression), the blob cache keeps only text surfaces (images and fonts were held in memory for nothing), and the DOCTYPE and ENTITY refusal scan covers the whole blob in ASCII and both UTF-16 spellings instead of the first 4 KiB of ASCII.
Suite: 1065 tests.
Three correctness fixes from the issue sweep, each in a surface that guards the library. Also riding this release: two doc commits that landed on main after v1.2.9 (a test pinning the patchnotes entry shape and the flag inventory in the prose docs, and a short CONTRIBUTING.md).
- The backup ring copies before it rotates (#56).
make_backupdeleted the oldest rotating backup before copying the new bytes, so a disk-full during the copy destroyed a backup and wrote nothing. And--backup-keep Ncould not trim a book that already held more backups than the cap: it removed one file per run and let the set stay over the cap forever. The copy now runs first, so a failed copy leaves every existing backup in place; the rotation moves run only after the new bytes are on disk; and a book over the cap trims down to it. The author original.bakis still never touched by the cap. - An
equalrepair writes nothing (#42). The rescue form (repair SRC DST) had noequalbranch, so a candidate that changed bytes without changing the epubcheck counts was written and reported asrepaired. The probe form and the library sweep already write and apply nothing on equal; the DST form now does the same, printing the measurement and exiting 0. This closes one of the four documented known limitations; #39, #40, and #41 remain. - A failed observe census refuses instead of lying (#53). A crashed or
misconfigured census JVM surfaced as exit 0 with a valid-looking artifact
claiming every book unreadable:
run_censusbackfilled every missing answer before the partial-census guard could fire, and itstimeout_sonly bounded the wait after the stream had already ended. A nonzero JVM exit now raises, andrun_observeprints the JVM's own diagnostic tail and exits 2, the documented harness-failure contract. The time budget now bounds the census while it streams (a watchdog kills a hung JVM), and the repair preview honors--limitthe same way the census does.
Suite: 1061 tests.
The documentation had grown by appending dated narrative to every file
instead of being rewritten in place. An audit on 2026-11-24 measured it.
AGENTS.md was 67 KB, with nine lines carrying 58% of it and 126 version
references. The roadmap had regrown to 60 KB, six weeks after its previous
minimization. spec.md opened "Library replacement" with an intro line and no
body, omitted audit shell and audit's exit 3, and said max_log_mb: 0
disables logging when it only disables rotation. And the flag reference
existed twice, as the CLI's long help and as docs/repairs.md, two hand-written
paraphrases that had drifted apart on six flags. This release is the cleanup.
Behavior is unchanged apart from help text and the --help-json payload.
- One flag reference. The long help in
_REPAIR_FLAG_TABLEis now the canonical text for all 45 opt-in flags: both paraphrases merged, every rule kept, version and issue numbers left to this file. docs/repairs.md is generated from the table (scripts/render_repairs_doc.py) and pinned to it by tests/test_repairs_doc.py, the same pattern as the plugin zip. The six stale help strings are corrected: the downgrade list lacked nav and header, item properties lacked svg and the form trigger, pagination said three safety nets, id-colons described only colons, and the delimiter encode and the dead-font drop omitted keep rules the code enforces. - The reference was verified claim by claim. An independent pass checked
every statement against the code: 35 flags confirmed, 6 imprecise, 4 false
against a documented safety rule. The documentation now states what the
code does, and the four gaps are filed: #39 (
--fix-double-colon-tagscan escape the next real tag), #40 (the watermark fallback deletes any short tag-free stamp link, whatever its text), #41 (a document with no<head>fills an empty SVG title), and #42 (repair SRC DSTwrites a no-gain result). AGENTS.md lists them as known limitations until they are fixed. - spec.md states present-tense behavior only. The hollow Library
replacement section now carries the write contract (atomic replace,
backups, the two metadata.db doors).
audit shellis in the verb signature and described. Audit's exit 3, the oracle budget and retry, minimum Calibre 7.0, the cover analyzer's OPF-relative resolution, and the 32 MiB entry refusal are stated.--reserializemoved into the flag inventory, and the acceptance bars are stated once, in the gate section. - README.md is the manual: a contents list, a quick start, one section
per command, an epubcheck-code-to-flag table, an exit-code table, and
troubleshooting. "Nothing runs ungated" contradicted the Install section
and is corrected.
audit shellis documented there and in docs/audits.md. - AGENTS.md is rules, decisions, and constraints (67 KB to 32 KB). It absorbed the roadmap's decision records and records the docs layout.
- roadmap.md is the plan plus a one-line-per-batch ledger (501 lines to 280). Open items are rewritten to their current state, and the 2.0 plan's groundwork text no longer describes epubcheck 5.4 as side-by-side.
- Help surfaces. The package and audit module docstrings and audit's help
say ten analyzers, not nine.
--help-json's exit contract gains observe and run phase3, and its exit-1 line no longer says the library and run verbs exit 1 on trouble (they exit 2). The new test module rides CI's 3.12 and 3.13 leg. - Logo and screenshot. The logo is an open book with a sewn gutter, gold thread on the Kanagawa tile. The README screenshot is a real dry run over a synthetic library with invented titles. The old one showed real library titles and Calibre ids; regenerating it had been an open roadmap item since September.
- Housekeeping. docs/OBSERVE-RESEARCH.md moved to docs/research/observe-error-code-surgery.md, with a stub at the old path because published entries below link there. project.done is removed (the September completion report; its decisions live in AGENTS.md). Em-dashes are gone from every document that is not a frozen entry.
Suite: 1046 tests.
The stub drop's existence set reaches the prune: links into dropped stubs read as absent (the Goldfinger ten)
The first real work v1.2.7 unblocked exposed the fifth member of the same
defect family. A scoped dry run over the ten library books whose repairs had
been gate-rejected since the stub strip shipped (Goldfinger, both Dexters, The
Eye of the World, three Robin Hobb books, The Elegant Universe, Surely You're
Joking, Mr. Feynman!) still rejected all ten: 0f/3e -> 0f/29e on Goldfinger.
The manufactured errors were never guide references on these books -- they are
surviving content documents LINKING into the dropped stub docs (split_054's
<a href="..._split_002.html#filepos476">): --prune-missing-resources
kept every one because its existence set (present) still described the
SOURCE archive, where the stub files exist. The drop removed the files; the
prune's set did not follow; the candidate carried one RSC-007 per dropped
doc, and the gate refused.
The fix: the prune's existence set is now the stub drop's set
(anchor_present / anchor_present_src = present minus stub_hrefs,
wired at both prune_missing_resources_doc call sites), and the dropped
docs' id sets leave ids_by_doc so no fragment cleaner reads against ids the
drop is removing. The rename/encode passes deliberately keep the full sets
(they read the SOURCE layout by design; the #10/v1.2.2 layout rule). The
href strips and the anchor text stays, which is exactly the
--prune-missing-resources contract.
Result: all ten books repair accepted (Goldfinger's 26 dangling links strip; the stub shells' own malformed-XHTML mass leaves with them). Alongside, the damage audit these books prompted answered the question that motivated it: no library book was ever damaged by the v1.2.7 defect classes -- the only two books a stub drop ever applied to (You Had Me at Hola, 41 docs; The Age of Innocence, 3 docs) carry zero orphaned images, resolving cover references, and full prose, and every candidate that manufactured errors was REJECTED by the gate, untouched.
Suite: 1044 tests.
The EPUB2 fixes read a prefixed package, image carriers keep their placeholder text, and every prune drops the guide references it orphans (the Morimoto cookbook)
A new testing_facility book (Mastering the Art of Japanese Home Cooking, an
oceanofpdf-flavored EPUB 2.0 package carrying EPUB3 markup) rejected --all
with a rising gate: 0f/8e/0w -> 0f/11e/0w. The gate held; the repair pass
itself had manufactured the regression it was rejected for. Three defects, one
shared lesson (the book now repairs accepted, 0f/8e/0w -> 0f/3e/0w):
- The version gate reads a namespace-prefixed package element. The book's
OPF declares
<opf:package version="2.0">and_PACKAGE_VERSION_REmatched only bare<package, sopackage_version()returned None and--strip-epub3-attrs/--downgrade-epub3-tagswent inert on a book whose uncapped error mass was 2,507 epub:type + 137 section + 5 nav + 1 hidden. The issue #20 matcher lesson (package matchers accept the prefix) now covers the version read too. - The stub drop keeps image carriers whatever short text they carry. The
v0.47.0 image-carrier exemption required EMPTY body text; the oceanofpdf
shells stamp a one-line ad link on every page they gut, so the COVER and
TITLEPAGE -- image carriers the book needs -- counted as the stub class and
dropped with 74 real shells.
_stub_is_image_carriernow keys on the<img>/<image>presence alone, and carriers stay out of the license count and the returned set (placeholder text on an image page never licenses a drop). The audit side deliberately keeps its empty-text rule: an ad-stamped gutting still reads as the placeholder class it is. The Morimoto spine: 76 docs dropped pre-fix, 51 after -- 23 gutted-but-illustrated pages keep their images. - Every prune drops the guide references it orphans. The stub drop removed
the cover's manifest item while the OPF guide still named
text/9780062344397_Cover.xhtml: 2x OPF-031 + 2x RSC-007, four of the candidate's net-new errors. The newprune_guide_refs_todrops guide<reference>elements whose target path a prune removed (the stub cascade) or whose absence a prune confirmed (the manifest prune, the shell prune), wired beside the id-edge rewrite on all three cascades and comment/CDATA-protected like the guide's own fragment fixer. - nav and header join the downgrade map. nav joined on the named RSC-005
finding ("element nav not allowed anywhere"; the toc/landmarks/page-list
navs of the EPUB3-on-EPUB2 conversion class). header joined through the
unmasking door: epubcheck never reported it while the enclosing illegal
<section>held each file's parse, so the source census showed no header findings and the section->div repair surfaced 91 of them -- one gate pass must converge, not trade one named class for another. Both follow the section rules (block children kept, the semantic name lands in class, stylesheet protection book-wide: this book's ownnav#toc olprotected its navs, so those two findings stay, honestly, beside the charter-kepthiddenattribute).
Suite: 1043 tests.
The pre-v1.2.5 damage audit (prompted by the All About Cake REJECT) asked which library books the strip had ever touched and whether the old gate could have missed damage. Structural damage never applied: five books were REJECTED on every historical run (The Sheik 205 blocks, The Prelude 999, The Science of Good Cooking 1,770, Strange Code 12, The Tangled Web 1). But two applied books carry real, minor damage the gate could never see, because epubcheck measures well-formedness, not content semantics:
- Don Juan (62 stanza numbers, issue #38). The verse class: stanza numbers sit between blank-gap paragraphs in plain prose flow, and an enjambed stanza (Byron's comma-ended or lowercase-started stanzas) is the exact verse analogue of a page-number sentence interrupt, so both baked signals fired. The removals were delete-only: the stanza text is 100% intact, but 62 of 2,011 stanza numbers are gone (63 gap sites in the current copy; the selection-effect proof is that 0 of 1,859 surviving adjacent stanza pairs follow a comma-ended stanza while 45 of the 63 gap sites do).
- Roman Blood (one welded sentence). The source OCR had page 145 both glued into the sentence and duplicated as a standalone paragraph; the old confident-merge welded the sentence around the leftover, and the applied copy reads "instead it's some rich 145 man down in Rome who comes up twice a year to play farmer." -- one stray number embedded mid-sentence. The second merge in the same book ("By Hercules," / 190 / "he said") was correct, and v1.2.5's flat-corridor gate now refuses both shapes.
v1.2.5 does not fix the verse class: stanza numbers sit in genuine prose flow
(blank gaps), so the flow gate never fires, and no text-shape signal can tell
an enjambed stanza's number from a real page bleed. The discriminator is
book-level and order-independent: stanza/section numbers restart per unit,
so their values reappear across documents; page numbers are unique by
construction (pages never repeat). collect_internal_numbering flags every
document whose standalone-number values are substantially shared with other
documents (>= 25%), and the strip takes no numbers from a flagged document;
detect_page_layer excludes them from both license signals. A single-document
book can never be flagged; front matter that restarts arabic numbering at 1
gets protected at the cost of missing those page numbers, never at the cost of
stripping verse numbers. The paginated shape keeps working: Roman Blood's
per-doc page ranges are disjoint, so its docs are never flagged, and the dense
page-layer fixture (unique values between many paragraphs) is untouched.
Re-run verification against every book the strip ever touched: Don Juan 0 (19/45 canto docs flagged), Kwaidan 0, Other Worlds Than These 0, Roman Blood 0, All About Cake 0 -- no behavior change on any current library copy. Kwaidan and Other Worlds show no damage signatures; their historical removals were genuine page furniture. Both damaged books stay as-is per Brandon's call; the full audit trail lives in issue #38.
Tests: the internal-numbering class (canto docs flagged, disjoint page values never flagged, front-matter restart protects the front doc only, verse numbers survive both strip paths, paginated prose still strips beside verse docs, the detector self-computes its flags) and a skip-gated regression over the real Don Juan copy asserting the strip finds nothing. Suite: 1031 tests.
The testing facility gained a new fixture on 2026-11-20: All About Cake
(Penguin Random House, 138 MB), and the phase-1 sweep REJECTED it. The
--all candidate regressed 0f/1e/0w -> 1f/2e/0w: a net-new RSC-016 fatal
(an unterminated element where a table used to open) plus new RSC-012
broken-fragment errors, and the gate correctly refused to apply it.
Isolating the fired flags one at a time pinned the whole regression on
--strip-pagination alone; every other fix came back clean.
The strip's text-shape signals are blind to structure, and this book is nothing but structure. Three failures compounded:
- The merge swallowed a table (the fatal). A recipe-intro paragraph
followed by the ingredient table and a lowercase cell after it read as a
confident interrupt (
lower_cont), and the merge splice[first.start, last.end]replaced everything between the two prose paragraphs with one merged<p>-- including the<p class="rec_line"/><table><tr><td>opener run the block model never saw (_P_REcannot match a self-closing start, and<table>markup is not a block at all). The rest of the table survived as orphaned closers behind the merged paragraph. Character conservation passed (the consumed markup carries no visible text) and the p/a tag-balance net passed (it reads only two names). - The page layer licensed a recipe sweep. Hundreds of bare-digit
quantity cells (
<p class="rilf">5</p>) satisfied the ">= 20 standalone arabic numbers" signal and lowercase ingredient cells satisfied the interrupt signal (4 "confident interrupts" book-wide), sodetect_page_layerfired and the aggressive path deleted 110 blocks of ingredient quantities. - The runhead classifier harvested the cells.
1 tsp,large eggs,110g: short non-numeric text repeated >= 8 times across a cookbook is exactly the running-header signature, and the cascade dropped them as page furniture hugging the deleted digits.
The fix is one principle applied at every destructive decision point:
prose flow. A number block sits in prose flow when at least one of its
immediate gaps (to the previous or next block) is pure whitespace; a digit
enclosed by foreign markup on both sides (a lone table cell) is layout
content, never page furniture, and one-sided furniture (the issue #31
divider-adjacent shape) stays in scope. A confident interrupt additionally
requires a flat corridor -- every gap between the prose, the number, and
the continuation prose is whitespace -- so the merge splice can never
consume markup the block model does not own (a self-closing divider inside
the corridor now degrades the merge to delete-only instead of swallowing
the divider). The runhead cascade only reaches runheads in the number's own
prose run. On the real bytes the signals now score zero across the board,
the sweep never licenses, and the strip finds nothing to remove: the book
reads accept.
A fourth safety net rides in _safe: the splice may not change ANY
element's open/close balance (the all-tag delta net). The p/a net reads two
names; the table-opener loss sailed straight through it. The net compares
per-tag deltas, not absolute counts, so a pre-existing stray close keeps
the strip running instead of reading as a splice error.
Tests: the prose-flow gate class (the table-boundary merge refused, cell digits never swept and never licensed as a layer, divider-adjacent numbers still swept but never merged, the runhead cascade stays inside the prose run and still works inside it), the delta-net class (a foreign-tag balance change refused, a pre-existing stray close tolerated, a legitimate merge clean), and a skip-gated regression over the real facility fixture asserting the strip finds nothing to remove. Suite: 1024 tests.
Every EPUB whose package document lives in a subdirectory had its cover
judged cover file absent from the archive: the analyzer resolved the
manifest item's href against the archive root instead of the OPF's own
directory. Manifest hrefs are OPF-relative by specification, so on the
common publisher layout (OEBPS/content.opf with the cover at
OEBPS/Images/cover.jpg) the lookup missed, and 6 of 8 EPUBs in the
2026-11-18 cookbook batch read as coverless while their covers sat exactly
where the package said they were. The analyzer now resolves through the
loader's own OPF path (the same basis the spine resolution already uses),
keeping percent-decoding, fragment stripping, and path normalization. The
inverse hazard is covered by test: a root-level image can no longer satisfy
a nested package's cover reference.
Fix adopted from PR #37 (OpenDeernet) with its test matrix: both EPUB 2
meta and EPUB 3 properties="cover-image" wiring, nested packages,
parent-relative hrefs, percent-encoded names, fragments, and the
root-image negative case. Audit reports only; no repair or gate behavior
changes, and the record vocabulary is additive (Book.opf_path).
Suite: 1014 tests.
The oracle moved and the observatory had to follow it safely. epubcheck
5.4.0 caps serialized JSON message entries at 25 per ID-and-text
combination by default (the new --maxOfEachMessage option). The observe
census counts those entries and their summed locations, so the default cap
would have silently shrunk repetitive-code books and poisoned every
--against trend diff taken against 5.3.0-era artifacts, which had no cap.
ObserveSweep now pins the uncapped scale before generate(). The repair
gate was never exposed: its counters come from the checker totals block,
not the messages array.
The pin itself had to survive compilation. The census harness compiles
against the resolved jar's classpath, so a direct call to the 5.4-only
setMaxOfEachMessage setter failed compilation outright on any pre-5.4
oracle and killed the whole census JVM: every book surfaced as "unreadable"
in a clean, exit-0 artifact (live-replicated against the 5.3.0 jar: 3 real
books, clean 0, unreadable 3). The call now goes through reflection: it
compiles against any classpath, lifts the cap on 5.4 and later, and no-ops
on older oracles, which are uncapped by nature. Verified identical counts
under both the 5.3.0 and 5.4.0 jars.
The release also carries the day's records: the roadmap's 2.0 program (the
library updater, planned and decided) and the 2026-11-20 opportunities
census (four measured 1.x roads with specimens), and 2.0-A marked partially
done: epubcheck 5.4.0 is the machine's default oracle with update_epubcheck
added to the update suite, and the baseline observe ran under the 3.4 rules.
Suite: 1012 tests.
One specimen, two fixes. The Flux amputation (live in the 2026-11-17
mega-batch: dead_spine_items_pruned:31 on a book whose archive carried
every document, spine applied down to a lone 758-byte title page behind
which 31 content docs sat unreachable) had a root cause in the census and
a hole in the gate, and this release closes both.
- The shell census reads the layout its hrefs are written in (the
v0.52.0 lesson, census edition). The
--prune-dead-spinecensus checked each manifest href against the renamed output layout and consulted the raw source layout (present_src) only for the #26 delim variant, so whenever--encode-url-spacesco-fires, every raw-space href "misses" and reads dead. Flux measured a 97% shell signature (31 of 32 content items) on a book whose files were all present under the spellings its hrefs carry; the census now consults the source layout for the plain href before judging an item dead, because an item whose file exists in the layout its href is written in is the rename pass's repair class, never prune material. The diagnosis also explains the issue's off-by-one clue: pre-fix, the prune amputated the documents whose references the rewrite pass would have covered (30 rewritten instead of 61). Flux now repairs cleanly: 31 entries renamed, 61 references rewritten, zero items pruned, zero dangles. - The half-spine veto:
process_book's structural veto gains its second arm beside the #10 spine-collapse check. The dangle-count veto is blind to a prune: pruning removes the dangling declarations along with the rest, so an amputation LOWERS the dangle count to zero while epubcheck measures an error win on the smaller book (Flux measured0f/38e/31w -> 0f/30e/0w). The rule, resolved-vs-resolved per the issue's Elminster-rule intent: adead_spine_items_prunedcandidate whose spine resolves to less than half of what resolved before the repair is a REJECT with(spine halved)in the summary, regardless of the epubcheck delta and regardless of which promotion produced the verdict (the entries_renamed no_worse promotion and the #26 missing-file mask both rank below it). Counting documents that RESOLVE on both sides keeps the genuine shell's v0.64.0 contract intact: the Wandering Inn prune drops only never-resolving positions, so the same documents resolve before and after and no veto fires; only a prune that orphans live documents trips the arm. A prune that leaves exactly half the resolution is not the class ("less than half" is strict). spine_danglesgeneralizes intospine_resolution(total, resolved, dangles; the old name delegates), the same fail-open probe contract as before: a package the probe cannot read carries no evidence and vetoes nothing.
Suite: 1012 tests.
Issue #30 (v1.1.1) fixed the three id-attribute matchers, but the pre-commit
review had also flagged two adjacent matcher families sharing the same
\b-fires-after-a-hyphen shape, left out of scope there and filed as issue
#34. This patch release is that cleanup: no CLI surface change, behavior
tightened to what the docs already promised.
--fix-idsedge matchers: thefallback=,media-overlay=, spinetoc=, and bothmeta content=cover matchers infix_manifest_idsanchored on bare\b<attr>=, sodata-fallback="0-item"/data-media-overlay=/data-toc=/data-content=read as the manifest edge attribute; a value colliding with the rename plan would have rewritten arbitrary data while the real edge attribute beside it stayed. All five now carry the(?<![\w:.-])guard (unprefixed-only, the_IDREF_ATTR_REprecedent: OPF edge attributes are never namespaced).- The NCX uid sync and the cover-meta hybrid:
_DTB_UID_RE,_DTB_UID_RE_REV, and_COVER_META_RE's lookahead carried the same shape (data-name="dtb:uid"/data-name="cover"read as the real thing). The same guard lands there;data-name="cover"is no longer wired or removed by--fix-cover, and a data-attribute dtb:uid no longer answers the uid sync. (_EDGE_ATTR_RESand_COVER_CONTENT_REwere already whitespace-anchored and needed nothing.) - Pagination anchor guards:
_ID_ANCHOR_REand_OPEN_ID_REmatched\bid=, sodata-id="page7"-- arbitrary data no reader can resolve -- over-protected a number block from the strip (kept when it should have been removable). The anchor is the #30 class generalized to xml:id now:idandxml:idboth count (xml:id is an id the oracle resolves fragments against, per the v1.1.1 anchor-index ruling),data-idprotects nothing. - The completion pass (the v1.2.1 review probed three more same-class
matchers that still fired, so the release is honestly "every remaining"):
--fix-package-versionrewrote adata-version="1.0"on the<package>element; the guide's cover-statement scan readdata-type="cover"as the producer's cover reference (a misfire, not just conservativeness: a dangling cover meta was re-pointed at the data-type reference's target); andfix_pagelist_class's satisfaction checks accepteddata-class/xml:idas the plainclass/idepubcheck demands, suppressing the insertion the flag exists for. All three carry the anchor now: a data-* attribute never satisfies or triggers, and an xml:id pageList gets the plainidinserted beside it.
Suite: 1002 tests.
Found 2026-11-13 converting four azw3 cookbooks to epub with ebook-convert
before import. The converter carries the source's @font-face CSS
declarations but NOT the font payloads they reference: the output's
page_styles.css and page_styles1.css fill with blocks whose src is the
literal placeholder url(styles/XXXXXXXXXXXXXXXX) -- fonts named in the
source (Dante, Nexa, SourceHan, FreeSans) but never carried over. epubcheck
reports each dead reference as RSC-007 (Referenced resource could not be
found): live counts 149/316/159/450 errors across the four files, 0 fatals.
The gate's --all set never converges them: --prune-missing-resources
works the OPF manifest, and these references live in CSS url(), where no
item exists to prune (the OPF never declared the fonts).
--strip-dead-font-faces(structural repair #35): for every@font-faceblock in a stylesheet, resolve eachurl()reference against the archive (the shared href resolver: XML entities, then RFC 3986 percent-decoding, relative to the stylesheet's directory). A block whose every reference misses the archive is dead by construction -- the font never loaded, so the fallback rendering is what the file already does -- and drops, rendering-neutral. The semantics-preserving guards (the last two from the pre-commit review): one liveurl()keeps the whole block; a scheme, query, fragment, raw space, or empty reference keeps it (never guessed at: first#/?starts fragment/query, so a query-carrying url whose path portion exists is a LIVE reference); alocal()-only block is not this class; a block with nested braces the flat-brace matcher cannot read exactly is refused; and comments are never rewritten -- XML comments and CDATA through the protected-region split, plain CSS comments through a span-intersection check (a}inside a comment truncates the flat-brace match short, and a drop keyed on the match START alone would leave comment garbage in the stylesheet), because dropping a commented-out block is a byte change epubcheck cannot measure that another flag's gain could carry into an applied candidate.- Gate behavior: normal
gate, like the other reference repairs -- the RSC-007 count is the measured gain. Runs on.cssentries only. When--encode-url-spacesrenames entries, the pass judges references against the pre-rename layout (first in the stylesheet branch, before the reference rewrites), so a live font under a raw-space name can never read as dead. - Facility verification (the two pristine converter outputs the issue
attached): scoped-flag gate runs 0f/6e -> 0f/3e (16 blocks dropped) and
0f/5e -> 0f/2e (25 blocks dropped), both ACCEPT, zero residual
RSC-007 -- the remaining errors are other flags' classes (
epub:typescrubs, colon ids) and clear under their own flags.
Suite: 985 tests.
Six defects filed from the 2026-11-16 deep codebase audit, each one live-replicated before the fix. No CLI surface changes: every fix tightens an existing flag's behavior to what its documentation already promised.
--fix-id-colonsfragment sync (#28):fix_ncx_src_fragmentsfollowed the old colon-only predicate, so a digit-led id (<body id="0-25c121ec">) renamed on the content side left its NCXcontent srcfragment untouched and the ToC dangled against the id that no longer existed, and a digit-led COLON-bearing id translated to two different spellings (id_1_introon the content side,1_introin the NCX). The NCX half now uses the same_is_invalid_ncnamepredicate and_ncname_renamescheme as the content ids, and both fragment passes (the NCXsrcand the in-documenthref) carry the quote-tempered idiom: an apostrophe inside a double-quoted value (href="c1.xhtml#Lisey's_story") translates whole instead of truncating at the apostrophe and never translating. Two guard rails came out of the pre-commit review: a fragment carrying an escape (a percent-escape like#caf%C3%A9or an entity reference like#café) is refused outright, because it names its target under decoding rather than NCName spelling and renaming the encoded form would manufacture a target that exists nowhere (undoing this release's own #29 decode match whenever both flags run, which--allalways does); and both matchers are whitespace-anchored with the optional namespace prefix, sodata-hrefanddata-srcvalues are out of scope whilexlink:hrefstays covered.- Percent-decoded fragments (#29):
--strip-broken-anchorscompared raw attribute fragments while the wire spelling of a link to a non-ASCII id is percent-encoded (href="#caf%C3%A9"naming<h2 id="café">), so valid links lost their href; the NCX and OPF guide halves dropped the same valid ToC entries and landmarks the same way. All three cleaners decode the fragment (XML entities, then RFC 3986 percent-decoding -- the same chain the href resolver has always applied to the path) before the existence check. Cyrillic ids (#%D1%82%D0%B5%D1%81%D1%82namingid="тест") survive too. - id-attribute lookbehind guards (#30):
\bid=also fires right after a hyphen or colon, sodata-idandxml:idread as THE id in three matchers: the duplicate-id rename (adata-id="c1"made the realid="c1"a "duplicate" and renamed it away from the fragments pointing at it),fix_manifest_ids(a manifest item'sdata-idwas renamed while its real id stayed), and the anchor indexer (ids_by_doccollected data attributes as link targets). All three now carry the(?<![\w:.-])guardfix_id_colonshas had since v0.32.0. The anchor index keeps a deliberate exception:xml:idis a real XML id the oracle resolves fragments against, so the anchor collection still reads it (a dedicated(?:xml:)?idpattern) while the strict rename matchers exclude it. - Self-closing paragraphs (#31):
--strip-pagination's paragraph matcher matched<p class="divider"/>as a block start; with no</p>of its own the match ran forward to the NEXT paragraph's close tag, welding divider and content into one block whose text could read as a page number and strip real markup with it. The matcher refuses a/immediately before the closing>. - The downgrade's shields (#32):
--downgrade-epub3-tagsran unshieldedre.subover the whole document, downgrading markup inside commented-out sections and CDATA (phantom transform counts, the CDATA invariant broken); it runs throughoutside_protected_maplike every other markup transform now. Its class merge matcheddata-class=and appended the semantic hook to arbitrary data while the element's real class stayed untouched; the matcher is whitespace-anchored. - The declarer's close tag (#33):
--declare-missing-itemslocated the manifest close tag by the literal string</manifest>and silently no-opped on prefixed (</opf:manifest>) or whitespace (</manifest >) spellings; the close-tag matcher now carries the same namespace-prefix tolerance as every other OPF matcher.
Suite: 972 tests.
A raw # in a filename reference defeats its own resolution: the bookmate
conversion of Elminster: The Making of a Mage stamped #01 into 36
filenames, every manifest href parsed as file Elminster_ plus a fragment,
epubcheck read RSC-001 'File ... could not be found', and the archive's 38
documents sat unreachable. The defect's real danger was the gate's answer:
the ACCEPTED candidate was the shell prune dropping all 36 live documents
(0f/3e -> 0f/1e by deleting them, against the encode's 0f/3e -> 0f/6e by
opening them), a 2-doc husk shipping as an error-count win -- the inverse
of the #10 spine collapse, invisible to the dangle veto because pruning
LOWERS the dangle count.
--encode-ref-delims(structural repair #34): percent-encode a literal#/?in internal src/href and stylesheet url() references, under two required gates -- the reference must NOT resolve as written (its path portion, read the way the oracle parses it: first#/?starts fragment/query) and the delimiter-encoded spelling MUST match an archive entry (the issue #19 decode-before-lookup mechanism; entries stay raw-spelled). Working fragments are never touched,a-and-a#bboth-exist keeps the RFC spelling, genuinely missing files stay as written, numeric-entity values are refused wholesale (the entity's own spelling carries a raw#; the verbatim rewrite would corrupt a working reference into a malformed entity), and an empty-path value (#intro) is an in-document anchor, never filename damage.- The shell census guard: the
--prune-dead-spinedead set excludes delim-recoverable items (against the output layout AND the raw layout, closing the co-fired rename hole where output-layout names would miss the raw-spelled variant). The Elminster shape can never cross the 50% shell signature again; a mixed book prunes only the genuine dead. - The missing-file mask bar: when
refs_delim_encodedfires, the keyed promotion replaces the error-cleanup answer -- net-new fatals reject, a still-fatal candidate stays partial, a fatal-free candidate accepts the unmasking rise (documents epubcheck never parsed surfacing their own latent damage); the #10 spine veto still overrides. - The audit says what the archive holds: the loader counts
spine_missing_delimand the shell verdict runs on the genuine fraction -- the Elminster fixture reads ADVISORY naming the encode, never SHELL/re-source; a true shell still reads SHELL. - Two latent gaps closed: the OPF branch dispatch never listed
--encode-ref-brackets, so its documented OPF coverage could not fire on a standalone selection (now listed, pinned by a real-core row); and the stylesheet decode lacked the markup branches' non-UTF-8 guard once the reference encodes select that branch (a windows-1252 stylesheet is copied byte-for-byte,non_utf8_docs_skipped).
On the facility fixture (elminster-hash-in-href-broken.epub, kept
permanently): probe accepts 0f/3e/0w -> 0f/4e/0w with refs_delim_encoded:36,
no amputation, spine dangles 36 -> 0, all 38 documents resolve, and the
audit flips SHELL -> ADVISORY. Suite: 943 tests.
bindery-cli is 1.0. The observatory's final cycle states the mission's completion in numbers: the library's default-pass preview answers accepted 0 / partial 0 / rejected 0 / equal 46 -- the arsenal has nothing left to give on this library -- clean sits at 4,126 of 7,156, error mass at 11,455 (from 16,182 across the session's waves), and the library carries ZERO fatal books. 2,055 books were repaired across the session's waves; every finding class in the census is dispositioned: repaired, detected at intake, or leave-measured with a recorded reason.
What 1.0 means (the stability contract, now a section in spec.md):
the flag surface is additive from here -- new opt-in flags may appear,
existing flags' names and documented semantics do not change; the gate's
improvement/no-worse bars, the spine-collapse veto, and the shell
signature's 50% gate are stable; the JSON record vocabulary, the fix
breakdown, the exit-code contracts, and the observe schema (v2) are
stable, and downstream consumers can pin bindery>=1.0. Predicate
refinements ship documented in patchnotes with oracle evidence -- the
standard this session set (base-free v0.62.0, the doctype narrowing
v0.63.0, both proven against epubcheck before they moved).
This release carries: the shell-% denominator fix (a shell now reads
its true manifest fraction -- 75% for the Wandering Inn shape -- instead
of the resolved-spine-only denominator that read shells at over 100%),
and the 1.0 stability section in spec.md plus the README status line.
The tool itself is v0.64.0's: --prune-dead-spine closed the Wandering
Inn repair (both books live-applied at 0f/2e and 0f/3e from 0f/739e and
0f/742e), and the remaining census is the documented leave-measured
edge.
Suite: 917 tests.
The Wandering Inn feasibility dig proved the recipe on the facility copies (0f/742e -> 0f/5e, 0 fatals, a complete coherent book of its own chapters); this release builds it as a flag. The diagnosis falsified the 2026-10-25 "different spelling" hypothesis: Book 18 and Book 19 carry their REAL, complete chapter ranges (730-742 and 743-755, full-size prose docs) -- the converter shipped the right chapters and wrote the ENTIRE serial manifest, so 738 and 736 of 755/752 manifest items name files that were never this book's chapters. The books are not damaged goods: they are complete books wrapped in another book's manifest.
--prune-dead-spine fires ONLY at the shell signature -- half or more
of the manifest's content hrefs name files the archive does not carry
(the audit battery's shell analyzer, v0.63.0, names the same shape).
At the signature it drops the dead manifest items and the spine itemrefs
that name them, prunes the dead NCX navPoints (the existing
dangling-target prune, coordinated on via a dataclasses.replace), and
re-sequences the surviving playOrders to 1..K. Below the signature --
a lone missing chapter, a broken fragment -- it never fires: the spine
non-goal ("missing spine documents mean corrupt archives or broken
fragments") stays in force for ordinary damage, now with a third,
measured exception: the wholesale shell.
Two live findings the build closed out:
- The playOrder contract is not base-free on the shell shape. The
v0.62.0 base-free clause was built from a minimal matrix that validated
offset runs (448..461-shaped) clean -- but epubcheck 5.3 flagged BOTH
"playOrder sequence has gaps" AND "the first playOrder value is not 1"
on the post-prune Wandering Inn NCX. The oracle rules: the shell
repair re-sequences to 1..K unconditionally (a
forceparameter onfix_ncx_playorder), and the base-free clause's test matrix gains the shell shape as a known divergence. - fix_ncx_playorder gains
force: the shell repair's playOrder half must re-sequence even where the contract reads satisfied.
The proven end state on the facility copy: 0f/5e (from 0f/742e), a complete readable book of its own chapters -- nothing real is lost; the dropped positions never resolved in any reader.
Suite: 917 tests.
Running each v0.63.0 flag alone against its real carriers caught two wiring slips the --all-sized sweeps could never see:
--encode-ref-bracketsalone was a silent no-op: the encode readspresent(the archive existence set), butpresentonly fills when one of the prune/anchors/media-types/declare/prune-NCX flags asked for it -- the new flag wasn't in that guard, so the set stayed empty, every reference resolved to nothing, and the flag answered "no applicable fixes" on a book whose NCX carries 59 bracket srcs (The Given Day:Dennis_Lehane_-_The_Given_Day_[html]_split_000.html). The guard now includes the flag; the live apply encodes 59 NCX srcs, zero raw left.- The audit CLI's
--onlychoices lackedshell: the analyzer shipped in v0.63.0 butbindery audit --only shelldied at argparse (invalid choice). The choice is registered.
Suite: 913 tests.
The 2026-11-04 dig asked the honest question about the remaining 14,109 error mass, and the answer was: not entirely the floor. A stratified family census over the RSC-005 carriers plus live diagnosis of the RSC-001/RSC-020 populations surfaced three repairable lanes, built here with the specimen-first discipline:
--strip-presentational-attrs(the census's largest attribute family): strips the deprecated presentational hints the XHTML 1.1 DTD rejects wherever they appear --align,valign,border,bgcolor,vspace,hspace,compact; body'slink/vlink/alink/text/background(body-scoped;linkon anything but<body>survives);typeon list elements (style/link/scriptkeep theirs); the Amazondata-AmznRemovedscraper junk. HONEST CAVEAT (Brandon-approved 2026-11-04): these are presentational hints, and readers that honor them render differently after the strip.--encode-ref-brackets(RSC-020's 59-book bracket lane, 1,439 messages): percent-encodes raw[/]in the PATH portion of internal references whose target exists -- the issue #19 mechanism (encode-url-spacesonly does it while renaming space-bearing entries, so brackets without spaces were uncovered). Fragments and queries stay raw, entry names stay raw, external and unresolvable references stay as written; runs on content documents, the OPF, the NCX, and stylesheeturl()tokens.--fix-id-colonsbroadened: the predicate goes from colon-bearing to every value_is_invalid_ncnamerejects -- digit-led scraped ids (<body id="0-25c121ec...">, the census's 72-location family), apostrophe-bearing calibre ids (whose content-doc half could never hold the apostrophe: the value charset[^"']+was the issue #3 blind spot again; the matcher is the tempered pattern now). The rename base is the manifest scheme's (id_+ sanitized), fragments sync, and the NCX half (fix_ncx_src_fragments) broadens identically.- The audit battery gains the
shellanalyzer (the Wandering Inn detector, advisory by contract): the fraction of spine positions whose files the archive never carried -- 738/752 and 736/752 on the two shells -- at or over 50% reads SHELL: re-source, never repair. The manual handling of the two shells (Brandon re-sources; the spine guard was CORRECT to refuse) is documented in docs/OBSERVE-RESEARCH.md and the report.
Also moved: the XML NCName check and sanitize scheme now live in
transforms.py (the vendored base), shared by the manifest half and the
broadened content-doc half; _sanitize_ncname stays prefix-free with the
prefix in the callers, so the manifest scheme is single-prefixed.
Suite: 913 tests.
A three-reviewer pass over the v0.62.x range (code review, test-gap map, docs-vs-code audit) converged on one ship-blocking defect and a set of smaller findings; this patch carries every fix.
--fix-item-properties's insertion branch emitted malformed XML (ship-blocking): an item with nopropertiesattribute got the new attribute appended after its self-closing solidus (<item .../ properties="scripted">-- a violation of EmptyElemTag), so the gate rejected every candidate on exactly the books the flag targets. No test had ever driven the branch: every fixture pre-carriedproperties="nav". The branch now appends before the solidus (properties="scripted"/>), a fixture pins the self-closed well-formedness with an ElementTree parse, and the paired-item shape is covered too. The affected books will harvest on the next--allsweep.fix_missing_title's empty-title fill is head-scoped: an empty<title>inside<svg>is the image's accessibility name and hover tooltip -- filling it with "Unknown" is a visible text change the gate cannot measure. The fill now runs inside the<head>section when one exists; a document with no head keeps the document-wide behavior.--fix-double-colon-tags' tail is bounded at 120 characters: a pseudo-tag whose own bracket was escaped (<b::c>, only the leading<raw) would run the lazy tail to the next real tag's>and swallow prose plus markup into display text -- damage the gate cannot always see. Real code constructs are short; the bound keeps any failure local.- The on* handler disjunct is gone from the item-properties census:
\son[a-z]+=lexically cannot tell a handler fromonly=/once=, and the handler demand was never verified against the oracle the way the<form>demand was (tag-off bisection). The census keeps the oracle-verifiedscriptedtriggers (<script>,<form>). _scan_doctype_spanrefuses unterminated declarations: a<met at bracket depth 0 before any>means the next tag has begun and the declaration's true end is unknowable -- the span must not swallow it.- The guide-prune docstring matches the code: both element shapes are removed (self-closed and paired), not "self-closed only".
- The documentation inventories caught up (the drift the reviews
measured): README's opt-in list gains the seven flags it was behind
(two of them since v0.51/v0.59), spec.md's structural section gains the
four v0.62.0 behavioral bullets and the safe-opt-in section for
--fix-double-colon-tags, the body counts read thirty/twenty-seven, and AGENTS.md's inventory carries the five new flags. The v0.62.1 entry's claim that the spec drift was closed was true only of the intro counts; this entry closes the rest of it.
Suite: 895 tests.
An XML name can carry at most one colon (the QName production is
(NCName ':')? NCName), so a pseudo-tag whose name contains :: is
never markup -- every occurrence is unescaped author text, and the
parser dies on it with a fatal RSC-016. The Book of Debugging's C++
code samples carried exactly that: std::vector<std::shared_ptr> with
the template's closing bracket escaped as > but the pseudo-tag
itself raw, at EPUB/xhtml/part3.xhtml:399. It was the library's one
remaining fatal after the 2026-11-03 wave.
The new opt-in flag escapes both ends of the construct, restoring
exactly the text the author wrote. Real markup is unreachable by
construction: the double colon lives in the name grammar itself, so no
legal tag can match, and prose comparisons (a < b) never form the
shape. Nested templates escape inner-first until stable, and the
trailing >s of a fully-escaped nesting stay raw -- legal text that
renders as >. Live on the facility specimen: 1f/15e/0w -> 0f/14e/0w,
the gate accepts, and the book opens again. The unmasked residue
(the OPF-030/048 uid-empty family, the XHTML 1.1 strictness findings
the fatal was masking, and the <int>/<dbghelp.h> header-name
pseudo-tags, which are legal QNames and ride the content-model lane
rather than this one) is the manual list the observatory tracks.
Also closes a spec.md drift the release audit noted: the four v0.62.0 flags join the structural-repairs inventory (now thirty) and this flag joins the safe opt-ins (now five).
Suite: 887 tests.
The 2026-11-03 whole-library observatory run answered the default pass's
0/0/0 (nothing applies, nothing rejects) with two discoveries: twelve
census codes had never been triaged, and the full --all arsenal's 322
rejections were 283 bundles poisoned by two transforms whose firing
predicates outran what epubcheck actually polices. This release carries the
batch that came out of it, every piece verified against epubcheck 5.3 on
real specimens or minimal matrices before the code moved.
The three predicate repairs (the playOrder precedent repeating):
fix_ncx_playorder's contract demanded values 1..K; the oracle polices sharing, distinctness, and gaps and never the base (Age of Innocence validates clean at 0..43; singleton-2, pair-2-3, and offset-5-8 verified). The clause is base-free contiguous now, silencing the 107 no-op renumberings the observatory measured while keeping every real fix.fix_pagelist_classinserts the collision-checked id alongside the class: class-only insertion flipped epubcheck into demanding the id on the element that had just gained the class (Feel Free: bare pageList validates clean,class="pages"alone draws RSC-005 'missing required attribute "id"', id+class validates fully clean) -- the 215-rejection poison. The books that used to regress now measure flat; the ones that used to accept still do.fix_missing_titlefills the self-closed<title/>: the paired-fill branch was unreachable dead code behind the no-op check, so every self-closed shape fell through to injection beside the standing tag (the 70-rejection poison; 84 sampled reject docs, all exactly<title/>, each gaining RSC-005 'element "title" not allowed here').
The four new flags (the never-triaged census lanes):
--fix-package-version(OPF-001, 26 books): rewrites the literalversion="1.0"on the package element to"2.0"-- an EPUB version epubcheck cannot parse. Refuses everything else: the OEB-1.0-namespace package with no version attribute is the designed refusal, and any other spelling would be a guess about the producer's intent. Audition validates fully clean after the bump.--fix-doctype(HTM-004, 135 books): replaces a content document's DOCTYPE when it carries a public identifier its package profile forbids -- EPUB 3 requires any DOCTYPE to be<!DOCTYPE html>(an XHTML 1.x public doctype is a spec violation), and EPUB 2's OPS content docs are XHTML 1.1 (the Hound-of-the-Baskervilles shape: found 1.0 Strict, expected 1.1). Both census shapes verified on facility copies. The first build also inserted a DOCTYPE when absent; the whole-library firing census measured that flat on ~2,400 of 2,545 firing books -- an absent DOCTYPE is legal in both profiles and the oracle tolerates it -- so insertion was removed before release: the flag fires only where the declaration exists and is wrong. A whitespace-variant of the expected form is a no-op, and a DOCTYPE carrying an internal subset is never touched (the subset declares entities).--prune-invalid-guide-refs(OPF-032, 125 books): removes guide<reference>elements whose target is declared but is not an OPS content document -- the Random Housemsrguide block pointing cover/thumbimage references at JPEGs is the dominant fingerprint. The guide is furniture, so removal is content-neutral; a reference to an undeclared file stays OPF-031 (declare-missing's lane), as do external schemes and paired elements. Widdershins validates fully clean after the prune.--fix-item-properties(OPF-014, 74 books): a whole-book census reads what each content document contains and merges the tokens into the owning manifest item'spropertiesattribute, sorted and deduplicated.scriptedfrom a<script>element, an on* handler attribute, or a<form>-- epubcheck 5.3 demands scripted for form documents, proven by tag-off bisection on the Rustonomicon's scraped GitHub page;svgfrom an<svg>element;remote-resourcesfrom an absolute-scheme src attribute, a remote<link href>, or a remote CSS url(). EPUB 3 packages only: the matrix proved declaringpropertieson an EPUB2 item draws the illegal-attribute finding while its OPF-014 demand stands, so the EPUB2 carriers refuse and stay measured. The census's own lane specimen (Rustonomicon) cleared its OPF-014 live.
Suite: 878 tests.
The first whole-library --all dry run (the 2026-11-03 observe lane)
crashed with exit 1 forty minutes in: _decode_numeric_refs raised
ValueError: invalid literal for int() with base 16: 'x2013' inside the
prune's content-doc pass, and the exception escaped the sweep's repair
loop, killing the run and its report.
Two fixes:
- The decoder (epub.py):
_NUMERIC_REF_REcaptured the hex ref'sxinto the digits group (–->'x2013') and the repl fed the whole capture toint(_, 16). XML spells hex character references with a lowercase x only, so the regex was right and the int call ate the x; the fix strips the prefix before the int. The bug sat dormant since v0.58.0 shipped the decode because the resolver runs only on the opt-in paths (prune, anchor strip), so the default pass never met it. Library census: 36 hex-ref hrefs across 5 books, every one an external URL (en-dashes and ampersands in macmillan/tor/techcrunch query strings) that the decode reaches before the scheme check discards it. Five new tests pin the decode, the internal-href contract extended to hex, and the crash shape end-to-end throughstrip_missing_file_hrefs. - The sweep crash guard (cli.py): an unexpected per-book exception is
now that book's
errorverdict (crash (ValueError): ...; not applied), counted in the existing errors tally and flowing to --json like every other record, instead of a run-killing traceback. The unified trouble exit contract is unchanged. The single-file repair verb keeps its traceback: there an operator is watching one book.
Suite: 838 tests.
Space Prison (Calibre book #11556, the Pyramid 1960 scan-conversion rip)
surfaced the defect in a phase-3 sweep: the book's 205-byte shell page
(OEBPS/text00001.html, <body></body> under an XHTML 1.0 Strict
DOCTYPE) made --fix-empty-body flip its own --all candidate from a
clean decrease (0f/6e/0w -> 0f/5e/0w core) into a regression the gate
had to refuse (0f/6e/0w -> 1f/4e/0w --all), the delta exactly
fix_empty_body:1 and the new count a FATAL RSC-016, "The entity nbsp
was referenced, but not declared".
The root cause has two halves, both verified against epubcheck 5.3 with
a minimal-EPUB matrix across XHTML 1.0 Strict / Transitional / XHTML
1.1 / no-DOCTYPE shapes on EPUB2 packages and plain <!DOCTYPE html>
on EPUB3:
- epubcheck validates EPUB2 content docs against the XHTML 1.1 DTD and
resolves named entities only from DTDs it carries locally (the XHTML
1.1 one).
is not one of XML's five predefined entities, so under every DOCTYPE epubcheck does not resolve locally -- XHTML 1.0 Strict and Transitional, and no DOCTYPE at all -- the injection was an undeclared-entity parse fatal. EPUB3 is no refuge: XHTML content documents are validated as XML there too, and is fatal under every DOCTYPE shape tested. - The XHTML 1.1 body content model is block elements only, so bare character data (named or numeric) never satisfied it anywhere: the error the fix was named for ("element body incomplete") never cleared. The old injection therefore never once applied under epubcheck 5.x -- every run was either a fatal-regression reject or an equal-noop -- which is why hardening it breaks no user: there was no working behavior to preserve, only a dead flag whose only live behavior was flipping candidates into rejects.
The injection is now the exact literal <p> </p>. The numeric
character reference needs no DTD in any validation path, and the
wrapping <p> is the block element the content model demands; the
matrix shows it clearing "body incomplete" on every EPUB2 DOCTYPE
shape with zero fatals and zero new errors, while on EPUB3 books
(where an empty body raises nothing) the gate answers equal and
nothing applies. The gate now accepts the fixture honestly:
0f/6e/0w -> 0f/4e/0w (body incomplete and the NCX playOrder error
both fixed; the book's four pre-existing error-nits stay), applied
under --all.
The flag's name, selection rule, opt-in status, and count key are
unchanged; only the injected bytes differ. --fix-empty-body and the
plugin's default pass never overlapped (the plugin runs the default
pass only), so the Bindery Repair zip in this release just carries the
updated transform. Tests: TestFixEmptyBody (test_transforms.py) pins
the literal, the no-named-entity invariant, whitespace/attribute/case
shapes, and untouched non-empty bodies; test_epub.py carries the
issue #25 regression shape (a Strict-DOCTYPE shell doc whose candidate
must show the numeric-in-block injection and never ). Suite:
832 tests.
The Summa Theologica (Calibre book #7301: 10,440,245 bytes, 3,831
archive entries, 3,808 spine documents, a 16,456-finding playOrder NCX)
kept dying at the gate even after v0.55.0's size-scaled budget, and the
first miss was the units: the size term divides by binary MiB, and
10,440,245 bytes is 9.96 MiB, so the book every doc reports as 10.4 MB
computed the flat 300s base with no size chunk at all. Even with a size
chunk it would have missed: epubcheck measured 384s on the source and
445s on the --all candidate (both runs under sweep contention), because
the book's cost is entry-count-bound (3,831 entries, 3,808 spine
documents), not bytes-bound. Either way the retry burned the same way
and every sweep misfiled the book as (epubcheck timeout) -- it stayed
a candidate forever.
Two budget changes, same 1800s cap. The size term counts decimal MB (how book sizes are actually reported), so exactly-10-MiB files earn their chunk instead of straddling the threshold. And the budget gains an entry term shaped like the size term at finer granularity: +60s per started 500 archive entries above the first 1,000. The Summa computes 720s (300 base + 60 size + 360 entries) against its measured 445s worst case; books at or under 1,000 entries and 10 MB keep their historical budget exactly, and a path that does not open as a zip (the budget is computed before the book is judged) falls back to the size term alone. No gate or CLI surface changes; the sweep selectors and the OracleTimeout contract are untouched, and no library dry-run re-validation is triggered (the change is the oracle's patience, not an acceptance bar).
The diagnosis also settled what the repair buys: epubcheck DOES police
the playOrder contract (2 of the source's 6 RSC-005 error entries are
exactly that: identical playOrder values for different targets, and
playOrder sequence gaps), so the default-pass candidate measures
0f/6e -> 0f/4e, a strict error decrease the gate accepts; the scoped
--all candidate measures 0f/0e/0w. Measured pins live in
tests/test_validate.py: exactly 10 MiB earns its decimal chunk (360s),
the 3,831-entry shape at <= 10 MB computes 660s, the full Summa shape
(10.44 decimal MB + 3,831 entries) computes 720s, exactly 1,000 entries
stays at the size budget, 1,001 entries adds the first chunk, and 2,500
entries compute 540s.
--prune-dangling-ncx-targets is the twenty-sixth structural repair. The
class: an NCX navPoint (or pageTarget) whose <content src> names a document
the archive never contained. epubcheck answers RSC-007 from toc.ncx, and
nothing reached it: --prune-missing-resources prunes manifest items whose
FILE is absent, and a producer that drops the document without declaring it
leaves no item to prune, so the navPoint survived --all with "no applicable
fixes" (the Splintered Harmony fixture, 0f/1e/0w). Hand removal works but
cascades: every surviving playOrder then reads as starting at 2 (391 RSC-005s
on the live book), naive renumbering splits the navPoint/pageTarget
same-target contract (79 more), and the working rescue was a second --all
run to let the contract-gated playOrder pass heal the survivors. The new flag
folds that whole recipe into one gate.
The rule is node-exact, over a balanced stack scanner that tracks navPoint,
the legacy navTarget spelling, and pageTarget as one family: a navPoint dies
when its OWN target document is absent from the archive. A dead node whose
whole subtree dies with it is removed as one element; a dead node above
surviving descendants is spliced (its tags, its navLabel, and its dead
<content> go; the children are re-homed one level up), because dropping
live navigation to repair a dead label is no repair. Scheme URLs, bare
fragments, contentless nodes, comment-hidden elements, and escaped-ampersand
srcs that resolve (the issue #20 decoder) are never this class. The token
walk tracks the navMap/pageList containers too: an unbalanced walk (a stray
close, a wrapper crossing a node's span) aborts the pass unchanged, and so
does a prune that would EMPTY a container, because the NCX requires
navPoint+/pageTarget+ and an empty navMap is itself one RSC-005 (verified
against epubcheck 5.3): without the rule, the gate would happily apply a
TOC-less NCX, and a wholly dead TOC is the manual list's finding, not a
repair. When the prune fires, the
contract-gated playOrder pass re-runs in the same branch, the fragment
strip's v0.58.0 pattern. On the fixture the one run went 0f/1e/0w to
0f/0e/0w: one navPoint pruned, 389 playOrder values re-sequenced across
navMap and pageList, epubcheck clean, and a second probe reports no
applicable fixes.
Wiring follows the house pattern: the RepairFlags.prune_ncx_targets field,
the _REPAIR_FLAG_TABLE row (compact --help and --help-repairs), the
_flags_from_args mapping, --all enabled like every structural flag, and
the wiring test's dest-to-field pin. Tests: TestPruneDanglingNcxTargets
pins the node-exact rule end to end (dead leaf, splice, dead subtree,
refusals, the unbalanced abort, the container-emptying refusal, the
escaped-ampersand resolve, pageTarget and navTarget, and the resequence
through repair_epub), and the real-core
suite drives the flag through argv. Suite: 820 tests.
The 2026-10-25 whole-library structural run filed four issues and applied nothing; every fix here was bisected on the specimens first, and the forensics each turned up a mechanism the issue text had only half of.
Issue #18: one root cause under all 57 "unreadable" books. The copy
loop handed the source's own ZipInfo objects to zout.writestr, and
writestr stamps the info it is given with the DESTINATION offsets
(header_offset and the sizes land on it for the central directory).
After an entry was copied, zin's own name lookup for it pointed into
the output file; the media-type peek's by-name open (v0.56.0) then read
whatever bytes sat at the drifted offset. Fifty-six books died with "Bad
magic number for file header" and one (Development as Freedom) tripped
the read-side zip-bomb guard instead ("Overlapped entries ... possible
zip bomb"): same mutation, different landing spot, which is why the
issue's proposed disposition (a dedicated rebuild path for the bomb
book) is unnecessary. The write now always gets a private ZipInfo (a
shallow copy, so output bytes stay identical; a fresh one on renames, as
before), the stale-container replacement too, and the peek additionally
catches zipfile.BadZipFile per the issue's hardening ask (it subclasses
Exception directly, not OSError): one entry with a genuinely corrupt
local header is now a skipped probe, never an unreadable book. Both new
tests fail on the pre-fix code.
Issue #19: the renames were only half of what the references needed.
Five of the six rejects (Magic Bites, King Beyond the Gate, Lavondyss,
Sun Sword, Infinite Jest) share one mechanism: the renamed spellings
still carry [ and ], epubcheck answers RSC-020 "Illegal character in
path segment" for a raw bracket in a URL path, and every rewritten
reference re-flagged -- Magic Bites went 25 -> 37 errors with the space
fix measured as PKG-010 18 -> 0. Renamed-reference spellings now
percent-encode the brackets (%5B/%5D); epubcheck decodes before
lookup, so the encoded form resolves to the raw-spelled entry, and the
same books now go 25 -> 6, 41 -> 7, 28 -> 3, 48 -> 2 and 108 -> 22
(RSC-020 85 -> 0 on Infinite Jest). The sixth reject (Hacking: The Next
Generation) was pure corruption: the book TEACHES HTML, its display text
carries href="...", and the bare attribute regex paired the phantom
quote with the next real markup quote, encoding a space into the
following start tag's element name -- two RSC-016 parse fatals, and its
seven counted "fixes" were all phantom. Both the space encoder and the
rename rewrite now anchor on real start tags and processing instructions
(comments and CDATA excluded; the PI branch is what keeps
xml-stylesheet hrefs getting fixed), and the fatals are gone with zero
phantom edits. Both new tests fail pre-fix.
Issue #20: hrefs are XML, entry names are not. The prune+declare
clash on the four Designers & Dragons volumes: their file names carry
raw & while the manifest correctly spells &, and the href
resolver never decoded the entity, so the prune judged live declarations
absent (30 new RSC-008s alone), the census then re-declared the same
files from the raw-ampersand content references (30 OPF-074 duplicates
alone), and the two flags literally swapped the items inside one run
(net zero, by accident). _resolve_href now decodes the five predefined
entities and numeric character references before the fragment split
(attribute text arrives escaped; entry names are raw bytes; decoding
first is also what keeps the # inside & from cutting the
target), and the OPF item/itemref/reference matchers accept
an optional namespace prefix -- the second shape, where Sony-style
<opf:item> packages (Roadside Picnic, Twenty Love Poems, Zhuangzi)
made the census see an empty manifest and duplicate every declaration.
All seven books now probe as clean no-ops for both flags, and the
prefix-tolerant matching fixes a latent --fix-manifest-ids gap on the
same packages (a prefixed item's id used to be invisible to the rename
while its spine idref was not).
Issue #21: three small deltas, three different mechanisms. Troubled
Man and Fools Crow both died in the NCX after the anchor pass: the
always-on playOrder pass validates the contract BEFORE the fragment
strip runs, and stripped fragments collapse distinct navTargets onto
their documents, violating the same-target-shares-one-value rule the
pass had just verified. The pass now re-runs on the final navMap (it is
contract-gated, so a still-valid NCX re-runs as a no-op). Fools Crow's
second new error was the OPF guide: its type="toc" reference pointed
at a filepos fragment that never existed anywhere in the book, invisible
while the target carried its own broken links and surfaced once they
were fixed; --strip-broken-anchors now gives guide references the same
document-precision fallback the NCX half has (guide_fragments_stripped).
Fools Crow repairs 1e -> 0e, Troubled Man 2e -> 1e. Seven Principles was
the duplicate-id rename counting a commented-out copy of an id as a
second definition: epubcheck sees one definition, so renaming the REAL
one (the only one a reader resolves) dangled the index's cross-document
fragment. The shared rename now skips comment/CDATA-hidden tags
entirely; the book's phantom rename is gone, its 11 errors hold, and the
38 CSS-007 font normalizations still fire.
Suite: 809 tests.
Same night as v0.57.0, on the follow-up call: the Hackers specimen
repaired to 0f/1e because its residual error was NCX-001, not embed
damage. That book's 2010-era NCX spells every element with the ncx:
prefix (<ncx:meta name="dtb:uid" .../>), and the always-on sync's
matchers anchored on a literal <meta, so a prefixed dtb:uid carrier
was invisible: the sync skipped, and the drift survived an otherwise
clean repair. Both matchers (_DTB_UID_RE and the reversed
content-before-name form) now accept an optional namespace prefix on the
meta element; the group layout is unchanged (the prefix lives inside the
reconstruct group), so the quote-agnostic replacement logic is
untouched, and a prefixed element whose local name merely starts with
"meta" (the <p:metadata> shape) still matches nothing. The --only ncx sweep selector reads the same matchers, so prefixed-NCX books with
drifted uids are now candidates too. Live gate on the specimen chain:
the scarred Hackers book now goes 1f/1e/0w -> 0f/0e/0w in one run
(unbound_prefixes_bound:2, ncx_uid_synced), the exact end state the
hand repair had reached.
Suite: 793 tests.
The reconcile-embed fallout's last scar shape, plus the reporting gap its investigation exposed.
--fix-unbound-prefix binds element prefixes (shape 1). Calibre
9.7.0's embed_metadata self-declares xmlns:dc on every dc: element it
writes but one, leaving that element's own ELEMENT prefix unbound:
FATAL(RSC-016): The prefix "dc" for element "dc:date" is not bound. The
v0.51.0 repair covered attribute prefixes only (ns0:scheme); the element
name is a different use site and nothing in the inventory touched it, so
the specimen chain sat one fatal apart from clean with no repair left to
run. The same scope-tracking walk now checks each start tag's own name:
an unbound element prefix is bound inline on the element, the exact shape
the file's healthy siblings already use. The evidence rules carry over
with one addition: rule 1 is unchanged (the prefix declared elsewhere in
the document, every declaration agreeing), and rule 2 for a literal dc:
element under an OPF-namespaced package resolves to the DC namespace
itself (the attribute half's rule 2 names the OPF namespace because
opf:scheme rides on DC elements; a dc: element IS the Dublin Core
element). Ambiguous or unevidenced prefixes still refuse the whole
document, clean documents stay byte-identical, and the each-use-site
counting contract holds (nested unbound elements each get their own
declaration, mirroring the attribute half). One start tag never carries
two declarations for one prefix (XML forbids the duplicate attribute;
the code-review pass caught the collision between an unbound element
prefix and an unbound same-prefix attribute on one tag, and fixed the
attribute-vs-attribute variant the attribute half had always carried).
Live gate on the specimen
(Hackers, the issue's own chain): the scarred original went
1f/1e -> 0f/1e with unbound_prefixes_bound:2 (attribute + element in
one run), and the half-repaired intermediate that v0.56.0 refused as
equal now repairs (1f/0e -> 0f/1e, the element bind alone). The
residual error on the specimen is NCX-001, not embed damage: its 2010-era
NCX spells every element with the ncx: prefix, which the always-on
dtb:uid sync's <meta\b matcher does not read; that sync gap is recorded
on the issue and left unrepaired here.
Still-fatal noops reclassify as partial (shape 2). The same
investigation caught the gate answering equal (no measurable gain) on a
book whose fix had cleared one fatal and unmasked a latent second:
unbound_prefixes_bound:1 fired, 1f/1e -> 1f/0e, fatals read 1 -> 1,
and the silent skip buried a book that still will not open. The v0.51.0
masked-ncx-gain rule already reclassified exactly this shape for the uid
sync; it is now general (the gate's noop on any book that started and
stayed fatal means the fix's real axis lives below epubcheck's per-file
halt, whatever the fix was): the verdict is partial, the book lands on
the manual list (still_fatal), and the still-fatal rule is untouched
(partial candidates were never auto-applied). Clean books are unaffected:
the rule cannot fire without fatals on both sides, and the gate's own
partial and reject answers never enter it.
Twenty-five structural repairs. Suite: 789 tests.
The v0.55.0 census lanes left two deterministic-but-marginal candidates recorded as recipes; both shipped the same day on the follow-up call.
--fix-unique-identifier (the OPF-030 recipe). The dominant family:
the package names an id (bookid, uuid_id, ISBN shapes) but no
dc:identifier carries any id attribute at all. The repair writes the id
the package itself names onto the first dc:identifier start tag; the
dc: values are never touched. It refuses to guess every ambiguous shape:
an absent or empty unique-identifier attribute, a non-NCName id, an
already-wired OPF, no dc:identifier element, or a first identifier that
already carries an id. The live gate on the census specimen (The Eagle Has
Landed) surfaced a masking twist: the broken wiring was hiding a real
NCX-001 (epubcheck cannot compare dtb:uid to an unresolvable
identifier), and the default pass's uid sync skipped because the source
had no resolvable uid. The repair now predicts the post-wiring uid (the
same pure transformation the OPF branch applies; never a snapshot of a
different layout, the issue #10 lesson) so one run wires the OPF AND
aligns the NCX: the specimen went from 2 errors (OPF-030 + a masked
latent) to 1 (a pre-existing out-of-scope OPF-032), accept, with
unique_identifier_wired:1 and the NCX sync fired. The multi-OPF merge
leftovers whose failing OPF is a stale non-rootfile are unreachable by
construction (only the located rootfile is repaired).
The CSS-007 font half of --fix-media-types. The census found the
INFO-severity family: @font-face srcs whose OPF declaration sits
outside epubcheck's version-specific blessed font set (text/plain
fonts, application/xfont+otf, octet-stream woff2). The map gains
ttf/otf/woff/woff2 with their magic bytes; the font/*
spellings are blessed on BOTH package versions (EPUB2 blesses the prefix,
EPUB3's exact list carries them), so no version gate is needed, and the
existing magic-byte confirmation rule is unchanged (a font is rewritten
only when its bytes name the format the extension does; .eot is never
touched -- epubcheck rejects EOT as a font src however it is declared, so
correcting it can only churn). Because CSS-007 is INFO, the error counts
do not see the gain, so the flag is now accepted under the no_worse bar
(the cover-wiring ruling's shape): the OPF-029 error slice still measures
its real decrease through the normal gate, and a font-only repair no
longer reads as gainless. Live gate on Brave New World (8 text/plain
fonts): media_types_normalized:8, accept, CSS-007 fully cleared.
Twenty-five structural repairs. Suite: 768 tests.
The error-code surgery left six open issues; this release works all of
them, each on its own evidence (the census lanes and live gate runs are
recorded in docs/OBSERVE-RESEARCH.md, specimens in the gitignored testing
facility).
--strip-epub3-attrs covers role and aria-hidden (issue #11). The
resample had found EPUB3 semantics on legacy packages the dominant RSC-005
family (role 6,645 sampled occurrences, aria-hidden 239) while the
flag's fixed set carried only three attributes. The population census
settled both design questions with data: every role/aria-hidden carrier in
the sample is an EPUB2-declared package (the values are DPUB-ARIA
doc-* roles and aria-hidden="true", no visual default either way), and
the DOCTYPE-gate concern is falsified (seven EPUB3 packages carrying
XHTML 1.1 doctypes show zero attribute findings; epubcheck keys on the
package profile, so the existing package-version gate is correct as
built). The set grew; the gate stayed. hidden deliberately stays out:
stripping it would reveal content the author hid.
--fix-duplicate-ids (issue #14). The 20-book sample caught duplicate
ids in HTML content documents (the Calcutta Chromosome heading_id_2)
that no flag addressed. The SVG fix's first-keeps-name rule extends
cleanly: the first occurrence keeps its name, later duplicates gain
_2/_3, and no reference is rewritten because #fragment anchors, CSS
#id selectors, and NCX fragment references all resolve to the first
definition exactly as readers resolved them before. Live gate on the
specimen: accept, net error decrease alongside the default pass.
--declare-missing-items (issue #16). The coverage study answered the
question both ways. RSC-001 is already covered where it can be: 95.3% of
its mass is spine documents whose files exist under a different spelling
(the Wandering Inn pair alone is 1,474 of 1,546 entries), which the spine
guard refuses by design and --encode-url-spaces owns; the long tail is
cleared by the existing prune; the boundary is documented, not widened.
RSC-008 had zero coverage, structurally: the prune's predicate is
target-absent and an undeclared resource is by definition present. The new
flag is the inverse move: it adds the manifest <item> declarations the
OPF never wrote for files the book references and the archive carries
(content img/link, CSS url() resources, OPF guide references), with
sorted deterministic bindery-dN ids, blessed extension-map media types
only, and no <itemref> ever written (the spine is untouched; an itemref
with no manifest item stays unrepaired, since which file it meant is
underdetermined). Live gate on the facility specimen: 3 items declared
(the three Calibre split-CSS files), RSC-008 fully cleared, accept, and a
second run declares nothing.
The epubcheck timeout stops lying (issue #15). The Summa Theologica
timed out at the fixed 300s in one whole-library run and passed the
identical gate in another. The default oracle budget is now size-scaled
(300s at or under 10 MB, plus a minute per started 10 MB above, capped at
30 minutes), one subprocess retry follows a timed-out attempt, and only a
double timeout raises the new OracleTimeout, which the gate reports as
(epubcheck timeout) instead of filing the flake under
(epubcheck failed) with crashes and unparsable output. Sweep selection
catches it and keeps the book a candidate; a timed-out book is still never
applied.
Observe schema v2 (issue #13). The census counted aggregated epubcheck
JSON message entries and labeled them occurrences; the Feynman specimen
measured the gap at 20,307 text sites vs 7,030 entries (up to ~600x on
other books). codes.occurrences is renamed codes.messages (the gate's
scale), a true codes.occurrences now sums each message's locations
(the per-site scale), a counting block in the artifact states both
scales, the census harness reads the JSON with Jackson (already on
epubcheck's classpath; the legacy code scan stays as the fallback), and
--against accepts v1 artifacts: the trend keys exist in both.
The content-model ruling (issue #12). The span-in-body, incomplete
blockquote, and bare-body-text families (well-formed but schema-invalid
under XHTML 1.1) are ruled measured-not-repaired in spec.md: they render
everywhere, the only mechanizable repair (wrapping the loose content in
the implied element) changes layout, and a repair that cannot be made
deterministically rendering-preserving does not belong in the inventory.
--reserialize stays deliberately inert here (its trigger is XML
ParseError; these documents parse). The spec's out-of-scope list carries
the ruling with the Dark Star falsification cited.
The census lanes (issue #17). RSC-012 is --strip-broken-anchors'
class (96.5% of 1,210 live locations across 188 books; the 42 OPF-guide
locations are furniture no repair touches). OPF-029 is --fix-media-types
for 216 of 280 locations (the Tress probe went 75 errors to zero, fully
clean); the 64 survivors are honest-or-refused declarations the flag
correctly leaves. OPF-030 (27 books), CSS-007 (114 books, INFO), and
RSC-004 (84 books, all font obfuscation, zero DRM, the audit's benign
OBFUSCATED verdict) are recorded leave-measured with their mechanisms and,
where one exists, the recipe for a future pass. The full census, wordings,
and per-book tables live in docs/OBSERVE-RESEARCH.md.
The 2026-10-24 whole-library surgery (the record lives in
docs/OBSERVE-RESEARCH.md, specimens in the gitignored testing facility)
proved that the tool's two worst whole-library behaviors, 313 gate
rejections and a wall of no-change rewrites, were both self-inflicted.
Two always-on core transforms carried bugs; the epubcheck gate correctly
refused every damaged output, which is why no library book was ever hurt.
fix_ncx_playorder rewrote valid TOCs into violations. The old form
renumbered every <navPoint> playOrder to document-order 1..N
unconditionally. epubcheck's actual contract is subtler: navPoints whose
<content src> point at the same target must SHARE one playOrder value,
distinct targets need distinct values, and pageTarget/navTarget elements
participate in the same contiguous sequence. Real TOCs satisfy this with
duplicate-target sharing and interleaved pageTargets, so the renumbering
manufactured RSC-005 playOrder findings on books whose NCX had zero
findings before. Whole-library tally: 579 firings, 17 real fixes, 211
gate-rejected regressions, 347 no-op rewrites. The transform now parses
the contract (element kind, playOrder value, content target in document
order), returns unchanged when the NCX already satisfies it, and on a
violation re-sequences by first-appearance target order, rewriting only
the attributes whose value changes. Verified against a minimal synthetic
EPUB: a shared-target NCX that validates clean goes in and comes out
untouched; the genuinely broken shapes (all-1 NCX, split shared values,
sequence gaps) still repair.
strip_prolog_junk amputated the trailing */ of Calibre's CDATA style
wrappers. The protection map's CDATA alternative ends at the first
]]>, which inside Calibre's /*<![CDATA[*/ ... /*]]>*/ idiom sits
before the wrapper's own closing */. That orphan landed in the outside
segment, the prolog strip ate it as "stray bytes before the first <"
(the whitespace guard cannot catch *), and every wrapped stylesheet
came back with a truncated comment: one CSS-008 "Premature end of file"
per file, a phantom fix whose fired count exactly equaled the wrapper
count (18/18, 22/22, 6/6 in the samples). The protection map now carries
the Calibre wrapper as its own first alternative, so the idiom is one
protected unit; a genuinely truncated closer (no trailing */) stays
outside the span, where --fix-cdata-terminator can still reach it.
fix_named_entities is exonerated by the same surgery: it fired solo in 93 whole-library records with zero rejections (14 real fixes, 78 count-neutral). No change.
Verification: 9-agent research pass with an independent claim-verification lane (4/4 claims confirmed, minimal synthetic reproducers for both bugs); 730 tests green (the playorder suite now pins the contract semantics, including the shared-target regression test); a whole-library dry run after the fix confirms the rejection collapse.
v0.53.0's spec, README, and patchnotes promised per-book census rows in the
artifact ("any later question can be answered without re-validating"), and
the first real run proved the promise hollow: the writer composed every
aggregate but never the books array. The rows are written now, one record
per book, clean ones included: path relative to the root, counts, the
error-code list, and the unreadable flag. The schema is unchanged
(bindery-observe-v1: the field set grew; no existing consumer reads the
array), and the test pins the rows.
The 2026-10-24 whole-library autopsy answered "where are we at" the hard way:
a dry-run sweep plus hand tabulation in the main thread. That session is now
a verb. bindery observe PATH validates every EPUB under a tree in one
warm-JVM pass, paying JVM startup once and running the parallel stream across
all cores, and writes one self-describing .observe artifact: the library
totals, a severity histogram (fatal books, error-count buckets, warnings-only,
unreadable, error mass), the error-code profile as occurrences and distinct
books, the worst offenders, and the per-book census rows so any later question
can be answered from the artifact without re-validating.
The harness embeds its Java like the FastDaemon does (JEP 330 single-file
launcher, no javac, in-memory compile), so the verb ships in the wheel and
the scripts/ benchmarking facility stays unshipped and untouched. Counting
matches the subprocess oracle by construction: the harness scans the JSON
document generate() serializes, the same document epubcheck --json emits
and the gate is calibrated on. The census answers for every input path: a
book the JVM cannot read arrives as the -1,-1,-1 sentinel record instead of
being dropped (the scripts/ audit mode's silence is exactly why a missing-
rows warning was needed there), and a run that comes back short of the input
count refuses to write a partial census (exit 2).
The optional repair preview (default on; --no-preview skips) composes the
shipped library runner in-process, the run phase1 pattern: a dry-run sweep
over the default flag set recording per-candidate status, before/after
counts, and the fix breakdown. It measures what --apply would write and
never writes. Artifacts are versioned (bindery-observe-v1); --against FILE composes a trend block against a previous artifact of the same schema
(library deltas, error-mass delta, per-code book-count changes with
new_codes/resolved_codes), and a schema mismatch is a usage error rather
than a silently incomparable trend. The verb is strictly read-only: the only
file written is the artifact, and the writer refuses to land it inside the
scanned root (default output observe-<timestamp>.observe in the current
directory). Exit contract: 0 artifact written, 1 invocation problem, 2 census
harness failure.
The same session's census found two trashed books walking the tree as repair
candidates. iter_epubs (the library sweep's walk) and the audit directory
walk now skip anything under .caltrash: a deletion pending Calibre's own
cleanup is never a repair candidate, and an --apply could in principle have
written into the trash.
The 2026-10-21 re-source wave caught it live: six fan conversions (the Rihannsu
rips: My Enemy My Ally, three Ascendance rips, two The Final Reflection rips)
whose content filenames carry raw spaces (DUANE, Diane - [Star Trek - TOS - Rihannsu 1] - My Enemy, My Ally_split_000.htm) and whose manifest ids carry
commas and brackets, which are invalid XML name characters. The gated sweep
accepted 0f/17e/8w -> 0f/10e/0w and applied manifest_items_pruned:8: the
repair deleted every spine document's manifest item while the archive entry sat
right there under its new underscore spelling, and left a book whose spine
resolved to the title page. The gate measured fewer messages because the
destroyed documents' errors had left the measurement entirely.
Two stacked defects, both fixed:
- The prune's existence check read the wrong layout. With
--encode-url-spacesactive,prune_missing_manifest_itemsran ahead of the reference rewrite on hrefs still carrying raw spaces, but checked them against the archive's post-rename spellings; every raw-space href read as missing. The check now uses the layout the OPF text is actually written in (present_src, exactly what the content-document prune already did), so an href is judged against the archive as the text sees it and the rename half handles both sides together. - The spine guard described an earlier spelling of the ids. The guard that
keeps spine documents out of the prune was snapshotted from the OPF before
--fix-manifest-idsrenamed the item ids and spine idrefs, so by the time the prune ran it recognized nothing. The prune now derives its spine set from the very text it reads; the snapshot parameter is gone, and the guard can never drift from the text again.
And the class is guarded, not just this instance: process_book now probes
source and candidate with epub.spine_dangles (itemref to manifest item to
archive entry, resolved through the same helper the repair's own existence
checks use) and vetoes any candidate whose spine dangles more than the
source's: reject with (spine collapse) in the summary, riding above the
message counts and above every fix-class promotion. A probe that cannot read a
package vetoes nothing (the veto needs evidence on both sides), and
--no-validate skips it with the rest of the gate.
On the issue's fixtures: The Final Reflection now repairs clean and gates
accept (0f/30e/22w -> 0f/3e/0w, twenty-two entries renamed, zero prunes,
spine fully resolved). My Enemy My Ally still refuses, now for an honest
reason: the fan conversion's brackets and commas are illegal URL characters
too, and once the spaces clear, epubcheck re-reports each affected link as its
own RSC-020 (17 -> 32 aggregated), so the candidate measures as a regression
and nothing is applied. That book waits for a manual pass, or a future repair
class that percent-encodes the remaining illegal characters; refusing is the
correct outcome for a repair that cannot be made deterministically safe.
Eleven tests joined the suite (702 total): the spine_dangles probe unit
tests (healthy spine, the orphaned-itemref shape, the absent-file shape, and
probe-failure-is-None), the prune guard's renamed-id regression and its
non-spine prune, the end-to-end raw-space book (renames land, nothing is
pruned, every itemref walks to a file), the veto wiring in process_book
(collapse rejects improving counts, intact spine keeps the normal verdict,
unreadable candidate vetoes nothing), and a fixture-backed regression on the
real My Enemy My Ally pre-repair bytes (skipped where the local fixture is
absent). The stack-free module joined CI's 3.12/3.13 leg, and the full-corpus
dry run over the library (6,774 books, repaired candidates measured against
their sources) confirmed zero veto fires.
Century Rain (library book #11104) carried an OPF that repeated
calibredb embed_metadata rounds had scarred: one dc:identifier, the package
unique-identifier itself, carried an ns0:scheme attribute whose xmlns:ns0
declaration sat on a sibling element, out of XML scope. epubcheck answered with
two RSC-016 fatals (unbound prefix) plus OPF-030 (unique-identifier not found),
and because a fatal package halts the metadata checks, the stale NCX dtb:uid
was invisible to the oracle on both sides of the gate. The old probe report said
it all: 1f/1e/0w -> 1f/1e/0w, ncx_uid_synced (no measurable gain), the ncx
fix refused with the OPF half.
--fix-unbound-prefix(new structural repair, twenty-second) binds an attribute prefix the OPF never declares inline on the element that uses it, the exact shape the file's own healthy siblings already use. The URI is evidence-based, never guessed: the same prefix declared elsewhere in the document (every declaration must agree, or the document is refused), or the OPF namespace for a Dublin Core element under an OPF-namespaced package (the canonical EPUB 2opf:schemeshape); anything else refuses the whole document untouched. Scope tracking walks the document with a comment/CDATA-aware tokenizer over a lenient element stack, so declarations that genuinely cover a use satisfy it without an edit and clean documents are byte-identical. OPF only: content documents already have the invalid-attribute drop (--strip-bad-attrs) for this defect class. Normalgate(clearing the fatal is the measurable gain). On the fixture:1f/1e/0w -> 0f/0e/0w, epubcheck fully clean.- The masked ncx gain (the issue's second half) stops lying in reports:
when the gate answers noop but the NCX uid sync actually fired on a book
that started with fatals,
process_bookreclassifies the verdict topartialinstead ofequal/no measurable gain. The sync is real, deterministic work the oracle could not see; the still-fatal rule is intact, so the library sweep still refuses to apply such a book and the single-file verb still writes it under the honest PARTIAL label when given an explicit destination.
Twenty-seven tests joined the suite (691 total): the transform unit tests (scope, evidence, refusal, idempotence), the archive-level e2e, the masked-gain verdict rules, tokenizer spin guards beside the other matchers, and the argv wiring rows.
Three fixtures from the 2026-10-14 phase-1 wave slipped past the content
analyzer's ad-notice detection (the importknig class): two Grandmaster of
Demonic Cultivation volumes packaged by a sloppy fan bundle, carrying
"Full Metal Panic! Volume 5" in every content document's head <title> (the
bundle template's original book) plus a whole Jnovels/Zerobooks ad page whose
own head title names a third series; and Hothouse, whose front matter is
pasted Amazon review text ("3 of 4 people found the following review
helpful"). All three were approved for import regardless, so the new
detection is advisory by contract, like completeness/cover/tocdrift: it
never flags a book and never moves an exit code. The disposition for this
class is judge-and-import.
bindery audit contamination(new analyzer, ninth; rides inall) runs three sweeps over the archive's content documents:- foreign titles: a title or series named where the book's own identity
belongs, judged against the package's own metadata (dc:title, creator,
publisher, series). Two triggers, both tuned on the fixtures: a
volume/book marker with named words in front of it ("Full Metal Panic!
Volume 5"; a part label whose marker leads, "BOOK ONE: THE RING SETS
OUT", never flags), or a head
<title>repeated across the book. The head-<title>channel matters because the MDZS stamps are invisible to rendered text; a marker-stripped own-name comparison keeps a book's own running headers clean when the metadata spells the volume differently. - ad signatures: jnovels, kokoro connect, zerobooks, and a generic light-novel download plug, in visible body text.
- review paste: review-site fingerprints (helpful counts, "was this review helpful", "out of 5 stars", verified purchase) in the first five content docs; a strong fingerprint flags a doc alone, weak ones (reviewer bylines, star rows) need corroboration.
- foreign titles: a title or series named where the book's own identity
belongs, judged against the package's own metadata (dc:title, creator,
publisher, series). Two triggers, both tuned on the fixtures: a
volume/book marker with named words in front of it ("Full Metal Panic!
Volume 5"; a part label whose marker leads, "BOOK ONE: THE RING SETS
OUT", never flags), or a head
- The corpus is the archive's content documents, not just the spine.
Hothouse's manifest is broken: 52 of its 53 content docs sit in no
manifest item, the spine resolves to one document, and a spine-only sweep
would have read the book clean. The loader now retains the archive's
non-spine html on
Book.extra_docs(archive order, 64 MiB retention cap; a pathological archive stops feeding the corpus there and stays the corruption/completeness verdicts' business), and the contamination sweeps run over spine plus extras. - Directory and single-book mode actually run cover and tocdrift now.
run_directory/run_singledispatched analyzers through an if/elif chain whose terminalelseran the ocr analyzer, so since v0.44.0 anaudit allover a directory (oraudit all --id) reported ocr verdicts under the cover and tocdrift keys and never analyzed cover wiring or ToC drift. Library mode was unaffected. Both modes now share a dispatch map keyed on the analyzer names (_dir_dispatch), a missing key is a loud KeyError instead of a mislabeled verdict, andtests/test_contamination.pypins the map's key set to the analyzer list. Advisory analyzers never answer problem, soaudit alland multi-analyzer runs cannot change their verdicts; the one behavioral corner is a single-keyaudit cover DIR(or--id) run, which at HEAD actually executed the ocr analyzer and could exit 1 on an ocr-damaged book under the cover key, and now runs cover wiring and exits on cover's own (always-advisory) verdict. - CalibreQuarry-style
--jsonconsumers see the new analyzer's verdicts as an additivecontaminationkey (problem always false); nothing else in the audit record shape moved.
Found live in a phase-1 vetting run: bindery repair <file> --all --json report.json, the acquisition pipeline's documented single-candidate
probe, wrote its full repaired output as an 11MB ...(repaired).epub
sibling inside the vetted tree, where anything beside the files gets
inventoried: import litter by the pipeline's own rule, carrying a name
only the (repaired) suffix apart from the original, so a later driver
pointed at the pre-probe filename list either missed it or
double-handled it.
- No output path is now a probe: the epubcheck gate runs, the
console lines and the
--jsonrecord carry the full projection (status, before/after counts, the structured fix breakdown), and nothing is written anywhere; the repaired bytes stay in the scratch workdir and vanish. On a probe the record'soutputis null andappliedstays false. - Writing needs an explicit destination (
bindery repair book.epub out.epub), and that rescue form is byte-for-byte what it was: same gate, same copy-the-accepted-bytes rule, same--forceand refuse-to-overwrite-the-input guards. - The probe's console verdict is the record's own status vocabulary
(
accept:/equal:/unvalidated:; partial keeps its established PARTIAL phrasing), followed by an explicit "probe: nothing written" line; a probe that would be partial still exits 0 with the record's status carrying the verdict. - The repair
--helptext (new probe example, the output positional's no-write meaning) and--help-json's exit contract tell the new truth; README and spec.md document both forms. The exit contract itself is unchanged: 0 clean/probed/written including partial, 1 trouble, never 2. - Three pins added (643 total): the probe writes nothing on the accept
and partial paths, and the
equalnoop verdict is carried honestly rather than dressed up as repairable.
v0.48.0/v0.48.1 truthed the help and --help-json but touched only
cli.py; the four-lens documentation audit converged on that lag. This
propagates it (docs and two docstrings only, no behavior changes):
- README's exit-contract bullet taught repair's dead contract
(trouble=2, usage=1) and omitted partial-writes-at-0, audit's exit 3,
and the lock-class refusals: it is per-verb now, mirroring
--help-json's exit_contract block. - The enforced closed-Calibre gate is stated where trust is earned:
README's tagging section (advice became enforcement) and the
install-to-calibre story name the three doors and exit 1; spec's
Library replacement, Native installation, and audit sections name
their refusals; CLAUDE.md carries the v0.48 pair
(
_require_closed_calibre,--help-json) plus the per-verb exit truth. - spec's audit exit vocabulary gains the exit-3 class and the repair
carve-out is named where the inverse shape is attributed; the
partial-repair rule gets repair's writes-the-output exception;
spec's plugin config list gains
max_log_mb. - README: Repairing a book / Sweeping a library section headers (the
usage docs were buried headerless inside the tagging subsection),
cover/tocdrift audit examples,
--help-jsonin the help paragraph. - Two stale code docstrings the audit flagged:
__init__(four lossy strips, eight analyzers) and validate.py'sno_worse(stub strips and the rename half included). - One pin added (640 total): the newest patchnotes heading must carry VERSION.
Three waves of four lenses audited this help surface. The flag inventory verified perfect (30/30 repair flags, zero misses, zero fabrications); the defects were the exit contracts and the safety silences:
- repair --help stated an exit contract the verb has never honored (trouble returns 1, not 2; a PARTIAL repair writes its output and returns 0). The page and --help-json now tell the code's truth, per verb: repair 0/written + 1, audit's deliberate inverse contract (0 clean; 1 findings; 2 usage/environment; 3 findings plus a failed report write), library and the run slices on the unified 0/2/1. calibre_gates names the third metadata.db door (run phase3, guarded transitively), and the contract admits the missing-stack exit-2 and the exit-3 class.
- The library page states the no-backup default: --apply without --backup/--backup-inplace replaces in place and keeps no copy of the original. --no-validate says the write still happens (status unvalidated). --backup names the outside-the-library refusal. --only fatals names its --audit/--sweep precondition.
- audit and doctor got real descriptions (the eight analyzers, the CWD library resolution, the one-id --json rule; doctor's always-exit-0 contract); the --help-repairs preamble names the five always-on fixes, defines the gate metric, enumerates the status vocabulary, and states the no-worse classes; phase1's exit list gains audit-flagged books; repair's positionals, default output name, and never-modifies-the-input are stated; the --json envelopes name all keys including books; the root help points at doctor/README/spec.
- One code fix: the no-backup lossy warning now covers --strip-stub-docs (it warned for its three siblings only).
3 help pins updated to the new truths (639 total, unchanged).
The AI-grokability probe (a fresh agent learning the CLI from help alone, the same method CalibreQuarry ran) confirmed the repair-semantics help is complete and found the cross-cutting contracts missing. Three fixes:
- The closed-Calibre gate is enforced, not just stated. audit --tag and library --apply --install-to-calibre both write metadata.db, and nothing stopped that write under a live Calibre (WritableCalibreDB waits on the sqlite lock and proceeds; a running Calibre holds no persistent exclusive lock). Both doors now share a fail-closed pgrep refusal (exit 1: an environment condition, not a usage error), and --install-to-calibre's help says so.
- The help states the contracts the probe could not find: exit codes on the repair, library, and run-slice pages (0 clean, 2 trouble, 1 invocation problem); neither mode ever prompts (--apply is the only confirmation); an existing output without --force is exit 1; NCX-001 defined (toc.ncx dtb:uid != the OPF unique-identifier); --id works without --sweep; the repair and library --json envelopes name their keys.
- --help-json: the complete surface (subcommands with every flag, the run slices, the full repair reference, the exit contract, the Calibre gates) as deterministic JSON, generated from the live parser and _REPAIR_FLAG_TABLE, never colored.
15 new tests (639 total).
The lattice-music lesson, landed here the same day: Python 3.14's argparse
colors -h on terminals by itself, so the argparse-rendered surfaces (the
top-level help and -h for every verb) kept their theme through the
v0.47.1 restructure untouched. The one gap was the page v0.47.1 added: the
custom-rendered --help-repairs reference printed plain, silently losing
the colorization every other surface has (the exact regression
lattice-music repaired in its 6b88a52).
- The reference now paints with the exact CPython 3.14 default theme
(bold blue headings, magenta prog, bold cyan long options; read off real
3.14 output, so the page reads like the argparse-rendered
-hbeside it) through a single layout path whose disabled style emits empty codes. - The color gate IS argparse's own detection (
_colorize.can_colorizeon 3.14+; plain False below 3.14, where argparse has no colorization to match), so the two help levels can never disagree: verified under a pty that--help-repairscarries the same code vocabulary as-hand thatTERM=dumbandNO_COLORsilence both, and that piped output stays plain for README embedding and tests. - Four new tests: the theme codes, the strip invariant (colored, codes stripped == plain, byte for byte), pipe safety, and gate tracking. TestHelpLayout is now nine; suite: 624.
The per-verb help had grown into a wall: a 16-line usage line listing all 27 repair flags, then roughly 30 paragraph-length descriptions in one flat options list with the safe, structural, and lossy classes visually undifferentiated, and the shared set printed a third time in the top-level help. Flag names, semantics, and the argparse surface are untouched (CalibreQuarry's consent mirror drives the shipped parser); this release reorganizes how they are presented.
- One inventory, two renderings: the repair flags now live in a single
table (dest, one-line short help, long reference text) that registers
the compact
--helpinto titled argparse groups and renders--help-repairsas the full reference with every flag's long description. Structural repairs are grouped by defect class (markup and nesting; references and resources; package wiring), and adding a flag now means adding a table row. - Short usage lines replace the flag wall (
bindery repair [options] path [output]), repair and library carry examples epilogs, and the top-level help becomes a verb list plus a pointer to the two levels. - The four lossy strips are consistently
LOSSY:-prefixed (two of four carried it before) and live in their own warning-titled section ("these delete converter-injected content; accepted on a no-worse bar"). - library's own 13 flags are grouped (run control, candidate selection, backups, output and library integration) instead of one flat list.
--help-repairsis a custom argparse action, deliberately not store_true, so the wiring test's repair-selection count ignores it; TestHelpLayout (five tests) pins the usage lines, group titles, LOSSY prefixes, reference content, and that guarantee.
Tests: 620 (up from 615).
The 2026-10-05/06 acquisition wave filed five issues against real books; all five land here. Two are classifier and validity corrections to existing surfaces, three are new opt-in structural repairs, and each was verified epubcheck-gated against its own fixture before shipping.
- The stub classifier pools BODY text and exempts image carriers (issue #1).
The four Kobo part-divider pages of the Great Change carry only a
full-bleed
<img>each, and their identical head<title>welded them, with the title page, into a fake five-doc stub class: emptytext answered PARTIAL and--strip-stub-docsoffered a strip that deleted real illustrations (the apply-time gate caught the deletion, but the offer was wrong). Both the analyzer and the repair twin now pool the<body>span, and a doc with no body text that carries an image is furniture, never a candidate; identical titles alone are never a stub class. --fix-idssees every invalid character, not just colons and digit leads (issue #3). The Lisey's Story OPF carries ids likeStephen_King_-_Lisey's_story22(apostrophes copied from filenames), which passed the original empty/colon/leading-char NCName check wholesale, so a full--allsweep left the RSC-005 id errors standing (epubcheck's message says "without colons"; the defect was never colons). The check now enforces the XML NameChar set at every position, and the rename sanitizes every invalid character to_, references in sync as before. Fixture: 22 ids renamed, the OPF id error class cleared; the errors that remain on that book are unrelated classes (deprecated body attributes, stray GeoXML elements).--fix-svg-dup-ids(issue #2): old calibre 0.8.x SVG page renders repeat glyph ids within one document. The first occurrence keeps its name, later ones gain_2/_3, and references are deliberately untouched: they resolve to the first definition under every reader's first-match lookup, so first-keeps-id preserves exactly what rendered. Standalone.svgentries only; content-document ids are styled and anchor-targeted and stay out of scope. Fixture: 346 ids rewritten, 80 aggregated errors to zero.--fix-cdata-terminator(issue #4): completes the truncated/*]]>CDATA-terminator comment inside inline<style>blocks (the 2002-era conversion lineage whose 19 content docs each died with CSS-008 "Premature end of file"; the aggregated gate saw one message). Only the malformed-terminator token class: invalid CSS stays unfixed, stylesheet files are not touched, and an intact closer (even space-separated) is left alone.- The markup-fatal trio (issue #5):
--fix-misnested-inlinenormalizes the Mobipocket drop-cap mis-nest<i><b>X</i></b>(em/strong variants and either order; punctuation between the reversed closers survives outside both spans; a letter run is refused as ambiguous),--fix-stray-closeremoves an end tag whose element has no open start frame (a merely mis-nested pair is never touched; script/style text is skipped to its end tag and an unclosed comment stops the walk), and--fix-unterminated-attrcloses an attribute value open to the tag's own>(<p class="footnote>; bare-word values only, and only when no quote closes before the next<). Life (Keith Richards): 3 fatals to zero, gate-accepted with the unterminated-attr repair running before the tag-shape readers an open value would otherwise lie to.
Tests: 615 (up from 575), including a real-core row per new flag, the wiring-table pins for the five new dests, classifier regressions for both sides of the stub fix, and a version-sync pin for uv.lock's root entry (the pre-release audit found v0.46.1 shipped with the lock one patch stale, a class the pyproject pin cannot see). The plugin ships the default pass only; it vendors the changed modules byte-identically and CI byte-compiles it under 3.11 through 3.14.
The 2026-10-02 verification of the four-lane run left four documentation findings against the v0.46.0 tree; all four land here as text plus one plugin string. No surface change beyond the plugin's help text.
- The safety contract's lossy enumeration names all four modes: the
paragraph listed three and omitted
--strip-stub-docs(shipped v0.41.0), while the mode list twenty lines up, spec.md, and CLAUDE.md all carry four. Its rationale sentence now says converter-injected content rather than visible markup, true of the document-dropping stub mode too. - CLAUDE.md's tests bullet loses its em-dash: the one straggler in the v0.45.0..HEAD markdown delta, recast with a semicolon.
- ci.yml's core-compat comment describes every module its list runs: the v0.46.0 follow-ups added comment-hyphens, flags-wiring, and flags-real-core to the module list without touching the enumeration above it, so a reader reconciling comment against list found three orphans.
- The plugin's
customization_helpnamesmax_log_mb: the rotation cap is documented in the README and honored by the log writer, but the in-Calibre customization dialog never mentioned the key. Rides the release-attached plugin zip. - Suite: 544 -> 575 tests since v0.46.0 (the two follow-up wiring-test commits, unpinned in that entry's count), all green on this text-only sweep.
--fix-comment-double-hyphen(new structural repair, in the--allset): a--inside an XML comment is illegal XML (epubcheck fatal RSC-016, "The string "--" is not permitted within comments"), so such a book parses in lenient readers and never passes epubcheck. The fix replaces each--with an en-dash inside comment bodies only: text nodes are never touched (a--in character data is legal XML), CDATA sections stay protected, and every comment's-->terminator stays intact (the span ends there, so the replacement cannot reach it). It applies to content documents, the NCX, and the OPF alike, and each replaced sequence is counted under thefixeskeyfix_comment_double_hyphen(an additive key; CalibreQuarry's lossy-consent mirror reads the dict with.get()over its fixed lossy-marker tuple, so the new key is tolerated as structural, verified incquarry_cli/run.py). It is the sixteenth structural repair, built exactly to the 2026-09-16 classics-wave box's recorded design: the Theaetetus hand-rescue's en-dash half, now native. The normalgateaccepts it (clearing the fatal IS the measurable gain; verified against epubcheck 5.x on a synthetic book: 1f/1e -> 0f/1e), and the never-rewrite-comments invariant gains its one documented exception in spec.md.RepairFlags(internal): the opt-in selection that used to be a ~25-kwarg signature triplicated acrossrepair_epub,process_book, and the CLI's per-verb call sites is now one dataclass (epub.RepairFlags, one field per flag, all off by default; the all-off instance IS the default pass).cli._flags_from_argsis the single argparse-to-fields mapping, shared bylibraryandrepair; the EPUB2-targeted fixes' package-version gate swaps in adataclasses.replacecopy, so a caller's instance is never mutated. No surface change: the CLI flags, the gate, and the JSON records are untouched (end-to-end and byte-determinism verified against real epubcheck). One API note for in-repo consumers:bindery.epub.repair_epubandbindery.cli.process_booknow takeflags=RepairFlags(...)instead of keyword flags; the plugin's barerepair_epub(src, dst)call constructs exactly the default pass.- Suite: 524 -> 544 tests (
tests/test_comment_hyphens.py: transform units, end-to-end over content/NCX/OPF, and the gate on both sides; the flag-wiring tuples pin the new flag).
- Every per-book record now carries the fix breakdown as data, not only the rendered
summarystring (the roadmap box recorded 2026-09-18 from the CalibreQuarry side):library --jsonandrepair --jsonrecords, and therun phase1/phase3payloads built on them, expose the RepairReport'sfixesdict plusncx_uid_syncedandwatermark_refusals. Consumers that need to know whether a repair was lossy (CalibreQuarry's lossy-consent mirror) can read fix classes as data instead of substring-matching the flattened"k:v, k:v"summary; the summary itself stays rendered for human eyes, byte-identical to before. Purely additive: no existing key changed meaning. run phase1's own decisions read the data now:_phase1_decisionsnarrows theapply_lossyandmanual_watermark_repairquestions through the structured fields instead of matching summary substrings, and a book whose apply failed mid-run (the ENOSPC-class path) still reports the candidate's real fixes instead of an empty breakdown.- CalibreQuarry adoption is a deliberate floor bump:
bindery>=0.45.0. - Suite: 521 -> 524 tests (
TestStructuredFixRecord, plus the apply-failure and watermark-refusal records updated to the structured shape).
bindery doctorprintssys.executableon its python line, in the epubcheck line'sversion [path]shape. The version-only line hid which environment was probed, so an html5lib "not installed" read as wrong when the module sat in the system interpreter: a uv tool venv (include-system-site-packages = false) genuinely cannot see system site-packages, andfind_speconly ever consults the running interpreter. The path makes the install shape self-diagnosing.- Repo housekeeping with no runtime effect:
FUNDING.yml(GitHub Sponsors + Liberapay).
The wave-2 batch: PKG-010 entry renames, the cover and ToC-drift audit slices, and the roman grammar unified
--encode-url-spacesgained its rename half, the biggest real-prevalence repair class left (PKG-010: 8,237 occurrences in 284 books at the 2026-09-17 refresh). Archive entries whose names carry raw spaces are renamed to their underscore spellings and every reference is rewritten (OPF, NCX, contentsrc/href, stylesheeturl()). The design was decided by experiment, not by the roadmap box's plan: epubcheck 5.3 DECODES references before entry lookup, so percent-encoded entries are unfindable by the encoded references pointing at them (all four raw/percent/underscore combinations built and checked); underscore on both sides resolves and clears PKG-010. Ambiguous renames are refused per entry (a target that already exists, two names converging, a duplicated archive name), a book with any non-UTF-8 document refuses all of its renames, a renamed OPF regenerates a stale container, and the acceptance ridesno_worsebecause the gain sits on the warning axis the improvement gate does not measure (same bar as--fix-cover).- The matcher fix that explains Theaetetus (the 2026-09-16 hand-rescue): the encode pass's value class
[^"']stopped at apostrophes inside double-quoted hrefs, so the 270 raw-space OPF hrefs never matched and the fatal survived. The matcher now takes the tempered-quote idiom (possessive, house style), and an apostrophe in a double-quoted filename is ordinary. bindery audit cover(advisory, the EPUB3 half of the ruled hybrid): dangling EPUB2<meta name="cover">(the--fix-coverclass), the EPUB3properties~="cover-image"declaration, and whether the named cover file exists.bindery audit tocdrift: the structural diff between the NCX navMap and the EPUB3 nav toc, keyed on the full target including fragments: entries each side is missing plus label mismatches. Both never flag a book and never move the exit code; ToC synthesis stays out of the repair charter permanently. The loader exposes the parsed OPF, the NCX text, and the nav HTML onBook.- The audit-refresh deep-dive ran (read-only FastSweep extract over the full 5,228-book library; raw report in the facility): RSC-005 164,302 -> 13,782 occurrences, RSC-007 3,219 -> 14,162 in 604 books (the classics-wave imports), RSC-020 9,953 in 337 books, PKG-010 8,237 in 284 books (population flat: the rename class was still live, hence this ship).
- The roman grammar is one copy again: pagination.py is the canonical home (it vendors into the plugin; audit does not), audit.py imports
ROMAN_RE/ROMAN_MAX/roman_value, and the two byte-identical copies cannot drift. The RepairFlags dataclass refactor stays boxed with its reason (pure churn on the signatures this release touched). - Suite: 497 -> 521 tests (tests/test_space_renames.py, tests/test_cover_tocdrift.py, and the updated
--encode-url-spacesend-to-end pins).
--auditand everyload_bookcaller no longer decompress blind. Two protections, both stdlib-only (the defusedxml dependency stays declined): single entries whose declared size exceeds_MAX_ENTRY_BYTES(32 MB) are refused before decompression (a bomb entry in a tiny zip cannot be downloaded into memory), and the untrusted metadata files (container.xml, OPF, encryption.xml) parse through_safe_xml_parse, which refuses DOCTYPE/ENTITY declarations before xml.etree sees them. A refused or unparseable metadata file returns the shell book (the archive verdict is the book's whole story), never a hang or a traceback.- Pinned by
tests/test_xml_hardening.py(entity-bomb container returns the shell book; clean XML parses; the entry cap is sane). The defusedxml dependency ask is closed as declined with the stdlib shape delivered.
The follow-up box the 0.41.1 hotfix opened is closed with a full per-matcher census, and the audit found the box's own enumeration incomplete. Six GREEDY patterns of the exponential overlap class were unhardened: _START_TAG_RE (the quote-aware start-tag matcher anchoring --strip-epub3-attrs and --strip-bad-attrs, running under repair --all on every content doc; not even named in the box), _COVER_META_RE, _GUIDE_REF_RE, prune_dangling_edges' spine|item|itemref matcher, _ITEM_TAG_RE, and _SPINE_ITEM_RE. All six are possessive-bounded now: byte-identical on every successful match (the loop is always followed by a literal > that the [^>] branch cannot consume, so backtracking only ever happened on failure) and linear on failure. Five LAZY patterns of the quadratic class (_VOID_RE, the transforms <img> matcher, and epub's link/anchor/img matchers) took the disjoint catch-all [^>"'] instead of a blind possessive swap: mutually exclusive branches cannot re-partition, so any quantifier is linear, and an unterminated quote inside a tag now fails to match instead of pairing with a distant quote and matching across markup. Every well-formed shape is byte-identical. The epub _IMG_TAG_RE is renamed _PRUNE_IMG_TAG_RE (it collided with the transforms matcher of the same name). Everything else in the package audited safe by construction: tempered-quote value matchers, two-branch quote alternations, [^>]* single-class prefixes (linear, not quote-aware; accepted, documented), lazy paired-delimiter spans, and the analyzer tokenizers.
Pinned by tests/test_matcher_hardening.py (15 tests): alarm-guarded spin shapes per greedy site (OPF flavor, the truncated-OPF prune shape), unterminated-quote skips, and well-formed byte-identity. CLAUDE.md's hazard note now carries the census and the rule for new matchers. The full suite is 491 tests.
- The regression.
repair --allspun CPU indefinitely on real books (found on a Hackett Aristotle Physics whose 843k-character back-matter document is full of apostrophes and span candidates whose closer never comes). 0.40.0 repaired the same book in seconds. Brandon bisected it to 0.41.0 and root-caused it to the wheel diff: the 0.41.0 quote-aware rewrite ofunwrap_block_in_inline's start tag replaced the linear prefix with an overlapping alternation (double-quoted | single-quoted | any-non-bracket), and because the non-bracket branch also matches quote characters, every failing candidate let the engine re-partition the prefix across the branches exponentially. The flag-bisect had looked interaction-shaped because earlier transforms move where the failing candidates sit; the regex was input-sensitive, not the flags broken. - The fix: possessive quantifiers. The repeated group is now
possessive (
*+, Python 3.11'sre, the same floor as the plugin's minimum Calibre): the engine commits to its first-alternative consumption, which is the nearest-paired-quote path ending at the first unquoted>(the correct tag end), and never re-partitions. Failure becomes linear; successful matches are unchanged. Applied to all three patterns the 0.41.0 commit rewrote:unwrap_block_in_inline(the spinner),unwrap_illegal_tags, anddowngrade_epub3_tags. The pre-existing quote-aware matchers (_VOID_RE, the OPF tag matchers) were tested against the same shape and do not spin; their audit is a recorded follow-up box. - Verified on the fixture. The transform went from still-spinning
at 15 seconds to 0.01 seconds; the recorded reproduction
(
repair --all --force) completes in 7.7 seconds (epubcheck's own time) with output identical to the 0.40.0 shape (cover_meta_repointed:1, pagelist_class_added:1, ncx_uid_synced). Two regression tests pin it: the spin shape itself (a span followed by a 40k-character apostrophe run with no>: the old pattern provably cannot finish it) and the quote-aware function the rewrite was for (a>inside an attribute value).
- Analyzer robustness: one malformed book costs its own verdict,
never the run. A spineless EPUB (empty spine) no longer dies with
an IndexError inside spine integrity: an unjudgeable span is the
honest "unknown" verdict, and every post-load analysis call now sits
inside the per-book try, so an unexpected crash becomes that book's
error record while the sweep continues. A corrupt or absent
container.xml is the CORRUPT archive verdict naming the entry instead
of a NameError from the
_readclosure (which consultedencrypted_namesbefore its declaration) and a TypeError that read as a generic scan error. And DRM books no longer get a false EMPTY verdict beside their own ENCRYPTED skip: the emptytext/completeness skip gate is now the shared_archive_owns_bodyhelper, extended from corrupt entries to DRM-encrypted docs at all three sites. run phase3's aggregate summary tells the truth. A rejected candidate's projected after-state was summed into the printed before/after totals, so the 2026-09-13 OMW batch (one clean applied repair, one REGRESSION reject left untouched) printed 0f/53e to 1f/29e and cost a mid-run stop to verify no damage. The after total now sums real post-run states only: applied repairs at their after measurement, unapplied books at their before counts. The refused candidates' projection is its own labeled line (rejected_projectionin the JSON), and a regression test pins the Ghost Brigades shape (a reject must never move the aggregate past 0f).--strip-stub-docs: the lossy lane's live fixture. Drops spine documents whose entire visible text is one identical short placeholder repeated across the spine: the Bookmate/DRM-sample export whose chapters are all the same "content unavailable" notice, valid XHTML that passes epubcheck while the book reads as garbage. The identity rule mirrors the emptytext analyzer's placeholder signals and is deliberately conservative (12-600 chars, identical text across at least 3 spine docs and at least 30% of the spine, only the single most common class). The drop cascades: archive entries, manifest items, spine itemrefs (with package edges rewritten), NCX navPoints (the always-on playOrder resequencing heals the sequence), and nav toc entries. It refuses to fire on a book whose every spine doc is the same stub: that book is EMPTY and needs a re-source, never a repair. Rides theno_worsebar with the partial rule intact, like the other lossy strips.bindery doctor: the stranded stranger's first command. An environment self-check that reports the Python floor and stack tier (the full vir_tui+cquarry stack on 3.14, the stack-free repair core on 3.12/3.13), the epubcheck oracle and its version, Java (the daemon's viability), the optional html5lib, and whether a Calibre library is discoverable here. It imports none of the VirInvictus stack (their absence is the finding, not a crash), never raises, and always exits 0: a diagnosis is not a failure.repair --json FILE: the one machine-readable gap closed. The repair verb writes its record in thelibrary --jsonper-book vocabulary (status, applied, before/after counts, fix summary) on every processing outcome, including nochange and reject; exit codes unchanged.--backup-keep N: the backup rotation is boundable. The .bak/.bak2/.bak3... rotation grew unbounded across a 5,228-book library. Opt-in ring: at most N backup files per book, the author original .bak never deleted, the newest content at the highest name. Usage error below 2 or without a backup mode. The backup write itself is now atomic (a .part scratch copy then os.replace), so a disk-full mid-copy can never leave a truncated file at the final .bak name.- The plugin's log rotates. bindery_repair.log grew without bound
in Calibre's config directory; it now rotates at
max_log_mb(default 2MB, one .old generation kept, 0 disables) inside the never-break-an-import contract. - fast_sweep's audit CSV measures the gate's scale. The harness's
audit branch read the live report getters, which count message
occurrences, while bindery's gate is calibrated on the aggregated
messages epubcheck's JSON carries (the mismatch measured 243 vs 4 on
one book). The CSV now reads the aggregated checker totals out of
the JSON document
generate()serializes, the same shape the embedded daemon uses, so candidate selection and gating always agree. - PRIVACY: the census report is untracked (forward-only). testing_facility/top500candidates/REPORT.md was tracked on this public repo and listed real book titles at absolute library paths with internal Calibre ids; it is untracked and gitignored (the file stays on disk as the fast_sweep --summary target), per the same ruling class as the v0.33.0 test_facility untrack. The reachable history copy was weighed and kept: the strip would rewrite every release tag, and the leak no longer sits on the front door.
- The GitHub batch. publish.yml now extracts the tag's verbatim patchnotes entry into the release body (the three newest release pages rendered blank; all three are backfilled from their tag objects); the repo description leads with what the tool is instead of the daemon; [project.urls] gives the PyPI page its Homepage/Repository/Changelog; 7 wasted topics are swapped for epub3/calibre-plugin/python-cli/ebook-audit; the empty wiki is disabled; the redundant per-job suite run is gone from the publish workflow; concurrency blocks serialize publishes and cancel superseded CI runs; the publish workflow is top-level read-only with the third-party release action SHA-pinned. Two repo protections landed on a recorded go: a v*.. tag ruleset (deletion and non-fast-forward blocked, admin bypass preserved for the two deliberate tag repairs) and the pypi environment restricted to tag pushes. And the releases policy is recorded: forward-only from v0.37.0.
- The docs truth batches. spec.md's repair inventory no longer self-contradicts (one canonical list: 15 structural + 3 lossy + 4 safe opt-ins + --reserialize; --fix-ids moved to the safe group; --strip-bad-attrs gained its section; the gate sentence carves out --fix-cover's no_worse acceptance); the audit verb's own exit-code contract (0 clean, 1 flagged, 2 usage: the deliberate inverse of the repair verbs) is documented where the tool-wide shape is stated; the epubcheck install paragraph is written; the audit-only thresholds no longer masquerade as library flags; the mimetype fix is counted in the always-on core everywhere; validate.py's "degrades safely" fiction is replaced with the real refuse-without-the-oracle contract; a dozen header/docstring inaccuracies are corrected (the six-vs-four analyzer split, repair_epub's three undocumented flags, the blanket "OPF left untouched", the dead CalibreQuarry pointer, oceanstrip's tense, and more). The em-dash layer is swept from the living docs.
- Dead code removed (on a recorded go): validate.py's unused
_daemonpool alias, cli.py's incremented-never-readdone_count, and audit.py's inertsys.path.insert. - Dependencies: floors unchanged (cquarry stays >=1.19.0: nothing newer is required; vir-tui stays >=2.5.0). The lock re-resolves with this release per the lag rule.
- The plugin compatibility fix. v0.39.0 shipped PEP 758 unparenthesized except tuples, which are a SyntaxError on every Python before 3.14, and the Bindery Repair plugin failed to load on every released Calibre with a bare SyntaxError, silently. All six sites are parenthesized now (plugin/init.py, the vendored epub.py copies, validate.py), which is valid on every Python 3 and what the plugin needed all along.
- The compatibility matrix CI actually verifies. Released Calibre
embeds Python 3.11 through the whole 8.x series (7.0.0 = 3.11.5,
8.16.2 = 3.11.14) and 3.14 from 9.0 (9.0.0 = 3.14.2), per calibre's own
build manifests. CI gained a
plugin-compatjob that builds the plugin zip the way the release does, extracts it, and byte-compiles the zip contents plus the CLI sources under 3.11, 3.12, 3.13 and 3.14, so the class of failure that shipped in v0.39.0 is now a red build instead of a silent plugin.ruff'starget-version = "py312"pin keeps the formatter from re-stripping the parens, and a new grammar-floor guard in the version tests parses the whole tree under the 3.12 grammar. - Honest plugin metadata.
minimum_calibre_versionis (7, 0, 0), the oldest series whose embedded interpreter CI actually verifies, replacing the hollow (2, 0, 0). The README plugin section now documents platform support (developed and tested on Linux) and the exact verification level behind the floor. - requires-python drops to >=3.12, with one honest refinement. Every
cquarry (1.9.0-1.21.0) and vir-tui (2.2.0/2.3.0) release on PyPI
declares requires-python >=3.14, so a bare floor drop would have made
pip installfail on 3.12/3.13 in dependency resolution for exactly the strangers the floor is meant to invite. The VirInvictus pins instead carry; python_version >= '3.14'markers: Python 3.14 installs are byte-identical to v0.39.0, and 3.12/3.13 installs get the stack-free repair core, wherebindery repair(the one broken EPUB, no Calibre) works in full.bindery audit,bindery libraryandbindery runprint a one-line note that the command needs the Python 3.14 stack instead of a traceback (a lazy renderer proxy in the audit module and a dispatch guard in the CLI). CI runs the stack-free test modules on real 3.12 and 3.13 interpreters (258 tests per leg). - Repair-edge riders from the six-lens audit.
--fix-containerXML-escapes the book-controlled OPF path when it writes container.xml and unescapes at both readers, so a book with an OPF named likeTom & Jerry.opfdoes not gain a fresh fatal while being repaired, and the escaped form round-trips (regression-tested, including second-repair idempotence). The last two FRAGMENT em-dash verdict lines match the colon style.fix_cover_metaloses its deadpresentparameter.
--fix-coverrepairs dangling EPUB2 cover wiring. A<meta name="cover">whose content names no manifest item is re-pointed when the OPF guide's own cover reference resolves to exactly one manifest item (the producer's statement, so nothing is guessed), and removed when nothing identifies the item. A meta whose item exists is never touched: an absent cover file belongs to--prune-missing-resourcesand its edge completion.- Gate treatment: cover wiring is invisible to epubcheck, so a cover-only repair always answered 'equal' from the improvement gate. Cover repairs now ride the same no_worse acceptance the lossy strips use, with the partial rule intact: a regression rejects, a still-fatal book stays partial and is never auto-applied. Verified on a real dangling-meta book from the library: re-pointed 1, accepted.
- Scope by ruling (the hybrid): the EPUB3
properties="cover-image"slice stays audit-only. Choosing which image is the cover from filenames is exactly the non-determinism the charter forbids, and no library book is fully unwired (measured: 21 dangling EPUB2 metas, 3 absent cover files, 103 EPUB3 books without the property, 0 with no wiring at all). - The metadata-validity carve-out is ruled: routed to cquarry/CalibreQuarry. bindery's side is closed: human-facing dc: metadata stays a non-goal. The cross-repo handoff (a routed box in CalibreQuarry's backlog naming the 51 OPF-085 invalid-UUID warnings and the thin date/language tail) is filed for the next CQ lane.
- The tag-policy force-push repairs are executed on a researched
go: the v0.28.0 tag retargeted to the first green commit with its
title line restored (the historic
git tag -Fdefect had stripped it), the v0.33.0 tag message replaced with the corrected verbatim entry, and the 10 test_facility EPUBs stripped from all history (git filter-repo; main and all 14 tags force-pushed in one publish.yml-disabled session; verbatim tag messages survived; PyPI untouched). The roadmap's Tag policy section records the execution.
--fix-container, the gateway repair. A book whose META-INF/container.xml is missing, unparseable, or names a file the archive does not contain is locked out of every repair: epubcheck stays fatal while the OPF is unfindable. The new flag generates the standard container at the OPF the locator already finds by fallback (a byte-deterministic template with the constant epoch timestamp). Oracle-verified on a real-shaped fixture: fatal before, gate-accepted after. The Phase 16 prevalence study found 0 such books in-library (5,228/5,228 have valid containers); the repair ships for the acquisition phase, where the class actually lives.--prune-missing-resourcesrewrites what it drops. Removing a manifest item whose file is absent used to leave every package edge pointing at it dangling, manufacturing the regression the gate then rejects. The prune now carries the pruned ids into a rewrite of the four edge classes:spine@toc,item@media-overlay,item@fallback, and the EPUB2 cover meta. Optional edges of dead targets are removed; edges to live ids are untouched.--fix-media-types. Wrong manifest media-type declarations (OPF-029; 275 occurrences in 15 library books, the class being a jpg stampedimage/pngby an aggregator) are normalized attribute-only, preserving quote style, and only when the file's magic bytes confirm the extension: a PNG renamed .jpg keeps its wrong-but-honest declaration instead of a worse one. On the real Arthur sample the run goes from nochange to gate-accepted with 9 declarations fixed.- The audit distinguishes font obfuscation from DRM. encryption.xml entries under the obfuscation algorithms (the IDPF URI and both Adobe forms, including the ns.adobe.com URI real-world files actually carry, which the prevalence study caught) that read fine are the new OBFUSCATED advisory: publisher font embedding, benign, problem-False, exit-neutral. An unreadable obfuscation entry is CORRUPT (a broken font, re-source), and only non-obfuscation algorithms give the ENCRYPTED skip. 86 of the library's 5,228 books carry obfuscation-only encryption.xml; the library holds no real DRM at all.
- Boxed, not built, with real counts. The obfuscation-aware encryption repair (the magic-byte precondition validated on 424 real fonts: all genuinely scrambled, zero stale entries in-library), href case/backslash resolution (1 href in 1 book; 0 backslashes), and duplicate zip-entry dedupe (0 books) are recorded in the roadmap with their prevalence numbers and reopen conditions. The decision-gated Phase 16 C boxes (cover wiring, the metadata carve-out, the NCX<->nav drift detector, CSS url() pruning) carry recorded options and wait for rulings.
- 5,228 library books through the FastSweep epubcheck harness plus a direct zip-level pass: container.xml valid on every book; RSC-007 at 14,156 occurrences in 600 books and PKG-010 in 280 (the prune surface, 1,538 truly-absent manifest hrefs); OPF-029 at 275 in 15; case-mismatch hrefs exactly 1; encryption.xml in 86 books, all of it font obfuscation. Every Phase 16 repair box now carries its real count.
- Books are repaired as they are imported. Each release now attaches BinderyRepair-v.zip to the GitHub release: a Calibre FileTypePlugin (on_import) that runs the CLI's always-on core pass, the five well-formedness fixes plus the NCX pipeline, on *.epub files as they are added. run() never raises and never touches the original file or metadata.db: a repaired copy is built in a persistent temp file, testzip()-verified, and handed back for import; any trouble returns the original path and logs one line. The plugin is byte-idempotent, so re-adding a format re-runs it harmlessly.
- The vendor slice is byte-identical to the repo. The zip carries transforms.py, epub.py, pagination.py, watermark.py, and reserialize.py unchanged (the zip root is a package, so their relative imports resolve); a suite drift test pins the equality, and publish.yml regenerates the zip from the tag and attaches it to the release.
- Nothing runs ungated, ever. The structural repairs and the lossy strips stay CLI-only because their acceptance is the epubcheck gate, which cannot run inside Calibre. Identity: Bindery Repair / bindery_repair. Config via the plugin's customization string as JSON: log, log_path (default /bindery_repair.log), max_size_mb (recorded default 150MB), and epubcheck_path, the experimental on-PATH validation mode, default OFF (the three open questions, answered 2026-09-11).
- The already-correct comparison read the attribute value with its quotes, so every sequential navPoint counted as a fix on every pass while the rewritten bytes stayed identical. The Long Patrol reported fix_ncx_playorder=59 on every run of a repaired book; a book whose only fix was phantom was rewritten instead of reported as nochange; and a single-quoted sequential attribute was rewritten to double quotes, touching already-correct markup. Quotes are now stripped before the comparison and an already-correct attribute is returned untouched: honest counts, single quotes survive, and the plugin's zero-fixes contract holds end to end.
- Phase 16's FastSweep prevalence study (5,228 books) and the obfuscation magic-byte validation are recorded in the roadmap with real counts for every Phase 16 repair box.
- The phase-1 judgment step finally has a tool owner. The import skill's completeness step asks a human question with no tool behind it: "sample early, middle, and late pages ... read the LAST content page to confirm it reaches real back matter rather than cutting off mid-chapter". Two consecutive phase-1 runs answered it with a hand-rolled zipfile sampler in /tmp. The new analyzer rides the audit's existing single decompression pass (no second decode of any book) and reports, per book: spine doc count, prose-doc count (spine docs with at least 400 visible characters), the opening and closing 120 characters of the first/middle/last prose doc, a trailing-ToC classification of the final spine doc, and the fraction of unreadable docs (corrupt entries plus unresolved itemrefs).
- A trailing ToC never impersonates the ending. The final spine doc is classified as a chapter list when short link lines dominate it and no block runs to paragraph length; such a doc is book furniture and is excluded from the prose sampling, so the closing excerpt comes from the real back matter. Verified against the real 2026-09-10 Redwall fixtures: Lord Brocktree's trailing ToC is caught and the Epilogue is sampled as the last prose doc; The Long Patrol reads exactly 55/57 prose docs through the percent-encoded hrefs that defeated the hand-rolled sampler; Mattimeo's split doc (chapter headings with real prose after every one) stays prose.
- Advisory by contract. The analyzer never flags a book and never
moves the exit code: the archive, spine, and emptytext verdicts keep
owning the flags. The verdict status is ADVISORY (not OK) when a
trailing ToC is present or the unreadable fraction reaches 10%.
audit allandrun phase1include it through the battery, the CLI grows thecompletenessmode, and--jsonrecords carry its verdicts in the same shape as the other analyzers.
- Adopted cquarry 1.18.0 (floor + lock): the set_format repair lane now keeps Calibre's FTS index and page counts honest automatically (the sidecar's dirty queue and the pages rescan flag ride the write), and the search and runtime fixes come along in the shared layer.
- Adopted cquarry 1.19.0 (floor + lock): the repair lane gains its undo primitive -- save_original_format/restore_original_format -- so a format repair can put the original bytes back if it goes wrong.
- The release-tag backlog is settled forward-only from v0.35.0: the nine untagged 0.18.0-0.26.0 entries are exempted by decision of record (2026-09-11), and the v0.28.0 retag and the v0.33.0 em-dash tag repair stay recorded-only force-pushes (roadmap.md, "Tag policy").
- FastDaemon v2 measures exactly what the subprocess oracle measures.
The daemon's old Java side counted message occurrences from
CheckingReport's counters, while the gate has always measured the counts in epubcheck's own--jsonoutput, which aggregates identical messages (one book: 243 occurrences, 4 aggregated messages). On the staged-fixture corpus the two methods diverged on 11 of 14 books, so the daemon could never be enabled without changing what the gate measures. The new daemon callsCheckingReport.generate()and readsnFatal/nError/nWarningout of the JSON epubcheck itself serializes: identical numbers by construction. Verified against the subprocess oracle on all 14 staged books and on a 100-book real-library sample: 114/114 identical. - No more javac, no more version skew. The daemon now launches through Java's single-file source launcher (JEP 330): the running JVM compiles the daemon in memory with its own compiler, so the javac-newer-than-java skew that kept the daemon dead on this machine (javac 27-ea, java 25) cannot recur on any toolchain.
- Measured, working daemon throughput: ~0.27s/book warm against
~4.2s/book for the subprocess oracle (15.6x). With
--workers Neach worker gets its own warm daemon from the bounded pool, and every roundtrip stays bounded by the caller's timeout with the fail-safe fallback to the subprocess oracle. - The dedup semantics are pinned by a suite test: a book engineered with one defect repeated three times plus one different defect must answer 2 errors (the aggregated count), not 4 occurrences (the old daemon's answer). Skipped where no epubcheck/JDK exists, like the other oracle tests. README and spec's gate sections describe the new design.
Brandon's three calls: partial books are trouble, the contract reconciled, the daemon decision informed
- Partial books now fail every layer (exit-code decision, option A).
A
partialbook (repaired, improved, but still unable to open) used to exit 0 fromlibraryandrun phase3whilerun phase1counted it as trouble. All three layers now exit 2 on it: the run succeeded, but a book still needs a human. README and spec updated to match, and a regression test pins a 3f-to-1f book exiting 2 withapplied: 0. - spec.md reconciled with the shipped opt-ins (applied on Brandon's
go, from the draft filed in v0.33.0's roadmap box). The non-goals no
longer prohibit what ships: "fixing RSC-005 in bulk" now names the
scoped, version-gated repairs as the shipped exception, and "repairing
genuinely mangled structure" now describes
--reserialize's actual bounds (html root required, non-HTML XML sidecars refused). The missing--fix-idsOPF section is written (manifest item ids, spine idref/toc, fallback, media-overlay, EPUB 2 cover meta, both quote styles), the garbled NCX sentence is rewritten, and "the OPF is left untouched" now reads "by the default pass", naming the five opt-ins that edit it on request. - The daemon decision, informed: Brandon asked whether upgrading
java to 27 fixes the epubcheck daemon. Investigated and answered: his
javac is Fedora's
java-latest-openjdk-devel27-ea whilejavaisjava-25-openjdk(both official Fedora packages, no COPR involved), but the version skew is not the real blocker. epubcheck's own JSON output is deduplicated (it reports 4 errors for a book whose CLI summary says 243), the daemon counts everything, and bindery's gate has always measured with JSON-style counts, so a working daemon would change what the gate measures. The skew itself is fixable in code (Java's single-file source launcher needs no javac at all), but the daemon should stay off until its counting matches the JSON oracle; it already self-disables safely, and--workersparallelism works via subprocesses. Retire-or-reconcile remains the open decision; recorded in the roadmap's:958box.
The rest of the 2026-09-08 audit sweep's backlog, in the same shape as v0.32.0: every fix confirmed against current code first, each with its regression test.
Apply-path and oracle safety
- A failed write can no longer abort a sweep raw. The backup, replace, and install calls sat bare in the loop, so an ENOSPC or EACCES partway through a multi-hour run died with a traceback and no record. Failures are now error Outcomes; the summary and JSON always land, and exit 2 says scripts should look.
- Backups rotate and stay out of the candidate set. A second
--applyused to clobber the first backup (the only copy of the author original); backups now rotate (book.epub.bak2,.bak3, ...). A--backupdirectory inside the library root is refused (its copies would be swept as candidates on the next run). --workers Nparallelism is real. With epubcheck present, every worker serialized behind the daemon's one pipe. The daemon is now a bounded pool sized by--workers(default 1: the old behavior), a busy pool falls back to subprocesses instead of blocking, every roundtrip is bounded by the caller's timeout, and a daemon that dies or wedges is torn down and never retried; one failed attempt exhausts the pool, so the sweep degrades to pure subprocess checks instead of respawning a JVM per book. Measured: 8 books, 4 workers, two ~10s waves. The evidence for the recorded daemon-classpath decision grew: this machine's javac (27-ea) and java (25) cannot load each other's classes, so the daemon has never served a count here, and when forced to run its counts diverge from the CLI JSON oracle (243 vs 4 on one book): enabling it would change gate outcomes.- Smaller apply papercuts:
--limit < 1and a missing--auditfile are usage errors, not tracebacks; the fresh-format install registers the catalogued file's own name instead ofrepaired; and phase1 notes the dry-run--backupno-op instead of ignoring it.
audit.py correctness
- ToC accounting reads inside the open zip, a declared-but-absent
nav/NCX no longer poisons
Book.corrupt(a healthy book with a leftovertoc.ncxentry is not a damaged archive), NCXcontent srcresolves against the NCX's own directory (a nested NCX counted every target absent), and ToC hrefs are entity-decoded before comparison. - Archive and spine verdicts are first-class in library mode. Their
sections were dead code in the library report loop: a CRC-corrupt book
printed
emptytext CLEANand exited 0 there while directory mode said CORRUPT and exited 1. Both modes now agree. - The record pipeline's edges hold: a failed
--jsonwrite becomes a trouble exit instead of a post-scan traceback;--tagskips expected-foreign content findings; an unresolvable spine itemref is counted into the emptytext detail instead of silently reading EMPTY; DRM-encrypted entries get their own ENCRYPTED verdict ("not repairable, skip") instead of CORRUPT re-source; and part1a/part1b/part2-style spines no longer read as a broken span. - Dead surfaces removed (a duplicate argparse CLI, an unreachable
analyzer, duplicated imports) and directory mode catches uppercase
.EPUBlike the library walk always did. - Seven audit papercuts closed: the block-stack pop now matches the
closing tag, the nav property matches whole tokens (
data-navis not the nav), exit 3 is documented, the JSON analyzers list includes the always-on verdicts, the console problem counter counts books likesummary.problems,--min-charsabove--thin-charsis a usage error, and duplicate archive entries are counted instead of resolving last-wins in silence.
Tests, hygiene, and docs
- Direct tests for the safety contract: gate()/no_worse() including
the error-unmasking branch, the watermark gated-apply path,
atomic_replace failure injection (temp cleaned, target untouched,
re-raise),
--install-to-calibrewiring, and library-mode--tagend to end through cquarry's write path. Suite grew 342 → 381. - The weak two percent cleaned: mid-file
__main__blocks, constant-assertion tests, and module aliases gone; the non-interactive wiring is asserted through the real runner's JSON. - run_tests.sh runs CI's exact ruff pins before the suite, so the local loop fails where CI fails.
- Repo hygiene: the ten subsumed
scripts/find_*.pywedges plussweep.shandFastSweepExtract.javaare retired (git keeps them); the ten commercial EPUBs intest_facility/are untracked (forward-only, files stay on disk) and the dead never-run suite there is deleted. - Docs: the daemon is admitted to exist (README gate section, spec
gate section) with its bounding and fail-safe fallback; README's
--sweepbullet stopped describing the fixed classpath bug as current; the exit-code contract documents argparse's own exit 2 and the partial book divergence; CLAUDE.md's exception taxonomy names the safe opt-ins group.
Recorded for Brandon (unchanged, evidence sharpened): the daemon classpath decision, the exit-code-from-partial-books decision (both options written into its roadmap box; unifying on "trouble" is the recommendation), and the spec.md reconciliation draft (the non-goals vs. the shipped opt-ins, ready to apply on a go).
--strip-watermarksrefuses anchored matches larger than the stamp (the sweep demonstrated two paragraphs of real prose vanishing with count 1). The anchored stamp regex is DOTALL with no tag budget, so an unclosed stamp<a>matched through real prose to the next unrelated</a>, and the whole-match fallback deleted everything in between; epubcheck cannot see deleted text, so the no-regression bar accepted the loss. The fallback now fires only when the match demonstrably holds nothing but the stamp (a tag-free body within stamp length, or visible text exactly the watermark), a second<a>opening inside the match refuses it outright, and anything larger stays in place, counted in the newRepairReport.watermark_refusalsand surfaced byrun phase1as amanual_watermark_repairdecision on both the read-only and apply paths. Safe shapes (pure wrappers, inline stamp-only links) are byte-identical to before.- Roman page-number detection reads well-formed numerals only, in both
--strip-paginationand the audit pagenumbers analyzer. The old[ivxlcdm]{2,7}character set read ordinary English words as page numbers (mid= 1499), and a standalone<p>mid</p>before a lowercase-starting paragraph is exactly the confident interrupt shape, so real words were deleted and merged away. A roman counts only when well-formed (explicit subtractive pairs) and valued under 100, where front-matter page numbers live and words do not (mix= M+IX = 1009). Lowercase front-matter romans keep working; the audit copy's deliberately different year handling is untouched. install_formatverifies directory-guessed ids against metadata.db. In directory mode, an uncatalogued stray.epubinside a book directory made the(id)directory guess fire, and the row update re-registered the catalogued format name with the stray file's size: the catalogued 999-byte file untouched on disk whiledatarecorded 8123 bytes. A stale(N)directory for a deleted book crashed the sweep instead. A guessed id now drives a row update only when metadata.db corroborates it (the books row exists, the file sits in that book's own directory, and when an EPUB row exists it carries the row's stored name); anything else saves the repair in place with a warning and leaves the catalog untouched. The resolver path needs no verification: its id comes from the catalog's own path map.- The EPUB2-targeted fixes are gated on the package version. Neither
--strip-epub3-attrsnor--downgrade-epub3-tagschecked what the package declared, so under--allevery EPUB3 book in a sweep took the EPUB2 cure: a repairable EPUB3 book gained a net-new error from a stripped navepub:type(whole repair rejected), and a legalepub:type="chapter"was silently removed because the gate only sees epubcheck counts. Both fixes now fire only on EPUB 2 packages (major version 1 or 2) and are inert on EPUB 3 packages and when no version can be read, where their target defects do not exist. - The anchored-attribute regex cluster closes with the gate (the same
sweep's sharpest repair-pipeline finding): the attribute scrub runs
anchored on real start tags through the new
transforms.strip_attrs_in_start_tags, with CDATA sections and comments protected, so prose mentioningepub:type="chapter"is no longer deleted down toUse here;strip_invalid_valuematches its attribute name behind a(?<![\w:.-])valuelookbehind, sodata-value="42"survives instead of becoming a malformed<span data->.
--fix-id-colonsis consistent and honest. Only the bareidattribute is in scope (a lookbehind keepsdata-idandxml:idvalues untouched), the fragment of an external URL survives verbatim (it names a position in another document), the NCX'scontent srcfragments follow the rename through the newfix_ncx_src_fragmentsso a ToC never dangles against the ids it references, and only actual colons replaced are counted (byte-identical reruns report 0 and no longer trigger the re-encode the untouched-file guard exists to prevent).- The anchor pass runs last.
strip_broken_anchors' id snapshot used to predate the unwrap fixes, so an id they deleted still counted as present and fragments pointing at it survived dangling. The anchor pass now runs after every content fix, against a snapshot that replicates each id-moving fix ahead of it. - CDATA sections and comments are protected everywhere.
strip_broken_tagsandunwrap_illegal_tagsjoined the module's protected-span machinery (the wrapper now forwards arguments, so the protected_tags-carrying unwrap could be decorated); a leaked-looking tag inside either is literal rendered text, not markup. - Non-UTF-8 documents are skipped verbatim. A fix firing on a
windows-1252 or UTF-16 document used to decode with U+FFFD substitutes
and re-encode UTF-8 under a declaration still naming the old encoding:
usually well-formed, so the gate could not see the corruption. The write
loop strict-decodes first; failures are copied byte-for-byte, counted in
the new
non_utf8_docs_skippedentry, and left for manual repair. --reserializerequires an html root. A broken non-HTML.xmlsidecar used to come back html/body-wrapped withns0:prefixes, structurally rewritten while staying well-formed; it is now returned untouched.- Seven papercuts.
fix_ncx_playorderis anchored to<navPoint>start tags (nav-label text is untouchable); mimetype fixes incrementfiles_changed;fix_manifest_idsand its reference rewrites are quote-agnostic (a single-quoting OPF used to be a silent count-0 no-op; the two shadowed_IDREF_ATTR_REdefinitions collapsed into one); the css selector boundary recognizessvg|st,:is(st, w), and:where(...)forms and the stylesheet scan collects.xpgtpage templates, so styled tags keep their unwrap protection; watermark normalization decodes entities (OceanofPDF.com stamps now match); the prolog and duplicate-xmlns fixes run under the protected-span wrapper; and the archive comment field rides the rewrite.
Dry-run validation for this release: the 14 staged top500candidates plus
the 3 books_to_fix fixtures swept clean (9 accepted, 2 gate-refused
regressions, 0 errors), and a 200-candidate sample of the real library
(5,228 EPUBs) under --all --workers 4 matched the documented verdict
mix (94 accepted, 84 equal, 16 gate-refused, 0 partial, 0 epubcheck
errors, 0 unreadable) with zero crashes. Read-only throughout; the
gate-refused books are the safety contract declining marginal repairs,
left untouched for manual work.
--install-to-calibrereplaces the format row throughWritableCalibreDB.set_format(cquarry 1.17's sanctioned remove+add in one transaction) instead of composingremove_format+add_formatin abatch()by hand. Same contract as before: samedata.name, truthful size, OPF-resync queue, and a database failure still degrades to the in-place save with a warning. The cquarry floor moves from=1.9.0 to >=1.17.0 (
uv.lockre-resolved), and the failure-mode test now injects throughset_format.
library --workers N: the--sweepcandidate pass runs through N concurrent epubcheck workers (default 1: serial, byte-for-byte unchanged). epubcheck runs in a subprocess that releases the GIL, so threads parallelize the oracle honestly; this is the pass that measured ~4.4 s/book on the 2026-08-27 full-library walk (5,070 EPUBs ≈ 6 hours serial). Books are checked in windows of N consumed in input order, so the candidate set, the before-measurements, and every emitted line match the serial sweep, and--limitstays lazy within one window of overshoot. The repair phase stays serial on purpose: that is where the shared workdir and the atomic-replacement contract live. Without--sweep,--workersis a no-op (with a note); counts below 1 are a usage error.
The acquisition pathway's EPUB steps are now first-class CLI surface. Nothing here adds a repair class or changes an existing mode; the new verbs compose what already ships, in the phase-1 and phase-3 skills' documented order.
audit --json FILE: the audit subcommand writes machine-readable per-file verdicts in thelibrary --jsonshape (mode/root/summary plus one record per book), from all three modes: directory, library, and single-book. Records carry a status (clean/problem/error) and per-analyzer verdicts (problem/status/details); the always-on archive/spine verdicts appear OK when they were silent, emptytext is omitted from a record when the archive verdict owns the body-text story, and a scan error becomes its own record shape.--jsonwith--idaccepts exactly one book id, because each single-book run writes the file wholesale. This is the contract downstream consumers of the phase-1 EPUB slice read.run phase1 DIR [--json OUT] [--apply-lossy] [--backup DIR]: the pre-import vetting slice over a directory of loose files, in the phase-1 skill's documented order: the audit battery (corruption sweep, content battery, monolithic), then one fused repair sweep (epubcheck, watermark detection, repairability; the skill's two sweeps collapse into one epubcheck pass, with watermark hits read out of the per-book fix summary). Read-only until--apply-lossy, which IS the recorded lossy-strip consent;--backup DIRpasses through (keep backups outside the vetted directory). Exit codes 0/1/2 per the library contract; a consent question alone is not trouble.run phase3 --ids CSV [--json OUT]: the post-import scoped repair step, run from the library directory: exactlylibrary --id --sweep --only all --apply --all --install-to-calibreplus a pre/post epubcheck summary over the swept books. The phase-3 skill's step-10 scope warning is mechanized: an unscoped library-wide call is refused with exit 2, never run by accident. The verb drives the shipped library runner through the real parser, so its flags cannot drift from the subcommand it wraps.- Non-interactive contract: both run verbs take
--non-interactiveand never prompt (nothing in bindery prompts); open questions surface in the JSON asdecisions_neededentries: theapply_lossyconsent question in a read-only phase1,manual_repair/investigatefor books left partial or unreadable in phase3. - Skill sync: the phase-1 and phase-3 skills name the run verbs and the machine-readable contracts (the skill files live in the library directory, outside this repo).
- Dependencies: vir-tui 2.3.0 folded into the lock; the pyproject floor
stays
vir-tui>=2.2.0(additive bump at this release). - Docs and hygiene: CLAUDE.md's last surviving
calibredb add_formatline retired (it contradicted the v0.24.0 subprocess removal and carried a-applytypo); README's--sweepbullet and the pyproject description no longer advertise the validation daemon's speedup, which never engages because the daemon's classpath omits epubcheck'slib/dependencies (the fix is a recorded gate-behavior decision, not a drive-by);venv/and.venv_ci/are gitignored. Test count: 277 → 294.
The 2026-09-05 full-library sweep (testing_facility/top500candidates/REPORT.md)
catalogued the top recurring codes: RSC-005 (164,302), RSC-020 (8,431), PKG-010
(4,112), RSC-007 (3,219), RSC-012 (1,940), HTM-025 (800). Bulk RSC-005 repair stays
rejected (the spec non-goal stands); everything else gained a deterministic,
epubcheck-gated, opt-in repair. The structural-repair set is now twelve; --all
includes all three.
--prune-missing-resources(PKG-010/RSC-007) removes references to files the archive does not contain: dead<link>elements (dead_links_pruned), anchors' href to absent files with the text kept (missing_file_hrefs_stripped), absent<img>sources replaced by their escaped alt text when they carry one (missing_imgs_unwrapped) or dropped when they do not (missing_imgs_pruned), and orphaned non-spine OPF manifest items (manifest_items_pruned). Spine documents are never pruned: a missing spine document is a damaged fragment for the spine-integrity report, not a pruning candidate.--strip-broken-anchors(RSC-020/RSC-012, plus the HTM-025 scheme half) strips href attributes that cannot resolve while keeping the anchor text byte-for-byte: a#fragmentthe target document does not define (broken_fragment_hrefs_stripped; the anchor keeps its text, NCX navTargets fall back to the document target so chapter navigation survives, and the fragment is never re-pointed at a guessed sibling document), and non-resolvable URI schemes (nonfile_scheme_hrefs_stripped; fixed resolvable set: http, https, mailto). NCX counter:ncx_fragments_stripped. The id set for fragment checks is built from the documents as they will look when the pass runs (core transforms,--reserialize,--fix-id-colonsapplied), so an id rename can never make a valid reference look broken.--encode-url-spaces(the Death Masks shape: 67 RSC-020 "not a valid URL") percent-encodes raw spaces in src/href attribute values across the package — OPF manifest href, NCX content src, content documents (counterurl_spaces_encoded). Scope is fixed to the space character; archive entry names are untouched.- HTM-025 ampersand half closed by test:
escape_bare_ampalways covered attribute values (transforms run on raw text); the URL-attribute case is now pinned by an explicit test instead of an assumption.
Fixture validation (all /tmp copies, gate-accepted, zero regressions):
| Book | Before | After | Fixes |
|---|---|---|---|
| Swann's Way | 0f/31e/1w | 0f/2e/0w | dead_links_pruned:29, nonfile_scheme_hrefs_stripped:1 |
| Sodom and Gomorrah | 0f/53e/0w | 0f/42e/0w | ncx_fragments_stripped:9, broken_fragment_hrefs_stripped:2 |
| Death Masks | 0f/68e/34w | 0f/1e/34w | url_spaces_encoded:67 |
Every surviving finding is RSC-005 (the non-goal) or the Death Masks entry-name warnings (see below). The full label-vs-reality findings postscript lives in roadmap.md Phase 12; headline: the staged "PKG-010" book has no missing resources at all — its 34 PKG-010s are "file name contains spaces" warnings about the zip entry names, which no shipped flag touches. Renaming entries and rewriting every reference is a possible future flag.
scripts/FastSweep.javanow merges the audit (CSVfatals,errors,warnings,path, the formatbindery library --auditreads) and extract (path ||| CODE,...) prototypes behind--mode=audit/--mode=extract, keeping the stdin +parallelStream()shape.- The prototype's extract mode never worked:
CheckingReportbuffers every message and writes nothing to its writer untilgenerate()— andgenerate()NPEs without a precedinginitialize(). Every code list in the prototype'sraw_errors*.txtruns came back empty. The merged harness follows the CLI's own lifecycle (initialize→ validate →generate) and extracts codes from the JSON. The committed REPORT.md's per-book code attributions should be treated as unverified until regenerated with the fixed harness. scripts/fast_sweep.py(stdlib-only) is the wrapper: locates the epubcheck jar (--jar/EPUBCHECK_JAR/ parsed from the launcher), compiles the harness once with--release 25(cached on mtime), scans a directory or a path list, and--summaryaggregates extract output into the per-code REPORT-style table. Measured on the 14 staged fixtures: ~4.5 s across all cores vs ~42 s sequential.- The audit CSV feeds
bindery library --auditcleanly (smoke-tested for candidate selection both ways).
- epubcheck 5.3.0 surfaces disagree on counts: the human listing prints raw message
totals while the
--jsonchecker block prints deduplicated ones (Swann's Way: 31 vs 2 errors). bindery's gate reads the JSON surface consistently for both measurements, so gate decisions are unaffected. FastSweep's audit mode carries the raw CheckingReport counts; that CSV is used for candidate selection only. - Related, unchanged on purpose: validate.py's persistent daemon launches
java -cp ".:epubcheck.jar"without epubcheck'slib/dependencies, so it always fails its first check and silently falls back to the subprocess JSON path on this machine. Fixing the classpath would flip gate measurements from deduplicated to raw counts — a gate-behavior change that gets its own decision. - Tests 260 → 277: transform units (encoding, protection, idempotency, HTM-025), repair-level opt-in/counter/output tests for all three flags, the structural default-off case list, and the CLI wiring tuples.
- The element downgrade. The second half of the option-B verdict:
--downgrade-epub3-tagsrewrites EPUB3/HTML5 semantic elements to their EPUB2 equivalents —figureandsectionbecomediv,figcaptionbecomesp(counterepub3_tags_downgraded). Existing classes are kept and the semantic name is appended (<figure class="photo">becomes<div class="photo figure">), so class-selector stylesheets keep working. - CSS protection, generalized.
css_protected_tags/style_block_tagstake the tag set as a parameter now; a book whose stylesheet stylesfigure { ... }(element selector) has that name protected book-wide and the tags left untouched — preservation wins over compliance, and the book keeps its RSC-005 findings. The illegal-tags flow is behaviorally unchanged (same helpers, same defaults). - The structural-repair set is nine;
--allincludes the flag; the epubcheck gate applies as with every fix. - Tests 254 → 260: the three mappings, class preservation (both quote styles), the self-closing form, the protected-name path, and the end-to-end run with and without a styling stylesheet.
- The attribute scrub. Brandon picked option B on the NEW-AUDIT brief:
the low-risk attribute half ships first, the element downgrade separately
with its CSS-protection work.
--strip-epub3-attrsremoves the three EPUB3-only attributes epubcheck rejects on an EPUB2 package —page-progression-direction,epub:type,aria-label(counterepub3_attrs_stripped), in content documents and the OPF alike. - Fixed set, documented. The transform matches exactly those three names
and nothing else:
type="text"and the wider aria family survive, so a reader-legitimate attribute can never be swept up by accident. Extending the set requires a named epubcheck finding, per the roadmap note. - The structural-repair set is eight now;
--allincludes the flag; the epubcheck gate applies as with every fix. - Tests 250 → 254: the three attributes in both quote styles, the lookalike-survival guarantee, and the off-by-default / on / end-to-end run over an OPF and a content document.
--fix-page-mapnormalizes the two page-map defects epubcheck rejects on older HarperCollins / Anna's Archive conversions: the non-standardpage-map="page-map"attribute on the OPF<spine>(counterpage_map_stripped), and the classless NCX<pageList>that trips RSC-005 'missing required attribute "class"' (class="pages"injected, counterpagelist_class_added; a pageList that already carries a class is untouched).- Gated as a structural repair: opt-in, never part of the well-formedness
core, included by
--all, and epubcheck-gated like every other fix. The structural-repair set is seven now. - Tests 244 → 250: both quote styles for the spine attribute, a spine
without the attribute, injected/self-closing/already-classed pageList
forms, and the off-by-default / on / end-to-end zip render through
repair_epub.
bindery library --install-to-calibrewrites through cquarry now. Thecalibredb_replaceshell-out (acalibredb add_formatsubprocess) is replaced byinstall_format(): the repaired EPUB is placed atomically at the catalogued path — same directory, samedata.name, so Calibre's layout never changes — and thedatarow is re-registered throughcquarry.write.WritableCalibreDB(remove_format+add_formatin onebatch()transaction, becauseadd_formatrefuses case-insensitive duplicates). Two things improve beyond the crash fix: the storeduncompressed_sizebecomes the repaired file's true size (the CLI path updated it, but the row's truthfulness now holds for the fresh-format case too), and the book lands inmetadata_dirtied, so Calibre regenerates the sidecar.opfand re-pushes metadata to wireless readers — the raw subprocess never queued anything.- Fresh-format case. A book with no catalogued EPUB row gets the repaired
file placed under the repaired file's stem and a row registered fresh (the
resolver cannot see such books — its id map IS the format rows — so the
legacy
(id)guess plusCALIBRE_DBPATH, the old calibredb library contract, carries the id). - Failure posture. A database failure (locked, missing book) degrades to the atomic in-place save with a warning instead of losing the repair or crashing a multi-hour sweep; when the file was already placed, the warning says the row may be stale.
- Dependency.
uv.lockmoves to cquarry 1.9.0 (f22bbe7) in the same release, closing the lock-refresh note recorded at the 1.9 sync. - Tests 240 → 244: the routing battery was rewritten against the real write
module (id-wins-over-directory, row follow-through + queueing, guess via
CALIBRE_DBPATH, degrade paths for a wrong guess / missing library / database failure, the fresh-format placement).
- Fixed:
bindery library --install-to-calibrecrashed swapping repaired files back into the library. Thecalibredb_replacecall passed--replacetocalibredb add_format, but that flag does not exist — replacement is add_format's default behavior (--dont-replaceopts out) — so every install died withcalibredb: error: no such option: --replaceand aCalledProcessError(hit on a real repair pass, 2026-08-31). The subprocess call is now the plain four-argument form. The routing test that pinned the bad flag flips to reject it, and a dedicated regression test pins the exact command shape. spec.md and README no longer advertise the nonexistent flag. Phase 11 (roadmap) later retires the calibredb subprocess entirely in favor ofcquarry.write.WritableCalibreDB.add_format.
library --id <ids>: Added comma-separated book-id scoping for the sweep, mirroringaudit --id. Resolves EPUBs through cquarry'sget_format_path()viaCalibreIdResolver.audit --idcomma lists: The--idflag now supports a comma-separated list of IDs.- Spine-integrity reporting: Both audit and repair reports gain a field counting manifest/NCX references whose target files are absent from the archive, with a classification:
convention(consecutive chapter span despite absent files, e.g. bloated ToCs) orfragment(broken span).
bindery auditnames the corruption. The audit's single decompression pass now fully reads EVERY archive entry (CRC + real decompression, not just the central directory's word) before the text analysis runs, and a corrupt entry is reported as its own CORRUPT verdict —corrupt:N (first: <entry>)— in every mode, tagged like any other finding. A CRC-broken entry decompresses to nothing, and emptytext calling that EMPTY was the right alarm for the wrong disease: the re-source advice that follows from EMPTY ("content-less stub") mislabels a file whose problem is a damaged archive, not missing content. Emptytext now steps aside for corrupt books (classify returns CORRUPT; its buckets exclude them).library --sweep'sunreadablebucket splits by disease:not_a_zip/truncated/encrypted/corrupt_entry, so a CRC-damaged download is distinguishable from a DRM'd or truncated one without leaving the sweep (zipfile's message already names the broken entry; the summary prints per-reason counts).- The phase-1 skill's hand-rolled
zipfilecorruption sweep is retired — §2 now names the built-in verdict.test_bad_crc_entry_reads_emptyflipped to assert the corruption verdict instead of pinning the old empty-text reading.
bindery audit monolithicjoins the analyzer set (andall). One spine document at or above 300,000 characters flags — a book epubcheck and every other analyzer pass that still will not render on real readers (the motivating case: a ~30M-char dictionary EPUB, invisible to emptytext because it measures whole-book volume and to epubcheck because it never sees renderer memory limits).--max-doc-chars Nmoves the floor; the report carriesmax_doc_charsplus the offending document's href. Under-threshold books stay silent, like THIN. Reuses the shared visible-texts cache — no second decompression pass.- Wiring:
--id,--tag, directory and library modes all compose unchanged; flagged books tag like every other analyzer's. Phase 7's version-pin half shipped in v0.19.2. - Docs: spec's audit section, README, and the phase-1 skill's
"Chars per content document" step (no tool; run inline →
bindery audit monolithic).
CalibreIdResolver._loadoverformat_path_index(). The path→id map is now cquarry's canonical index (onedata ⋈ booksquery built exactly likeget_format_path()) instead of a per-bookget_format_path()loop — same construction, N queries collapsed to one. Keys are re-normalized the resolver's historical way (Path.resolve().lower()) so symlinked library directories and case-insensitive matching behave exactly as before. The(123)directory-name regex remains the documented no-catalog fallback. Theaudit.pyraw-join swap was waived at the Phase 9 design session (its three targeted joins are cheaper than whole-library hydration and bindery-cli wants per-book maps, not row dicts); do not "improve" it into a regression.- Dependency: requires cquarry ≥ 1.8 (
format_path_index). Theuv.lockstill pins the pre-1.8@maincommit until cquarry's 1.8.0 commits are pushed; after that, oneuv lock --upgrade-package cquarrylands the lock on current main. CI installs@mainfresh and self-corrects the same way.
- Fixed:
bindery audit --idwas unreachable from the CLI. v0.19.0 documented--idand shippedrun_single, but only the module's own argparse main (python -m bindery.audit) registered the flag; thebinderyconsole script's audit subparser never did, so the documented invocation died with "unrecognized arguments". The subparser now carries--id BOOK_IDandrun_audit_cmdroutes it torun_single(rejecting a directory argument with the module main's error text). Regression tests mirror the v0.18.1--tagwiring battery, which this bug duplicated: the earlier one shipped the write path unwired, this one the read path. - Removed a dead branch in audit's module main.
main()testedargs.dry_run, which no parser defines, so the "[DRY RUN]" header variant could never fire. - Version pin. New
tests/test_version.pyfails the suite whenpyproject.tomlandsrc/bindery/__init__.pydisagree (the v0.19.1 drift class); Phase 7's version-sync box. - Docs. pyproject's dependency comment and CLAUDE.md's hard constraint said
both git deps were hash-pinned; only
vir-tuiis (cquarry deliberately tracks@mainsince v0.19.0), and both texts now say so. The README's empty## Usageheading now introduces the three verbs.
- Dependency bump (deliberate pin move). The
vir-tuipin moved fromd13ad0etoe53f17e(vir-tui 2.2.0), per the repo policy of pinning exact commits and bumping deliberately. 2.2.0 is additive —progress_box(),interactive_session(),prompt_float/prompt_path/confirm,out_note,text_mode(), and results-pager search — and every API bindery-cli uses (ui.tqdm,ui.info,ui.print_header) is unchanged, so no behavior change is expected;uv.lockregenerated to match the new pin. - Version sync fix.
src/bindery/__init__.pystill said0.18.0whilepyproject.tomlsaid0.19.0; both now carry the release version (0.19.1) per the "pyproject must match VERSION below" rule.
- Accurate Calibre id resolution (no more guessing).
--install-to-calibrepreviously extracted the book id from the(123)directory-name fragment — a heuristic that replaces the wrong book whenever a directory was hand-renamed or its number no longer matches the catalog. Newlibrary.CalibreIdResolverbuilds a lazy, one-shot EPUB-path → id map through cquarry's own layout logic (CalibreDB.get_format_path()), so the id comes frommetadata.dband renamed directories cannot misroute a replacement. The(id)regex survives only as the no-catalog fallback; with neither source the repaired file is saved atomically in place (previous behaviour). - Single-entity audits:
bindery audit all --id 1234. New--idmode fetches exactly one row through cquarry'sCalibreDB.get_book()(no library-wide cache), resolves the EPUB viaget_format_path(), and reports the same verdicts as directory mode. Composes with--tag: the book is tagged only if the audit flags it. Mutually exclusive with the directory argument. - Dependency unpinned.
cquarrymoved from a frozen pre-1.1 commit to@main, matching Hermitage and CalibreQuarry — CI now always exercises current cquarry (1.6.x) instead of a year-old snapshot that lackedget_book/add_tag. - Roadmap: Phase 4 (Format Path Resolution, Safe Tag Application, Single-Entity Fetching) and the Phase 6 "cquarry Integration" checkbox are closed.
- Tests: 204 → 216 (12 new) — the resolver (catalogued hit, DB-truth-over-directory-name,
unknown file, missing catalog), the regex fallback, and the replace routing (resolver id
wins, regex fallback, atomic in-place fallback with
subprocessmocked);run_single(clean pass, unknown id, book without an EPUB) against a real minimalmetadata.db+ synthetic EPUB.
cquarry 1.2 adoption: audit tagging now actually reaches the write path, and tagged books regenerate their OPFs.
- Fixed:
audit --tagwas unreachable from the CLI. v0.18.0 documented--tag TAGand shipped_apply_audit_tag(), but theauditsubparser never registered the flag andrun_audit_cmdnever passed it — the write path existed only for Python callers. The flag now parses, defaults off (read-only audits stay read-only), and reachesrun_audit_library(tag=...); regression tests cover all three properties. - Tagged books are queued for OPF regeneration. The pinned cquarry bump (1.1 → 1.2) means every
WritableCalibreDB.add_tag()now records the book id in Calibre'smetadata_dirtiedqueue — the table upstream consumes to decide which sidecar.opfs to regenerate (and re-push to wireless readers) at next startup. Previously a bindery-cli-applied tag would appear in the GUI but never reach OPF/wireless sync. Verified end-to-end against a synthetic library: flagged book tagged,metadata_dirtiedgains exactly that id, clean books untouched. - Requires
cquarry@ e19c24c (v1.2.0); pin bumped accordingly.
cquarry 1.1 adoption: canonical format-path resolution and an opt-in tagging pass.
- Canonical EPUB resolution: library-mode audits (
bindery audit ...with no directory argument) now resolve each book's EPUB throughcquarry.db.CalibreDB.get_format_path()instead of hand-building<root>/<books.path>/<name>.epub. The storage-layout logic lives in exactly one place across the ecosystem, and a missing file surfaces as a normal scan error naming the expected path. --tag TAG(opt-in): after a library-mode audit, applyTAGto every flagged book via cquarry's separateWritableCalibreDBwrite module (trigger-safe: registers Calibre'stitle_sort/uuid4SQL functions, bumpslast_modified, cleans link tables before tags). The audit itself remains strictly read-only; nothing is written unless--tagis passed, and THIN emptytext advisories stay untagged. Books already carrying the tag are skipped (idempotent). Calibre must be closed so the write does not fight its lock.- Requires
cquarry>=1.1. - Tests: suite still green (201 tests) plus an end-to-end smoke run against a synthetic library:
foreign-language body text flagged, tagged
[Flagged],last_modifiedbumped, second run reports the book already tagged.
The default repair pass is well-formedness only again. v0.14.0 had promoted six structural
repairs into the always-on HTML_TRANSFORMS, so a plain bindery repair could delete
attributes, unwrap elements, and fabricate content on a book whose only defect was a stray
ampersand — exactly what spec.md forbids. Each now requires its own flag (on both repair and
library); --all still enables everything: --fix-empty-body, --fix-missing-title,
--fix-id-colons, --unwrap-block-in-inline, --strip-invalid-value,
--unwrap-illegal-tags.
The CSS precondition is real. --unwrap-illegal-tags no longer trusts callers to scan
stylesheets first. Every .css entry in the book plus each document's inline <style> blocks
are scanned for illegal-tag names used as element selectors (w { }, p st, x > w { },
pagebreak.new:after {}; class/id selectors like .st and #w do not protect), and those
names are protected for the whole book — styled formatting can never be silently destroyed.
Nested at-rules work (@media print { o > sentence {} }). This ports
scripts/find_css_illegal_tags.py into the library as transforms.css_protected_tags.
Housekeeping: git dependencies pinned to exact commits (vir-tui d13ad0ed = 2.0.0,
cquarry 4b771aa = 1.0.2) instead of floating branches, so builds are reproducible;
__init__.py VERSION resynced with pyproject.toml (drifted three releases behind at 0.15.0 vs
0.16.3); first tags cut (v0.16.3 backfilled on its release commit, v0.17.0 now);
spec.md / CLAUDE.md / README.md brought back in line with the code (audit subcommand, the pins,
the restored opt-in contract); roadmap Phase 6 boxes closed; run_epubcheck's docstring moved
above the daemon call where it is an actual docstring. Suite: 183 -> 201 tests.
- Fix: Resolved
test_audit.pyimport path failure. - Fix: Fixed
unwrap_block_in_inlinedata loss regex logic by capturing full text blocks. - Fix: Added
--replaceflag tocalibredb_replaceto prevent DB crash when file exists. - Fix: Corrected
analyze_brokentagsloop to properly analyze spines and docs instead of nonexistent iter method. - Fix: Removed hardcoded JVM release target in
EpubcheckDaemon. - Fix: Added regex word boundaries in
fix_id_colonsto prevent URL corruption. - Fix: Corrected
strip_invalid_valueregex to safely strip whitespace. - Fix: Fixed empty tag replacement regex in
fix_missing_title.
- Replaced local
ui.pymodule with standardizedvir-tuipackage.
- Build: Cleaned up orphaned scratch files to resolve strict ruff linting failures.
Centralized Calibre DB Access: bindery-cli has transitioned to the unified cquarry library for all read-only metadata.db accesses. The internal bindery.audit DB connection logic has been completely replaced with cquarry.db.CalibreDB. This inherits robust Calibre lock handling, database snapshotting, and ensures query logic stays perfectly synchronized with CalibreQuarry and Hermitage.
- Integrated EPUB Auditing (
bindery audit): Successfully absorbed the externalaudit_epubcodebase directly into bindery-cli as a native subcommand. This transforms bindery-cli from a pure repair tool into a complete EPUB lifecycle toolkit (Audit -> Repair -> Validate).content: Identifies non-English text by sniffing the text blocks, reporting the predominant script block (e.g., Cyrillic, CJK) to catch untranslated or mis-encoded EPUBs.pagenumbers: Detects books polluted with hardcoded print page numbers (using sliding window regex to find high-density sequential digits interrupting prose), seamlessly bridging intobindery repair --strip-paginationfor the fix.emptytext: Audits EPUBs to find effectively empty books or spine stubs (below configurable--min-charsand--thin-charsthresholds).ocr: Scans for systemic OCR damage by detecting disproportionately high densities of hyphenation, disjointed characters, or garbage sequences.- Library Integration: Directly operates on a Calibre library tree or loose directories, producing actionable console reports designed to be piped into
bindery library --audit.
- Supplementary Phase Structural Repairs: Integrated six highly targeted regex-based transforms to resolve the most common markup-level EPUB errors across the library, all safely guarded by the EPUBCheck gate:
- Duplicate NCX
playOrder: Safely rewrites duplicated playOrder attributes sequentially. - XML
idColon Violations: Translates illegal colons inid="X:Y"and their matching#X:Yfragment references to valid underscores. - Empty
<body>: Appends a non-breaking space to strictly empty body tags to satisfy parser requirements. - Missing
<title>: Injects a<title>Unknown</title>fallback in the<head>if missing, handling both empty<title/>self-closing tags and entirely absent tags. - Block-in-Inline Nesting: Safely unwraps
<span>tags that illegally contain a block-level element (e.g.<div>or<p>), leaving the block element intact. - Invalid
valueAttributes: Systematically strips invalidvalue="..."attributes from elements like<div>,<span>,<p>, etc.
- Duplicate NCX
- Illegal Tags Unwrapper: Added a sweeping transform that targets completely invalid or deprecated HTML tags that break EPUB3 validation (like
<st>,<font>,<sentence>,<o>,<w>, and<pagebreak>). Unwraps the tags without deleting their inner text. Automatically excludes tags when referenced by an EPUB CSS stylesheet to guarantee 100% format preservation.
- Epubcheck Daemon: Radically accelerated the
bindery libraryvalidation gate by implementing a transparent, persistent Java daemon. bindery-cli now automatically compilesFastDaemon.javain the background and pipes EPUB paths to it, eliminating the JVM startup penalty. - Validation time dropped from ~5 seconds per book down to under ~0.05 seconds per book, cutting library sweeps from 6 hours to 10 minutes.
- UI Upgrade: Integrated
tqdmprogress bars directly into the corebindery librarycommand, providing a real-time visual progress bar and ETA during the long-running sweep and candidate-processing phases. - Standardized documentation to reflect that
tqdmis a core required dependency, formally moving away from the "strictly stdlib-only" constraint.
- CLI Help Upgrade: Explicitly surfaced the
--install-to-calibreoption on the rootbindery --helpmenu by creating a dedicatedlibrary-specific integrationargparse group. - Documentation: Added a prominent code example for
--install-to-calibreto the Usage section of theREADME.md.
- CLI Help Formatting: Restructured the root
bindery --helpmenu to natively render the shared fix flags as a properly alignedargparsetable, matching the clean visual style of the subcommands and other portfolio tools.
- Oceanstrip Merged: Fully incorporated the
oceanstripstandalone tool directly into bindery-cli's primary pipeline. - Added
--strip-watermarksflag to systematically detect and remove producer/distributor watermarks (e.g. OceanofPDF stamps and zero-byte marker files, ABC Amber LIT Converter injections) from EPUBs. - This lossy transform is correctly governed by the
validate.no_worseEPUBCheck oracle, ensuring clean structural extraction without regressing file validity. - The
--strip-watermarksargument is automatically engaged when running bindery-cli with--all.
--strip-broken-tags: A new lossy transform to find and safely remove leaked HTML closing tags missing their open brackets (e.g.,</p>) that render as raw text in older uncorrected EPUBs. Guarded by thevalidate.no_worsegate.--install-to-calibre: A safer alternative to atomic replacement for Calibre users. Usescalibredb add_format --replaceto swap the corrected EPUB natively into the database, preserving all metadata, custom IDs, and read progress. Falls back to atomic replacement if the Calibre ID cannot be parsed from the filepath.--all: Added a meta-flag to automatically enable all opt-in non-fatal fixes and lossy strips (pagination, watermarks, tags, attributes, entities, image alt tags, etc.) simultaneously for a comprehensive repair.
- UI Upgrade: CLI scripts now feature rich terminal output with ANSI formatting,
tqdmprogress bars, and clear summary blocks. The project now relies ontqdmfor output formatting.
Repairing the same book twice now produces identical bytes. It did not before,
and had not for as long as the archive rewrite has existed. The mimetype entry was
written as zout.writestr("mimetype", ...) with a bare string arcname, and a string
arcname makes zipfile mint a fresh entry stamped with the current clock. Every other
entry in the archive is written from its source ZipInfo and keeps its own timestamp,
so this was the single entry that moved: two repairs seconds apart differed in exactly
those two bytes, with every entry's content identical.
Nothing malfunctioned because of it. No reader and no epubcheck run cares about that field. What it cost was the ability to checksum or diff two repairs to confirm they agree, which is exactly the check the v0.10.1 sweep leaned on, and it quietly made "deterministic repair" false at the byte level. spec.md now says determinism is meant at the byte level, so the claim is testable rather than aspirational.
The entry now carries the source entry's timestamp, or 1980-01-01 (the earliest a zip
can represent) when the entry is being added and there is nothing to inherit. It is
still built as a fresh ZipInfo rather than reusing the source one, because OCF
requires the mimetype entry to carry no extra field and reusing a broken book's entry
wholesale would propagate that violation; external_attr is set to what writestr
used to apply, so the timestamp is the only change to the output.
Measured, not assumed: three separate processes spaced over five seconds now produce one identical hash where they produced three. Over 99 real books, content, per-entry metadata, and fix reports are unchanged from v0.10.1, while timestamp preservation goes from 0/99 to 99/99. Three tests cover it, one of which documents that the naive "repair twice and compare" check passed by luck before the fix whenever both runs landed in the same clock second. Suite 122 to 125 tests.
A maintenance sweep, plus the roadmap decision recorded below.
Three bugs. Each fix was measured against the real library rather than argued from a fixture: the old and new code were run side by side over all 4,926 books (268,190 documents, content plus NCX). One of the three was actively firing; the other two are traps that were waiting for the right input.
--strip-bad-attrscould destroy a tag's self-closing slash. The unquoted-attribute-value pattern[^\s>]+swallowed the/in<img 31=x/>, so dropping the offending attribute left<img>: the one fix whose whole promise is "only the offending attribute is dropped" turned a well-formed self-closed tag into an unclosed one, introducing the very fatal it exists to remove. The gate would then reject the book, costing it every other repair it had earned. The pattern now stops before a/that ends the tag, while a/inside a value (a URL) is still consumed. No book in the library carries the pattern today, so this one was latent.strip_prolog_junkcounted a phantom fix for legal whitespace. Whitespace in the prolog is legal XML unless an XML declaration follows it, but any leading whitespace was stripped and counted. That marked the document changed, which forcesrepair_epub'sdecode("utf-8", "replace")round-trip on a file that had nothing wrong with it, and turned books that should reportnochangeinto books that spend two multi-second epubcheck runs to concludeequal. Whitespace before a declaration (where it really is fatal), a BOM, and any non-whitespace junk are still stripped. This is the one that was live: across the library the transform fired 119 times before and 106 after, so 13 phantom fixes in 7 books are gone, and every genuine case (a BOM ahead of an XML declaration, the real form in this library) still fires. Running the whole pipeline over those 7 books before and after confirms the change is surgical: every other fix count is untouched (fix_ncx_ids10 stays 10,fix_named_entities30 stays 30,stripped_pagination1 stays 1), only the phantom rewrites disappear.- Invalid-id renaming was not deterministic.
--fix-idsiterated the id set, so when two invalid ids wanted the same replacement (1:2and1_2both yieldid_1_2) which one received the extra_prefix depended on the hash seed: the same book repaired to different bytes from run to run, against a project that sells itself on deterministic repair. Both the OPF and NCX paths now plan renames through one sorted helper,_plan_renames.
The lint result no longer depends on which ruff is installed. There was no
[tool.ruff] section, so the rule set came from ruff's defaults: CI's pinned
0.15.20 passed clean while 0.16.2 reported eight findings on the same tree. The
selection is now pinned in pyproject.toml (ruff's default set plus import
sorting, pyupgrade, and bugbear), with a note on the two families deliberately left
out because they fight intentional code. CI moves to actions/checkout@v5, pins
ruff 0.16.2, and lints . rather than three named directories so a new top-level
script cannot escape.
Smaller: repair_epub opens the source archive once instead of twice; the dead
skip_empty parameter is gone from pagination._nearest; library --limit 20 on
a tree with 3 candidates counts [1/3] instead of [1/20]; and pyproject.toml
catches up to the VERSION bump in __init__.py. Suite 114 to 122 tests.
The Calibre hook question is settled, and it is FileTypePlugin with
on_import = True. Researched against the Calibre source rather than guessed:
run(path_to_ebook) is handed the file being imported and returns the path to a
modified copy, and Calibre imports that instead. So a repaired EPUB is what enters
the library, the user's original on disk is never touched, and nothing writes to
metadata.db.
That kills a roadmap item. The "optional metadata.db nudge so Calibre notices
the new file size" existed only because in-place replacement changes a file behind
Calibre's back. Under on_import the repair happens before Calibre reads the
file, so the size it records is already right. The nudge was solving a problem
that the correct hook does not create.
Two constraints recorded with the decision, because they shape what the plugin can
be: it runs inside Calibre's bundled Python, so it must vendor its own code and
cannot assume bindery-cli is installed (the minimal-dependency rule is what makes this
practical, and the optional html5lib path cannot come along); and epubcheck
cannot gate an import, being an external Java process of seconds per book, so the
plugin does the deterministic transforms and leaves gated work to the CLI where a
human is watching.
Locale hardening for the epubcheck wrapper (roadmap 5.2, the last open Phase 5
item). The wrapper parsed counts from epubcheck's human-readable summary line,
which the JVM localizes: on a non-English locale every book parsed as None and
was reported as error. Counts now come from epubcheck's locale-independent
--json - output first (the checker totals, verified against epubcheck
5.3.0), with the English summary-line regex kept as the fallback for
epubchecks too old for --json, and the JVM pinned to English via
JAVA_TOOL_OPTIONS (appended, so existing JVM flags survive) so that fallback
stays meaningful. New tests/test_validate.py (9 tests) mocks
subprocess.run itself to pin the JSON path, both fallbacks, the env pin, and
the failure modes; suite grows 105 to 114.
Two new fixes, born from a Dan Brown import batch whose books opened fine but carried 89 and 225 epubcheck errors.
--fix-idsnow covers the NCX. Old conversions stamp navPoint ids from UUIDs (digit-led) or colon-bearing strings; epubcheck rejects every one as RSC-005. Invalid NCX ids are renamed with the sameid_scheme as manifest ids. NCX ids are internal to the NCX (nothing in the OPF or content documents references them), so the rename needs no cross-file bookkeeping. Counted asfix_ncx_idsin reports.- New:
--add-img-alt(opt-in). Addsalt=""to<img>elements missing the required attribute. Rendering is unchanged (an empty alt draws nothing), but this is the one transform that adds markup the author never wrote, andalt=""asserts "decorative" to a screen reader where a missing alt did not; hence opt-in, never a core transform. Quote-aware, idempotent, CDATA and comments never rewritten; counted asimg_alt_added.
Real-world validation: the two motivating books went 89 errors to 0 and 225 to 190 (the remainder are dead NCX fragment identifiers, a fix candidate we deliberately passed on), both accepted by the normal gate.
New: --escape-unknown-entities (opt-in). The last fix candidate from the
v0.5.0 audit. An entity name that is neither XML-predefined nor in the HTML5 table
stays a fatal "entity not declared" (the core fix_named_entities deliberately
leaves it); with this flag such references are escaped (&foo; -> &foo;),
which renders exactly as browsers already render an unknown entity: the literal
text.
- Conditionally semantics-preserving, hence opt-in: rendering is identical except
against a document whose DOCTYPE internal subset declares the entity, so any
document carrying an internal subset (
<!DOCTYPE ... [) is skipped wholesale. - CDATA sections and comments are never rewritten (the standing transform
invariant), the normal epubcheck gate applies, and the fix is idempotent (the
&it emits is predefined and stays put on a re-run). - Available on both
repairandlibrary; counted asescape_unknown_entitiesin reports.
Phase 2 closes out: the audit workflow is now self-contained, and the mimetype fix joins the core repair set.
--sweep: re-audit integration.library --only fatals --sweepruns a live epubcheck sweep for candidate selection, replacing the separate CSV step (and with it the whole audit-path-mismatch bug class). Each sweep result is reused as that book's before-measurement, so no book is epubchecked twice. Mutually exclusive with--auditand--no-validate;--limitkeeps the sweep lazy.--json FILE: machine-readable run report. Per-book path, status, before/after counts, fix summary, and applied flag, plus the summary totals, for scripting and cross-run comparison.--manual-list FILE: the manual follow-up export. One path per line for every book the run did not (or could not) auto-repair: nochange, equal, partial, reject, error, unreadable.- A missing
mimetypeentry is added, and wrong or whitespace-padded content is normalized to the OCF constantapplication/epub+zip. The content is spec-constant, so this is deterministic and semantics-preserving; it is counted (mimetype_added/mimetype_normalized) and gate-checked like any other fix. - spec.md documents void end-tag swallowing (the 5.6 gap):
self_close_voidalso removes orphaned end tags for void elements (</br>,</col>), which are always invalid and cannot change what renders. Behavior unchanged since v0.4.2; the spec now says so.
The Phase 5 audit sweep: three confirmed safety bugs fixed, packaging honesty, and a round of CLI hardening and UX. Every fix ships with a unittest regression test.
Safety and correctness:
--strip-paginationcan no longer auto-apply a still-fatal book. Theno_worseacceptance bar for the lossy strip used to overwrite the gate's verdict outright, so a book going 3 fatals -> 1 fatal was classifiedacceptandlibrary --applyatomically replaced a book that still does not open.no_worsenow relaxes only the improvement demand: a result with remaining fatals is demoted topartialand never applied. This closes a hole in the hard rule that still-fatal books are manual work.- One corrupt
.epubno longer aborts an entirelibraryrun. A non-zip, truncated, or encrypted book raised out of the sweep and killed a multi-hour run with a traceback. Each book is now guarded individually; unreadable books are reported, counted in a newunreadable:summary line, and skipped.repairprints a clean error for the same case instead of a traceback. - The pagination strip no longer deletes
<p id=...>navigation targets. An id on the removed paragraph itself (the common<p id="page7">7</p>page-anchor shape) vanished with the block, breaking NCX page-lists and internal links; only inner<a id=...>anchors were rescued. Both removal paths now preserve it: delete-only keeps an emptied<p id=...></p>shell, and a merge hoists the id as an empty anchor. Single-quoted ids are recognized too.
Packaging:
html5libis now the optional extra the docs always promised. It moved fromdependenciesto[project.optional-dependencies], so a plain install is genuinely minimal;bindery[reserialize]pulls it in for--reserialize.
CLI hardening:
repairlabels partial output honestly. A book whose fatals were reduced but not cleared was written with arepaired:line that read as fixed; it now printsPARTIAL (still has fatals; needs manual work):.repairrefuses to overwrite an existing output file unless--forceis given.- Single-quoted attributes are visible to the OPF/NCX regexes. The NCX-001 sync, OPF location, and unique-identifier lookup all required double quotes, so a single-quoting toolchain made them silently no-op. All accept either quote now.
Book.EPUBis found. The library scan matches the.epubsuffix case-insensitively (Calibre emits lowercase, but a hand-added file should not be invisible).
UX:
- Progress output for long runs. A
[123/4051] Author/Title.epubline per book goes to stderr, so a mostly-clean library no longer shows hours of silence; stdout stays a clean report.--quietsuppresses it. - A warning fires when the audit CSV matches zero scanned books (the silent path-mismatch trap that read as "library is clean"). Paths are resolved on both sides first, so relative-vs-absolute mismatches no longer occur at all.
- Backup flags warn when inert.
--backup/--backup-inplacewithout--applyprint a note;--apply --strip-paginationwithout any backup flag prints a loud recommendation (the one lossy mode deserves a backup). libraryexits 2 when any book was rejected, unreadable, or failed epubcheck, so scripts and cron can detect trouble; 0 is a clean sweep, 1 a usage error.--limitlimits the scan, not just the work. Candidates are consumed lazily, so--only ncx --limit 20stops opening archives after the 20th candidate instead of probing every book in the tree.
New: --strip-pagination (opt-in, lossy). Removes print page numbers and running headers that a PDF/OCR conversion baked into the body text as literal paragraphs, which reflow into the middle of sentences ("where the hay cart 16 was taking him"). This is the first mode that removes visible content, so it is a deliberate, fenced-off exception to bindery-cli's semantics-preserving rule: off by default, and accepted by a new no_worse bar (no net-new fatals or errors) instead of the improvement-demanding gate, because a baked page number is valid markup that epubcheck cannot see.
- Removes only 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); page-listidanchors are hoisted into the merged paragraph so navigation still resolves. - A book is treated as paginated only when it has both a dense run of standalone arabic numbers (>= 20) and several confident mid-sentence interrupts (>= 3), so a merely chapter-numbered book is never touched. Roman chapter/front-matter numerals and year-range values are preserved.
- Three independent safety nets guard every edit, any failure leaving the document unchanged: character conservation (no prose character lost or fabricated),
<p>/<a>tag balance, and the epubcheck no-regression check. - Validated on /tmp copies of the real library: Fingersmith 372 numbers removed (zero left), Animal Farm 54 removed with all ten roman chapter numbers intact, zero prose characters changed in either, epubcheck no worse.
- EPUB 3 namespace prefixes are preserved.
--strip-bad-attrsno longer drops perfectly valid EPUB 3 prefixed attributes. It now correctly parsesepub:prefixandprefixdeclarations (e.g.epub:prefix="math: ...") instead of strictly requiring anxmlns:declaration to bind a prefix. - Nested orphaned void end tags are swallowed globally.
self_close_voidnow completely strips all explicit end tags for void elements globally (like</br>and</img>) after self-closing the start tag, preventing fatal XML parse errors when tools generate deeply nested orphaned void end tags (e.g.,<br><br></br></br>).
Bugfix and cleanup sweep. No new fixes or flags; several of these close real holes in the safety contract.
-
CDATA sections and comments are never rewritten. The transforms used to escape
&, convert entities, and self-close<br>inside<![CDATA[...]]>and<!-- -->, where that content is literal and already legal XML; escaping a&in CDATA-wrapped CSS/JS changes what renders. All body-text transforms (including--strip-bad-attrs) now skip these spans. This is now a spec invariant. -
Hyphenated custom elements are no longer mangled.
-,:, and.are valid XML name characters but not word characters, so the v0.2.0�boundary still let<colmatch inside<col-group>and self-close it. The matcher now requires whitespace,/, or>after the element name. -
The OPF is located via
META-INF/container.xmlinstead of "first.opfin archive order", so a stray duplicate OPF can no longer win and sync the wrong uid into the NCX. Falls back to the old behavior when container.xml is absent. -
--fix-idsupdates all references, not just the spine.fallback=,media-overlay=, and the EPUB 2<meta name="cover" content="...">also point at manifest ids; leaving them stale orphaned fallback chains and broke Calibre's cover detection when the cover item's id was renamed. -
Duplicate entry names survive the rewrite.
ZipFile.read(name)returns the first entry's bytes for every same-named duplicate (seen in broken EPUBs); entries are now read individually. -
Multi-codepoint entities are converted (
≂̸and friends become one numeric reference per codepoint) instead of being skipped. -
atomic_replacecleans up after itself and syncs the directory. A failure mid-replace no longer leaves a.bindery.tmpin the library, and the rename is fsynced so a crash right after a replace cannot lose it. -
--limit 0now means "process nothing" instead of being ignored; Ctrl-C during a long run exits cleanly (130) instead of dumping a traceback. -
repairnow writes the exact bytes the gate accepted. It used to produce the final output with a second repair pass that dropped--fix-ids,--reserialize, and--strip-bad-attrs, so the written file could be missing the very repairs epubcheck had just validated. The gated temp file is now copied to the output. -
An epubcheck failure no longer bypasses the gate. When epubcheck crashed, timed out, or produced unparsable output mid-run, the book was classified
unvalidatedandlibrary --applyreplaced it as if it had passed. Such books are now a distincterroroutcome: reported, counted, and never applied or written. Only an explicit--no-validateskips the gate. -
Unchanged archive entries are copied byte-for-byte. Eligible entries were decoded with
utf-8/replaceand re-encoded even when no transform fired, which would silently swap non-UTF-8 bytes for U+FFFD in otherwise untouched files. -
library --only fatalswithout--auditis an error. It used to silently treat every book in the library as a candidate; the README always saidfatalsneeds the audit CSV, and now the CLI enforces it. -
Audit CSVs without a header row no longer lose their first book; blank rows are skipped instead of crashing the load.
-
NCX
dtb:uidreplacement inserts the uid literally (a uid containing\1was previously parsed as a regex replacement template), and per-file change accounting no longer leaks across multiple.ncxentries in one archive. -
Cleanup: shared CLI flags are defined once for both subcommands, the transform pipeline is properly typed, and the spec/README document the new
erroroutcome and the byte-preservation guarantee.
- New
--strip-bad-attrs. Drops attributes that are invalid XML and so make a document unparseable: a name starting with a digit (e.g. a mangled31="") or a namespaced name whose prefix is never declared (e.g. Office VMLv:shapeswith noxmlns:v). It is surgical (only the offending attribute is removed) and a no-op on well-formed files, since those cannot contain such attributes. Off by default. - This cleared the last 2 markup-fatal library books that survived
--reserialize: The Selfish Gene (v:shapes) and The Rustonomicon (broken SVG31=""). Both now validate with zero fatals, open in Calibre, and preserve their full text. With this, the entire 38-book fatal set from the original audit is resolved.
- New
--reserialize(structural repair). Rebuilds content documents that are still not well-formed by re-parsing them with html5lib (lenient HTML5 recovery, like a browser) and re-emitting XHTML. This closes unclosed non-void elements (<p>,<div>,<span>,<blockquote>,<body>) that the regex transforms cannot, and even recovers some corrupted tag names. It runs only on documents that are not already well-formed, so good files are left byte-for-byte unchanged, and only when opted in. - New dependency: html5lib (for
--reserializeonly). Imported lazily; every other mode runs with no third-party dependency. This is the one approved exception to the minimal-dependency design. - Verified on the 12 markup-fatal library books:
--reserialize --fix-idsclears 10 of 12 to zero fatals (content preserved; the 2 holdouts are Office-VML and broken-SVG foreign content). All gate-accepted.
- Hardened
self_close_void. The matcher now requires a word boundary after the element name and is quote-aware, fixing a bug where<colmatched inside<colgroup>(self-closing it and orphaning the end-tag) and where a>inside an attribute value ended the tag early. This introduced fatals on 19 books during the library run; the gate rejected them, and they are now repaired cleanly. Already-self-closed tags are left untouched and not counted. - New
--fix-ids(RSC-005). Optionally rewrite manifest item ids that are not valid XML names (start with a digit, contain a colon) and update their spine references. Off by default, since it touches the OPF; the dc: metadata is never altered. On a real book this cleared 36 bad ids (794 to 723 errors), gate-accepted.
First release. A focused EPUB repair tool, sibling to oceanstrip, born from auditing a 3713-book Calibre library where 38 books carried fatal parse errors.
- Deterministic, semantics-preserving transforms: self-close void elements, named
entity to numeric reference, escape bare
&, strip pre-prolog junk, collapse a duplicated rootxmlns. - NCX-001 fix: sync
toc.ncxdtb:uidto the OPF unique identifier. - mimetype ordering/compression repair on rewrite.
- Two-mode epubcheck gate that understands fatal unmasking: when a book had fatals, success is fewer fatals, and the error count rising as hidden errors surface is not treated as a regression.
repair(single file) andlibrary(batch) CLI modes. Library mode is a dry run by default;--applyreplaces accepted books in place, atomically, with optional backups. Only the.epubis touched, so Calibre's Quality Check sync can reconcile the database.unittestsuite; minimal dependencies.
Validated on the real library: 24 of ~40 fatal books fully de-fataled (they now open), 6 partially improved and flagged for manual finish, the rest left untouched, and zero epubcheck regressions.