Importing a folder of Rush albums created documents for one of twenty. That was the only MP3 album: MUSIC_FILE_TYPES took .mp3 alone, so every FLAC was skipped without a word. The progress bar ran through all ~6 GB anyway, because the walk counted and ticked files it was going to skip. Formats: MUSIC_FILE_TYPES now takes mp3, flac, ogg/oga, m4a (AAC or ALAC) and wav. Tags already came from lofty, which sniffs every one of these. The decoders needed features: rodio gains ALAC (its defaults cover the rest), and the direct symphonia, which reads the sample-rate/duration line, gains isomp4/aac/alac. import_mp3_file is import_track_file, and FileType is the file's own extension rather than a hardcoded "mp3". FileTypeFilter's MIME types are now (mime, extension) pairs. extension_for_mime used to hand back a type's *first* extension for any of its MIME types, which would have staged a FLAC picked through Android's file picker as .mp3 (and already staged every PNG as .jpg). url_import's own image MIME table goes, as a duplicate. Skips: import_directory_tree takes a 'wanted' filter. Files it rejects are passed over unread, left out of the pre-counted totals and the ticks, and counted in ImportWalkStats::unwanted. The library screens' file and folder imports report them: a finished import that passed anything over says 'Imported 10 files. Skipped 196 files in formats this library doesn't read.' on a dismissable line under the running-imports strip, on all five library screens. Documents' folder import uses is_supported_path as its filter, so its progress no longer counts files it won't import either. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
41 KiB
Music Library: Tag-Derived Artist/Album Organization
Status
In progress. This document is the plan referenced by TODO.md's "Music metadata-driven
library organization" item and supersedes that item's sketch.
Landed (steps 1–4 of "Implementation order" below):
-
Edge store CRUD — idempotent
add_edge, backlink/kind-filtered getters, removal,edge_tombstones, and theON DELETE CASCADEfix for the latent bug where deleting any edge endpoint failed outright. -
Edge sync, the hard prerequisite:
EdgeRecord/EdgeTombstoneRecordinsideDocumentRecord, plus the deferred-apply pass for endpoints that arrive later in a batch. No ALPN bump was needed — the added fields are compatible with a pre-edge-sync peer in both directions, which is pinned by a test. -
CollectionRoleretired in favour ofDocumentType::Notebook+is_container(). -
DocumentType::{MusicArtist, MusicAlbum}+is_derived(),SearchParams::include_derived, and the purge guard. Declared but not yet populated. -
Tag extraction (step 5): the
loftydependency, the nine newPropertyKinds,read_tags/write_tag_properties/tags_are_current, and the scan wired intoimport_mp3_file— so an imported track carries a real title, artist, album and duration immediately, before any library exists. -
Key derivation and upserts (step 6): NFKC/casefold
normalize_key, UUIDv5 document and edge ids viadocuments::derived_id, and the idempotentensure_artist/ensure_album/ensure_library_edgehelpers — with the convergence test that two independent stores deriving from the same tags in different orders produce identical ids. -
incorporate_track(step 7): scan-if-needed, resolve grouping keys, ensure the artist/album documents and both edges, unlink from a stale album, and set the album's cover art. Plusimport_into_library, which joins a freshly imported track to an existing library but never conjures one. -
build_libraryand the sweep (step 8): the full run over every track, mark-and-sweep of artist/album documents nothing points at,JobKind::LibraryBuild, progress and cancellation through aJobHandle, and the property batching. -
gpui wiring (step 9): a "Build library" action in the Music header, run through
JobRunnerso the Jobs screen shows and can cancel it, with a one-line result beside the button. Not visually verified — this machine has no GUI session, so it is compile- checked viajust build-gui-nixonly;just guistill needs a human look. -
CLI verbs (step 10):
syn music build-library,syn music artists,syn music albums, dispatched through the daemon per ADR 0004. Verified end to end against a real store and daemon, not only compiled. -
The browsable views: the gpui desktop's Music screen and Android's both carry a Library tab over
library_entries— an artist level, an album level, and a track level, with the art layering below — alongside the Folders tab over the document tree. Android reaches them throughMusicFfi::{list_library, entry_art, build_library}, and the mosaic itself is composed in this crate (music::compose_artist_art) so both modalities derive the same image from the same covers. The TUI still has no view of the derived graph.
The feature is functionally complete. Not yet done: a TUI view, and the
docs/data-model.md polish noted below.
Problem
Music today is organized purely by the document tree: import_mp3_file
(rust/lib/src/agents/music.rs) creates one MusicTrack document per file, parents it
under whatever Collection mirrors the user's on-disk folder, and sets Title to the file
stem. build_music_nodes then walks that tree for the UI. Nothing reads the file's embedded
tags. Consequences:
- An MP3 dropped at the top level with no folder structure is a single flat track with a filename for a title.
- Two files from the same album filed under different folders are unrelated.
- The "Artist → Album → Song" hierarchy named in
TODO.md's "Design a general media reader UI" cannot be rendered at all, because nothing knows an artist or an album exists.
The tree can't be made to fix this on its own. A document has exactly one parent_id, and
the tree carries ownership semantics (deleting a feed deletes its episodes) — but a track
belongs to an album and an artist and, eventually, several playlists, none of which own
it. That is precisely what docs/data-model.md's Edge is for, and Edge has no consumer
today besides a reseed round-trip test.
Shape of the answer
Three separable layers, on top of one prerequisite.
- Edge sync (prerequisite) — make
Edgea first-class synced entity. Not music-specific. - Tag extraction — read embedded metadata off a track's audio blob and write it as
Propertys on theMusicTrackdocument. Purely per-document; no graph involved. - The library graph —
MusicArtistandMusicAlbumdocuments, a new derived category of document generated by the agent rather than imported, linked byEdges to each other and to tracks. Additive: it never touches a track'sparent_id, so the user's folder tree survives untouched and the library can be discarded and rebuilt at will. - The build job — a user-triggered, cancelable, progress-reporting long-running job
that runs layers 1 and 2 over every
MusicTrack, plus an incremental single-track path so newly imported tracks join an existing library without a full rebuild.
No UI work is in scope. The graph is designed so both views the music screen wants — artist → album → track and album → track — are direct queries; see "Serving the two views".
Prerequisite: Edge sync
p2p/doc_sync.rs carries DocumentRecord, PropertyRecord, ArtifactRefRecord, and
artifact/document tombstones. There is no EdgeRecord. Edges are node-local today;
ensemble/reseed.rs round-trips them only because it copies tables wholesale.
Building the music library on top of that would mean leaning on "every node rebuilds its own
graph locally," which sounds fine given deterministic ids (below) but fails the case that
motivates the whole project: a phone that holds no audio files at all should still show the
full library. It can — track tag Propertys sync eagerly — but only if the edges that
express artist/album membership sync too. Rebuild-locally is a good robustness backstop, not
a substitute.
So edge sync lands first, scoped as its own change and designed against both classes of
consumer that exist on paper: user-authored edges (WikiLink, PlaylistMember) and derived
edges (this document's). Sketch:
EdgeRecord { id, to_id, kind, created_at, origin_node }rides inside theDocumentRecordof itsfrom_iddocument, mirroring howArtifactRefRecordrides in the document it belongs to. Matchesget_edges_from, and every mutation in this design is driven from thefromside.EdgeTombstoneRecord { id, deleted_at, origin_node }alongside it, plus anedge_tombstonestable. Merge rule is the oneArtifactTombstonealready documents: set union byid, with a strictly newer re-add beating an older tombstone. AnEdgehas nomodified_atand is never mutated in place — created or deleted, nothing else — so this is the whole conflict story.add_edge/remove_edgemusttouch_document(from_id). The sync cursor and thesincefilter both key offdocuments.modified_at; without this an incremental sync silently never carries new edges.touch_documentalready exists.- Dangling endpoints are the hard part.
apply_recordsalready topologically sorts records so a parent precedes its child, with a "dangling parents" fallback. An edge'sto_idis unconstrained — it can be in a later chunk, or in a document set the peer will only send on a later sync — so it cannot be ordered around. It needs a deferred-apply pass: buffer edges whoseto_idisn't locally known, apply them after all chunks land, and drop whatever is still dangling (it will be re-announced next sync, since thefromdocument'smodified_athasn't advanced past this peer's cursor). Theto_idFK is what forces this; the alternative — creating skeleton documents for unknown endpoints — invents rows from a bare id with nodoc_type, which the schema doesn't allow. - Resurrection guard.
apply_recordsskips any document whose id is tombstoned. Edges need the same check on both endpoints, or a purge leaves edges that fail the FK.
This is on the order of a few hundred lines against well-established patterns in that file,
and it makes Edge mean what docs/data-model.md already says it means.
Layer 1: Tag extraction
Library choice: lofty
TODO.md floated symphonia (already a dependency) or lofty. Use lofty (0.24).
- symphonia's metadata support is per-format-feature gated (
lib/Cargo.tomlenables onlymp3) and is a by-product of its decoder — reading tags means building a probe and format reader for a file we don't want to decode. - symphonia sits behind the
multimediafeature, which also pullsrodioandsoundtouch(native/bundled C). Library organization must work on a headless node and on Android, neither of which wants the playback stack.import_mp3_fileis deliberately not behindmultimediatoday; tag reading must not be either. loftyis pure Rust, no native dependencies (cross-compiles clean toaarch64-linux-android), and covers ID3v2/ID3v1 (MP3), MP4ilst(M4A/AAC), Vorbis Comments (FLAC/Ogg), APE, and RIFF INFO behind oneAccessortrait — so wideningMUSIC_FILE_TYPESbeyondmp3later costs nothing here.
New unconditional dependency in rust/lib/Cargo.toml (workspace-pinned like the rest).
New PropertyKinds
Tags are Properties, not Artifacts, by docs/data-model.md's stated test: a node missing
a track's artist is in an error state that should be re-requested on next sync, not a normal
"user hasn't engaged yet" state. They are needed to organize the document — the library
graph is literally computed from them.
| Kind | Value | Merge | Notes |
|---|---|---|---|
Title (existing) |
Text |
LWW | Now the tag title, falling back to the file stem |
MusicArtist |
Text |
LWW | The track's performing artist |
MusicAlbumArtist |
Text |
LWW | Written only when present and different from MusicArtist |
MusicAlbum |
Text |
LWW | Album title |
MusicTrackNumber |
U32 |
LWW | Within its disc |
MusicDiscNumber |
U32 |
LWW | Written only when > 1 or when a disc total is present |
MusicYear |
U32 |
LWW | Release year; absent rather than 0 when unknown |
MusicGenre |
Tags |
SetUnion | ID3 permits several TCON frames; matches NoteTags precedent |
MusicDurationSecs |
F64 |
LWW | From tag/stream properties, for list display without decoding |
MusicTagScan |
Text |
LWW | Provenance stamp; see "Incremental rescans" below |
All are LastWriteWins, not Immutable: a user retagging a file, or a better scanner
correcting a bad read, must be able to win. Absence is meaningful everywhere — no sentinel
values, following Order/ComicPageDoublePage's established idiom.
MusicArtist, MusicAlbum, MusicYear and Title are reused on the derived MusicAlbum
and MusicArtist documents (layer 2), which is why they are named for the domain rather than
for MusicTrack.
Why not reuse Order for track number. Tempting (it would share OrderTotal for "12
tracks"), but wrong: Order is documented as position among tree siblings, and a track's
tree siblings are the other files in its import folder, not the other tracks on its album.
The album relationship is an edge, not a parent link. Track numbers are also not unique
across a multi-disc album, which Order's proposed UniqueAmongSiblings invariant would
eventually flag as a violation. Separate kinds; sort key is (disc, track, title).
MusicTagScan records "<scanner_version>:<plaintext_hash_hex>" for the blob the tags
were read from. It is what makes a rebuild cheap: a track whose stamp matches its current
PrimaryContent BlobRef and the current scanner version is skipped without touching the
blob store. Bumping the scanner version constant forces a re-read of every track on the next
build — the migration lever for "we now also extract X".
Cover art
Embedded art becomes an ArtifactKind::Thumbnail (blob-backed, Singleton, LWW) on the
MusicAlbum document, not on each track. Content addressing means twelve tracks with
identical art already converge on one blob, but writing twelve artifact rows pointing at it
is pure noise; the album is the natural owner, and a track view reaches it in one edge hop.
First art-bearing track of an album wins; a later differing image does not overwrite (avoids
churn between "front cover" and "back cover" frames across a folder).
This mirrors PodcastFeed, which carries Thumbnail artwork while being excluded from
DocumentType::has_blob_content — thumbnail bytes sync eagerly regardless of policy, so an
album owning one introduces no policy question.
Tracks whose audio isn't local
Tags live in the audio bytes, so a track that is RemoteOnly (document_availability →
Partial) cannot be scanned. It is counted and reported in the build summary, not treated as
an error, and it is picked up on a later build once bytes arrive.
This is where putting tags in Properties pays off: whichever node holds the bytes scans them once, and the resulting Properties sync eagerly to every other node — which can then build, or receive, the full graph without ever downloading audio.
Layer 2: The library graph
Derived documents as a first-class category
MusicArtist and MusicAlbum are new DocumentType variants, not Collections with a
CollectionRole. Three independent reasons:
Collectionis documented as "a pure organisational container. No domain-specific properties." An album has a release year, an album artist, a cover image, and a track count. This is the exact argument that already madeComicits own type: "UnlikeCollection…Comiccarries real metadata — it is shaped likePodcastFeed, not like aPictureAlbum-styleCollection."- The two views the music screen wants become direct queries rather than "list collections, then filter by a role property" — see "Serving the two views" below.
- Every
matchonDocumentTypebecomes an explicit decision.materialize_content,has_blob_content,display_name,title_property_kindall force a considered answer for the new types instead of silently inheritingCollection's.
CollectionRole::{MusicAlbum, MusicArtist} are then dead and should be removed — which
raises the question of whether CollectionRole should exist at all. It should not; see
"Retiring CollectionRole" below.
They are also the first documents in the system generated by an agent rather than imported or authored, which is a genuinely new category and deserves a name in the model:
impl DocumentType {
/// Whether documents of this type are *derived* — generated by an agent
/// from other documents' data, rather than imported or authored by the
/// user. Derived documents are reproducible: deleting them all and
/// rebuilding yields the same graph (see the deterministic-id scheme in
/// `docs/music-library.md`).
pub fn is_derived(&self) -> bool { ... } // MusicArtist | MusicAlbum
}
Hand-declared, like the neighboring has_blob_content(), and with the same instruction to
keep it in step with docs/data-model.md.
Consequences of being derived, all of which are the reason to name the category at all:
- Hidden from general document lists by default.
SearchParamsgainsinclude_derived: bool(defaultfalse), honored bysearch_documentsandsearch_document_items, with the rule that an explicitdocument_typesfilter naming a derived type overrides it — so "show me every album" is one call and the Documents agent's browse view doesn't fill up with four hundred albums. The Documents agent gets a "show derived documents" toggle for when the user does want to see them. - Never purge a derived document.
apply_records' resurrection guard makes a document tombstone permanent:is_tombstoned(id)→ skip, forever. Combined with the deterministic ids below, purging one album would poison that id ensemble-wide, so the same album could never be re-derived on any node again. A "clear library" action must therefore delete rows without writing tombstones (remove_document, notpurge_recursive), and the purge UI should refuse derived types outright. This is the sharpest edge in the whole design. - Rebuildable, so cheap to get wrong. Any bug in the derivation is fixed by bumping the scanner version and rebuilding, not by a data migration.
Per-type, not per-document, deliberately. Derived-ness is really a fact about how a
document came to be — a Provenance { Imported | Authored | Derived { agent } } field on
Document would be the fully general answer. Every case that exists today is cleanly
type-determined, and the codebase's own stated policy is not to generalize pre-emptively.
The trigger to upgrade is concrete: the first agent that derives documents of a type users
also create by hand (agent-generated Notes, say), at which point the type predicate can
no longer answer the question and a per-document field must.
Retiring CollectionRole
PropertyKind::CollectionRole and the CollectionRole enum should be deleted outright,
not merely trimmed of their music variants. This is a data-model change that outlives the
music work; it is documented here because the music work is what forces the question.
The evidence, from a full grep of every modality:
- Five variants, one real consumer.
Notebookis read byagents/notebook.rs.PictureAlbumis never read anywhere —agents/pictures.rsbuilds its hierarchy by walking ancestorCollections and never needed a role. The three music variants were speculative and this design retires them. - That one consumer,
list_notebooks, islist_root_by_type(Collection)followed by a per-documentget_property— an unindexed N+1 scan reimplementinglist_documents_by_type, which does the same job in one indexed query.
The decisive argument is CollectionRole's own declared merge strategy: Immutable. An
immutable classifier, set at creation, that determines which agent interprets a document and
how it is displayed, is this codebase's definition of DocumentType — "determines valid
properties and merge strategies", "how the document is displayed". CollectionRole is a
hand-rolled parallel type system for containers, and it is the worse of the two: no
exhaustiveness checking, no indexed query, and no forced decision in materialize_content
or the other per-type dispatches.
The replacement:
| Today | Becomes |
|---|---|
CollectionRole::Notebook |
DocumentType::Notebook |
CollectionRole::PictureAlbum |
deleted — never read |
CollectionRole::{MusicAlbum, MusicArtist} |
DocumentType::{MusicAlbum, MusicArtist} |
CollectionRole::MusicCollection |
DocumentType::Playlist, when playlists are built |
Collection itself stays, and afterwards means one honest thing: an untyped user folder
with no agent semantics — import-mirror folders, comic series/volume groupings, plain
subfolders inside a notebook.
Three costs, accepted knowingly:
- Roles attach to an existing document; types are fixed at creation. There is no
set_doc_type, and mutating a synced document's type is dubious (properties valid under the old type may not be under the new). So "turn this existing folder into a notebook" becomes create-and-reparent rather than one property write. This is the one genuine capability lost, and it does not appear to be wanted. - Container checks need a predicate.
pictures.rs,music.rs, andcomics.rseach domatches!(doc.doc_type, DocumentType::Collection)in ancestor walks, andnotebook.rshasrequire_collection_parent. These becomeDocumentType::is_container(), hand-declared alongsidehas_blob_content()andis_derived(). - A wire-fragility asymmetry, in roles' favour — resolved.
DocumentRecord.doc_typeis a bare serde enum; an unknownCollectionRole, by contrast, degrades harmlessly toNonebecause it rides asPropertyValue::Textparsed withfrom_str(...).ok().docs/adr/0020-sync-protocol-schema-version.mdcloses that gap: each document in aDocumentChunknow decodes independently, so a peer on a newer build adding aDocumentType/PropertyKind/ArtifactKind/EdgeKindvariant only costs the older peer the specific documents using it (reported viaSyncProgress::Complete.records_skipped), not the whole sync — and a golden test fails CI if a variant is added without bumpingSYNC_PROTOCOL_VERSION. Not a blocker here.
Node shape
MusicArtist { properties: Title }
MusicAlbum { properties: Title, MusicArtist, MusicYear;
artifacts: Thumbnail (cover art) }
MusicArtist is denormalized onto the album so an album card renders without an edge walk.
Both have parent_id = None. There is no synthesized "Music Library" root Collection.
Its only jobs would have been anchoring ("find all albums") and teardown
(delete_recursive), and distinct document types do both better —
list_documents_by_type(MusicAlbum) and "delete every document of a derived type". A fake
container that exists only to be a parent is worth avoiding, and is_derived() already keeps
these out of the root-level document lists that parent_id = None would otherwise put them
in.
Edges, not parenting, for the hierarchy
Two new EdgeKinds:
ArtistAlbum -- MusicArtist -> MusicAlbum
AlbumTrack -- MusicAlbum -> MusicTrack
Parenting would mean ownership, and an album by a guest-featuring artist or a "Various
Artists" compilation is legitimately reachable from more than one artist; making one of them
its parent would be arbitrary, and deleting that artist would take the compilation with it.
Edges are many-to-many and carry no ownership, which is exactly right here. Tracks are never
re-parented — their parent_id keeps pointing at the import folder Collection, so nothing
about building, rebuilding, or discarding the library can damage the user's own organization,
and build_music_nodes' existing folder view keeps working unchanged.
Serving the two views
Both are two or three direct queries, no tree walking and no role filtering:
- artist → album → track:
list_documents_by_type(MusicArtist)→get_edges_from_of_kind(artist, ArtistAlbum)→get_edges_from_of_kind(album, AlbumTrack). - album → track:
list_documents_by_type(MusicAlbum)→get_edges_from_of_kind(album, AlbumTrack).
A track's "what album am I on" backlink is get_edges_to_of_kind(track, AlbumTrack). All of
these need the store additions in "Required infrastructure changes".
Identity: deterministic UUIDs from normalized keys
Every derived document's DocumentID and every Edge's id is a UUIDv5 derived from a
normalized key, rather than a fresh v4:
artist = DerivedKey::new(Domain::MusicArtist).collapsed(artist_key)
album = DerivedKey::new(Domain::MusicAlbum).collapsed(artist_key).collapsed(album_key)
edge = DerivedKey::new(Domain::MusicEdge).part(kind).part(from_id).part(to_id)
The namespace, the separator between key parts, and the NFKC/casefold that collapsed
applies all live in documents::derived_id, shared with every other derived id in the
codebase — the library does not get to have its own opinion about any of them. See
docs/data-model.md's "Derived ids, and why they must be frozen".
Why, in order of importance:
- Cross-node convergence. Two nodes that each build a library would otherwise produce two distinct "Radiohead" documents with different v4 ids, and syncing them yields visible duplicates that nothing can reconcile. With v5 ids they produce the same document id, and the existing property-merge machinery handles the rest — no new sync concept, no dedup pass. This holds even with edge sync in place: nodes will still derive concurrently.
- Idempotent rebuilds. Re-running a build converges instead of accumulating.
- Edges converge too, so two nodes' independently-derived graphs are byte-identical rather than merely equivalent.
The tradeoff is that two genuinely different artists who normalize to the same key merge into one document. That is inherent to any name-based grouping, and is what every music player does. The other tradeoff is the purge hazard documented above.
Normalization (artist_key / album_key): NFKC, to_lowercase, trim, collapse internal
whitespace runs to one space. Deliberately not done: stripping leading articles ("The
Beatles" stays distinct from "Beatles"), stripping punctuation, or any fuzzy matching —
aggressive normalization silently merges distinct things and is unrecoverable. Sorting may
strip articles for display; identity may not.
The un-normalized, original-cased name is the document's Title (first writer wins on
casing, LWW thereafter so a user can correct it). The normalized key is not stored as a
property — it is implied by the id derivation, and storing it would create a second source of
truth that can disagree with the id.
Grouping rules
- Album key is
(album_artist_or_artist, album). Scoping the album by artist keeps the fourteen distinct albums named Greatest Hits apart. MusicAlbumArtistwins overMusicArtistwhen deciding which artist an album hangs off, which is what the tag is for on compilations and guest-heavy records. OneArtistAlbumedge per album, from the album artist only — a track's own artist does not additionally earn one. (The many-to-many capability is still there in the edge model if guest-artist cross-linking is wanted later; it just isn't turned on by default, since it clutters an artist's page with records they appear on for eight bars.)- Missing tags get sentinel documents rather than special cases: a track with no artist
tag joins
Unknown Artist(artist key""), one with no album tag joins that artist'sUnknown Album(album key""). Uniform structure means the UI never needs a null branch.
Layer 3: The build job
Entry points
Two functions in rust/lib/src/agents/music.rs, both multimedia-independent:
/// Scan one track's tags and (re)link it into the library graph, creating
/// whatever artist/album documents it needs. Additive; safe to call repeatedly.
pub fn incorporate_track(
store: &Store,
local_node: NodePubkey,
track_id: &DocumentID,
) -> Result<TrackOutcome>;
/// Full library build over every MusicTrack: incorporate each, then sweep.
pub fn build_library(
store: &Store,
local_node: NodePubkey,
job: Option<&JobHandle>,
) -> Result<LibraryBuildSummary>;
build_library takes Option<&JobHandle> directly rather than inventing a callback
abstraction — jobs is the same crate, JobHandle already exposes exactly
report_progress / is_canceled, and tests pass None. It reports progress every N tracks
(not every track — each report is a SQLite write plus a broadcast) and checks is_canceled
on the same cadence; cancellation leaves a partially built graph, which is valid and
converges on the next run precisely because every id is deterministic.
Per jobs::runner's documented contract the caller owns the task: each modality wraps
build_library in its own cx.spawn/tokio::spawn and calls JobRunner::start. New
JobKind::LibraryBuild (display name "Library build"); subject
JobSubject::DocumentType(DocumentType::MusicTrack), which dedups a second concurrent build
against the first without colliding with the eviction jobs that use the same subject under a
different kind.
Full build algorithm
-
list_documents_by_type(MusicTrack)→ the work list;units_totalfor progress. -
Batch-load existing properties for the whole list via
list_properties_for_documents(one query, not N). -
For each track: a. If
MusicTagScanmatches(scanner_version, current PrimaryContent plaintext hash), reuse the stored tags — no blob read. b. Else, if the audio blob is local, load it, parse withlofty, write the tag properties and the newMusicTagScanstamp. If not local, count as skipped and move on. c. Compute artist/album keys → ensure those documents exist → ensure theArtistAlbumandAlbumTrackedges exist → record the edge ids this track should have. d. Delete anyAlbumTrackedge pointing at this track that isn't in that set (a retagged track leaving its old album). e. If the album has noThumbnailyet and the audio is local, read the cover art and write it. Gated on the album, not on "did we just scan this track": import already scans, so a scan-only rule means a freshly imported album never gets a cover at all (found by the test, after the first implementation did exactly that). Gating on the album keeps the work bounded by the number of coverless albums, not by track count. -
Sweep: delete
MusicArtist/MusicAlbumdocuments that ended the build with no incident edges. Albums go first, so an artist whose last album just went goes in the same pass. Deletion isremove_document, neverpurge_recursive— see the tombstone hazard above. Without this step a full build is an append, not a reconciliation, and deleting your entire Beatles folder would leave a ghost Beatles artist forever.Edges are removed explicitly rather than left to the foreign-key cascade, because only an explicit removal writes a tombstone and only a tombstone propagates. The documents are deleted without one, per the never-tombstone-a-derived-document rule. The accepted consequence: an edgeless artist or album can come back from a peer that has not rebuilt yet. It is harmless — with no edges it holds no tracks and shows up in no library view — and the next build removes it again, converging once every node has run one.
A canceled run must not sweep. Half the tracks having been visited makes every unvisited album look empty, so sweeping a partial run would delete the rest of the library. There is a test for exactly this.
-
Return
LibraryBuildSummary { tracks_scanned, tracks_reused, tracks_skipped_not_local, tracks_unreadable, artists, albums, swept }.
incorporate_track is step 3 for a single track, with no sweep — a newly imported track joins
the graph immediately, and pruning stale documents waits for the next full build.
import_mp3_file calls it opportunistically when a library already exists (any MusicAlbum
document present), so importing into an already-built library Just Works; otherwise import
stays exactly as it is today and the user's explicit "build library" action is what creates
one.
Sweep versus sync, one wrinkle. A node whose tag properties haven't finished syncing can sweep an artist that another node still legitimately holds tracks for, then re-derive it once the properties arrive — a transient delete/re-add round trip. It self-heals (deterministic ids mean the re-add is the same document, and the tombstone-free deletion doesn't block it), and it is bounded by property-sync latency rather than by audio availability, since derivation reads properties rather than blobs. Worth knowing about; not worth a coordination mechanism.
Performance
Every DocumentStore/ArtifactStore method opens a fresh Connection. A naive build over
5,000 tracks would open six figures of connections. The build must therefore:
- batch property reads with
list_properties_for_documents(exists), - batch the artifact/
BlobReflookups the same way (needs alist_blob_refs_for_documentsaddition toArtifactStore, mirroring the existing document-store batch method), and - write through a single connection/transaction per chunk of tracks — a
DocumentStore::with_transaction-style helper, or at minimum a batchedwrite_properties(&[Property]).
Measured (debug build, 500 tracks / 50 albums / 10 artists, all tags already scanned —
the rebuild case): 2.2s before batching, 1.31s after, i.e. ~2.6ms per track, or roughly
13s for a 5,000-track library. Batching the property reads with
list_properties_for_documents was the whole of that 40% win: it was four connection opens
per track out of about eight.
The remaining per-track cost is the two add_edge calls and the stale-album check, all of
which open their own connection. Batching those would need an edge-level equivalent of the
property batch and is not obviously worth it — this is an explicit, cancelable job with a
progress bar, not an interactive path. The list_blob_refs_for_documents addition and the
per-chunk transaction sketched earlier were not implemented for the same reason; revisit
if a real library makes the wait annoying.
Required infrastructure changes
Each is independently committable.
1. Edge sync
See "Prerequisite" above. Carries with it the edge_tombstones table, the touch_document
call on edge mutation, and the deferred-apply pass for dangling endpoints.
2. Edge CRUD is a stub (stores/document.rs)
Today: add_edge (plain INSERT) and get_edges_from. Needed:
add_edge→INSERT OR IGNORE, plus aUNIQUE (from_id, to_id, kind)index, so idempotent rebuilds and the deterministic edge id agree with each other.get_edges_to(to_id), and kind-filtered variants of both directions (get_edges_from_of_kind/get_edges_to_of_kind) so a hub document doesn't load every edge to answer one question.remove_edge(id)andremove_edges_from(from_id, kind)for the retag and sweep paths.
3. Edges block document deletion (bug, exists today)
FOREIGN KEY (from_id) REFERENCES documents(id),
FOREIGN KEY (to_id) REFERENCES documents(id)
— no ON DELETE CASCADE, and remove_document runs with PRAGMA foreign_keys = ON. So once
a track has an AlbumTrack edge, deleting that track fails with an FK violation. Both FKs
need ON DELETE CASCADE (matching how properties and artifacts already cascade). Given
the project's no-backwards-compatibility status this is a table recreate, not a migration
dance.
4. Derived-document plumbing and the CollectionRole retirement
DocumentType::{MusicArtist, MusicAlbum}variants +is_derived().- Delete
CollectionRoleandPropertyKind::CollectionRole; addDocumentType::Notebookand portnotebook.rs'screate_notebook/list_notebooks/require_collection_parentto it; addDocumentType::is_container()and use it for thematches!(.., Collection)ancestor-walk checks inpictures.rs,music.rs, andcomics.rs. SearchParams::include_derived(defaultfalse), honored bysearch_documentsandsearch_document_items, overridden by an explicit derived type filter.- Arms in
title_property_kind,display_name, andhas_blob_content(bothfalse). - Materialization: not
Directory, as an earlier draft of this said. A derived album's members hang offAlbumTrackedges, not tree children, so the existing child-walking directory path would emit an empty folder. Both types fall through toUnsupportedRootTypeuntil an edge-aware materializer exists — an honest error beats a misleading empty directory. Edge-aware export is worthwhile follow-up (it would give "dump this album to disk as files" for free) but is not on this feature's path. - A "show derived documents" toggle in the Documents agent; purge refuses derived types.
5. Smaller additions
uuidworkspace features: add"v5".EdgeKind::{ArtistAlbum, AlbumTrack}variants.JobKind::LibraryBuildvariant + display name.loftyworkspace dependency.
Testing
Unit-testable without any audio device, which is the point of keeping this off multimedia:
- Edge sync: round-trip through two stores; a tombstoned edge does not resurrect; a
strictly newer re-add beats a tombstone; an edge whose
to_idarrives in a later chunk is applied by the deferred pass; an edge to a never-arriving document is dropped without failing the sync. - Normalization/key derivation: articles preserved, case/whitespace folded, NFKC applied.
- Determinism: building the same fixture set twice yields identical document and edge ids; building it in a different order yields the same graph; two independent stores that build the same track set produce the same ids.
- Compilations: album artist wins; the album is not duplicated; exactly one
ArtistAlbumedge. - Missing tags: sentinel
Unknown Artist/Unknown Album, one each, not one per track. - Retagging: moving a track to a different album removes the stale
AlbumTrackedge, and the sweep removes the now-empty album without writing a tombstone. - Incremental:
incorporate_trackafter a build produces the same graph a full rebuild would (minus sweeps). MusicTagScan: a second build reads zero blobs; bumping the scanner version reads all.- Not-local tracks are counted, not failed.
- Derived documents are absent from a default
search_documentsand present when asked for by type.
Fixtures: a handful of tiny MP3s with hand-written ID3v2 frames, following
agents/comics_fixtures' precedent. Tag parsing itself is lofty's job, not ours to retest.
Formats
Added 2026-11-13. MUSIC_FILE_TYPES takes MP3, FLAC, Ogg Vorbis, M4A (AAC or ALAC) and WAV,
which first shipped as MP3 alone. Widening it was nearly free, as this document predicted: lofty
sniffs every one of them, rodio's default codecs decode all but ALAC, and Android's ExoPlayer plays
them all. What it took was the codec features in rust/lib/Cargo.toml (rodio's for playback, the
direct symphonia's for the sample-rate/duration line, and both have to agree), FileType taken
from the file's extension instead of a hardcoded "mp3", and a MIME type mapping to its own
extension, so that Android's Storage Access Framework doesn't stage a picked FLAC as .mp3. Opus is out
until symphonia has a decoder for it.
Deliberately out of scope
- Any UI. The music screen's two views are specified above; building them is separate work.
- Playlists (
EdgeKind::PlaylistMember, and a futureDocumentType::Playlist) — the other half ofTODO.md's hierarchy, and a user-authored, ordered graph rather than a derived one. Edge sync is designed with it in mind. - Per-document
Provenance(see the upgrade trigger under "Derived documents"). - MusicBrainz or any network lookup. Embedded tags only.
- Per-track "last played", needed for the Recently Played tab
TODO.mdmentions.
Implementation order
All steps have landed; see "Status" above.
- ✅ Edge sync, standalone:
edge_tombstonestable,EdgeRecord/EdgeTombstoneRecord, deferred-apply pass,touch_documenton mutation, round-trip tests. Ships value on its own (WikiLinks start syncing). - ✅ Edge store work: unique index,
INSERT OR IGNORE, directional/kind-filtered getters, removal, FKON DELETE CASCADE(+ a regression test that deleting an edge endpoint works). Partly folded into step 1 as needed. - ✅ Derived-document plumbing: new
DocumentTypes,is_derived(),is_container(),SearchParams::include_derived, thematch-arm fallout, purge guard. Fold in theCollectionRoleretirement (DocumentType::Notebook,notebook.rsport) — it touches the same dispatches, and doing it separately means editing them twice. - ⏳
EdgeKindvariants,uuidv5 feature, and theloftydependency ✅; theJobKind::LibraryBuildvariant still to do (step 8 needs it). - ✅ Tag extraction: new
PropertyKinds,loftyread,MusicTagScan; wired intoimport_mp3_fileso new imports are tagged even before any library exists. A gap found here — a tag that disappears between scans left its old property behind, the store having no property-removal API — was what surfaced ADR 0043;write_tag_propertiesnow clears what a re-tagged file no longer carries. - ✅ Key derivation + document/edge upsert helpers, with the determinism tests.
- ✅
incorporate_track(+ the import hook). - ✅
build_library+ sweep + summary, batching. - ✅
JobKind::LibraryBuildwiring in gui-app (a "Build library" action on the music screen). A CLI verb for the Music agent is still to come, and needs a daemon-protocol command per ADR 0004. - ✅ CLI verbs. Still open: update
docs/data-model.md:MusicTrack/MusicArtist/MusicAlbumtype sections, theEdgesection's sync story, the newEdgeKinds, and the derived-document category. RetireTODO.md's sketch in favour of this file.