vir-tui floor raised to >=2.6.0 on Brandon's word, so the hacker theme is a supported surface for every lattice user: VIR_TUI_THEME=hacker styles the CLI formatters and the curses TUI's glyphs natively through vir-tui (no lattice-side code or flag; the environment variable is vir-tui's own mechanism). Targeted uv lock --upgrade-package vir-tui; the suite is green against the resolved 2.6.0.
- roadmap.md: the scripts/ retirement line no longer names a version. The 6.7.0 deprecation decision was "one cycle, retirement after aliases/cron are migrated", so the retirement lands in whatever release follows that migration; v6.8.0 shipped as the performance and adoption release with scripts/ untouched.
The large-library performance pass and the vir-tui adoption (issue #23), plus the vir-tui floor bump the companion sweep filed (issue #25):
--whereand--playlistrules parse once per invocation, not once per track: the regex split and the AST parse ran for every file on the library (50,000 redundant parses on a 50k-track scan) and now run once before the walk.- Snapshot diffs match moves in O(R + A) instead of rescanning the added list for every removed path (~400M comparisons on a 20,000-track genreMap diff become dict lookups keyed on the size+mtime signature).
--snapshot,--diff, and--exportDbread each file's tags and ReplayGain in one MutagenFile open instead of two (the newread_tags_and_replaygainseam; the export's track rows read the gains the scan already fetched), halving the disk opens and the mutagen parsing on the walks that touch every file.- The same three modes, plus
--playlist, walk the tree once and build the file total from that walk instead of a second full walk just for the progress-bar total. - Embedded-art probing goes in sorted order, so a two-format album's art pick no longer depends on readdir order.
- Terminal color follows vir_tui.core's gate, one policy across the workspace:
NO_COLOR=""no longer half-disables styling (the no-color.org truthiness alignment issue #25 flagged), and the interactive-CLI color-loss fixes from vir-tui 2.5.1 arrive with the floor bump. - The write-gate confirmations (
--stripRatings,--rerate,--apestrip,--embedArt,--flac2opus,--lyrics, and the--ingeststage gates) go throughvir_tui.confirminstead of hand-rolled input() parsing, inheriting vir-tui 2.5.3's prompt hardening. Deliberately not deduplicated:_reset_terminalkeeps its own subprocess-drivenstty sane, because vir_tui.reset_terminal's curses-engagement gate would skip exactly the post-flac/ffmpeg corruption it exists to fix. - vir-tui floor raised to
>=2.5.4per issue #25, with the targeteduv lock --upgrade-package vir-tui.VIR_TUI_THEMEpresets, including vir-tui 2.6.0's hacker theme, style lattice's vir-tui-rendered output wherever the installed library ships them; no lattice-side flag, since the environment variable is vir-tui's own mechanism.
The last three standalone scripts folded into the package as write modes, so PyPI, pipx, and PyInstaller users get the whole toolkit (issue #24; spec.md §4/§5/§6 amended before any code):
--embedArt(fromscripts/slipcover.py, living inmodes/artwork.pybeside--extractArt): embeds each album folder's cover image into the folder's audio files that carry no embedded art; files that already have art are never touched.--fetchadds the iTunes Search API lookup for folders with no art at all (https-only URLs through a seam that validates the download is a real JPEG/PNG before anything is written) and embeds the fetched cover in the same run. Dry-run by default,--applyto write, logged to<root>/embedart.log,--jsonsummary, TUI entry under ARTWORK.--flac2opus(fromscripts/flac2opus.py, newmodes/transcode.py): converts FLAC files to same-stem Opus via ffmpeg (--bitrate, default 128k;--workersparallel pool), verifies the duration, copies tags and cover art with mutagen, and commits through a temp file + atomic replace before deleting the FLAC (--keep-flackeeps it). The 6.6.2 script hardening is the contract: a pre-existing same-stem.opusis skipped outright, failures clean only the temp file and keep the FLAC, andREPLAYGAIN_*keys are never copied. Requires ffmpeg (exit 2 without it). Dry-run by default, logged to<root>/flac2opus.log,--jsonsummary, TUI entry under MAINTENANCE.--rerate(fromscripts/rerate.py, inmodes/stripratings.pybeside--stripRatings): rewrites exactly the two POPM bytes DeaDBeeF and foobar2000 read differently (127 -> 64, 254 -> 196), leaving foobar's canonical bytes, MusicBee's values, unrated files, and every non-MP3 alone. MP3/POPM-only by contract, idempotent, and the dry run reports the same read errors the apply pass would. Dry-run by default, logged to<root>/rerate.log,--jsonsummary, TUI entry under MAINTENANCE.- All nine
scripts/helpers are now launchers, and every one prints a deprecation line on stderr pointing at its mode. The directory retires in 6.8.0 (one deprecation cycle, so aliases and cron that hit the launchers keep working until then); the launchers keep their historical apply-by-default contracts unchanged.
genreMap's undo record is now written before the move it describes (issue #16):
- Every
--genreMap --applymove appends a pending intent row to the manifest and flushes it to disk (fsync included) before anything moves, then appends the completed row after the move succeeds. The old order moved first and recorded second, so a disk-full or write-back failure at the wrong moment could leave a completed move with no undo record and an uncaught traceback. A manifest that cannot take a record now refuses the move outright: the tree is untouched, the refusal is counted, and the run exits 1 with a clean stderr line, so a completed move always has durable recovery information. --revertresolves every interruption window from the two paths alone: a pending intent whose move never applied is skipped as unapplied (nothing undone, nothing overwritten), a completed-but-unrecorded move still restores from its intent alone, and rows whose source and destination both exist are never overwritten. A manifest written by any older version replays exactly as before.
Write-path hardening in the rating stripper and the FLAC-to-Opus converter, plus two workflow bugs in the ingest ritual and the lyrics fetcher (issues #17, #18, #20):
--stripRatingsno longer strips through a symlink: the protected-root guard resolves both sides with realpath, so a link pointing into a rating-protected library refuses with exit 2 exactly like the real path. Untagged FLAC/OGG/Opus/MP4/WMA containers (carrying no tag block at all) plan as clean files instead of crashing the run with an AttributeError. An APEv2 rating-0 shell no longer triggers a byte-changing rewrite: the save is gated on an actual removal, keeping both the zero-shell contract and byte-identical idempotence. And--apply --jsonreports the removals the write pass actually made, not the planning pass's count, so a file that errors or loses its tags between passes no longer inflates the summary (#17).scripts/flac2opus.pycan no longer destroy data in multi-format folders. A pre-existing same-stem.opusis skipped outright:ffmpeg -yused to overwrite it, and any later verification failure then deleted it. Every conversion now encodes to a.parttemp file that is committed with an atomic replace only after the duration check, the tag copy, and the save all succeed; any failure cleans up only the temp file, keeps the original FLAC, and the batch continues. The FLAC's ownREPLAYGAIN_*Vorbis comments are no longer copied verbatim onto the Opus output (they are computed for the lossless stream at the wrong reference for Opus; rescan the new files withlattice --replayGain) (#18).--ingest --apply --jsonno longer prints per-stage prompts into the JSON summary (a machine run proceeds the way a pipeline does), and the post-state health digest reads the tree at the layout the ritual built: Genre/Artist/Album after an applied genreMap stage, instead of flagging every genre-filed album as a stray wrong-depth finding. A declined genreMap stage (interactive runs) keeps the plain{artist}/{album}layout (#20).--lyricspaces only real LRCLIB traffic: an already-sided track and an untagged file make no request and take no sleep, so an incremental run over a large sided library no longer burns half a second per local skip. Its progress bar routes through the shared progress dispatch (TUI progress boxes work), and--quietnow prints nothing at all (#20).
Machine-surface purity, selector hardening, four parser edge cases, and resume correctness (issues #15, #19, #21, #22):
--jsonis now one parseable document on stdout in all seven report modes (--health,--healthScore,--auditTags,--auditAlbums,--auditBitrate,--auditReplayGain,--duplicates), with the default output and with--output -: the human intro banners used to prefix stdout and break every pipeline consumer. In JSON mode the banners are suppressed; text mode prints them as before and--quietbehaves unchanged.--resume(FLAC/MP3) is scoped to the roots it recorded and drops stale entries: verdicts recorded for files deleted since the interrupted run no longer ride the resume into the report (they used to be tallied and flagged, forcing exit 1 on a clean tree), and a progress file reused against a different--rootis discarded instead of mixing two libraries' verdicts. Progress files written before 6.6.1 carry no roots, so a--resumeacross the upgrade re-verifies from scratch, which is the safe reading.- Four parsing fixes:
--whereand--playlistrules short-circuit boolean operators, soduration > 0 and bitrate / duration > 1no longer raises ZeroDivisionError on every zero-duration track; UTF-8-BOM playlists (foobar2000 on Windows) parse their#EXTM3Uheader instead of reporting a phantom missing track; snapshot TSV round-trips survive paths and genres containing literal\n,\t, or\\(the unescape chain used to corrupt them into real newlines and tabs); and a malformed rating candidate such as1.2.3falls through to the next valid key instead of aborting the fallback chain, while whitespace-padded values like4now decode. - A blank
--whereor blank--revertrefuses with exit 2 before anything is planned: option presence is checked, not truthiness, so a lost shell variable can no longer widen a scoped genreMap run to match-all or turn a--revertinto a forward move. Standalone playlist rules keep their intentional blank-means-match-all behavior.
Documentation-only pass; the package is unchanged at 6.6.0:
- README: restored the
## Companion scriptsheading the v6.4.1 edit accidentally deleted (eight script sections had been orphaned under it), gave "Importing new music: the circuit" its missing heading (two body links had pointed at an anchor that never existed), closed the<details>element the same edit left unclosed, and replaced the embedded help sample (frozen at 6.4.1) with a pointer to the new generated page. - docs/help.md (new): the categorized
lattice --helpindex checked in as a page, regenerated withjust help-docand pinned to the live parser by tests/test_help_doc.py. - roadmap.md: collapsed to the shipped ledger plus the open/parked section; the pre-collapse prose is one commit back in git history.
- AGENTS.md: trimmed to rules, decisions, and constraints (behavior prose now lives only in README), refreshed the test count and modes inventory, and recorded the docs-layout and historical-tag decisions.
- spec.md: §6 now names AGENTS.md instead of the retired CLAUDE.md filename.
- logo.svg: replaced the first-generation placeholder with a lattice-equalizer mark (a waveform built from cells of the lattice; adaptive light/dark).
- project.done: removed (the September blitz handoff note, fully absorbed into the roadmap ledger and patchnotes).
The library, in relational form, built the same way the wings are: GENRE (primary) -> ARTIST -> ALBUM -> SONG, queryable from any SQL client.
lattice --exportDb [ROOT] --output PATHrebuilds the whole hierarchy into a SQLite database on every run:genres,artists,albums(dominant genre, contributing paths, year, track count, total duration, embedded-art coverage),album_genres(the "/" split of the contributing directories' dominant genres, exactly the wing membership--all-wingsbuckets by), andtracks(title, per-track artist, track number, raw genre, year, rating, duration, bitrate, and ReplayGain track/album gain dB). A denormalizedv_trackview joins the whole chain for one-line queries. The filesystem stays the source of truth: the database is a derived artifact, rebuilt wholesale from a fresh walk each run into a temp file and swapped into place with os.replace only after an integrity_check passes, so a failed or interrupted build never damages the previous export, and lattice never reads the database back (spec.md §5 carries the carve-out).--output PATHis required (a missing or-target refuses with exit 2): binary bytes have no stdout report, making--exportDbthe one mode with no stdout form (spec.md §4).--wherescopes the export album-granularly like the other exports.- Duckdb users:
ATTACH 'library.db' AS lib (TYPE sqlite, READ_ONLY)and qualify tables (lib.tracks,lib.albums, ...). The sqlite scanner imports tables, not views, sov_tracklives in sqlite clients only.
Housekeeping since v6.5.0: the release workflow now mints the GitHub Release body from the annotated tag object (the v5.6.0 casualty class; v5.7.0's body repaired in place), the v6.5.0 spec sync that its bump commit lost has landed, and two dependency bumps (actions/setup-python 7.1.0, pypa/gh-action-pypi-publish 1.14.3).
The last of the ten audit issues (#6), and the only one that changes behavior you can see from the couch: report modes no longer write files into the caller's working directory unless asked.
- Omitting
--outputprints the report to the terminal. Every report mode obeys the sentence its own help page has always carried ("omit it to print to the terminal"):--library,--healthand the whole digest and audit family, the integrity scans,--snapshot,--diff,--playlist,--checkPlaylists,--missingArtand the art audits.--output PATHwrites the file, exactly as before, and--output -remains the explicit stdout form. A read run now litters nothing into the cwd: nohealth_digest.txtappearing beside whatever directory a cron job happened to run from. The multi-file exports (--all-wings,--ai-wings) keep their output directories, and--stats(which already printed by default) is unchanged. This is the flip the audit asked for; scripts that consumed a default report file must add--output. utils.resolve_output(output)lost its default argument. The old signature resolved an omitted--outputto the mode'sDEFAULT_*constant; the default is now stdout, uniform across every report writer. TheDEFAULT_*names survive as the TUI's prompt prefills.- The TUI's
lattice_-prefixed report names retired. They existed so an interactive run could not clobber the file a CLI default wrote in the same cwd; with no CLI default files left, the hazard is gone and the TUI prefills config.py's own names (health_digest.txt, notlattice_health_digest.txt). - A stdout integrity scan keeps no resume state, and
--resumewithout--outputrefuses with exit 2. The transient<output>.progress.jsonlives beside the report file; with no file there is nowhere honest to hang it, so a stdout run persists nothing (it also used to park a-.progress.jsonin the cwd until the scan finished) and a--resumeaimed at stdout is a usage error, not a silently stateless cache. help --jsonkeeps itsoutput_defaultkey at null (the machine help surface is additive-only) and gainsoutput_notefor the per-mode exceptions (the wings' directory outputs). The help pages'--outputline now reads "Path for the report file; omit it (or pass '-') to print to the terminal."
9 new tests (826 total): health/library/tag-audit/snapshot/diff/MP3 scans
printing to stdout with an empty cwd afterward, --output still writing
the file, the --resume refusal, and the TUI constants carrying no
lattice_ prefix.
The other half of the 2026-11-16 audit haul: the read and report paths whose verdicts were subtly wrong.
--cleanconfirms a DROP DUPE with a full byte compare (#7): the destructive branch unlinked on the sampled check (equal size, equal first and last 64 KiB) whose own docstring concedes a difference confined to the middle slips through. The sample stays as the cheap pre-filter; the unlink now requires a fullfilecmpconfirmation (the same primitive cquarry's duplicate refusal uses), so a padded-to-size pair that differs mid-file survives as a.from-fragmentcopy instead of being destroyed. A genuine duplicate still drops (pinned by test).--diffreports RETAGGED ahead of RESIZED (#11): the diff sized each shared-path file first and skipped the tag columns on any byte change, so every retag (which rewrites container headers and therefore changes the size) was classified RESIZED with no tag detail at all. Tag changes are now the section a retagged file lands in; a same-path file with no tag changes and different bytes is still RESIZED.--health's duplicate count folds like--duplicates(#13): the digest keyed its exact-album-dupe count on the raw dominant artist+album strings, so casing/quote/whitespace variants of one album counted as two separate keys and the digest reported 0 pairs while--duplicatesflagged the same tree. The keys now go through_norm_key, the exact lens's own fold, so the digest's number is the audit's number.--auditReplayGain --wherestops double-advancing its progress bar (#14): the where-scoped second tag read passed the same progress bar the ReplayGain read had already driven through the file total, so the bar counted to 200% and terminal output misled. The second read advances nothing (the health walk, which legitimately reads twice, sizes its bar to total x 2 instead).
5 new tests (817 total): a mid-file-difference pair kept as a fragment, a genuine >64 KiB duplicate still dropped, a resized-and-retagged file reporting its tag changes, a casing/whitespace album variant counting as one duplicate pair, and the RG audit's bar advancing once per file.
The 2026-11-13/16 audits filed ten issues; this release ships the five machine-shape lies: flags that promised behavior the code did not deliver.
- A missing library root is a usage error (#5):
lattice --stats /typo/pathused to print "No audio files found" to stdout with exit 0, indistinguishable from a genuinely empty library, and--fail-on-findingsgave the typo a false green. An explicitly passed root (positional or--root) that does not exist now refuses with exit 2 and one stderr line naming the path, in every mode. An existing root with zero audio keeps the true empty report (exit 0), and configured roots keep the lenient skip they always had. --apply --jsonactually applies (#8): the planning JSON summaries in--stripRatingsand--apestripsat ahead of the dry-run guard, so the flag pair printed a document claiming"dry_run": trueand exited 0 having written nothing. Both now follow the replaygain convention: the planning summary ends a dry run only, an apply run reaches the write loop and reports the committed counts withdry_run: false, and a--jsonrun proceeds past the confirmation prompt like a non-TTY run (a prompt would corrupt the stdout the JSON contract owns).--resumeno longer wipes prior verdicts (#9): a resumed FLAC/MP3 scan loaded the cached verdicts into a side dict but seeded its state empty, so the first periodic flush (or a second Ctrl-C) rewrote<output>.progress.jsonwith the new session's results alone. Resuming a 9,000-of-10,000-track scan and pausing again used to erase 9,000 verdicts; the resumed state now carries everything forward.--output -streams the decode scans (#10):--testMP3,--testOpus,--testWAV, and--testWMAwere the one report family still resolving the dash throughPath().resolve(), writing the full report to a literal file named-in the caller's working directory while stdout got nothing. They go throughresolve_outputlike every other report writer (run 1 of the v6.3.0 conversion missed them), and a stdout report no longer prints "Report written to: -".--ingest --output -streams the summary (#12): the ritual wrote a literal-file and anchored the health-digest and snapshot-diff sidecars toPath("-").parent, the caller's working directory. The summary now streams to stdout (still suppressed under--json, whose machine summary gains alogsmap carrying the per-stage log paths), and the sidecars always land beside the root the ritual ran over.
16 new tests (812 total): the missing-root exit class (stats and a write
mode, repeated roots naming every path, empty-root exit 0 unchanged), both
apply+json pairs writing for real and reporting dry_run: false, resumed
FLAC and MP3 scans surviving a second interrupt, decode scans and ingest
streaming - without littering the cwd, and the ingest JSON log pointers.
Born the hard way. Hours after v6.4.0 shipped, a first-generation rating-strip pass over the owner's live library (run before this mode existed, under a wrong "the stamps are foreign" read) deleted his hand ratings from 10,946 files. The journal brought every one back the same day (a Hetzner backup cross-check confirmed 30/30 identical), and this release makes the tool refuse to be the instrument next time.
- New config key
rating_protected_roots: a list of trees whose rating tags--stripRatings --applywill never touch. A protected target refuses with exit 2 and a message naming the protection; dry-run previews are never blocked (seeing what a strip WOULD do is always safe), and the staging inbox (theUnfiltered/component) inside a protected tree stays strippable, matching the ingest ritual's staging-scoped contract. No CLI override flag on purpose: changing the protection is a deliberate config-file edit. --ingestinherits the guard through its staging-scoped strip stage: a ritual over a protected root strips only the inbox, which is exactly the carve-out.- spec §3/§5 carry the amended
--stripRatingscontract; README's stripRatings bullet names the config key; the mode's help page explains the refusal.
6 new tests (796 total): refusal at and under a protected root, dry-run still previewing, the staging-inbox carve-out, and unprotected roots stripping normally.
Rips and shared downloads carry the sharer's player ratings: Windows Media Player popularimeter frames, MusicBee/fre:ac POPM, FMPS floats, Vorbis RATING stamps, MP4 rate atoms, and anything that seeds a star display from file tags imports them pre-rated. The values are never the listener's own: a real library has 2- and 3-star tracks, sharer stamps are uniformly 4/5 with zero play counts. MusicBrainz and Picard never supply ratings, so there is nothing on the tagging side to disable; the tags have to go.
- New write mode
--stripRatings(apestrip-shaped): dry-run by default,--applyopts in behind a worklist confirmation (auto-proceeded on a non-TTY), append-only log at<root>/stripratings.log, idempotent, single-root,--jsonsummary, exit 1 on any read or write error. Deletes rating tags wherever they carry a nonzero rating: POPM frames (any email) and rating-desc TXXX frames plus the APEv2Ratingkey on MP3s, Vorbis rating/score/stars keys on FLAC/OGG/Opus, rate/rating atoms on M4A (the Explicit/Cleanrtngadvisory is not a rating and survives), rating attributes on WMA. Zero-value shells stay: a rating-0 POPM frame still carries the ripper's play count and displays nowhere. MP3 saves use the retag convention (ID3v2.3 plus a refreshed ID3v1). - Reader and stripper cannot drift: tags.py's inline rating-source
predicates (the ID3 TXXX desc check, the Vorbis/MP4/ASF key scans) are
extracted into shared helpers (
is_id3_rating_desc,is_vorbis_rating_key,is_mp4_rating_key,is_asf_rating_key) thatget_all_tagsand the stripper both consume, and the strip verdict is the reader's own decode (_popm_stars/_tag_rating), so a stripped file always reads back rating-less. - The shared predicate drops advisory keys: "content rating" (and any content/parental key) is Explicit/Clean metadata, not stars: the substring match had read a content rating of "1" as one star, and the live library carried four such files. Excluded before the substring tests, so the reader and the stripper both ignore them.
--ingestgains its first stage, staging-scoped by contract: the ritual now runs stripRatings -> genreMap -> apestrip -> clean --all -> health, but the strip stage runs over the staging inbox (root/, default Unfiltered) and never over the filed library: a library whose owner hand-rated the tracks must never lose those tags to a ritual run. An absent inbox (or --staging "") skips the stage. Sequencing only, no new write verb beyond the mode's own §5 amendment.- spec.md §5 amended first (the house rule for new write surfaces): the
"Not a tagger" list carries
--stripRatingsand its nonzero-only, shared-predicate contract. README updated around it: the write-mode census is nine surfaces (eight dry-run by default), the flag table, the multi-root refusal list, the no---wherelist, the import-circuit steps, the ten-entry TUI Maintenance menu, and the embedded help block regenerated byte-identical at 6.4.0. CLAUDE.md's mode list, write-mode list, and test count current. Live dry-run over the 11k-file library finds the 60 rating tags the first-generation sweep's narrower MP4 policy missed (iTunes freeform atoms on M4A, album-level ratings, provider ratings): the drift-proofing doing its job. - rerate.py is untouched and still a script: it reconciles byte-scale conflicts on kept ratings, the opposite job.
19 new tests (789 total): the brain against fixture copies (the committed Cursive MP3's WMP POPM, the Aphex Twin FLACs' Vorbis ratings, stamped FMPS/APE/MP4/ASF cases), zero-shell and play-count retention, the house save convention, idempotency, apply-only logging, the advisory exclusion, the dispatch pins (dry-run default, --apply, dry-run-beats-apply, multi-root refusal, mutual exclusion, --json), and the staging-scoped ingest stage (a rated album under Unfiltered is stripped; a rated album in the filed tree is never touched).
Four lenses (a completeness census, a usability walk including live fixture probes, a doc-drift fact-check, and a human+AI dual read) audited this documentation set and found the registry provably synchronized (zero misses, zero fabricated flags; the README's embedded help block byte-identical to live output) with the defects concentrated in the exit legend and the machine surface:
- The exit legend exists in one hand-maintained place now. EXIT_CODES dropped two false claims (an invalid --where/--playlist rule is exit 2, not 1; exports exit 0 when nothing matches), and the index footer RENDERS FROM EXIT_CODES, so --help, README's embedded block, and help --json can no longer disagree. The README embed was regenerated; its byte-identity is preserved.
- --output - piping is complete. v6.3.0 routed every output path through resolve_output (dash passes through) but 15 writers then bare-opened out_path, still writing a literal file named '-'; all of them go through utils.open_report now, so the documented piping works for every --json/--output mode. Live-verified against the fixture library.
- The write-mode census is stated once correctly (eight surfaces write; seven are dry-run by default; genreTidy-build writes its map directly), --ingest is counted in the multi-root refusal list, the TUI is described as its nine-entry Maintenance menu with Settings listed, and the --json applicability sentence is scoped (the write modes except --lyrics).
- The extractArt examples carry the writes-by-default warning inline; SKILL.md's 'remove junk files' fabrication about --clean is corrected; CLAUDE.md's B2 note gets a supersession marker, its layout map gains lyrics.py, and its test count is current; the README Contents gains the four unlisted sections, fixes the broken Help anchor, and drops the doubled .
1 pin updated (769 total).
Three waves of four lenses audited this help surface. The registry verified provably synchronized with the parser (zero misses, zero fabricated flags or fields); the defects were the exit taxonomy, two broken machine promises, and the thin machine surface. Approved fixes:
- --output - actually pipes now. Every report writer abspath-ed the dash into a literal file named '-' in the working directory (dead '!= "-"' guards throughout showed piping was the intent); all 21 sites go through utils.resolve_output, which passes the dash through to open_report. --stats already handled it and is unchanged.
- The exit legend tells the truth: 1 is findings or failure (the integrity scans exit 1 on any CORRUPT file with no flag; --fail-on-findings does not apply to them and is refused with exit 2; write modes on run failure; exports when nothing matched; invalid rules), not "audit findings only with --fail-on-findings". All five integrity pages name the tiers (CORRUPT / SUSPECT / METADATA / OK) and their exit rule.
- Behavior: an invalid --where/--playlist rule is a usage error (exit 2), matching every other malformed-input refusal; the old exit-1 pin flipped with the behavior.
- Behavior: the dry-run JSON summaries exist. --replayGain --json (the default preview) and --retag --strip-junk --json printed nothing while the shared --json text advertises {mode, root, dry_run, counts} on every write run; both emit it now.
- The two dry-run-promise exceptions are labeled: --extractArt's index summary says WRITES by default (--apply silently ignored) and its page notes skip-existing; --genreTidy-build's page says the map write happens on every run (no dry-run/apply gate).
- help --json is a real agent surface: per-mode own_options, shared applicability, and output_default join the dump, plus rule_grammar (fields with units, operators, connectors, the no-format-field note) and integrity_tiers.
- The grammar carries its real operators (== != < <= > >= in / not in, and/or/not, parentheses, arithmetic like bitrate / duration > 200) and units (duration seconds, bitrate kbps, rating 0-5, exact case-sensitive strings); --replayGain scopes the rsgain requirement to --apply (previews never needed it); the junk-frame page drops the phantom duplicate-frames class; the --playlist usage admits --rule is optional (omit for all tracks); --all-wings usage shows --where; --ingest states the non-TTY auto-proceed; the --apply entry states the TTY-confirm convention and the --root entry the config-file path with the non-interactive cwd fallback.
7 pins added or updated (769 total).
The same AI-grokability probe CalibreQuarry and bindery-cli ran (a fresh agent learning the CLI from help alone) validated the per-mode pages and found the cross-mode layer inconsistent. Fixed:
- The two contradictions are gone: the --diff page's example read in
the opposite order from its own usage line (snapshot first now, as the
parser binds it), and the --stats example filtered
format == 'FLAC'even though the rule grammar has no format field (formats are not tags; --stats breaks them down natively, and the grammar listing now says so). The example was the bug in both;formatwould have been a RuleError at runtime. - The --where entry names its modes: all fifteen flags that accept it, and the fact that everywhere else is a usage error (exit 2), instead of "modes that never read tags refuse it" and a guessing game.
- Exit codes and the --json envelope are stated: the index footer carries the consolidated table (0 clean; 1 audit findings only with --fail-on-findings; 2 usage or missing dependency; 130 interrupted), and the --json entry names the two envelope shapes (read: {mode, root, findings, payload}; write: {mode, root, dry_run, counts}).
lattice help --json: the whole registry (every mode's page fields, the shared options, the rule fields, the exit-code table) as deterministic JSON, generated from the registry the rendered pages read, never colored. The machine surface an agent reads once instead of paging through 38 modes.lattice --help MODEis a per-mode form now: the token after the help flag resolves likehelp MODE, and a non-topic word is an unknown-topic error (exit 2) instead of silently printing the index.
8 new tests (763 total).
The help-surface restructure: one registry, two levels, zero invocation changes.
- Two-level help, rendered from one registry:
lattice --helpwas a flat 270-line argparse dump (38 mode flags in one list, ~45 options under it, each option's mode scoping buried in its description text). It is now a categorized mode index (Library trees & exports / Reports & snapshots / Integrity / Artwork / Audits / ReplayGain / Write modes; the TUI menu's grouping), and a second level prints a full page per mode:lattice help MODE(dash- and case-insensitive topics) or--MODE --helpshows what the mode does, its own options, only the shared options that actually apply to it (a repeatable--rootfor scans vs the one-root text for write modes,--outputwith that mode's default filename, exactly the--where/--json/--fail-on-findingsthe mode supports), and a worked example. All help text lives in the newlattice/help.pyregistry (MODES/SHARED/CATEGORIES); cli.py intercepts the help paths before argparse, carries a one-line usage for error paths, and itsadd_argumentcalls hold no help strings anymore, so the registry is the single home of CLI help text. An unknown topic exits 2; bare-h/--help/helpprint the index with exit 0. - No invocation changed: the flag grammar, the mutually-exclusive mode group, dispatch, and exit discipline are untouched; the restructure renders text, it does not move the surface. tests/test_help.py pins the registry to the parser (every mode flag has an entry, every listed option dest exists) and to the enforcement sets (
_WHERE_MODES/_JSON_MODES/_FAIL_MODES) in both directions, so a page cannot claim applicability the CLI would refuse, or the reverse; a test bans em-dashes from all rendered help. - Color, restored: the old help's colors were Python 3.14 argparse's own colorization, which the registry renderer silently dropped; it now paints the exact CPython 3.14
_colorizedefault theme (bold blue headings and usage, bold magenta prog, bold cyan long options, bold green short options, bold yellow metavars), so lattice's help reads likepython --helpin the same terminal. Auto-detection:FORCE_COLORforces,NO_COLORandPYTHON_COLORS=0suppress, and piped output stays plain (README embedding, tests,| cat). Column math runs on visible length because the codes are zero-width; a test pins the invariant that the colored render stripped of codes equals the plain render byte for byte. The index also makes the second level visible, the point of the lane: every mode flag renders in the option color, and a footer line states that every mode above has a full help page (lattice help MODE). - Docs: README's embedded help block is regenerated from the live registry (plain, as piped) and its Help section documents the two-level surface; spec.md §2.6 names it; CLAUDE.md's module map carries
help.py. - Tests: 20 new (15 registry-completeness/interception, 5 color): 735 -> 755, green; ruff@0.15.14 clean throughout.
The 2026-10-05 expansion program in one release: the four companion folds (A1-A4) and the four capability phases (B1-B4) that the atuin-history comparison against CalibreQuarry called for. One version carries the whole program because the phases ship as one reviewed tree; the roadmap's per-phase version targets (v5.8.0-v6.0.0) are superseded by this single release. The major is justified by the spec.md §5 amendment that lands with A4 (the package's first file-moving mode), the same precedent as v5.0.0, where the amendment itself was the major.
- New write mode:
--replayGain(fold A1):scripts/replaygain.pyis promoted into the package aslattice.modes.replaygain, exposed aslattice --replayGain. This completes the ReplayGain trio (--auditReplayGain,--verifyReplayGain,--replayGain), and the read half was already package code, so the writer and the verifier now share one module: the coverage reader, the value reader (lattice.tags.read_replaygain_values, which the post-write read-back log formats through), and the rsgain command builder.run_replaygainkeeps the script's two-phase shape (coverage pass, worklist, confirmation with the non-TTY auto-skip), inverts the default like every fold before it (dry-run unless--apply), joins the single-root refusal, and requiresrsgainon PATH for a real run (exit 2 without it; a dry-run still needs nothing).--skip-tagged,--threads, and--target-lufsreach the mode from the CLI;--target-lufsbecomes optional (default None = the 89 dB standard for writing, the same -18 reference it always was for--verifyReplayGain). The TUI's Maintenance section gains the fourth write-mode entry behind the same ask_yn gate.scripts/replaygain.pyis now a PEP 562 launcher over the package (apply-by-default, same flags, same<directory>/replaygain.log); its 27 tests retargetlattice.modes.replaygainwholesale (the scripts/ sys.path hack is gone), and six wiring tests pin the new dispatch intest_write_modes.py. - README "The Circuit" tells the truth (fold A1's truth pass, owner ruling 2026-10-05): apestrip, cleaner, and replaygain appear as the package invocations they have been since their folds (
lattice --apestrip ... --apply,lattice --clean ... --all --apply,lattice --replayGain ... --apply); the stale./scripts/apestrip.py -yline is deleted, not patched (the launcher's parser defines only--yes, so it was a documented command that argparse-errored). Only the two scripts that remain hand-run tools (flac2opus.py,slipcover.py) keep script-shaped lines; the.agents/skills/lattice-import/SKILL.mdcircuit is rewritten to match. - New write mode:
--retag DIR GENRE [GENRE...](fold A2):scripts/retag.pyis promoted into the package aslattice.modes.retag, the package's first dir-scoped mode: the positionals name one album directory and one or more genres (in the house mutually-exclusive flag group; a trailingretag_genrespositional that every other mode refuses),--rootis refused, and the log defaults to<dir>/retag.logwhere the launcher keeps its historical--logopt-in.--strip-junkrides along with its detection half already package code (lattice.modes.audit.audit_id3_junk, one classifier); the hidden-genre clearing (stray APEv2 deleted,TXXX:GENREremoved, stale ID3v1 byte refreshed), theis_noopidempotence, and the convert-or-drop junk policy are preserved verbatim. The genre-write-path direction, decided and documented:lattice.modes.retagis the package's one genre-write path (retag_directoryis the loop,apply_genresthe per-file writer with anerrorslist for in-process callers), andlattice.modes.genretidynow calls it directly;modes/clean.py's Pass 4 never wrote genre and keeps its own four-field writer, sharing only the MP3 save convention (ID3v2.3 + refreshed v1) the retag module establishes.scripts/genre_tidy.pyis rewired in the same change: the subprocess (and the retag.py path lookup, and the sibling import for the writable-format set) are gone; apply callsretag_directoryin-process with the dry-run flag propagated and the exit-1-on-retag-failure contract intact.scripts/retag.pyis now a PEP 562 launcher (apply-by-default, same flags); its 25 tests retarget the package module wholesale, and nine wiring tests pin the new dir-scoped dispatch intest_write_modes.py. - New write modes:
--genreTidy-build/--genreTidy-apply(fold A3):scripts/genre_tidy.pyis promoted into the package aslattice.modes.genretidy, the subcommand-shaped script resolved into two flat flags in the house mode group (two verbs, two TUI Maintenance entries;--mapoverrides the<root>/genre_map.tsvdefault, the repo'sartist_genre_defaults.tsvauthority still passes as--map artist_genre_defaults.tsv). Build stays read-only over the shared scanner with its append-only preserve-edits behavior; apply is a write mode (dry-run unless--apply, the script's dry-run opt-out inverted like every fold) writing the same<root>/genre_tidy.logand drivingretag_directoryin-process. The_QUOTE_DASH_FOLDdesign point, resolved on purpose: the key table stays private inside the module, becauselattice.norm.normalize_nameadditionally strips apostrophes from keys and re-keying on it would makebuildre-append every saved-map artist whose name carries a quote as if it were new; a new FoldTableDivergenceTests pin documents the divergence and the dash/case folds that DO agree. The TSV map contract (byte-stable round-trip,#-comment rules, EXCLUDED artists,#1 Dadas data) is unchanged.scripts/genre_tidy.pyis now a PEP 562 launcher (build/apply subcommands, apply-by-default); its tests retarget the package module (the sys.path hack is gone) and seven wiring tests pin the new dispatch intest_write_modes.py. - The spec.md §5 amendment and the folder-moving write mode:
--genreMap(fold A4, the change that makes this release a major):scripts/genre_foldermap.pyis promoted into the package aslattice.modes.foldermap, and §5 now sanctions folder reorganization in exactly one place: album folders move under their dominant genre withmv-only semantics on one filesystem (a move is a rename, so tags and audio bytes are never read or rewritten by it), dry-run by default with--applyto perform, every move appended to a manifest TSV thatlattice --genreMap --revert <manifest> --applyreplays in reverse. "No tags and no audio" holds for everything else. The script's whole contract rides along: the v1.2.0 depth-aware classify (TOO DEEP as the wrong-root guard), the live genre-vocabulary gate, the v1.3.0Unfiltered/staging-inbox semantics,--only-genrestaged rollouts,--refile-mismatchedas the retag follow-up, and the never-overwrite rule. The--allow-new-genredesign point, resolved conservatively: it stays opt-in in the package (the vocabulary gate stays closed by default; the launcher keeps today's behavior, where 92 of 92 recorded runs pass it explicitly). The Runner unification, the real work: genre_foldermap's Runner andmodes/clean.py's Run were two implementations of the same dry-run virtual filesystem; the shared core is extracted tolattice.vfs.VirtualFS(virtual removed/created sets with byte-origin tracking, existence-aware views, and the guarded move/unlink/rmdir/rename ops) and both modes now import it (one implementation, no second Run), and the dry-run-vs-apply parity harness covers the folder-moving mode intest_write_modes.pyalongside clean's.scripts/genre_foldermap.pyis now a PEP 562 launcher (the one fold needing no default inversion); its 71 tests retarget the package module wholesale, and five wiring tests pin the new dispatch including the manifest round-trip. - New:
--where 'expr', the global selector (B1): the--playlistrule engine (the whitelisted-AST evaluator; the same grammar, never a second one) is promoted intocompile_where, and the predicate scopes the toolset the way CalibreQuarry's--restrictscopes queries: the library exports (--library,--ai-library,--all-wings,--ai-wings) aggregate only matching tracks and drop albums with no matches,--statsdescribes the matching subset (its header states--where scoped: N of M files), and the tag-reading audits (--auditTags,--auditAlbums,--auditBitrate,--auditReplayGain,--healthScore,--duplicates) filter their walks. The write-targeting design point, stated and pinned:--genreTidy-build/--genreTidy-apply/--genreMap/--replayGaintake--wherealbum-granularly; a rule matching ANY track of an album selects the WHOLE album as a target, and no mode ever acts on a partial album. There is no index and no cache: the predicate evaluates over the walk's own TagBundles, and nothing new persists. Modes that never read the tags a rule could evaluate (the decode scans,--auditAudioDupes,--auditStrays,--auditJunkFrames, the art audits,--clean,--retag,--apestrip,--lyrics) refuse--wherewith exit 2 rather than silently ignore it, via the explicit_WHERE_MODESset in cli.py; the snapshot-TSV evaluation shortcut from the roadmap box stays a deferred optional. Twelve new tests in test_where.py pin the predicate, the track-granularity scoping, the album-granular rule, and the refusals. - New:
--json,--output -,--fail-on-findings(B2): opt-in machine shapes beside the.txtdefault (spec §4 amended: ".txt by default ...--jsonfor machine consumption"). Flag shape, resolved: bare--json, matching the house modifier style.--statsand the six tag-reading audits emit the uniform envelope ({"mode", "root", "findings", "payload"}viautils.json_report: counts, grades, buckets, and per-item verdicts with root-relative paths), and the write modes (--clean,--apestrip,--replayGain,--retag,--genreTidy-apply,--genreMap) end with autils.json_summaryrun summary whosedry_runflag tells a pipeline preview from commit.--output -pipes any converted report to stdout (utils.open_report;--stats --json --output -is pure JSON on stdout).--fail-on-findingsgates cron/CI: the six audits exit 1 on findings, default stays 0, refusals stay 2, interrupt stays 130. The same explicit-support discipline as--where:_JSON_MODES/_FAIL_MODESin cli.py refuse unlisted modes with exit 2 instead of silently ignoring the flag (--lyricshas no JSON summary yet and is refused rather than half-supported). Ten new tests in test_json.py. - New mode:
--health, the one-walk digest (B3): CalibreQuarry's--healthtranslated. Running six audits today is six full walks;--healthreads each file's TagBundle once (plus its ReplayGain flags, the art checks, and the stray classification) and feeds every lens, then prints one screen of counts, each row pointing at the full-report mode (--auditTags,--auditBitrate,--auditReplayGain,--missingArt,--auditStrays,--checkPlaylists,--duplicates,--healthScore) and listing the worst health-scored albums. The derivation principle is structural, not aspirational: the digest calls the same lens code the audits expose (_tag_findingsextracted as the shared tag-completeness classifier;_rg_bucket,_album_health,classify_stray,check_playlistreused as-is), so the digest and the lenses cannot drift, the same way cquarry's--auditand--healthshare one collect_issues. Read-only, always exits 0: the digest informs, the audits gate.--jsonsupported;--fail-on-findingsdeliberately refused (exit 0 is the mode's contract). Wired into the CLI and the TUI's Metadata section; seven new tests in test_health.py. - New mode:
--ingest, the ritual, packaged (B4): the shell history shows one ritual typed by hand about five times (foldermap, then apestrip, thenclean --all, against the staging inbox, from memory);--ingest [DIR]is that ritual as one command over one root. It sequences the package modes in process and never re-implements them: each stage keeps its own dry-run/apply contract and its own log (the genreMap manifest,apestrip.log,cleanup.log), the write modes' single-root refusal is respected by sequencing one root across the stages (never aggregating), and--staging/--allow-new-genrepass through to the genreMap stage. The design points, resolved: apply granularity is a per-stage confirm on a TTY (auto-proceeding when stdin is not a TTY, the house convention; a declined stage is recorded and skipped, never fatal; the TUI's ask_yn is the gate), and the summary shape is one top-level file (<root>/ingest_summary.txt,--outputoverrides) pointing into the per-stage logs. After an apply, the post-state health digest runs in process (ingest_health.txt), and--baseline before.tsv(a--snapshottaken first) adds a diff report so the import is a before/after record. Not a new write verb: no §5 change beyond what A4 landed. TUI Maintenance entry (4,8); seven new tests in test_ingest.py. - Docs ride every phase, in its own commit: README's "The Circuit" tells the truth (fold A1), the companion-script sections convert to launcher notes as each script folds (six launchers now; only
rerate.py,slipcover.py,flac2opus.pyremain hand-run tools), the--where/--json/--health/--ingestsections are new, and the full--helpblock is regenerated from the real parser. spec.md carries the §4 output amendment (--json/--output -/--fail-on-findings) and the §5 folder-move amendment (--genreMap: mv-only on one filesystem, dry-run default, manifest TSV +--revert; "no tags and no audio" holds for everything else). CLAUDE.md's module map, companion-script bullets, and conventions carry the same facts for the next agent. Every design point the roadmap left to the implementing agent is resolved in the roadmap box it was hit in: the retag genre-write-path direction, the two-flag genreTidy shape, the kept_QUOTE_DASH_FOLDtable (with the divergence pinned by a test), the conservative--allow-new-genrepackage default, bare--json, the--wherealbum-granular rule, per-stage ingest confirms, and the one summary file. - Tests: 64 new across the program (the four script suites retargeted wholesale, dispatch pins for every new mode and flag, and the four new phase suites): 671 -> 735, green; ruff@0.15.14 clean throughout. The cli/tui kwargs-parity suite holds untouched: every new read-side flag defaults to a value the parity binder treats as identical to the TUI's omission, and the write modes stay structurally pinned in test_write_modes.py.
Contract amendment: the package now touches the network in exactly one place. spec.md §1 carries the exception (the open, unauthenticated, GET-only LRCLIB API as the one sanctioned external lookup), §3 gains the --lyrics row, and §5's not-a-tagger/not-a-sync-tool wording names the mode, its .lrc sidecar output, and the fetch-not-sync carve-out. CLAUDE.md and the README callouts now say three write modes.
- New write mode:
--lyrics(the recorded lyrics candidate, unparked): walks one library root, matches every track against LRCLIB (exact/api/getby artist+title+album+duration, then/api/searchwith a ±2s duration-window pick), and on--applywrites the synced lyrics as a same-basename.lrcsidecar beside each audio file. Players and servers that read sidecar lyrics (Jellyfin 10.9+) pick them up with the files, so a library that clones to several machines takes its lyrics along instead of parking them in one server's database. Instrumental and plain-only matches are reported, never written; tracks already carrying a sidecar are skipped unless--lyrics-force. Dry-run is the default and performs the read-only lookups so the preview's hit/miss counts are real; requests are serial and paced (--lyrics-sleep, default 0.5s, LRCLIB fair-use etiquette); every written sidecar lands in an append-only<root>/lyrics.log. Wired into the CLI and the TUI's Maintenance section, like the other write modes. .lrcjoined--auditStrays' recognized-sidecar set, so the lyrics mode's own output is not flagged as import junk by the stray audit.- The suite grew its first network seam: test_lyrics.py injects a fake LRCLIB fetcher (hand-built JSON, no HTTP in the suite), covering dry-run safety, apply+log, skip-existing/force, instrumental and plain-only handling, the duration-windowed search fallback, per-file error isolation, and the multi-root/usage guards.
- Suite: 651 -> 668 tests.
- The
utils.IN_TUIflag retired onto vir_tui's own session lifecycle:utils.in_session()readsvir_tui.session_screen()(screen ownership; the work order's other candidatetui_active()is true on any tty, which would have disabled CLI color and swapped tqdm for curses boxes on plain terminal runs), tui.py sets nothing, and stats.py's four print gates read the same predicate. The wiring tests now publish a fake session screen instead of setting the flag. - testWAV/testWMA coverage landed (they had zero): missing-decoder refusal for both (no decoder = exit 2, never a successful-looking empty scan), per-mode report plumbing (title, extension), and the always-writes-report contract with the exit code keyed on corruption.
retag.py --strip-junk(script-only, retag 1.2.0; the strip half of B.8's audit/strip split, seeded by the real finding of three MP3s carrying five obsolete v2.3 frames each): convert-or-drop of the audit's obsolete class through mutagen'supdate_to_v24(TYER/TDAT/TIME fold into TDRC; v2.2 three-letter names normalize), empty text frames deleted, nonstandard iTunes-era frames left alone (functional; report-only class), saves as ID3v2.4. Apply-by-default like the script it lives in,--dry-runhonored, idempotent, refuses genre arguments. Detection reuseslattice.modes.audit.audit_id3_junk, so the classifier cannot drift from the strip.- Suite: 641 -> 651 tests.
--verifyReplayGain is reference-aware: R128-tagged files no longer false-positive at the default target
The verifier applied one identity to every file -- stored gain must equal --target-lufs minus the fresh measurement -- but Opus R128 keys are -23-LUFS-referenced by the Opus/R128 spec, so every correctly-written R128 album reported off by exactly -5.00 dB at the -18 default. The reader now surfaces which key family each file's gains live in (read_replaygain_values_with_convention, joining read_replaygain_values, which keeps its shape): replaygain_* files verify at --target-lufs, R128 files at the -23 baseline their format implies, and the report header counts both. A genuinely wrong R128 gain still flags, with the -23-based expectation in the row. Found by B.7's first real-library run (the decision-#110 gate): the gains in the reference slice were internally consistent per write reference (MP3s at -18, opus at -23), so the held health-score bucket stays closed -- and the run closed the nested-parent direct-file scan option too (zero nested albums).
Also: justfile (test/lint/fmt/version -- PYTHONPATH=src is baked in, closing the stale-site-packages trap for good), the dated research reports archived under docs/research/, and the research-section roadmap boxes ticked with their ship records.
- New mode:
--verifyReplayGain(B.7, the recorded next lane): the audit that checks whether stored ReplayGain values are RIGHT rather than merely present. The engine is rsgain itself, scan-only (rsgain custom -l N -a -O -q -s s): the fresh measurement comes from the same libebur128 that computed the stored tags, so stored == target - measured holds exactly and a delta beyond--tolerance(default 0.5 dB) means a wrong or mismatched tag, not jitter. One call per album folder with the album aggregate for the album-gain check; clip-protected rows are reported separately, never flagged OFF (clip protection legitimately breaks the identity). Knobs:--target-lufs(default -18; a -14-targeted library verifies clean only at -14) and--tolerance. Requires rsgain on PATH; refuses with exit 2 without it, like the integrity modes' missing-decoder refusal. The tags layer growsread_replaygain_values, a key-aware value reader (standard replaygain_* strings as dB, Opus R128 integers as Q7.8 /256, MP4 freeform bytes decoded), and scripts/replaygain.py'sread_gain_stringsnow delegates to it and formats, so the two readers cannot drift (log strings unchanged for dB-convention tags). Report sections: GAIN OFF (with the numbers), UNGAUGED, CLIP-ADJUSTED, SCAN FAILED, and OK with--verbose. Wired into the CLI and the TUI's Metadata section. - New mode:
--checkPlaylists(B.4):--playlistwrites absolute-path .m3us that every mover the repo ships can orphan; this walks the roots for .m3u/.m3u8 files and reports, per playlist, entries whose target no longer exists (with line numbers) and a missing #EXTM3U header. Relative entries resolve against the playlist's own directory, so hand-made playlists check the same as generated ones.--verbosealso lists the clean ones. - New mode:
--auditAlbums(B.5): per-album consistency across three lenses: mixed codecs (the leftover .mp3 beside the .flac), track-number gaps over 1..max plus duplicates and untagged files, and year tags (missing, partial, or diverging across files). The year read is additive onTagBundle(a new trailing field) via a generic late pass in get_all_tags: year keys share naming, not frame machinery, so suffix matching (TDRC/TYER, Vorbis date keys, MP4 day atom, ASF WM/Year) covers every container; MusicBrainz keys are skipped (their "...Date" TXXX descs carry MBIDs). - New:
--snapshot/--diff(B.10): the before/after evidence half for every writer.--snapshotwrites a per-file TSV (path, size, mtime, track/rating/genre/year, ReplayGain presence);--diffreplays one against the current tree: MOVED (paired on size+mtime, the signature mv-only writers preserve), RETAGGED (per-field old -> new), RESIZED, ADDED, REMOVED. Compound runs compose because the diff is state-versus-state, never log replay. A file without the snapshot header is refused (exit 2), never diffed as everything-removed. - New mode:
--auditArtMismatch(B.9): compares the extractArt pick (same priority-ordered embedded source) against the folder cover. MATCH is byte-identical; SAME PIXELS is a different-bytes re-encode at identical dimensions (benign); DIFFERENT IMAGE is a real mismatch, reported with both dimensions. Folders carrying only one of the two are not findings: players resolve a missing half silently, but there is nothing to disagree about. - New mode:
--auditJunkFrames(B.8): audits MP3 ID3v2 tags for obsolete frames (v2.3 leftovers like TYER/TSIZ, plus v2.2's three-letter names), empty text frames, and nonstandard iTunes-era frames (TCMP, GP1, TGID...), which are reported so keeping them is a choice, never called junk. The audit loads the tag raw (translate=False) because mutagen's default load silently upgrades TYER to TDRC, hiding exactly the junk being audited. Duplicate frames are documented as undetectable here: mutagen's dict model collapses same-hash frames at parse. MP3-only; stripping stays with apestrip and the write modes (the same audit/strip split as the ReplayGain pair). - Fixed (HIGH, latent since v4.17.0): the TUI library submenu's migration regressions, one root cause: the c6575dc vir-tui migration rebuilt the submenu without the kwargs the mode functions had grown, and the error containment paged the TypeError politely instead of surfacing it. "Generate smart playlist (.m3u)" called
generate_playlistwithout the required rule and died on every invocation; the rule and layout prompts are back. The layout kwarg and the genre/paths toggles are restored on all four library entries (a genre-first config's exports were mis-attributed). Multi-root configs scan all roots again, exactly as the CLI passes them, with the root count in the title; the write modes refuse a multi-root config like the CLI instead of silently picking the first tree; the TUI's AI-export default realigns to the CLI's library_ai.txt; the health-score entry gains the CLI's --verbose toggle. A new kwargs-parity suite drives both faces with the modes patched out and compares each call bound to the mode's signature, so any future cli/tui drift fails the suite instead of paging a TypeError (13 new wiring tests). - Fixed: integrity modes tell the truth about what they verified.
--testFLACnow honors--ffmpeg(the path never reached run_flac_mode) and warns when an explicit--prefer ffmpegcannot be honored instead of silently switching decoders. A decode scan with no decoder refuses with exit 2: before, a typo'd--ffmpegpath graded every file OK ("decode check skipped") with exit 0. FLAC--resumefolds cached records in with .get like the decode path, so a state record damaged by the interrupt degrades to OK instead of crashing the resumed scan. - CI/publish hardening: publish.yml's three actions are SHA-pinned (checkout v4.4.0, setup-python v5.6.0, pypi-publish v1.14.2) with a new assertion step that refuses to build unless the tag equals both pyproject.toml's version and config.VERSION (the v5.2.0 incident class); workflow permissions drop to least-privilege with a publish concurrency group; ci.yml tests the tree (PYTHONPATH=src) instead of the pip-installed copy and SHA-pins its actions too; the ruff==0.15.14 pin moves into the dev group so local format output matches CI; actions-only dependabot keeps the pins current.
- GitHub: SECURITY.md; a release.yml opens the GitHub Release automatically on every future tag (body = the verbatim tag message, stock gh CLI; per Brandon's decision, closing the gap that left v5.0.0-v5.4.0 without Releases until the 09-13 hand batch); CI and PyPI badges join the README badge row.
- Docs: the hero screenshot is recaptured from the current TUI (it still showed the v4.10.2 pre-rename menu, then was recaptured again after the feature lanes so all six new modes render); vir-tui is enumerated where the other runtime deps are (README Requirements and Credits, spec's binary section, which had listed two of three); the lattice-import skill's step 2 no longer passes
-yto apestrip (argparse error since the 5.0.0 fold) and follows the lattice-music rename; nine stale comments corrected (the TUI's deliberate lattice_ output-name prefix stated, the tag-workers consumer list completed with the GIL-vs-hashing caveat, flac2opus's docstring no longer claims metadata verification, and so on); four doc truth riders (README's multi-root exception for the write modes, --only-errors covering WAV/WMA, spec's TUI sections, spec §5's write-set wording); README's companion table and architecture list completed; the stale kernel microversion dropped. - Dependency: the vir-tui floor moves to
>=2.5.0(landed 2026-09-14 after v5.4.0; upstream 2.4.0/2.5.0 are additive terminal-safety and session-awareness releases, and the suite has been running against them since). - Tests: 74 new (wiring/integrity plus the six new modes'): 560 to 634, green; ruff@0.15.14 clean. Two tests had hidden dependencies on the dev machine's environment and now pass anywhere: the MP3 resume test stubs its decoder (the new missing-decoder refusal used to fire first on a runner without ffmpeg) and resolves ffmpeg identically across both runs (the resume scan_id carries the resolved path, so a stubbed run could not resume against a PATH-resolved one); the --verifyReplayGain run tests stub rsgain's PATH lookup the same way.
- New mode:
--auditAudioDupes(the content-hash duplicate audit from the 2026-09-12 landscape research; closes the retagged/renamed blind spot in the tag/name/size-based--duplicates). One read-only pass, tags never consulted (it runs even without mutagen), matching on three sha256 tiers: exact (the whole file byte for byte; catches renamed and copied dupes), audio-stream (the container's tag regions are parsed and skipped, so MP3s differing only in ID3v2/ID3v1/APEv2, FLACs differing only in metadata blocks, and M4As differing only in box layout match on identical audio), and sampled (raw first/last 64KB fingerprints for the formats without a parsed region; survives a rename and most retags). Malformed containers fall back safely; nothing is ever matched across encodings. Writesaudio_dupes.txtby default; wired into the CLI and the TUI's Metadata section. - New mode:
--healthScore(the library health score from the same research): one read-only pass scores every album out of 100, aggregating the existing audit lenses: tag completeness (40 points), ReplayGain coverage (30), art presence and resolution (20), and the bitrate floor (10). Albums below full score are listed worst-first with point-by-point deductions and letter grades (A/B/C/D);--verbosealso lists the perfect albums. No decode scans: the integrity walks remain their own modes. Writeshealth_score.txtby default; reuses the--min-bitrateand--min-art-resfloors; wired into the CLI and the TUI's Metadata section. - Docs: the README's "completed software" claim (falsified by the v5 line itself) is reworded to maintained software with the audit family still accruing; the pre-fold descriptions in pyproject.toml and
--helpare refreshed (pyproject feeds PyPI); CLAUDE.md's progress-bar dispatch line now namesvir_tui.progress_box, the real implementation, instead of the_TUIPbardeleted in v4.17.0. The README's sample-output em-dashes stay: they mirror the library tree's real join, which prints a literal em-dash between artist and title (verified againstlibrary.py). - Tests: 43 new: synthetic duplicate fixtures for all three matching tiers (identical, retagged, distinct), unit coverage for the ID3v2/ID3v1/APEv2/FLAC/MP4 boundary parsing and the trailing-tag strip, health-scoring units for every deduction bucket and the grade bands, patched-reader run tests for both modes, and the CLI/TUI wiring pins. Suite 517 to 560, green; ruff@0.15.14 clean.
- New:
--resumefor--testFLACand--testMP3(Progress Persistence, the roadmap's long-standing open box, scoped to the two big-library walks). Every run writes each verdict through to a transient<output>.progress.jsonbeside the report as the scan progresses; Ctrl-C leaves that state behind, and re-running with--resumereuses the recorded verdicts and decodes only the remaining files. The report is always complete (cached and fresh rows alike), so the severity tiers, the summaries, and the exit code are identical to an uninterrupted run. A state recorded with a different verification tool (libFLAC vs ffmpeg) is discarded rather than trusted, a scan that finishes deletes the state, and the file is best-effort: persistence can never fail the scan itself. The TUI's FLAC and MP3 entries ask whether to resume. Four new tests; suite 513 to 517.
- Fix (release hygiene): the v5.2.0 commit missed the pyproject half of the version sync set (config.VERSION said 5.2.0, pyproject still said 5.1.0). The tagged v5.2.0 build therefore produced artifacts named
5.1.0, which raced the real v5.1.0 publish and won: PyPI's 5.1.0 files are the v5.2.0-commit build (internallylattice --versionprints 5.2.0 andRequires-Distis the newervir-tui>=2.3.0), the true v5.1.0 build lost the race with a 400, and no 5.2.0 was ever uploaded. PyPI forbids re-uploading a filename, so that 5.1.0 record is permanent; it is functionally complete but its embedded version string lags. This release restores the sync set and ships the real 5.2.1 to PyPI. No code changes.
- Dependency: the
vir-tuifloor moves to>=2.3.0(mouse support, type-to-filter in menus of 15+ items,configure_theme). The lockfile has resolved 2.3.0 since the v4.17.0 refresh, so installs already receive it; the floor now says so. - Chore: dropped
pytest-asynciofrom the dev dependency group. The suite is stdlibunittestand the repo carries no asyncio anywhere;pyteststays as an optional runner.
- New mode:
--auditStrays(the stray-file audit from the 2026-09-12 landscape research). One read-only pass reports everything that does not fit the library's own layout: audio at the wrong depth for the configured--layout(a flatArtist/Albumstray in a genre-first tree, a root-level file), loose tracks sitting directly in a folder at the artist slot, audio hidden in dot-directories and dot-names that the scanners and integrity walks prune silently, and unrecognized non-audio files inside album folders. Recognized furniture (cover images, playlists, cue sheets, checksum sidecars, and the companion tools' own logs) is ignored via documented extension sets; anything else is listed for curation. Writesstray_audit.txtby default; wired into the CLI and the TUI's Metadata section. Twelve new tests; suite 501 to 513. - Cleanup:
audit.py's hand-mirrored quote/dash fold table (kept because the cleaner used to live outside the package) now importslattice.norm, removing the last copy of the fold rules.
- New write modes (the fold):
scripts/cleaner.pyandscripts/apestrip.pyare promoted into thelatticepackage aslattice --cleanandlattice --apestrip, per the commissioned fold in REPORT-12-Sept.md. The pure name/tag rules engine now lives inlattice.norm(zero I/O), the four consolidation/normalization passes and their dry-run virtual filesystem inlattice.modes.clean, and the APEv2 classify/plan/apply/repair brain (including the verified atomic malformed-tag repair) inlattice.modes.apestrip. - Contract amendment: spec.md §5 now reads "reads tags; writes metadata only via the explicit
--clean/--apestripwrite modes (opt-in, logged, dry-run by default)". Every other mode remains read-only, and the remaining seven companion scripts stay put. - Behavior change (the one deliberate break): inside
lattice, the write modes dry-run by default and write only on--apply(--dry-runalways wins). The scripts keep their historical apply-by-default contract, so aliases and cron are unaffected. - New:
lattice --clean DIR [--normalize-names|--normalize-filenames|--normalize-tags|--all] [--layout]consolidates fragmented album folders and optionally normalizes names and tags. Every change is logged (default<root>/cleanup.log) and the dry-run preview predicts the real run exactly. - New:
lattice --apestrip DIR [--keep-metadata] [--repair-malformed]strips stray APEv2 tags from MP3s. A real run prints the worklist and asks for confirmation (auto-skipped when stdin is not a TTY); the log defaults to<root>/apestrip.log. Both write modes take exactly one root; an aggregated--rootlist is refused. - TUI: a new Maintenance section exposes both write modes behind yes/no confirms; answering No to the apply question runs the preview instead.
- Companion scripts:
cleaner.py(1.6.0) andapestrip.py(1.3.0) are now thin launchers that re-export the package implementation, so flags, log formats, idempotency, and the non-TTY auto-confirm are unchanged while the two implementations cannot drift. - Tests: test_cleaner.py and test_apestrip.py retarget the package modules wholesale (the
scripts/sys.path hack is gone; the dry-run fidelity classes moved whole), and new test_write_modes.py pins the CLI/TUI write-mode contract. Suite: 489 to 501, green.
- Refactor: Dropped lattice-music's hand-mirrored TUI progress implementation —
_TUIPbar, the_TUI_BOX_W/color-pair id mirrors, and the_SHARED_SCREEN/set_shared_screenplumbing (~110 lines) are replaced byvir_tui.progress_box()(vir-tui 2.2.0's first-class, session-screen-aware progress widget). Rendering can no longer drift from the TUI's style when vir-tui restyles. - Refactor:
interactive_menu()delegates the curses session lifecycle (open, degrade-to-text, close, KeyboardInterrupt cleanup) to vir-tui 2.2.0'sinteractive_session()context manager; theutils.IN_TUIflag is now set from the yielded session screen. - Chore: Report footers use vir-tui's public
out_note()instead of a local copy. - Chore: Removed the stale tracked
tests/test_tui.py.bak(referenced the removed API). - Dependency:
vir-tuitracks@main; requires 2.2.0+.
- Fix: TUI library-tree scan crashed with
TypeErrorwhen the output prompt was left blank; blank now renders the tree to the results pager like Library Statistics (write_music_library_treeacceptsoutput_file=None). - Fix: Progress boxes are back in the TUI. The vir-tui migration dropped the
IN_TUI/shared-screen wiring frominteractive_menu, so scans silently fell back to tqdm bars swallowed by the output capture and the screen sat frozen until the pager opened. Usessession_screen()from vir-tui 2.1.0.
- Refactor: Eradicated 1,267 lines of duplicated TUI framework code. lattice-music now delegates completely to
vir-tuiv2.0.0. - Dependency: Pointed
vir-tuireference to local path for editable testing, then restored remote URL on 2.0.0 bump.
- TUI Extraction (
vir-tui): The generic CLI/curses interface has been extracted into a shared library,vir-tui. lattice-music now delegates tovir-tuifor all interactive menus and text prompts, sharing this layer withCalibreQuarry.
cleaner.pynow supports an--allflag to run all normalization passes concurrently.
- New Companion Script: Added
flac2opus.pyto recursively find FLAC files, encode them to Opus at 128kbps usingffmpeg, verify output quality (duration match) and seamlessly copy metadata tags via Mutagen, and delete the original FLAC files.
- Feature: Added
--fetchto query the iTunes Search API and automatically download high-resolution cover art for albums completely missing art. - Feature: Added
--reportto find and report albums completely missing cover art.
- New Companion Script: Added
slipcover.pyto embed existing folder cover art (cover.jpg, etc.) into audio files that lack embedded art. Supports MP3, FLAC, Opus, Ogg, and M4A. Idempotent and dry-run capable.
- Added tag deduplication to
cleaner.py(Pass 4). Tags displaying asA / AorA, A(often remnants of flattened multi-value tags) are now automatically merged down to their unique values during--normalize-tags. Substrings are also resolved (e.g.Title (feat. Artist) / Titlecorrectly becomesTitle (feat. Artist)). This cleanly fixes cases where ffmpeg or other tools accidentally join ID3v1 and ID3v2 tags.
- Feature: Added
--allflag to easily enable all normalization passes at once (--normalize-names, --normalize-filenames, --normalize-tags).
- Feature: Added
tag_dedupefunction to properly clean up and deduplicate identical or substring multi-value tags (e.g.Title / Title) during tag normalization.
- Added global artist tag authority logic to
cleaner.py(Pass 4). The tag normalization pass now scans all artist-level folders across the entire library to build a global canonical map. Any track whose artist tag normalizes to a known canonical artist folder (handling case, punctuation, and guest credits correctly via a new_base_artisthelper) will have its artist and albumartist tags rewritten to perfectly match the casing of the canonical folder. This unifies artist names even across different genre boundaries. cleaner.pynow explicitly outputs a summary line (Cleanup run complete (APPLY). See ... for details.) on stdout when it finishes, resolving silent completion behavior.
- Feature: Tag normalization (Pass 4) uses a global map of artist folders as the tag authority. Tracks featuring guest credits (e.g.
Artist feat. Guest) are correctly matched to the baseArtistfolder. - Fix: Added a terminal
printnotification when the script concludes, ensuring the user is informed of completion rather than seeing a silent exit.
Second full-repo sweep on top of v4.10.2 (suite 487 to 520). One fix corrects a defect that made report values non-reproducible between runs, and one performance finding reverses a long-standing default; both are called out first.
- Behavior change: ratings are selected by rank, not by whichever key the container happened to yield first. A file can carry several rating-ish keys at once (
ratingbesidealbum rating,love rating, or a tagger's private_custom_rating).get_all_tagstook the first match and stopped, and mutagen builds a Vorbis comment's key list from aset, whose iteration order is randomized per process by Python's hash seed. The same FLAC/Opus file therefore reported a different rating on different runs: 41 files in a 9,589-file library were affected, so--playlist "rating >= 4"and the--statsrating histogram silently disagreed with themselves between invocations. Candidates are now ranked (the standard names first, an album-level rating last because it is not the track's rating, alphabetical ties), which also fixesalbum ratingoutranking a real track rating. Applied to all four container branches (ID3 TXXX, MP4, Vorbis, ASF); verified stable across eight hash seeds and byte-identical across whole-library runs. - Behavior change: tag reads are serial by default, and the worker count is now tunable. The concurrent tag read was never a win: mutagen decodes in Python, so the GIL is held for everything except the file open, and the per-task handoff costs more than the overlap saves. Measured with hyperfine on a 9,589-file NVMe library, serial is 1.41x faster for
--stats(9.6s vs 15.3s user CPU) and 1.49x faster for--auditTags;--statswall clock drops from 16.3s to 11.4s. The pool is kept rather than removed, because the picture inverts where an open genuinely blocks (SMB/NFS shares, spinning disks): set thetag_workersconfig key or theLATTICE_TAG_WORKERSenvironment variable to an integer orautoto opt back in. Gated on the storage rather than on a file count, since concurrency loses at every library size on fast local disk.--workersin the integrity modes is a different pool (flac/ffmpeg subprocesses, which do release the GIL) and is unchanged. - Fix: integrity modes no longer scan hidden directories.
--testFLAC,--testMP3,--testOpus,--testWAV, and--testWMAwalked with a bareos.walk, while every other mode goes throughiter_audio_dirsand prunes dot-directories. A scratch tree with a.hidden/copy measured 7 files found against the package's own 3, so a.testing/working copy of an album was decoded on every integrity run. The walk now prunes and is sorted. - Fix: MP3/Opus/WAV/WMA report rows are ordered by path. Rows were appended in
as_completedorder and written unsorted, so two scans of an unchanged library produced differently-ordered reports that could not be diffed.run_flac_modealready sorted its sections; the decode scanner now matches. - Fix: a tie in a directory's dominant artist/album/genre breaks the same way every run.
_scan_album_dirsiteratedos.walk's raw readdir order, so a directory whose files split evenly between two artists picked its headline name by coin flip. Filenames are now sorted before the tally. - Fix:
--auditArtQualitypicks the same cover twice running. A directory holding more than one recognized cover name took whicheveros.listdirreturned first. The lookup is now shared with_has_cover_filethroughutils._find_cover_fileand is sorted. - Fix: an empty-list tag value no longer raises. The rating readers did
val[0] if isinstance(val, list) else val, which raisedIndexErroron an empty list rather than reading as absent. - Cleanup:
stats.pyhad four copies ofimport lattice.utils as utilsinside one function (hoisted to module scope, which preserves the deferredIN_TUIlookup they existed for), a deadfsize = 0assignment, and an inline extension test whereis_audioalready exists. - Tests: 33 new, covering hidden-directory pruning in the integrity walk, decode-report ordering (the guard forces reverse-completion order rather than trusting scheduling luck), rating rank selection and its permutation-invariance, the tag-worker knob, the shared cover lookup, and scan tie-break determinism. Suite at 520.
- Verification:
--library,--ai-library,--all-wings,--playlist,--stats, and--auditTagswere diffed against a v4.10.2 baseline over the real 9,589-file library and are byte-identical apart from the intended rating corrections.
- Behavior change: hidden directories are pruned. The walk descended into dot-directories, unlike
rerate.pyandreplaygain.py, which both prune and document.testing/album copies as the reason. This is the destructive companion, so a hidden working copy was the worst place for the inconsistency to sit. Directory and file order is now sorted too, so a run's worklist is deterministic. - Fix: an unwritable log path is reported instead of raising.
open()on the log was unguarded, so a bad--logproduced a traceback wherererate.pyandreplaygain.pyprinterror: cannot open log fileand exit 1.
- Fix: a dry-run reports the same read errors as the apply run.
read_remapscaught every exception and returned a bare[], so an unreadable MP3 counted as "no changes" and the dry-run summary claimed zero errors on files the apply run then reported as failures. It now returns(changes, error), the same shapererate_filereturns, and distinguishes a missing ID3 header (not an error) from a genuine read failure. The two paths share one_popm_changeshelper so they cannot drift again. - Note for callers:
read_remapsreturns a tuple now, not a list.
- Behavior change:
applyexits 1 when any album failed to retag. It returned 0 unconditionally, so a wrapper script could not tell a clean run from one where every write failed.retag.py,rerate.py, andreplaygain.pyall already returned nonzero on error;applynow matches. - Fix:
build's "N artist(s) carry multiple genres" count is accurate. It counted every row beginning with#, which also swept up theEXCLUDEDcompilation comments and the "no genre tags found" comments, so the number bore little relation to the artists actually worth reviewing. It is now counted from the reduced artists that genuinely carry more than one genre.
- Fix: an unwritable log path is reported instead of raising.
Runopens the log in its constructor, so a bad--logproduced a traceback; it now printserror: cannot open log fileand exits 1, matching the other companions.
- Fix: an unwritable
--logpath is reported instead of raising, matching the other companions.
Full-repo bug sweep (package, TUI, and all seven companions reviewed; every fix below is regression-tested; suite 462 to 487). Three fixes change report values on purpose, called out first.
- Behavior change: canonical POPM bytes read as whole stars for any rater email. The bytes 1/64/128/196/255 (the WMP convention that foobar2000, Winamp, MusicBee, and
rerate.pyall write) only mapped to 1-5 stars when the frame's email was exactly "Windows Media Player 9 Series"; any other email fell into the linear 0-255 scale, so byte 196 read as 3.84 stars and arating >= 4playlist missed every 4-star MP3 rerate.py had just fixed. The canonical bytes now map to whole stars regardless of email; non-canonical bytes still use the linear scale. - Behavior change: FMPS_Rating tags read on their real 0-1 scale.
FMPS_Rating=0.8(4 of 5 stars, a documented Vorbis/TXXX convention) was read as 0.8 stars by the magnitude heuristic. Keys containingfmps_now scale 0.0-1.0 by five; everything else is unchanged. - Behavior change: multi-valued ID3 title/artist/album keep every value. The readers passed
frame.textinto_first_text, whose list branch took the first element before the "/" join could run, so a multi-valued TPE1 read as "Artist One" instead of "Artist One/Artist Two" (TCON already joined; now they agree). - Fix:
--verboseMP3 rows print the real bitrate mode. The row metadata took the enum's class name, so every CBR/VBR/ABR file printed the literal "BitrateMode"; it now prints the member ("CBR", "VBR", "ABR"). - Fix: smart-playlist rules that divide by a field validate correctly.
validate_ruleprobes the rule against all-zero dummy metadata, sobitrate / duration > 200died with "division by zero" before the walk even though real tracks never carry zero duration. Division by the dummy zeros is now treated as data-dependent, not structural. - Fix:
--all-wings --pathslists every directory of a duplicated album. When the same (artist, album) lives in two folders their songs merge into one wing entry, but the path annotation was last-wins, misattributing the merged track list to a single folder. It now lists all contributing paths ("; "-joined). - Fix: layout-aware album counting in
--stats. Albums were counted by raw path depth, which undercounted flat layouts and counted a loose file's artist folder as an album on a{genre}/{artist}/{album}tree. A directory now counts when the layout's{album}slot is actually filled. - Fix: a file directly at the scan root no longer defeats the "Unknown Artist" fallback.
parse_layoutfilled the first layout slot with a present-but-empty string for root-level files, soparsed.get("artist", "Unknown Artist")returned "" instead of falling back. - Fix:
relpath_underhandles a root of "/". The prefix check built"//"and never matched, so scanning from the filesystem root returned absolute paths where every other root returns relative ones. - Fix:
--quiet --verboseshows the progress bar. The decode scanners built the bar before--verboseflippedquietoff, producing a barless run that still printed the full verbose report. - Fix:
--extractArt --dry-run --quietis quiet. The dry-run announcement line ignored--quiet, unlike its real-run sibling. - Fix: a hand-edited
library_rootexpands~like the plural form.get_library_root()and the singular fallback inget_library_roots()returned the raw string, so a hand-written"~/Music"failed the CLI/TUI existence filters and the app re-prompted as if unconfigured. - Fix: the CLI validates configured roots with
isdir, matching the TUI.os.path.existsaccepted a root that had become a plain file, silently "scanning" zero files where the TUI correctly re-prompts. - Cleanup: dead
DEFAULT_STATS_OUTPUTconstant and unused_prompt_pathTUI helper removed; an impossible!= "None"string guard dropped; the always-truehasattr(args, "layout")condition simplified. - Known limitations noted, deliberately unchanged: the audit's fuzzy-duplicate normalizer does not strip nested-bracket suffixes like
(Deluxe [Remastered]), and blind non-TTY confirmation auto-skip in replaygain/apestrip remains the documented convention.
- Fix: a stale ID3v1 genre byte now defeats the noop check.
is_noopverified TCON, APEv2, andTXXX:GENREbut never the trailing ID3v1 block, one of the "hidden genre spots" the tool exists to clear: a file whose TCON already matched kept its stale v1 genre forever. The v1 genre byte is now compared against what the refresh would write; a file with no v1 tag at all is still a noop (nothing stale to clear, and a write would only mint a v1 tag nobody asked for).
- Fix: a Pass 1 survivor rename no longer hides the artist from Passes 2-4 in a dry-run. The renamed survivor's old path lands in the virtual
removedset, and Passes 2 (album consolidation), 3 (name normalization), and 4 (tag scan) all skipped it, so--dry-rununder-reported work--applythen performed (the headlineJAY‐Zexample triggered it). Rename origins are now recognized as surviving (their bytes live on under the new name) and previewed at their current on-disk path; a new end-to-end test drivesmain()dry and apply over identical trees and asserts identical stats. - Fix: Pass 4's dry-run no longer tag-scans files an earlier pass dropped. The tag walk ignored the virtual
removedset, so an exact-duplicate file (DROP DUPE) was still previewed and counted, inflating the dry-run's scanned/rewritten stats over the apply run's. - Fix: an unparseable image can no longer win a cover collision on byte size. When exactly one colliding cover parses as an image, the parseable one now wins; the larger-bytes fallback applies only when both parse (the pixel comparison) or neither does.
- Fix: the dry-run now predicts cross-device refusals. The mv-only guard (refuse instead of letting
shutil.movedegrade to copy+delete) only ran on--apply, so a library spanning a mount point previewed clean "would move" lines for moves the real run then refused. The check runs in both modes, against the destination's nearest existing ancestor. - Fix: a refused cross-device move leaves no stray directories. The destination tree was
mkdir-ed before the refusal check; the check now runs first andmkdironly happens for a real, accepted move. - Fix: a multi-disc album's destination collision is flagged once, not once per disc. The COLLISION branch now records the rejection like the DEST EXISTS branch always did.
- Fix: a genre folder emptied by
--refile-mismatchedis pruned. Moving the last artist out of a genre left the empty genre folder behind forever (only the artist level was pruned, unlike revert's upward prune). Emptied genre folders are now removed; the library root and the staging inbox (documented to stay in place) never are.
- Docs: the
-y/--yeshelp now states the confirmation prompt is auto-skipped when stdin is not a TTY (the shared companion convention apestrip.py already documented).
Built for the library-wide genre audit: retag first, then make the folders follow.
- New:
--refile-mismatched. An already-organizedGenre/Artist/Albumalbum whose tag genre disagrees with its genre folder used to be reported as aNOTEand left in place: correct behavior for a conversion run, a dead end after a retag pass. With the flag, such albums move to their tag's genre folder through the same machinery as strays: vocabulary gate (unknown target genres flagged unless--allow-new-genre), existing-folder spelling reuse, never-overwrite, manifest rows for--revert, source-artist pruning, and sidecars following the artist. Disc-subfolder records still collapse to their parent album, which moves as one unit. Default behavior without the flag is unchanged. - Fix: a multi-genre tag can no longer become one folder name. A single tag value joining genres with
;(tagger-joined TCON) or/(the library's own multi-genre convention) passed throughsanitize_componentintact, since;is NTFS-legal, and once produced a realDrill;East Coast Hip Hop;…/folder.split_multi_genrenow takes the first component for placement and flags the rest as aMULTI-GENRE TAGissue so the tag gets fixed at the source; a separators-only value falls through toNO GENRE. - Tests: 13 new (
MultiGenreTagTests,RefileMismatchedTests) covering the gate interplay, spelling reuse, disc-unit moves, dest-exists skips, sidecar follow, and the unchanged default. Suite at 462.
Carry-backs from the cquarry review: cquarry finished porting the 2026-07-01 audit, and its adversarially verified code review confirmed four defects in the shared curses skeleton that v4.10.0 still carried. The fixes mirror cquarry's (CalibreQuarry 0304cfa). One deliberate behavior change is called out below.
- Fix: the "Report written to ..." footer no longer appears after an error or cancel.
_run_with_captureappended the success footer unconditionally, so the pager could show[Error]plus a traceback (or[Cancelled]) followed by a footer claiming a file that was never finished. The footer is now suppressed whenever the mode raised or was cancelled. - Behavior change: Ctrl-C at the text-fallback menu exits 130, not 0.
_fallback_inputswallowedKeyboardInterruptinto a clean Quit, so a wrapper script checking for the documented 130 saw success. The interrupt now propagates to the session handler (which already maps it to 130), matching the curses menu; EOF remains a quiet Quit. Verified end-to-end: SIGINT at the degraded text menu exits 130. - Fix: the prompt and pause curses-failure fallbacks delegate instead of duplicating.
_tui_prompt_str'scurses.errorhandler re-implemented the text prompt inline (and both copies rendered aNonedefault as[None]); it now degrades and calls_prompt_str, which renders an empty default as[]._tui_pauselikewise delegates to_pause. - Cleanup: widget color init runs once per screen, not per widget. Every widget
_runre-called_init_tui_colors()although the session screen already initialized colors; the one-shot init now lives in_with_screen's wrapper branch (session screens get it from_open_screen), and the four per-widget calls are gone. No behavior change. - Found and fixed while verifying: the library submenu broke the persistent screen with
stty sane._library_submenuran_reset_terminal()unconditionally after every selection; under the v4.10.0 session screen that re-enabled echo and canonical mode, so the very next prompt echoed keystrokes over the TUI and only saw input after Enter. The v4.10.0 pty verification drove a main-menu flow and missed it. Fixed at the source, matching cquarry's shape:_reset_terminalnow returns early while a session screen is published (utils._SHARED_SCREEN), since a live curses session owns the terminal state. CLI use is unchanged (no session screen there). Re-verified under a pty: menu → submenu → prompt → Esc-cancel → quit works with one alternate-screen enter/leave. - Tests extended (
tests/test_tui.py+tests/test_utils.py, 449 total across the suite): footer suppressed on error and cancel (still shown on success),_fallback_inputpropagating Ctrl-C and quietly quitting on EOF, the prompt/pause fallbacks routing through their text counterparts, and_reset_terminalstaying quiet while a session screen is live.
The persistent-curses-screen rework: audit item T7, the last parked entry from the 2026-07-01 TUI/UX audit. Purely a lifecycle change; no menu, prompt, or mode behavior differs.
- One curses screen per session. Every menu, prompt, pause, and pager used to be its own
curses.wrapperinit/teardown, so multi-prompt flows visibly flashed to the shell between widgets.interactive_menunow opens the screen once and every widget draws into it (_with_screen); a widget invoked outside a session still gets its own one-shot wrapper, so nothing changes for direct callers. Measured under a pty: a full menu → prompt → cancel → mode → pager → quit session enters the terminal's alternate screen exactly once, where the same flow on v4.9.0 entered it seven times. - The in-mode progress bar joins the session.
_TUIPbardraws into the shared screen the session publishes (viautils.set_shared_screen) instead ofinitscr()-ing a screen of its own, and itsclose()no longer tears down terminal state that isn't its to tear down. Standalone use (no session) keeps the old start-and-end-a-screen behavior. - One degradation path. A mid-session curses failure (terminal died, capability lost) funnels through
_degrade_to_text: the screen is suspended once and the rest of the session runs the text fallback. Session startup failure does the same before the first menu. All the v4.8.2 guarantees (no stuck terminal, no silent exit) hold. - Ctrl-C is coherent everywhere. At a prompt it cancels exactly like Esc; in the pager it closes the pager; at the menu it ends the session cleanly with exit code 130 (previously an unhandled traceback).
- Tests extended (
tests/test_tui.py+tests/test_utils.py, 441 total): session-screen routing, wrapper fallback, degradation clearing every piece of session state, the 130 exit, and the progress bar leaving a shared screen alone.
TUI parity and UX release, closing the 2026-07-01 audit's T1 to T6 (T7, the persistent-curses-screen rework, stays deliberately parked). One deliberate behavior change is called out below.
- Multi-root configs are visible to the TUI (T1). A
library_roots-only config used to read as a first run: the TUI prompted and overwrote the user's intent with a singlelibrary_root. The session check now consults both keys, the menu title shows[N roots], and every mode receives the full roots list exactly as the CLI passes it. "Change library root" edits onlylibrary_rootand says so when a roots list exists. - Behavior change: Esc in a prompt cancels (T2). Esc used to mean "accept default", so selecting a scan by accident and mashing Esc launched it. Esc (or Ctrl-C at a text prompt) now unwinds the whole prompt chain back to the menu with nothing launched; bare Enter still accepts the default. The hint bar reads "⏎ Accept Esc Cancel Ctrl-U Clear".
- Library-root changes are validated before persisting (T3). A typo'd root was saved over the good one, every retry of the recovery loop was labelled "First run:", and Esc or a blank answer at the true first run silently made the launch directory the permanent root. Paths are now checked with
isdirbeforeset_library_root; a bad answer shows "Not a directory" and keeps the old root; a missing configured root gets its own "Configured root missing" wording; a blank first-run answer re-prompts (type.to choose the CWD explicitly). - Output-path prompts expand
~(T4).~/reports/x.txtused to create a literal./~/reports/. Every output prompt now expands the tilde (paths otherwise stay relative), and the results pager ends with "Report written to /abs/path" so the report's location answers itself. - CLI parity in the prompts (T5). The decode-scan modes gained an "ffmpeg path (blank = auto)" prompt (the CLI's
--ffmpeghad no TUI equivalent); stats gained the layout prompt its siblings have; the FLAC prefer-tool prompt re-asks until it getsflacorffmpeg; the OK-rows question is labelled "(verbose report)" since one answer drives both knobs; and the unreachableor "{artist}/{album}"arms after layout prompts (which would have shadowed a configured layout if ever reached) are gone. - TUI niceties (T6). Bad numeric input re-prompts with a note instead of silently using the default; menus taller than the terminal scroll to keep the selection visible; the pager pans horizontally (←→/h/l) with
…truncation markers and no longer recomputes its width on every keypress; Ctrl-U clears a prompt field; the in-mode progress box is throttled to ~10 redraws/s and showsn/total · Ctrl-C cancels; the Quit/Change-root result tuples are named constants. Mode-level: a bad smart-playlist rule is now rejected once, up front (validate_rule), instead of printing one error per track — the CLI benefits too. - Tests extended (
tests/test_tui.py+tests/test_playlists.py, 436 total across the suite): a hermetic menu harness (config stubbed, pager captured) covering cancel chains, root validation, multi-root passthrough and titling, prefer-tool re-prompting,~expansion, integer re-prompts, and the rule validator.
Polish release from the 2026-07-01 audit (roadmap L-cleaner batch); one behavior change, strictly safer.
- Fix: "identical" duplicates are verified by content sample, not size alone. A colliding file was dropped as a DROP DUPE purely on byte count, so a same-size re-encode or retag of a different take was deleted. The drop now also requires equal first/last 64 KiB (
head_tail_equal); a same-size file with differing sampled bytes takes the collision path instead, so audio survives as.from-fragment. A mid-file-only difference within same-size files can still slip through the sample; the log line says "sampled bytes" for that reason. - Fix: an MP3 with no ID3 header (tags only in APEv2/ID3v1) is reported and counted (
SKIP (no ID3 header ...), newtag_no_id3_skippedstat) instead of silently skipped; the.wavpath was already the model. - Fix: the ASF tag write deletes case-variant keys first. The
.wmabranch read keys case-insensitively but wrote canonical case beside a variant original, leaving two keys; it now clears variants like the Vorbis branch. - Fix: pass headers no longer orphan the log timestamp.
log("\n--- PASS ---")put the timestamp prefix on the blank line; the blank line is emitted separately now. - Fix: a merge survivor that also gets renamed is one tag target, not two. The rename hook and the group both recorded the artist; the group's record (which also carries the merged sources) is now the only one for that case, while Pass 3 sweep renames still record their own.
- Cleanups:
_normalize_folder_name/_normalize_file_nameshare one_rename_toguard helper (H3's fix no longer has to be made twice),consolidate_groupcomputes each folder's file count once instead of walking twice, andfile_countno longer uses_as a load-bearing variable. - Tests extended (
tests/test_cleaner.py, 82 total): same-size-different-bytes collisions,head_tail_equaledge cases, the headerless-MP3 report, the ASF case-variant delete, the log format, and tag-target dedupe (merge+rename vs sweep).
Polish release from the 2026-07-01 audit (roadmap L-genre_foldermap batch). Also corrects a housekeeping miss: yesterday's v1.3.2 changes shipped without bumping __version__ (it still said 1.3.1); this release moves it straight to 1.3.3.
- Fix: the genre gate matches case-insensitively and reuses the existing folder's spelling. A stray tagged
hip hopagainst an existingHip Hopfolder was flagged UNKNOWN GENRE, and--allow-new-genrewould then mint a case-variant duplicate top-level folder. A case-variant match now files into the existing folder (artist-level sidecars follow the same spelling), and an organized album whose tag differs from its folder only by case is no longer a NOTE. - Fix: cross-device moves are refused.
shutil.movesilently degrades to copy+delete across filesystems, against the documented mv-only contract (audio bytes are never rewritten); the Runner now compares device numbers and refuses with aCROSS-DEVICE (refused)line and its own stats counter. - Fix: paths containing a tab or newline are refused, not moved. Such a path would corrupt the manifest TSV, making the move unrevertable; it is flagged
UNSAFE NAME(rename the folder first) and its bookkeeping is skipped. - Docs honest about revert and reversibility. Every
--revertmention now says it is a dry-run by default (add--applyto execute, same as a forward run), including the hint the manifest header writes; the "reversible" claim is scoped to files and moved folders (source folders pruned empty are not recreated); the vocabulary is documented as record-derived (a genre folder with no readable audio that run drops out of the gate). Comment fixes: theMove.kindcomment no longer claims pruning behavior, thedst == srcguard is annotated with its only reachable case (genre folder named like the staging inbox), and the prune comment describes the real single deepest-first pass. - Tests extended (
tests/test_genre_foldermap.py, 55 total): case-variant gate reuse (with and without--allow-new-genre), the case-variant NOTE suppression, unsafe-name refusal, and the cross-device refusal.
Polish release from the 2026-07-01 audit (roadmap L-genre_tidy batch).
- New:
--layouton both subcommands. The scanner was pinned to{artist}/{album}, so on the genre-foldered library genre_foldermap produces, an untagged file's artist fell back to the genre folder name. Pass--layout "{genre}/{artist}/{album}"to recover artist/genre from the right path levels, exactly like cleaner.py. - Fix: tabs and newlines in tag values no longer corrupt the map. A genre like
Rock<TAB>Popwas written as two TSV columns, so it read back as two allowed genres and a fresh map was not a no-op (applyrewrote the tag). Generated fields fold tab/newline to a space;norm()collapses whitespace the same way, so the sanitized row still matches the raw tag at compliance time. - Fix: silent last-wins on normalized-key collisions. Two hand-edited rows that normalize to the same artist (
Jay-Zvs a curly-dashJay‐Z) silently dropped the earlier row; the overwrite warns on stderr now. - Docs: the EXCLUDED trade-off is stated. A real artist actually named "Various" or "VA" is permanently unenforceable; the comment block above
EXCLUDED_ARTISTSacknowledges it. - Tests extended (
tests/test_genre_tidy.py, 40 total): TSV sanitization round-trips, the collision warning, and the layout passthrough.
Polish release from the 2026-07-01 audit (roadmap L-retag batch); no new features. RT4 (the "subdirectories not descended" note) had already landed with M17.
- Fix: direct invocation is byte-idempotent. A file already carrying exactly the target genre was still fully rewritten on every run (APEv2 deleted, v2.4 tag re-saved as v2.3, ID3v1 minted). A per-file no-op guard now skips the write and logs
unchanged; for MP3 the guard also checks the hidden genre spots retag exists to clear, so a matching TCON with a stray APEv2 tag or bareTXXX:GENREframe still gets the write. Dry-run predicts the same skips. (genre_tidy already gated via compliance; this hardens direct use.) - Fix: an unreadable Vorbis-family file reports its failure.
mutagen.File()returning None for a corrupt file used to return False silently, invisible next to every other failure path's[!] Failedline; it prints one now. - Fix: WMA dry-runs show the real old genre.
read_genresusedeasy=True, which has no ASF wrapper, so.wmaalways read back[];WM/Genreis read directly now. - Docs: dead code dropped. The Vorbis branch popped both
"genre"and"GENRE"with a comment about clearing "both cases"; mutagen's comment dict is case-insensitive, so the second pop could never do anything and is gone. - Tests extended (
tests/test_retag.py, 24 total): byte-identical second run, the stray-APE and bare-TXXX force paths, dry-run unchanged prediction, the WMA read, and the unreadable-file report.
Polish release from the 2026-07-01 audit (roadmap L-rerate batch); no new features. RR4 (error accounting) had already landed with M10.
- Fix: hidden directories are pruned from the walk.
.testing/album copies (and any dot-directory) were rerated along with the library; the walker now prunes them, matching replaygain.py. - Fix: a bad
--logpath is a clean error (exit 1 with a message, not a traceback), matching the directory validation. - Docs: the REMAP comment no longer claims extra entries are harmless. They are not: the map is deliberately closed because only DeaDBeeF's 2★ (127) and 4★ (254) have a byte both players agree on. Byte 64 is a fixpoint collision (DeaDBeeF 1★ and foobar 2★ share it, unfixable by byte rewrite alone) and DeaDBeeF 3★ (190) has no byte both players read as 3 stars. The comment now says so, and warns that any candidate entry needs verifying in both players first.
- Docs: the save is described honestly. "Rewrites the POPM byte in place" undersold it; the save re-serializes the whole ID3 tag (v2.4 comes back v2.3, ID3v1 refreshed, matching retag.py), audio untouched.
- Tests extended (
tests/test_rerate.py, 12 total): hidden-dir pruning and the guarded log open.
Polish release from the 2026-07-01 audit (roadmap L-replaygain batch); no new features.
- Fix: an album rsgain silently declined is a NO-OP, not "scanned". Easy mode exits 0 with "No files were scanned" when it finds nothing it can tag; the run counted it scanned and logged nothing unusual. The album's gains are now read back before it counts: no message and no gains means a distinct
NO-OPlog line and its own summary counter. - Fix: M4A gains read back as text.
MP4FreeFormis a bytes subclass, so the post-scan verification loggedb'-6.66 dB'; bytes values are decoded now. - Fix: every run leaves a log trail. A run where everything was skipped (
--skip-taggedon a fully tagged library) or that was declined at the confirmation prompt wrote nothing at all to the log; both now write a properRG RUN START/summary/ENDblock saying why nothing happened. - Fix: a bad
--logpath is a clean error. The log open was unguarded, so an unwritable path was a traceback; it now validates likedirectorydoes and exits 1 with a message. - Docs:
--skip-taggedtarget-blindness stated. It checks only that gain tags exist, not what target they were computed against, so an album tagged at the default 89 dB reads as tagged under--target-lufs -14; the docstring says to rescan without--skip-taggedwhen changing targets. Also tidied: the worklist filter unpacks its tuples instead of indexingw[5]. - Tests extended (
tests/test_replaygain.py, 27 total): NO-OP vs scanned accounting, the bytes decode, skip-everything and declined-prompt log blocks, and the guarded log open; themainharness is now shared between the dry-run and apply test classes.
Polish release from the 2026-07-01 audit (roadmap L-apestrip batch); no new features.
- Fix: unmigratable APE items are reported and skipped, never written as junk frames. Under
--keep-metadata, a binary item bound for a TXXX passthrough became an empty TXXX frame, an external cover reference became anAPICwith zero bytes of image data, and a cover in an unrecognized image format was mislabeledimage/jpeg. All three now land in a per-file[skip]report (with the reason) and are dropped with the tag; the preview summary counts them. - Fix: a described COMM frame no longer blocks a real comment migration. The redundancy check counted any
COMM*frame, so an iTunesCOMM:iTunNORM:engnormalization blob made a sole-source APE Comment read as redundant and silently dropped it; only an unqualified comment (empty description) counts now. - Fix: the raw item parser bounds each value length. A malformed item whose declared length overran the footer would slurp footer bytes into its value; the parse now stops at such an item instead.
- Fix: repair-path fsync ordering. With migrations,
id3.save(tmp)rewrote the temp file after the flush+fsync, so the atomic swap could install a half-flushed tag on power loss; the file is synced again after the save. - Docs honest about the redundancy check. The docstring promised value-level preservation ("so nothing is lost") but the check is presence-only: a field ID3 already has, whatever its value, is treated as authoritative and not overwritten. Now says so. Also tidied: the garbled
_RawAPEValuedocstring, a narration comment, the mid-fileAUDIO_EXTconstant, andplan_file's annotation (it also accepts raw-parsed items). - Tests extended (
tests/test_apestrip.py, 53 total): binary/external/unknown-format skip paths, the iTunNORM redundancy trap, and the overflowing item length.
Bugfix release from the 2026-07-01 audit (roadmap items M1 to M6); no new features.
- Fix:
--keep-metadataon an ID3v1-only MP3 no longer clobbers the v1 values. Without seeing ID3v1, every APE field looked sole-source and the eventualsave(v1=2)rebuilt ID3v1 from the sparse v2 frames, blanking the old title/artist (exactly the old rips most likely to carry APE tags). Migration planning now seeds from the trailing v1 block when there is no v2 tag. On mutagen 1.46+ (which reads v1 intoID3()itself) the bug never fired; the seed covers older mutagen and the test pins the behavior either way. - Fix: multi-value APE text items migrate as separate values. They were flattened to one NUL-joined string, and an embedded NUL truncates a v2.3 UTF-16 frame so players showed only the first value. Values now stay separate through the migration (the v2.3 save renders them slash-joined, all values visible); labels render them readably.
- Fix:
--repair-malformedpreserves file permissions. The atomic-swap temp file (mode 0600) was installed verbatim, silently stripping group/other access on shared-mount libraries; the original mode is copied before the swap. - Fix: a repair-path I/O error is a per-file error, not a crash. An unreadable file or read-only directory raised out of the unguarded repair body and killed a library-wide run mid-write-pass; it now returns an error result the loop's accounting handles.
- Fix: the repair excision recognizes trailing structures. Everything between the APE footer and a strictly terminal ID3v1 used to be cut as junk: a Lyrics3v2 block was deleted, and an ID3v1 followed by stray padding was itself excised (the end-anchor missed it). Lyrics3v2 and a terminal ID3v1 are now preserved byte for byte; junk before a terminal ID3v1 (the shape that motivated the flag) is still excised; anything else refuses the repair and reports instead of guessing.
- Fix: honest audit log and exit code. A file whose APE tag vanished between the planning and write passes was logged as "stripped APEv2 tag"; it now logs "no APEv2 tag at write time (skipped)".
mainexits 1 when any file errored (was always 0). - Tests extended (
tests/test_apestrip.py, 46 total): v1-only preservation, multi-value migration, permission preservation, read-only-dir error path, the three trailer shapes, and first coverage of themainexecution loop (happy path, vanished tag, error exit).
Bugfix release from the 2026-07-01 audit (roadmap items M7 to M9); no new features.
- Fix: custom mode no longer fails a whole album over one rsgain-unsupported file.
rsgain customrejects its entire file list when one entry is unsupported (verified live: a raw ADTS.aacbonus track failed a 12-FLAC album under--target-lufswhile default easy mode sailed through). The custom branch now filters to the formats rsgain 3.6 can write (perrsgain --help), logs eachSKIP (rsgain-unsupported)file, and skips an album with nothing left. - Fix: dry-run honors
--skip-tagged. The preview printed "Would scan" over the unfiltered worklist while apply filtered it; on a mostly-tagged library it predicted hundreds of albums where apply would scan a handful. The scan set is now computed once, before the dry/apply split; the dry-run marks skipped rows and summarizes "Would scan X of Y". - Fix: nested album folders are no longer rescanned via rsgain easy's recursion.
rsgain easyscans a directory recursively, so a parent album dir with a loose track besideCD1/meant CD1 was scanned twice and, with--skip-tagged, rewritten even when skipped. Such parents are excluded from easy-mode runs and reported (NESTED ALBUM (skipped): ... scan the subfolders or flatten); custom mode passes explicit direct files and is unaffected. The fuller option (scanning the parent's direct files as their own unit via custom mode) is deliberately not taken yet; flagged as an open decision. - Tests extended (
tests/test_replaygain.py): supported-set filtering and argv exclusion, nested-parent detection (including the sibling-string-prefix trap), and firstmaincoverage via dry-run runs; the test file now importsAUDIO_EXTENSIONSfromlattice.configinstead of carrying a copy.
Bugfix release from the 2026-07-01 audit (roadmap items M10, M11); no new features.
- Fix: one bad file no longer crashes the whole run.
tags.savesat outside the try in a function documented "never raises", so a read-only file or full disk killed the walk with no log line and no SUMMARY.rerate_filenow returns(changes, error);mainlogs anERRline per failure, counts errors into the SUMMARY, and exits 1 when any occurred. - Documented decision (M11): the remap stays byte-only, with no POPM email filter. Safe in a DeaDBeeF/foobar-only library; the docstring now states the assumption prominently and points at the dry-run output (which prints each frame's email) for libraries touched by other taggers. Revisit with an email gate only if a foreign tagger actually shows up.
- Tests extended (
tests/test_rerate.py): the error result on a read-only file, and firstmaincoverage (error accounting, exit codes).
Bugfix release from the 2026-07-01 audit (roadmap items M16, M17); no new features. Exit-code contract change: main now returns 1 when any file failed to write (known callers: genre_tidy.py apply, which wants exactly this, and manual use).
- Fix: failures are visible to callers. Per-file failure messages go to stderr (they were buried in stdout), and a run where files failed exits nonzero, so
genre_tidy.pycan count the album as an error instead of a successful retag. - Fix: unwritable audio in a mixed album is named. Files retag cannot write (
.wav,.aac,.alac,.ape,.wv,.aiff) were silently skipped; each now logsskip (unsupported): <name>, and the "No valid audio files found" note mentions that subdirectories are not descended. - Tests extended (
tests/test_retag.py): stderr routing, nonzero exit with a read-only file, full-success exit 0, and the mixed-album skip line.
Bugfix release from the 2026-07-01 audit (roadmap items M14 to M17); no new features.
- Fix: artists whose name starts with
#are data, not comments.#1 Dadused to be discarded by the map parser, could never be enforced, and was re-appended as a "new" artist on every rebuild. The comment rule is now explicit (#+ space, dash, or end of line); generated comments always match it, so a#-leading artist survives the round-trip. The rule is documented in the map header. - Fix: EXCLUDED (Various Artists) entries no longer re-append on every rebuild. They intentionally have no data row, so the "already present" check could never see them and every
buildappended a fresh dated marker plus a duplicate EXCLUDED comment; they are now filtered from the new-artist diff and the "No new artists" path is reachable. - Fix: a failed retag counts as an error, not a retag.
applycounted an album intoretaggedbefore invoking retag and retag always exited 0; with retag v1.1.1's exit code, a nonzero run now incrementserrors(with the captured stderr logged) andretaggedonly counts successes. - Fix: albums retag cannot write are skipped with a reason. A
.wav-only album with a stray genre was "retagged" forever (retag skipped every file, exited 0, nothing converged).applynow checks the album's extensions against retag's writable set (imported fromretag.py, so the two cannot drift), logsUNSUPPORTED FORMAT (skipped)once, and counts it under a newunsupportedstat. - Tests extended (
tests/test_genre_tidy.py): the comment rule and round-trip, rebuild no-op with a VA comp, and firstcmd_build/cmd_applycoverage (success, failure-counts-as-error, unsupported-format convergence) with the real retag subprocess.
Bugfix release from the 2026-07-01 audit (roadmap items M12, M13); no new features.
- Fix: a rejected album move no longer triggers its sidecar bookkeeping. When an album was skipped (
DEST EXISTS/collision), its artist-level sidecars (cover art, .nfo) were still relocated to the target genre, stranding the un-moved album without its artwork, and the source dir was still queued for pruning. Bookkeeping is now gated on the move actually being planned. - Fix:
--revertruns through the Runner. Reverts moved as much as an apply but bypassed the context manager: no audit trail, no replay manifest (the.revert.tsvwas named but never written), and a dry-run revert always predictedpruned=0because nothing fed the virtual-removed set. Each restore now goes throughdo_move(kindrevert), so the manifest, stats, and dry-run prune prediction all come for free; the Runner also models virtual creations, so a dry-run revert sees restored albums as children of their original parents and predicts exactly the prunes a real revert performs. - Tests extended (
tests/test_genre_foldermap.py): rejected-move bookkeeping, the replayable.revert.tsv, dry-vs-real revert prune parity, and dry-run-revert-touches-nothing.
Bugfix release from the 2026-07-01 audit (roadmap items M18 to M20); no new features.
- Fix: multi-valued tags keep all their values through the typographic fold. The tag pass read only the first value and wrote back a singleton, so a FLAC with
artist=["Artist A’s Band", "Artist B"]lost the co-artist whenever the first value needed folding. Every value is now folded and written back as the full list. The authority restamp deliberately still collapses to the single survivor name (that is its semantic), now stated in a comment. - Fix: dry-run models creations, not just removals. Collision and rename decisions consulted the raw disk, so previews diverged from apply in several shapes: a three-way merge where both sources carry the same extra track previewed two plain moves where apply performs one move plus an
AUDIO COLLISION; two siblings folding to the same rendered name previewed two renames where apply performs one. The Run now tracks virtual creations (mapping each virtual destination to the real path holding its bytes, so size/kind checks still read real data), every existence/size check in the merge and rename paths goes through the virtual-aware views, and Pass 2/3 walks skip folders an earlier pass virtually merged away. Dry-run stats now match apply on all the audited fixtures; the residual limitation (contents of virtually-moved folders are not modeled recursively) is noted in the docstring. - Docs: the module docstring's stale v1.2.0 tag-pass text is gone. Two passes were both numbered "4." and the survivor described the pass as MP3-only and merged-folders-scoped, contradicting shipped v1.3.0 behavior; one accurate pass description remains, and the misleading "Pass 3" comment on the tag-target hook (which also fires for Pass 1/2 survivor renames) is corrected.
- Tests extended (
tests/test_cleaner.py, 72 total): multi-value fold and authority collapse, dry-vs-apply parity for the three-way merge and same-render siblings, and virtually-removed folders being skipped by the group scan.
Bugfix release for the TUI, from the 2026-07-01 audit (roadmap items H6 and H7); no new features.
- Fix: a mode error no longer kills the TUI with the terminal stuck in curses mode.
_run_with_capturehad no exception boundary, so a mode failure (say, an unwritable output path after a completed scan) escaped as a raw traceback, lost the captured results, and left the screen in curses mode because the in-mode progress bar had started a screen nothing tore down. Mode exceptions are now caught and paged under an[Error]heading with the full traceback plus whatever output was captured; Ctrl-C pages a[Cancelled]notice the same way. The curses screen is explicitly ended and the terminal reset before paging, and_TUIPbar.close()now ends the screen it started, so well-behaved modes hand back a sane terminal too. - Fix: a plain-text fallback session no longer routes progress to the curses bar.
interactive_menusetutils.IN_TUIunconditionally, so a session that had already degraded to the typed-input menu (curses missing, or stdin not a TTY) still handed progress to_TUIPbar, which could crash on the missing module or hijack the screen mid-session.IN_TUInow tracks_USE_CURSES, re-evaluated every menu pass. - Fix: a curses init failure no longer reads as "Quit". On capability-poor terminals (
TERM=vt100, dumb terminals)curs_set/color setup raisedcurses.error, which the menu treated as the user choosing Quit: the TUI silently exited 0 even though the text fallback works. Cosmetic capabilities (colors, cursor visibility) are now non-fatal, so such terminals get a monochrome TUI; a realcurses.wrapperfailure flips the session to the text fallback menu instead of exiting. - New tests in
tests/test_tui.pypin all three behaviors (paged tracebacks, fallback sessions leavingIN_TUIunset, the fallback sentinel re-entering the menu loop).
Bugfix release from the 2026-07-01 audit (roadmap items H1, H2, H3); no new features.
- Fix:
feat.detection no longer matches inside words. The guest-credit regex used a zero-width\s*boundary, so theftending "Left", "Swift", or "Croft" read as a feat marker:--normalize-tagsunder a merged/renamed artist folder rewrote a clean "Left Boy" tag to "Left Boy feat. Boy", and every further pass appended another "feat. Boy" (non-idempotent corruption). The marker now requires a real token boundary. Also fixed in the same change: a parenthesised credit like "A (feat. B)" no longer leaves the stray closing paren on the guest. - Fix:
.wmacollisions are treated as audio..wmawas inTAGGABLE_EXTbut missing fromAUDIO_EXT, so a differing-size.wmacollision during a merge fell into the non-audio branch and the source copy was deleted, violating the "audio is never overwritten or deleted" guarantee. It now survives as a.from-fragment.wmacopy, and--normalize-filenamesreaches.wmatracks.AUDIO_EXTis now documented against the package'sAUDIO_EXTENSIONS(.mp4stays deliberately excluded as ambiguous with video). - Fix: dry-run now predicts the survivor rename. The rename collision guard checked only the disk, where the merged-away source folder still exists during a dry-run, so the flagship scenario (canonical
Drive‐By Truckerswith a U+2010 hyphen absorbingDrive-By Truckers) previewedRETAIN NAMEwhile apply performed the rename, and the tag pass preview consequently missed the authority restamps. The guard now consults the run's virtual removals, so dry-run and apply report identical stats and tag targets. - Tests extended (
tests/test_cleaner.py): mid-wordftcases, paren stripping, feat idempotency,.wmacollision and rename, and a dry-vs-apply parity check on the survivor-rename fixture.
Bugfix release from the 2026-07-01 audit (roadmap item H4); no new features.
- Fix: multi-disc album subfolders no longer poison the genre vocabulary. The scanner emits one record per audio-bearing directory, so
Artist/Album/CD1in a flat library arrived as a depth-3 record and classified as "organized", which put the artist's name into the genre vocabulary, turned the placement gate on, and flagged every ordinary strayUNKNOWN GENRE: one disc folder broke the whole flat-to-genre conversion, and the disc album itself was never filed. Disc subfolders (CD1,Disc 2,disk_3,DVD 1,Side 1,Vinyl 2, ...) now collapse to their parent album, which moves as one unit with the discs inside; CD1+CD2 records dedupe to a single move, and discs whose genre tags disagree keep the first and flag aDISC GENRE MISMATCHissue instead of planning two moves of one folder. - Fix: organized disc albums no longer spam
TOO DEEP. A legitGenre/Artist/Album/CD1is recognized as that album (in place, no issue) instead of producing perpetual wrong-root noise. - Fix: inbox content can never read as "organized".
Unfiltered/Artist/Album/CD1strips to the album and is filed like any stray; anything deeper or stranger under the inbox is flaggedSTAGED TOO DEEP (left in inbox)for manual review rather than being silently treated as an organized album stuck in the inbox forever. - Tests extended (
tests/test_genre_foldermap.py): disc classification (flat, organized, staged, and an album genuinely named like a disc), one-unit end-to-end move with the gate off, vocabulary hygiene, disc genre disagreement, and the staged-deep flag.
Bugfix release from the 2026-07-01 audit (roadmap item H5); no new features. retag.py is unchanged.
- Fix: a slash canonical no longer causes a permanent retag loop.
applyused to split"Emo / Orgcore"on/into two genre values; retag wrote them as a multi-value tag that never read back equal to the map (lattice reads only the first Vorbis genre field; MP3's v2.3 save slash-joins without spaces), so everyapplyre-ran retag on the same albums forever: files rewritten, APEv2 stripped, mtimes churned, dry-run never converging. The canonical is now passed verbatim as one genre value, so the tag written is exactly the string the compliance check reads back and the run converges. This treats a slash genre as one genre (which is what DeaDBeeF/foobar2000 display anyway); nothing in the shippedartist_genre_defaults.tsvused a slash genre, so no live behavior changes. - Tests updated (
tests/test_genre_tidy.py): the single-argument invocation is pinned, and a new end-to-end check writes the slash canonical throughretag.apply_genreson FLAC and MP3 fixtures and asserts the re-read tag is compliant (a second apply would plan zero retags).
New feature (no package change): a staging inbox, so albums dumped outside the organized tree can be filed without being mistaken for a genre.
- The problem. A tagger such as MusicBrainz Picard drops fresh
Artist/Albumfolders into a holding area to keep them out of the organized root. If that holding folder lives at the library root (e.g.Music/Unfiltered/), the old depth logic readUnfiltered/Artist/Albumas an already-organized album under a genre literally named "Unfiltered" and refused to move it out. - What it does. A staging folder name (default
Unfiltered) is stripped from the front of a path before classification, soUnfiltered/Artist/Albumclassifies as a flat stray and is filed into the real taxonomy at the root, exactly likeArtist/Album. The genre vocabulary gate still applies, so a staged album only lands in a genre the library already uses (or pass--allow-new-genre). - The inbox is kept. Each staged album's per-artist source folder is pruned once emptied, but the
Unfiltered/inbox itself is never treated as a source dir, so it survives the run for next time. - New
--staging DIRsets the inbox name (defaultUnfiltered); pass--staging ""to disable the behavior entirely. The wrong-rootTOO DEEPguard is unaffected. - Tests extended (
tests/test_genre_foldermap.py): classify stripping for album and loose shapes, the unchanged no-staging behavior, end-to-end filing into the taxonomy with the cover carried along and the inbox kept, and the vocabulary gate still applying to staged albums.
Extends the v1.2.0 tag work into a general, library-wide typographic normalizer covering names at every depth and the title/album/artist tags across all formats.
--normalize-tagsis now library-wide and multi-format. It walks every audio file, not just merged/renamed artist folders. Title and album get a pure typographic fold (CP1252 mojibake, curly quotes, and broken hyphens cleaned; the words never change, so the folder is never an authority for them). Artist and albumartist fold the same way everywhere, except under a merged or renamed artist folder, where they are still restamped to the surviving folder name (guest credits preserved). All formats are handled (MP3/FLAC/Ogg/Opus/m4a/WMA), each written in its native fields; ID3 stays v2.3 + refreshed v1. Only changed fields are touched, so a clean file is a no-op and the pass is idempotent.- Correct typography is preserved. The tag fold now matches the folder rename's philosophy: en/em dashes and the ellipsis are kept (
Selected Ambient Works 85–92keeps its en dash), and a CP1252-mojibake dash is repaired to the real dash rather than flattened to a hyphen. Genuinely broken hyphens (U+2010-2012/2015) are still folded to ASCII. --normalize-namesnow recurses to every folder depth (it was capped at two), so album folders under aGenre/Artist/Albumlibrary are reached.- New
--normalize-filenamesrenames audio track files the same way (extension kept verbatim). It is separate from--normalize-namesbecause renaming files is a distinct change (filenames are referenced by playlists and cue sheets); the two compose. - Behavior-change note.
--normalize-namesreaching all depths and--normalize-tagssweeping the whole library are both broader than v1.2.0. Both remain off by default and dry-run-previewable; the v1.2.0 single-folder behavior is a subset of the new one. - Tests extended (
tests/test_cleaner.py): multi-format writer (FLAC + MP3, case-insensitive Vorbis keys, authority vs plain fold, no-op, absent-field), library-wide folding with and without a merge, deep folder + filename renames with collision/illegal guards, dry-run fidelity, and a run-twice idempotency check.
New feature (no package change): --normalize-tags teaches cleaner.py to rewrite embedded artist/albumartist tags so they match the surviving folder name after a merge or rename.
- The problem. The merge passes consolidate variant artist folders (
Bonnie 'Prince' Billy/Bonnie Prince Billy/ a CP1252-mojibakeBonnie \x93Prince\x94 Billy) into one folder, but the tags inside still carry the old spellings. Players that show the artist tag, not the folder, still see three artists. - What it does. With
--normalize-tags, a fourth pass rewrites the MP3artist/albumartisttags under every merged or--normalize-names-renamed artist folder to the survivor's name, which is the naming authority. CP1252 mojibake and curly punctuation fold to straight ASCII; a trailing guest credit is preserved (... feat. Tim O'Brien). A file already correct is left untouched. - Artist level from
--layout. A new--layoutoption (default{artist}/{album}) tells the pass which path depth names an artist, so a genre or album folder is never restamped as one. On a genre-first library, pass--layout '{genre}/{artist}/{album}'. - MP3-only, same guarantees as the other companions. Non-MP3 audio is reported and left alone (its tags are already authoritative); writes are ID3v2.3 + refreshed ID3v1, matching
retag.py. Off by default,--dry-runpreviews every change, and the run is idempotent. Runapestrip.pyfirst if a stray APEv2 tag is in play (APEv2 overrides ID3 on the players that read it). - Tests extended (
tests/test_cleaner.py): the fold/feat helpers directly, plus merge restamping, dry-run fidelity, the clean-file no-op count, and the artist-depth gate.
Behavior change (no package change): the default is now a pure strip. apestrip deletes the APEv2 block and leaves ID3 byte for byte; it no longer absorbs APE fields into ID3 unless you ask.
- Why. Migrating APE values into ID3 by default was backwards. The whole reason to run apestrip is to drop stray APE values (the genre above all), so copying them into ID3 is exactly how a bad APE genre ends up baked into the real tags. The old default forced manual genre cleanup afterward.
--keep-metadatarestores the old behavior. With the flag, every APE field whose value is not already in ID3 is migrated into the correct frame before the strip, exactly as before (genre still never migrated, ratings still report-only). Without it, nothing is migrated.- Always reported. APE
GenreandRatingare scanned and reported in both modes, so the worklist still shows what is being dropped (and still warns when stripping an APE genre would leave a file with no genre at all). - Repair too.
--repair-malformedfollows the same rule: the malformed block is always excised, but sole-source fields are migrated into ID3 only when--keep-metadatais also given. - Tests extended for both modes (
tests/test_apestrip.py).
New companion script (no package change): a lossless stripper for stray APEv2 tags on MP3s.
- The problem. Some MP3s (commonly torrent rips) carry a hidden APEv2 tag alongside their ID3 tags. Players that read APEv2 on MP3 (foobar2000, DeaDBeeF) merge the APE values over the ID3 ones, so a stray APE genre such as
Trash Metalkeeps showing up asTrash Metal, Metalno matter how often the ID3 genre is corrected, and ordinary tag editors never touch the APEv2 block.retag.pyalready deletes APEv2 as a side effect of rewriting the genre, but only the genre;apestrip.pyis the general fix. - Lossless by design. Before deleting the APEv2 tag, every APE field whose value is not already in ID3 is migrated into the correct frame: core text to its native frame (
Year→TDRC,Title/Artist/Album→TIT2/TPE1/TALB,Album Artist→TPE2, etc.),Comment→COMM,Cover Art (Front)→APIC,Unsynced lyrics→USLT, sort orders toTSO*, and anything else (MusicBrainz IDs, ISRC, barcode, ReplayGain, ...) to aTXXX:<key>passthrough. - Two deliberate exceptions. Genre is never migrated (ID3 stays authoritative; the APE genre is the value being removed; a file with no ID3 genre is reported, not invented). Rating is never written, because APE and
POPMuse different scales and an auto-conversion would corrupt star counts (the hazardrerate.pyexists for); APE ratings are reported instead. - Guarded like the other companions.
--dry-runpreviews the full worklist and writes nothing; the real run prints the worklist and asks for confirmation (--yesto bypass, auto-bypassed when stdin is not a TTY); an append-only timestamped log is written (default<directory>/apestrip.log); the operation is idempotent. Recursive over the given directory, so it handles one album or a whole library. MP3-only (the APEv2-over-ID3 conflict is specific to MP3). Migrations are saved as ID3v2.3 + refreshed ID3v1, matchingretag.py. Tested bytests/test_apestrip.py. - Malformed-tag handling (
--repair-malformed). Some rips carry a structurally broken APEv2 tag (footer with theIS_HEADERbit wrongly set, junk bytes before a trailing ID3v1) that mutagen refuses to load. By default these are reported, not silently skipped, so the run is honest about what it could not touch.--repair-malformedopts into fixing them: the tag is parsed straight from the bytes, but only after proving the footer sits exactly where the header's size field points (so the excision boundary is a real tag edge, not a chance signature in the audio); sole-source fields are migrated first, then the APE block is cut out via direct byte surgery, written to a temp file, verified (still decodes, no APE signature left), and atomically swapped in. Audio frames and the trailing ID3v1 are preserved byte for byte; any failed check leaves the original untouched.
Bugfix release from a full code review; no new features.
- Fix: the no-curses fallback menu dispatched the wrong modes. The typed-input menu shown when curses is unavailable (or stdin is not a TTY) had a hand-maintained key map that drifted as modes were added: "6" was labelled "Test WAV files" but ran Extract cover art (which writes
cover.jpgfiles if the dry-run prompt is declined), "7"–"9" were each shifted one mode group over, "10"–"13" were rejected as invalid, and the WAV/WMA tests, art-quality audit, bitrate audit, and ReplayGain audit were unreachable by number. The fallback listing and key map are now both generated from the same_MAIN_SECTIONS/_LIB_SECTIONSdata the arrow-key menu renders, so they cannot drift again, and new word aliases (wav,wma,quality,bitrate,rg/replaygain) cover the previously unreachable modes. The curses menu itself was never affected. Pinned by the newtests/test_tui.py. - Fix: smart-playlist AND/OR no longer rewrites string literals. The SQL-style convenience was a plain substring replace, so
genre == 'Drum AND Bass'was silently rewritten to compare against'Drum and Bass'and could never match. The fold is now word-bounded and applied only outside quoted segments; as a side effect,(rating >= 4)AND(...)without padding spaces now also works. - Fix: art-quality audit no longer truncates folder covers. Folder art was read 8 KB at a time "for the header", but a large EXIF/ICC block can push the JPEG size marker past any fixed prefix; such covers parsed as unreadable and were silently skipped instead of flagged. The whole file is read now (embedded art always was).
- Fix: FLAC report header now includes the Metadata tier count, matching the other integrity reports, so the per-tier counts always sum to Scanned (previously METADATA-tier files, mostly from the ffmpeg fallback path, were invisible in the report).
- Hardening/cleanup:
_parse_track_numbertolerates a malformed MP4trknatom containingNone(previously an uncaughtTypeErroraborted the rest of that file's tag parse); the rule evaluator's comparison walk useszip(strict=True); an unreachable duplicatedreturninrun_replaygain_auditwas removed;.gitignorenow covers the default report outputs so runs from the repo root stay out ofgit status. - Known limitation (deferred): the curses prompt accepts ASCII-only typed input, so a non-ASCII path or output name cannot be typed into the TUI (the CLI and the prompt defaults are unaffected).
Companion-script fix and hardening (no package change):
- Wrong-root guard.
classifycollapsed any directory to its last two path components regardless of depth, and its docstring's promise to "flag" deeper directories was never implemented. Pointing the tool at the parent of an already-organizedGenre/Artist/Albumlibrary (e.g./mnt/SharedDatainstead of/mnt/SharedData/Music) therefore read every album one level too high, discarded the genre level, and planned to move and prune the entire tree. A directory deeper thanGenre/Artist/Albumis now flaggedTOO DEEPand skipped. On a real ~1810-album library the parent-root dry-run went from 1820 planned moves plus 930 prunes to zero moves and a wall ofTOO DEEPflags. - Placement gated by the library's existing genres. The tool now learns the genre vocabulary from the folders that already hold a
Genre/Artist/Albumtree and only files a stray into one of those. A stray whose dominant tag genre isn't already in use is flaggedUNKNOWN GENREand skipped instead of spawning a new top-level folder from a typo or junk tag;--allow-new-genrelifts the gate. A flat library with no genre folders yet has an empty vocabulary, so the gate is off and the originalArtist/Album→Genre/Artist/Albumconversion is unchanged. The same gate is what makes a wrong-root run inert: nothing matches the (absent) vocabulary. - Organized albums are never silently re-filed. An album already at
Genre/Artist/Albumwhose folder genre disagrees with its tags is reported as aNOTEand left in place, rather than being moved across genre folders without warning. - Tested by
tests/test_genre_foldermap.py(depth classification, gating known/unknown/greenfield/--allow-new-genre, in-place skip and mismatch NOTE, the too-deep flag).
Companion-script hardening (no package change):
- Cross-platform robustness. The rsgain subprocess output is now decoded with
errors="replace", so a stray undecodable byte (cp1252 on Windows, or a non-UTF-8 Linux locale) is logged rather than crashing the run. The "rsgain not found" message now points to the right installer per OS (dnf/package manager,brew,winget/scoop/choco) instead of Fedora only. The script was already portable Python (paths viaos.path, no shell, UTF-8 logging); these close the two remaining rough edges. Documented under the script's new "Cross-platform" note in the README.
- Feature: ReplayGain audit (
--auditReplayGain). A new read-only mode reports per-album ReplayGain coverage, sorting every album into one of four buckets: MISSING (no track tagged), PARTIAL (some tracks tagged, some bare), NO ALBUM GAIN (every track has track gain but album gain is absent, so album-mode playback has nothing to apply), and OK (fully tagged, summarized and listed only with--verbose). It is format-aware: Opus stores gain asR128_TRACK_GAIN/R128_ALBUM_GAINrather than thereplaygain_*_gaintext tags MP3 and FLAC use, and both are recognized, so an R128-tagged Opus album is not mis-flagged as untagged. Added to the CLI, the TUI (Metadata section),spec.md, and the test suite (format detection and bucket classification as pure-helper tests, plus an end-to-end mode test over a generated FLAC library). Newread_replaygainreader intags.pyand aDEFAULT_REPLAYGAIN_AUDIT_OUTPUTconstant. - Companion script:
replaygain.pyv1.1.0. The writing counterpart to the audit. It wrapsrsgain(libebur128, ReplayGain 2.0, the -18 LUFS / 89 dB reference foobar2000 uses) to scan and write track + album gain/peak tags album-by-album, the way foobar's "Scan selection as album" does. Album = one folder, rescanned as a whole so album gain is correct;--skip-taggedskips a fully-tagged album as a unit (never half-skips, which would corrupt album gain).--dry-runlists every album and its current coverage without invoking rsgain; a real run prints the worklist and asks for confirmation before writing (--yesto skip). After each album the written tags are read back and logged.--target-lufs N(v1.1.0) targets a louder or quieter result than the 89 dB / -18 LUFS standard (e.g. -14 ≈ 93 dB, the streaming-loudness range): it switches rsgain to custom mode and writes standard replaygain_* tags for every format including Opus (the R128 convention is fixed at -23 LUFS and cannot carry a custom target, so it is not used for that path); valid range -30 to -5, default stays the 89 dB standard. Lives inscripts/(outside the package's read-only contract, like the other companions) and importslatticefor the format-aware ReplayGain reader. Requiresrsgainon PATH (not bundled). Tested bytests/test_replaygain.py(pure helpers; the rsgain call is mocked). - Cleanup:
read_tags_concurrentnow delegates to a small generalmap_concurrenthelper inutils.py(the ReplayGain audit reuses it); behavior is unchanged.run_bitrate_auditnow returns0explicitly to match its-> intannotation and the sibling audits (the exit code was already 0).
Hardening pass from a full code audit.
- Security: smart-playlist rules no longer use
eval.--playlistrules were evaluated witheval(rule, {"__builtins__": {}}, ...), which is not a sandbox: a rule likegenre.__class__.__mro__[-1].__subclasses__()escapes it to arbitrary code. Rules are now evaluated by walking a restricted AST (comparisons, boolean and arithmetic operators, the exposed field names, literals); attribute access, calls, and subscripts are refused. Same rule syntax, no behavior change for valid rules. - Fix:
--statsartist count on a genre-first tree. The artist tally was derived from the top-level directory, so on a Genre/Artist/Album layout it counted genres, not artists.run_statsnow takes the pathlayout(like the other modes) and reads the artist from the correct component. Album counts were already layout-independent. - Performance: read-heavy modes read tags concurrently. New
read_tags_concurrenthelper (a small thread pool, since tag reads are I/O-bound) now backs duplicate detection, the tag and bitrate audits, and statistics, matching the integrity scanners' existing concurrency. Duplicate detection also drops a redundant whole-library tag cache, roughly halving its peak memory. - Fix: bitrate audit default output path now uses
DEFAULT_BITRATE_AUDIT_OUTPUTinstead of string-rewriting the tag-audit constant. retag.py(v1.1.0) now writes genres to.wma(ASFWM/Genre); raw ADTS.aacstays unsupported (no tag container) and is documented as such.genre_foldermap.py(v1.1.0): artist-level sidecar files (e.g. anArtist/cover.jpgbeside album subfolders) now follow the artist to its dominant genre instead of being orphaned in an emptied folder; the dry-run now predicts directory pruning instead of reading the unchanged disk.- Cleanups:
rerate.pyshares one read-only scan between preview and apply; lazier POPM rating fallback intags.py;cleaner.py/rerate.pyexception handlers collapsed to a single base class where one subsumed the other.
- Feature: configurable path-extraction layout. The layout lattice-music uses to recover artist/album/genre from a file's path (when a tag is missing) is now settable. A new
layoutkey in~/.config/lattice/config.jsonbecomes the default for every scanning mode, and--layoutoverrides it per-run. A genre-first library can pin"{genre}/{artist}/{album}"once instead of passing the flag each time. The default remains{artist}/{album}, so existing setups are unaffected. Newconfig.DEFAULT_LAYOUTconstant andconfig.get_layout()helper back this. - Feature: genre falls back to the path. The library scanner already recovered a missing artist/album from the directory layout; it now does the same for a missing genre (
t.genre or parsed.get("genre")). With a{genre}/...layout, an untagged file is still placed in the right wing. - Companion script:
genre_foldermap.pyv1.0.0. A new destructive tool inscripts/that restructures a flatArtist/Albumlibrary intoGenre/Artist/Album, moving each album folder under its dominant genre (read through lattice-music's scanner). Dry-run by default,--applyto perform, an append-only manifest with--revert, and--only-genrefor a staged rollout. Loose single tracks are wrapped in aSingles/folder, and artist-level cover art follows the artist to its genre rather than being orphaned.mv-only on one filesystem, so audio bytes and embedded ratings are never rewritten.
- Fixes: Fixed a flaky
test_plain_when_not_a_ttytest that failed when the suite was run under a pseudoterminal. - Typing: Added a missing
type: ignorefortqdminutils.pyand correctly scoped the ignore forOggOpusintags.pyto ensuremypyruns completely clean.
(Companion-script change; no package version bump.)
- Compilations are excluded from the genre authority. An album whose album-artist is
Various Artists(orVA/Various) has no single canonical genre, so enforcing one would wrongly flatten the disc.buildnow writes such artists as a flagged# ... EXCLUDED (compilation)comment instead of an enforceable row, andapplyhard-skips them even if a stale row exists. The shippedartist_genre_defaults.tsvhad itsVarious Artistsrow converted to the exclusion comment. (lattice-music's tag layer already prefers the album-artist, so this keys off album-artist.)
(Companion-script addition; no package version bump.)
- New
scripts/rerate.py: reconcile DeaDBeeF and foobar2000 MP3 ratings. The two players store MP3 ratings in an ID3 POPM byte on different scales, so a rating set in DeaDBeeF reads one star too high in foobar: 2★ (byte 127) shows as 3★, 4★ (byte 254) shows as 5★.rerate.pyrewrites those bytes to the foobar values that both players read identically (127→64,254→196), so DeaDBeeF ratings sift correctly in foobar without changing DeaDBeeF's own display (byte 196 reads 4★ in both, verified on real files). MP3/POPM-only; foobar's own bytes, MusicBee's186/242, unrated, and non-MP3 files are left alone, and Vorbis/Opus ratings already agree.--dry-run, append-onlyrerate.logrecording every change (so a run is auditable and reversible), idempotent. Covered bytests/test_rerate.py.
(Companion-script change; no package version bump. Refinements learned from a real-library run.)
- Accurate
--dry-run. A dry-run now tracks virtual removals, so itsRMDIR/retain lines and summary counts match the real run instead of misreporting emptied folders as retained. - Survivor names are normalized. The folder with the most files still wins as canonical, but its name is now rewritten to a normalized form afterward (so merging a unicode-hyphen
Drive‐By Truckersno longer leaves the non-standard name as the survivor). Uses a new narrowcanonical_renderfold deliberately kept filesystem-safe for NTFS/exFAT targets shared with Windows: only broken hyphens (U+2010/11/12/15) and curly single-quotes/apostrophes go to ASCII. En/em dashes (correct in ranges like85–92), curly double quotes (straight"is forbidden on Windows), the ellipsis glyph (...would end a name in dots, which NTFS rejects), and prime marks are all preserved. Distinct fromnormalize_name, which stays aggressive for duplicate matching. - Rename safety. A rename whose target would be illegal on Windows/NTFS/exFAT (forbidden
<>:"/\|?*, or a trailing./space) is skipped and logged; anyOSErrorduring a rename is caught and logged so a single bad name can never abort the run mid-way. - Higher-resolution cover wins. On a cover-image collision (
.jpg/.png), the higher-resolution file is kept rather than blindly keeping the canonical folder's copy (ties or unparseable images fall back to larger bytes). Dimensions are read with a stdlib JPEG/PNG parser ported from the package. Other non-audio collisions are unchanged. --normalize-names(opt-in). A third pass renames lone, non-duplicate folders whose names carry non-standard characters (e.g.At the Drive‐In→At the Drive-In) to the same normalized form. Off by default; preview with--dry-run. Covered by expandedtests/test_cleaner.py.
(Companion-script addition; no package version bump.)
- New
scripts/genre_tidy.py: artist→genre authority + reconciler. A two-phase companion for libraries whose genre tags have drifted.buildscans (read-only, through lattice) and writes an editable tab-separatedgenre_map.tsv: oneArtist<TAB>Genre<TAB>Genre2<TAB>...line per artist listing every genre that artist currently uses (most-common first), with#comments giving per-genre counts for multi-genre artists. Every listed genre is allowed, so a fresh map makesapplya no-op; you tidy by removing a stray genre from a line, andapplythen callsretag.pyto collapse that artist's albums tagged with the removed genre to the first (canonical) genre. Reorder to retarget, blank a line to skip an artist.--dry-runand append-only logging like the other companions, idempotent. The lattice package stays read-only; every write goes throughretag.py. Keys on the normalized artist tag, not folder name. A real ~877-artist map ships atartist_genre_defaults.tsvas a worked example and maintained authority (re-runbuildto append new artists; hand-edit to accept new genres). Covered bytests/test_genre_tidy.py(21 cases); the same work backfilledtests/test_retag.pyandtests/test_cleaner.py, so all threescripts/companions now have tests.
--rootis now repeatable.lattice --duplicates --root /mnt/A --root /mnt/Bwalks both libraries in one pass; a path passed twice is de-duped. Every mode (trees, wings, stats, audits, art, playlists) aggregates across the roots.- Cross-library duplicate detection. With more than one root, an album that lives in two libraries is grouped as a single exact duplicate. Each entry is prefixed by its root's basename (
Music/...vsRin's Music/...) so the two copies are distinguishable; single-root reports are unchanged. - Optional config array. A
library_rootsarray in~/.config/lattice/config.jsonsupplies default roots when no--rootis given. The first-run prompt still saves only the singlelibrary_root, so a throwaway--rootis never persisted.
- Colorized status summaries. Integrity summaries print a green all-clear, yellow suspect counts, and red corrupt counts. Color is gated on an interactive terminal: off inside the TUI, off when piped or redirected, off under
NO_COLOR, so report files and pipes stay byte-clean.
retag.py: stale genres fully cleared (the deadbeef trap). A genre can hide in more than the standard ID3TCONframe: an APEv2 tag, the ID3v1 genre byte, and a bare customTXXX:GENREframe. The oldEasyID3path left those overrides in place, so players like deadbeef kept showing the old value. The MP3 path now clears all of them and writes one cleanTCON(v2.3, refreshed ID3v1), while deliberately preserving qualifiedTXXXframes (AcousticBrainzAB:*,ALBUMGENRE, MusicBrainz).cleaner.py: apostrophe-fold fix.normalize_namenow strips apostrophes and collapses whitespace after the existing NFKC/dash/quote/case folding, soDirector's CutandDirectors Cutconsolidate. (Closes the 2026-05-25 found bug.)
- Richer report pager. The in-TUI viewer every report passes through now supports PageUp/PageDown, Home/End, and vim g/G on top of line scrolling, uses the full terminal height, and widens to the longest line (up to the terminal width) instead of a fixed 80 columns so long paths are no longer truncated. Folded in from the CalibreQuarry TUI.
- Python 3.14 modernization. With the floor at 3.14, legacy
typinggenerics were dropped for builtin generics and PEP 604 unions (Dict/List/Tuple[...]todict/list/tuple[...],Optional[X]toX | None) across the package and scripts; the redundantfrom __future__ import annotationswas removed fromcleaner.pyand onesubprocess.runsimplified tocapture_output=True. - Expanded test suite. Added a committed fixture library (
tests/fixtures/) and integration tests (tests/test_modes.py) that run the report modes end to end, plus decode-classifier tests. 78 stdlibunittesttests; run withpython -m unittest discover.
- Companion scripts moved to
scripts/. Invokecleaner.pyandretag.pyas./scripts/cleaner.pyand./scripts/retag.py. They remain outside thelatticepackage (spec §5). - Documentation pass. Recast em-dashes out of the prose, trimmed marketing language, fixed an unclosed README code fence, and condensed the per-mode sections.
Running every mode against a real 8,400-file library exposed the integrity scanners crying wolf: they treated any line ffmpeg wrote to stderr as a failure, producing roughly 187 flags where essentially no file had damaged audio. This release reworks them.
- Forced demuxer.
--testMP3,--testOpus,--testWAV,--testWMA, and the FLAC ffmpeg fallback now force the demuxer from the file extension. ffmpeg's format autodetection had been mis-probing valid MP3s with large ID3v2 tags as RIFF and reporting bogus failures; forcing-f mp3(and so on) eliminates the whole class. On the test library this turned dozens of false positives into zero. - Cover art ignored.
-vndrops non-audio streams, so a malformed embedded image is no longer decoded and counted as an audio fault. - Severity tiers. Each file is classified CORRUPT / SUSPECT / METADATA / OK
instead of pass/fail. CORRUPT means the decoder could not get through the file,
or a FLAC lost sync before its declared sample count (true truncation). SUSPECT
means it decoded to the end but the tool complained (these usually play).
METADATA means only tag-parse warnings; the audio is fine. CORRUPT and SUSPECT
are always listed; METADATA and OK are summarized and listed only with
--verbose. - Exit code change. Integrity modes now exit
1only when a file is CORRUPT, not whenever the decoder printed anything. Scripts relying on the old "exit 1 means any complaint" behavior should read the tier counts in the report instead. - FLAC reporting. A failed verification now shows the preferred tool's
message (libFLAC's "decoded N of M samples" rather than ffmpeg's terse "invalid
sync code"), and the mode warns when
flacis absent and the stricter ffmpeg fallback is used. The FLAC report is now always written, not only on failure.
- Added
tests/test_integrity.pycovering the decode classifier across all four tiers using real ffmpeg and libFLAC stderr signatures.
- Latent
Tupleimport in the art-quality audit:modes/artwork.pyannotated_get_image_sizewithTuplewithout importing it. The code ran only because Python 3.14 defers annotation evaluation;typing.get_type_hints, a type checker, or any pre-3.14 interpreter would have raisedNameError. The import is now present.
- Test suite added. A stdlib
unittestsuite undertests/(no third-party dependencies) covers the pure helpers: rating and key normalization, duration clustering, JPEG/PNG header parsing, filename cleanup, and track-number parsing. Run it from the repo root withpython -m unittest discover. - Library and stats refactor. The three duplicated walk-and-aggregate loops and two identical tree-writers in
modes/library.pywere unified behind_scan_album_dirs,_song_display_name, and_write_tree; the file shrank by roughly a third with byte-identical output. The repeated rating-bucketing block inmodes/stats.pywas replaced with a single label helper. Output across every mode was verified unchanged against a captured baseline. - Formatting and lint. The package was run through
ruff format, unused imports were removed, and the misplaced mid-file imports intui.pywere moved to the top.
spec.mdnow lists all shipped modes;--testWAV,--testWMA,--auditArtQuality,--auditBitrate, and--playlistwere missing from its table. A stalepython lattice-music.pyexample in the README was corrected, and the test suite is now documented.
- Expanded
--duplicates: The duplicate detection mode was rewritten to emit a four-section report instead of a single album-level list. Section 1 (exact album duplicates) continues to flag the same artist/album pair across multiple directories, but now aggregates the most-common artist and album across every track in the folder rather than sampling the first audio file; per-location lines include the format breakdown, average bitrate, and total size to support keep/discard decisions. Section 2 (within-directory multi-format) reports folders that hold the same track in two or more formats (e.g.,01 - Track.flacnext to01 - Track.mp3), listed track-by-track so partial overlaps stay visible. Section 3 (similar-name candidates) flags within-artist album pairs whose names match at adifflibratio of 0.85 or higher after stripping trailing parentheticals ((Deluxe Edition),(Remastered)) andfeat.clauses; this catches cases likeDomesticavsDomestica (Deluxe Edition)that exact matching misses. Section 4 (track-level duplicates) reports the same artist + title appearing in two or more directories, partitioned into duration-clusters within a 2-second window so a studio cluster and a live cluster for the same song surface as separate rows instead of being lumped together (or one of them silently dropped). - Quote / dash normalization in matching: Album and artist keys now apply NFKC normalization plus the same curly-quote and dash-variant fold table that
cleaner.pyuses ('→',‐/–/—→-, etc.).JAY‐ZandJay-Zcollapse to the same key, so the two are reported together instead of slipping past as separate albums.
- Minimum Python is now 3.14. lattice-music was previously declared
>=3.9. The bump is for runtime quality, not language sugar: end users get faster CLI cold starts (cumulative ~25% startup improvement since 3.11, with continued specializing-interpreter gains through 3.14), fine-grained tracebacks (PEP 657) so tag-read or subprocess failures point at the exact column rather than just the line, and faster general bytecode performance from the 3.11+ specializing interpreter. No 3.14-specific language features (template strings, free-threading, tail-call interpreter, etc.) were adopted because they either require a non-default build or have no use case in lattice-music's read-walk-report workload.
run_duplicatesfirst-file bias: Reading album/artist tags from only the first audio file in a directory would mis-key entire folders when track 1 had bad tags, was a hidden track, or the album was a compilation with per-track artists. The new aggregation reads tags from every file and takes the mode across the directory.- Empty-album false positives: The exact-duplicate section accepted directories with an empty album key (e.g., singles or weirdly tagged folders), grouping every album-less folder for an artist together as "duplicates." Both
norm_artistandnorm_albumare now required to be non-empty for inclusion in the exact group. - Multi-format display title lowercasing: When tracks lacked title tags, the within-folder multi-format section fell back to the normalized lookup key for display, which had been lowercased. Filename stems are now carried alongside the key and used as the display fallback, so case is preserved.
- Track-level cluster dropping: Track-level dupe detection previously returned only the single largest duration cluster per
(artist, title)key, silently discarding a second valid cluster when the same title legitimately existed as both a studio version (in two albums) and a live version (in two more). Replaced with a partitioning helper that returns every cluster with 2+ entries spanning 2+ directories. - Removed dead code:
_DirInfo.track_countwas computed but never read; removed._fmt_sizehad an unreachable finalreturnafter a loop that always returned in its last iteration; loop refactored to only iterate over B/KB/MB with GB as the natural fallthrough.argparse.BooleanOptionalActionfallback incli.pypredates 3.9 and was dead even at the prior 3.9 floor; removed.
Companion Script: cleaner.py. Added a standalone consolidator for fragmented album folders to the repository. It detects sibling directories whose names differ only in quote rendering (' vs '), dash/hyphen variant, case, or whitespace (the typical artifact of inconsistent metadata across import sources), and merges them via filesystem mv only. Audio collisions where sizes differ keep both copies (source renamed with a .from-fragment suffix), never overwriting user audio. Includes a --dry-run preview mode and per-file logging to <directory>/cleanup.log. Intentionally narrow scope: it does not rewrite tags or re-encode audio. Lives outside the lattice package alongside retag.py, preserving the package's read-only contract.
- TUI Artwork Submenu: Restored missing "Audit art quality" option to the interactive TUI menu.
- TUI Integrity Submenu: Added missing "Test WAV files" and "Test WMA files" options to the interactive TUI menu.
- TUI Metadata Submenu: Added missing "Audit bitrates" option to the interactive TUI menu.
- WAV/WMA Integrity Modes: Fixed a crash caused by missing
DEFAULT_WAV_OUTPUTandDEFAULT_WMA_OUTPUTimports during--testWAVand--testWMAruns. - Genre Split Formatting: Refined genre splitting logic in
write_all_wingsto correctly extract multiple genres without splitting literal paths or bracketed tags when saving library files.
- Dual-Genre Wing Splitting: The
--ai-wingsand--all-wingsmodes now intelligently split dual-tagged items (e.g.,Coke Rap/Midwest Rap). Instead of creating a single, combined.txtfile for the multi-genre string, lattice-music now separates the genres and correctly filters the album into both respective genre text files, ensuring accurate categorization across the library.
- Retag Tool Overhaul: Fixed an issue where
retag.pywas duplicating genre tags instead of replacing them. The tool now safely clears APEv2 tags from MP3s, correctly pops all existing standard/custom genre keys across formats, and explicitly forces ID3v1 synchronization to prevent ghost tags in older media players. - Null Byte Sanitization: Fixed an issue in all library generation modes (
--library,--ai-library,--ai-wings,--all-wings) where non-legible null bytes (\x00) from ID3v2.4 multi-value frames were being printed into the text output. Multiple values (e.g., dual genres) are now properly joined with a slash (/). - Wing File Names: Improved file name generation for
--ai-wingsand--all-wingsto preserve word boundaries when encountering slashes or special characters (e.g.,Coke_Rap_Midwest_Rap_AI.txtinstead ofCoke_RapMidwest_Rap_AI.txt).
- Album Overcounting Fix: Resolved an issue where tracks in "Various Artists" or soundtrack directories were being counted as separate albums. All library generation modes (
--library,--ai-library,--all-wings,--ai-wings) now correctly group tracks by their containing directory. - Improved Metadata Consolidation: For each directory, the toolkit now automatically determines the most frequent artist, album title, and genre to use for headers, ensuring accurate representation even when track-level tags vary.
- AI Wings: Added
--ai-wingsto generate separate, token-efficient library files for each genre. These files hide individual songs and only include Artist, Album, Genre, and Directory Location, making them ideal for large-scale LLM processing or quick library overviews. - TUI Submenu Expansion: The Library Tree & Exports submenu now includes both "Generate AI wings" and the previously omitted "Generate smart playlist" options.
- TUI Persistence Fix: Fixed an issue where the TUI would exit or "blink" back to the menu when running background tasks (like Stats). This was caused by the progress bar calling
curses.endwin(), which terminated the curses session prematurely. - Improved Progress Bar: The TUI progress bar now correctly updates within the existing curses session without corrupting the terminal state.
- Stats Page Fix: Fixed a
NameErrorin the statistics module wheregenre_ratingswas not properly initialized. - Missing Report: Properly implemented the "Rating Distribution per Genre" report section in
--statswhich was previously omitted. - Version Synchronization: Corrected version mismatches across the repository.
lattice-music now supports dynamic directory structures via the --layout flag, completely decoupling library generation from the strict ARTIST/ALBUM assumption. You can now generate .m3u playlists using rule-based filters.
- Configurable Layout: A new
--layoutargument specifies your directory structure (e.g.{genre}/{artist}/{album}).write_music_library_tree,write_ai_library, andwrite_all_wingsnow intelligently parse paths according to this structure if tags are missing. They no longer fail or produce garbage output on flat folders. - Smart Playlists: Generate
.m3uplaylists based on dynamic evaluation rules using--playlistand--rule(e.g."rating >= 4 and genre == 'Jazz'"). - WAV & WMA Support: Extended the unified FFmpeg decode scanner to verify WAV (
--testWAV) and WMA (--testWMA) files. - Art Quality Audit: Added
--auditArtQuality(with configurable--min-art-res) to parse and report extracted or embedded covers falling below a minimum resolution threshold (default: 500x500). - Bitrate Floor Audit: Added
--auditBitrate(with configurable--min-bitrate) to report audio files falling below a designated kbps floor (default: 192). - Rating Distribution per Genre: The library statistics page (
--stats) now cross-tabulates rating distributions (e.g., 5-star vs 1-star spread) independently per genre.
- TUI Close Button Fix: Fixed an indexing error in the interactive menu where selecting "Quit" would accidentally trigger the "Change library root" prompt due to a missing settings group in the main
_MAIN_SECTIONSlist.
- Fixed an issue in the TUI main menu where selecting "Quit" (or pressing 'q') would unintentionally trigger the "Change library root" prompt due to a mismatched menu array index.
- Fully Immersive TUI: Addressed an issue where background operations (such as cover art extraction or tree generation) would write their output directly to the terminal stdout and pause, which dropped the user out of the full-screen curses environment.
- The TUI now features a global output capture wrapper (
_run_with_capture) using anio.StringIObuffer. - Standard output and error output are automatically intercepted while a background task executes, allowing progress bars to draw undisturbed.
- Upon task completion, any logged output (e.g., dry-run details, success messages, errors) is formatted and displayed within the
_tui_pageviewer, ensuring the user never leaves the curses application.
- The TUI now features a global output capture wrapper (
- Fixed a rendering bug where
_TUIPbardid not erase the screen on its first draw, causing overlapping text from previous prompts in the curses interface. - Fixed a crash (
ValueError: embedded null character) when scrolling through the library statistics TUI page by sanitizing null bytes from the output report.
- First-Run Configuration: Added a persistent configuration file stored at
~/.config/lattice/config.json.- The CLI and TUI now save the root music library location upon first run, eliminating the need to repeatedly specify
--rootor manually enter the path in the interactive menu. - A new "Change library root" option has been added under the
SETTINGSsection in the TUI main menu. - If no
--rootis provided, the CLI gracefully falls back to the configured location (or prompts if unconfigured).
- The CLI and TUI now save the root music library location upon first run, eliminating the need to repeatedly specify
- TUI Immersion Enhancements:
- Progress bars now render inside a stylized curses box when running from the TUI, preventing screen tearing and keeping the interface consistent.
- The library statistics page now displays its full report in an integrated, scrollable curses pager (
_tui_page), rather than dropping you back into standard terminal output.
- PyInstaller Multiprocessing Fix: Fixed an issue where the standalone binary would crash (
unrecognized arguments: -B -S -I -c) on Python 3.14 due to themultiprocessing.resource_trackertrying to spawn a new process using the executable as the Python interpreter. The executable now properly intercepts-ccommand strings from the tracker. - Positional Root Argument: The CLI now supports providing the root directory as an optional positional argument. You can run commands like
lattice --library .instead of explicitly using--root ..
lattice-music has been completely refactored from a single ~2500-line monolithic script (lattice-music.py) into a proper, modern Python package architecture.
Layer-Based Package Design. The codebase is now housed in src/lattice/ and split by logical functionality (cli.py, tui.py, tags.py, utils.py, config.py, and a modes/ directory for individual feature operations). This dramatically improves maintainability while preserving the exact same functionality and CLI interface.
Modern Build System (Hatch). lattice-music now uses pyproject.toml managed by Hatch, replacing the need for manual pip install mutagen tqdm commands. You can now cleanly install lattice-music via pipx install . and have the lattice command available globally in your terminal.
Standalone Native Executable. We have integrated PyInstaller support to compile lattice-music into a self-contained standalone binary. This means end-users no longer need to install Python or external packages (like mutagen) on their machines. The compiled binary (lattice) can be dropped into any directory in your PATH.
Absolute Paths for Genre Wings. The --all-wings mode now accepts a --paths flag. When enabled, the absolute directory path is appended to the album header in the generated text files (e.g., ALBUM: Jane Doe [/path/to/Music/Converge/Jane Doe]).
- This bridges the gap between visualization and execution. It eliminates the need to write brittle shell scripts that guess file locations by scraping artist and album strings. You can now pipe the generated wing files directly into command-line tagging utilities.
- The interactive TUI's Library submenu has been updated to prompt for path inclusion (
Include paths? (y/N)) when generating genre wings. Companion Script:retag.py. Added a standalone universal genre tagger to the repository. It abstracts away container-specific tagging differences (ID3, Vorbis, Apple atoms) and is designed to cleanly consume the absolute paths generated by the--all-wings --pathsflag. This allows for safe, bulk-overwriting of genres at the album-directory level.
Album Artist Prioritization. Fixed an issue where albums were being split up due to featured artists on individual tracks. The tag extractor now consistently prioritizes "Album Artist" over "Artist" across all supported formats:
- MP3:
TPE2>TPE1 - FLAC/Ogg/Opus:
albumartist>artist - MP4/M4A:
aART>\xa9ART - ASF:
wm/albumartist>author
The entire interactive experience now stays in curses. Previously, selecting a
menu item dropped to raw input() calls for parameter prompts (root directory,
output file, worker count, etc.) and the post-operation pause, breaking the
visual flow. All prompts and the pause screen now render inside the same styled
Unicode boxes as the menus.
Curses prompts. _tui_prompt_str draws a centered box with a yellow header
label and a cursor-visible input field. Typing, backspace, Enter to confirm,
Esc to accept the default, all within the curses session. Since _prompt_path
and _prompt_int call _prompt_str internally, every parameter prompt in the
interactive menu gets the TUI treatment automatically.
Curses pause. _tui_pause replaces the raw input("Press Enter…") with a
styled box. Accepts Enter, q, or Esc to dismiss.
Fallback preserved. If curses is unavailable or stdin is not a TTY,
prompts and pause fall back to plain input(), same as before.
All CLI flags (--library, --ai-library, --all-wings, etc.) are unchanged.
The interactive menu is now a full-screen curses TUI with arrow-key navigation,
color-coded sections, and a highlighted selection cursor (►). No more typing
numbers; just ↑/↓ to move, Enter to select, q or Esc to quit.
The menu is drawn as a centered Unicode box with labeled section groups: Library (yellow), Integrity, Artwork, and Metadata, separated by ruled dividers. The selected item is highlighted in bold cyan reverse video. A hint bar at the bottom shows available controls.
Library submenu. AI-readable library export and genre wings (all-wings)
are now nested under a "Library tree & exports" submenu (marked with →)
alongside the standard library tree builder. Selecting it opens a second
curses menu; Esc returns to the main menu. This trims the top-level menu
from 11 flat items to 10 navigable entries and groups the three library-output
modes where they logically belong.
Curses colors:
- Cyan box frame
- Bold yellow section headers
- Bold cyan-on-black highlight for selected item
- Dim hint bar
Fallback path. If curses is unavailable (e.g. windows-curses not
installed) or stdin is not a TTY, the menu falls back to a static boxed
text display with numbered options and typed input, the same layout, just without
arrow-key navigation.
Post-operation pause. Every mode now waits for Enter before redrawing the menu, so results aren't immediately scrolled off screen.
Indented prompts. All interactive prompts are visually aligned with the menu box for a tighter feel.
All CLI flags (--library, --ai-library, --all-wings, etc.) are unchanged.
--all-wings scans genre tags across the entire library, groups albums by
genre, and writes a separate library tree file for each genre into an output
directory, analogous to virtual library wings in Calibre's getBooks.
lattice --all-wings --root ~/Music --output wings/Produces files like Alternative_Rock_Library.txt, East_Coast_Rap_Library.txt,
etc. Albums with no genre tag land in Uncategorized_Library.txt. Each file
uses the same tree format as --library. Pass --genres to include the genre
label in album headers. Available from both CLI and interactive menu (option 11).
The --ai-library export no longer overrides the directory-based artist name
with tag data. Previously, the artist field fell back through TPE1 → TPE2
(ALBUMARTIST) from tags, which added noise without value; the AI export
doesn't distinguish album artist from track artist, and the directory name is
the canonical artist in a well-organized library. This keeps the output cleaner
and more predictable.
--ai-library generates a flat, token-efficient summary of the music
library for use in LLM recommendation prompts. One line per album in
pipe-delimited format:
Artist | Album | Genre | Rating | Tracks
--------------------------------------------------
Converge | Jane Doe | Metalcore | 4.8 | 12
- Rating is the average of all rated tracks in the album, rounded to one decimal. Blank if no tracks are rated.
- Tracks is the number of audio files surviving in the album directory:
the post-cull headcount. An AI reading
5.0 | 1vs4.6 | 12gets the density signal without extra framing. - Genre is sampled from the first track with a genre tag.
- Output defaults to
library_ai.txt. Available from both CLI and interactive menu (option 10).
get_all_tags reduced to a single MutagenFile open per file. The v2.1.0
unified reader still opened each file twice, once via the EasyID3 abstraction
pass, once via the full format-specific path (because rating, duration, and
bitrate aren't available through the easy interface). The easy pass is now
eliminated entirely; all tag extraction runs against the single full object.
The MP3 branch also had a separate ID3(file_path) call on top of the
MutagenFile open; that call is now removed, and tags are read from audio.tags directly.
On a 6,300-track library, this eliminates ~12,600 redundant file opens per full-library mode.
TagBundle extended with duration_s and bitrate_kbps. These fields are
extracted from audio.info during the same single open. run_stats previously
opened every file a second time just to read duration and bitrate; that
redundant open is gone.
First-song double-read eliminated in --library --genres. Genre was read
from the first song before the per-track loop, then the loop re-read the same
file. The album header is now deferred until the first track's tags are available
inside the loop.
count_audio_files was called twice in --ai-library. Once for the console
message, once for the progress bar. Now called once, result reused.
_has_embedded_art duplicated _extract_best_art's directory scan logic.
Collapsed to a one-liner: return _extract_best_art(directory) is not None.
Low-quality bitrate count in --stats used a list comprehension just to
call len(). Replaced with a generator sum.
--root ~/Music didn't work from the CLI. main() was missing
os.path.expanduser(); tilde expansion only worked in the interactive menu.
--library --output subdir/file.txt crashed. write_music_library_tree
opened the output file directly without creating parent directories, unlike
every other mode. Added os.makedirs.
_find_files_by_ext_path matched false extensions. Used
filename.endswith('.flac') which would match a hypothetical file named
notflac. Replaced with os.path.splitext for exact extension matching.
Rating bucketing in --stats used Python's round() (banker's rounding).
A 4.5 rating rounded to 4, but so did 3.5. Replaced with int() (truncate)
for consistent behavior matching the star display logic in format_rating.
Unified MP3/Opus decode scanner. _scan_one_mp3, _scan_one_opus,
run_mp3_mode, run_opus_mode, and _format_mp3_meta collapsed into three
shared functions: _scan_one_file, _run_decode_scan, and _format_row_meta.
Format-specific behavior is parameterized via ext, enrich, and
ffmpeg_required flags. Adding a new format is now a three-line wrapper.
_FallbackProgress class replaces all if pbar: conditionals. _make_pbar
now always returns an object with .update() and .close(), whether tqdm is
installed or not. Eliminated 6 conditional blocks and 4 dead counter variables
(current_file, checked, scanned_count, current) that existed only to
feed the manual fallback.
is_audio() helper. Replaced 6 inline
os.path.splitext(f)[1].lower() in AUDIO_EXTENSIONS patterns. Two callsites
where ext was already extracted for other purposes were left as-is.
_looks_numeric() helper. Replaced 4 inline
str(val).replace('.', '').isdigit() patterns in rating extraction code.
_prompt_path() helper. Consolidated 8 identical
os.path.abspath(os.path.expanduser(_prompt_str(...))) patterns in the
interactive menu.
test_flac simplified. Two mirrored if/elif branches (one per tool
preference) collapsed into a priority-ordered tool list with a single loop.
Four standalone tag functions removed (~190 lines). get_title_artist_track,
get_album, get_genre, get_rating, all superseded by get_all_tags in
v2.1.0 but left in the codebase. No internal callers remained.
_get_cover_file_path: defined but never called by any mode.
_scan_one_mp3, _scan_one_opus, _format_mp3_meta: replaced by the
unified scanner.
ID3 and ID3NoHeaderError imports: no longer needed after the MP3
branch was rewritten to use audio.tags from MutagenFile.
Stale (NEW) markers removed from section headers.
Opus mode wrote to mp3_scan_results.csv. Copy-paste bug in _write_header
hardcoded DEFAULT_MP3_OUTPUT as the fallback filename for all modes. Opus scans
silently wrote results to the wrong file.
_extract_art_from_mp3 called MUTAGEN_MP3 without checking
HAVE_MUTAGEN_MP3. If mutagen installed but mutagen.mp3 failed to import,
art extraction threw NameError.
verbose flag mutated only_errors and quiet inside the MP3 scan loop.
Dead writes on every iteration after the first. Moved above the loop. Opus mode
now has the same verbose behavior for consistency.
Terminal corruption after subprocess modes. Running FLAC/MP3/Opus integrity
checks from the interactive menu left the terminal with icrnl disabled; Enter
sent ^M instead of newline, and input froze. Caused by run_proc using raw
bytes mode while flac -t wrote binary diagnostic data to stderr, colliding
with tqdm's cursor manipulation. Fixed with _reset_terminal() (stty sane)
called at the top of every menu loop, and in a finally block on CLI exit.
Unified tag reader: get_all_tags() → TagBundle. The old code opened each
file up to 4× via independent MutagenFile() calls (get_title_artist_track,
get_album, get_genre, get_rating). Consolidated into a single function
returning a TagBundle named tuple. ~19,000 fewer file opens per --library
run on a 6,300-track library. Callers updated: write_music_library_tree,
run_tag_audit, run_duplicates. Original standalone functions preserved for
any external imports but no longer called internally.
Duplicate file-finder eliminated. find_files_by_ext (string generator) and
_find_files_by_ext_path (Path list) did the same job. Removed the former,
pointed FLAC mode at the latter.
Vestigial paths list removed from run_mp3_mode. Leftover from a
multi-root design that never shipped. Replaced with a plain root_path.
Counter import consolidated. Was at module level via defaultdict but then
re-imported locally in run_tag_audit. One import, one location.
Removed unused Iterable from typing imports.
All output modes now write .txt reports instead of .csv. None of these
outputs were destined for spreadsheets; they're checklists and diagnostics
read by one person, and the format now respects that.
- FLAC/MP3/Opus integrity: Header with scan totals, results grouped by severity (ERRORS → WARNINGS → OK). Relative paths, tool/error details, compact metadata where relevant (bitrate, sample rate, duration).
- Missing art: Two sections: no art at all, embedded only. Relative paths with file counts.
- Duplicates: Grouped by artist/album pair with directories nested underneath showing format sets.
- Tag audit: Grouped by directory, each file showing format and missing fields. Header includes field-level breakdown counts.
_write_header / _close_writer / _rotated_path: Entire CSV writer
infrastructure gone. These managed csv.DictWriter lifecycle via a
monkey-patched _file_handle attribute. With text output, file writes are
straightforward open() calls.
import csv: No longer imported.
lattice-music.py is now a single unified toolkit. The standalone
extract_opus_art.py and extract_mp3_art.py scripts are retired; their
functionality lives in the main script as --extractArt, with improvements.
--testOpus: Opus file integrity checking via FFmpeg decode (same pattern as--testMP3).--extractArt: Extract embedded cover art tocover.jpgwith format priority ranking (FLAC > Opus > M4A > MP3) and--dry-runsupport.--missingArt: Report directories with no cover art (distinguishes "no art at all" from "embedded only").--duplicates: Detect same artist+album appearing across multiple directories or formats.--auditTags: Report files missing title, artist, track number, or genre with a summary breakdown.
- Fixed cover.jpg collision: Cover detection is now case-insensitive.
Running art extraction in a folder with both Opus and MP3 files no longer
produces both
cover.jpgandCover.jpg.
- Art extraction prefers front cover (type 3) over generic embedded images.
- Art extraction supports four formats: FLAC, Opus/OGG, M4A, MP3.
- Interactive menu updated with all eight modes.
- All existing CLI invocations remain backward-compatible.
extract_opus_art.py(folded into--extractArt).extract_mp3_art.py(folded into--extractArt). les no longer produces bothcover.jpgandCover.jpg.
- Art extraction prefers front cover (type 3) over generic embedded images.
- Art extraction supports four formats: FLAC, Opus/OGG, M4A, MP3.
- Interactive menu updated with all eight modes.
- All existing CLI invocations remain backward-compatible.
extract_opus_art.py(folded into--extractArt).extract_mp3_art.py(folded into--extractArt). rt`).