From 7b0d7e3a07910bc062af978ce7ba90bb65a967fd Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Sat, 19 Sep 2026 13:48:45 +0200 Subject: [PATCH] Finished Rekordbox adapter --- .claude/handoffs/export.md | 221 ++++++++++++++++++ .claude/handoffs/rekordbox-adapter.md | 40 ++++ CLAUDE.md | 21 +- backend/konduktor/adapters/rekordbox/store.py | 9 +- backend/test_rekordbox_adapter.py | 14 ++ 5 files changed, 294 insertions(+), 11 deletions(-) create mode 100644 .claude/handoffs/export.md diff --git a/.claude/handoffs/export.md b/.claude/handoffs/export.md new file mode 100644 index 0000000..fe5d706 --- /dev/null +++ b/.claude/handoffs/export.md @@ -0,0 +1,221 @@ +# Handoff: the export feature + +**For**: an agent picking up Konduktor with no prior context. +**Task**: build library export — converting a curated slice of the loaded library +into a **fresh, self-contained library for another platform**, with the audio +files copied alongside. +**Status of the plan**: the multi-platform work is done through the Rekordbox +adapter. Export was originally sequenced *after* a Serato adapter; Ben has +chosen to bring it forward, so **the only export targets that can exist today are +Traktor and Rekordbox**. + +Every *design* decision was settled in +[`.claude/discussions/discuss-multi-platform-library-2026-09-17.md`](../discussions/discuss-multi-platform-library-2026-09-17.md) +— read its **Export** sections and **"If Moving to Planning/Implementation"** +before designing anything. This handoff is the current-state companion: what +exists, what to build, and what will bite you. Where they disagree, the +discussion doc wins on intent and this one on facts about the code. + +The Rekordbox handoff ([`rekordbox-adapter.md`](rekordbox-adapter.md)) is worth +skimming too — its §8 Findings are the format knowledge any Rekordbox *writer* +will need, and its history is a good model of how this project verifies things. + +--- + +## 1. Where the project is + +Konduktor is a library-management and track-prep tool for DJ software, built on a +**generic model + per-platform adapter** architecture. Two adapters exist: + +- **Traktor** (`collection.nml`) — full read/write, byte-exact saves, version + history. +- **Rekordbox** (`master.db` + ANLZ analysis files) — read/write for metadata, + playlists, hot cues and beatgrids. No version history (a deliberate, accepted + scope decision). Gaps: cover art, `remap_locations`. + +``` +backend/konduktor/ + core/ generic. MUST NOT import a native library type (test_layering.py) + model.py Track, CuePoint, GridMarker, TrackCues, PlaylistNode… + adapter.py LibraryAdapter / LibraryDriver protocols, SaveOutcome, errors + capabilities.py what a loaded library can persist + query.py TrackIndex: query/filter/sort/facets/stats + registry.py adapter selection by can_open() probe + adapters/traktor/ store.py (native model) adapter.py projection.py driver.py … + adapters/rekordbox/ same shape; store.py owns the SQLCipher session + ANLZ + app_state.py the one loaded library + version-history commits + prefs.py userprefs.json in the per-OS app-data dir (paths.app_data_dir()) + main.py thin FastAPI routes, all under /api +``` + +**Tests**: `cd backend && ./run_tests.sh` → 331 assertions across +`test_layering.py`, `test_save_fidelity.py`, `test_traktor_adapter.py`, +`test_rekordbox_adapter.py`, `test_rekordbox_fidelity.py`, `test_phase3.py`, +`test_history.py`. Frontend: `npm run build && npm run test`. +**The suite must be green at the end of every step** — that discipline is why a +1,500-line refactor of the save path landed without a fidelity regression. + +--- + +## 2. The one architectural gap, and it is not small + +**No adapter can create a library from nothing.** + +`LibraryDriver` is `can_open` / `open` / `detect` / `describe` / `restore`. +`LibraryAdapter` is built entirely around *one already-open library* that commands +are replayed onto. Export needs the opposite: **write a brand-new library at a +path where nothing exists yet.** + +This is the central design question of the whole feature, and the discussion doc +does not settle it. Decide it deliberately and write down why. The obvious +shapes: + +1. **A separate `LibraryWriter` protocol** — `create(path)` returning something + that accepts tracks, playlists and prep data, implemented per target. Keeps + the edit path untouched, which matters because the edit path is the one with + the fidelity guarantees. Some duplication with the adapters' write code. +2. **Extend `LibraryDriver` with `create(path) -> LibraryAdapter`** — an empty + library is then just a library, and the existing commands populate it. Elegant + on paper; the risk is that "empty new file" and "the user's real library" + start sharing code paths, and the *reason* the current architecture is safe is + that the write target is always a retained native model that was parsed from a + real file. +3. **Target-specific exporters with no shared protocol** — fastest to a working + Traktor export, and it will rot. + +The discussion doc's strongest constraint bears on this: *"Two distinct write +paths must coexist: a high-fidelity in-place edit path per platform, and a +lossy-by-design export path. They have opposite requirements and should not +share an implementation."* Read that as pointing at (1), but make the call +yourself with the code in front of you. + +--- + +## 3. What the design already settles + +Do not relitigate these. They are decided, with rationale and rejected +alternatives recorded in the discussion doc. + +**Shape of an export** +- Always a **fresh, self-contained library** at a user-chosen destination. + **Never merges** into an existing target library. This is what removes any need + for cross-platform track identity — there is nothing to match against. +- **Always copies the audio files**, for every target, not just Serato. +- Audio layout is a **global, persisted setting**: **flat single folder + (default)** or **mirror the source directory structure**. +- Flat-layout filename collisions get a **counter suffix** (`Xtal-2.mp3`). + Known consequence: numbering depends on processing order, so repeat exports may + assign different suffixes to the same tracks. +- Playlist folders: **preserve where the target supports them**, otherwise + flatten to path-encoding names (`House / Peak Time`). +- Re-export to an occupied destination: **warn, overwrite on confirm.** +- Provide an explicit **"export entire library"** action that skips export-set + creation entirely. + +**Export Sets** (the unit of curation) +- A named, persisted list of **track and playlist references** scoping an export. + Called an **Export Set**, never a "Crate" — Serato uses "crate" for a playlist + and Konduktor will import those. +- **References are LIVE**: an export set stores pointers, and export resolves + them at export time, so later additions to a playlist are picked up. + **Consequence: the export preview must be computed at export time, never + stored.** +- Playlist resolution **auto-includes** referenced tracks, **deduplicates**, and + copies each file **exactly once**. +- Stored in **Konduktor's own store**, not in the platform library and not in + `userprefs.json`, keyed by a **stable library ID**. + +**Running an export** +- **Pre-scan for missing audio files**, report them, let the user cancel or + proceed without them — fail fast rather than halfway through a multi-hour copy. +- **Pre-check disk space** before starting. +- **Progress with a working cancel.** Known consequence: cancelling leaves a + partial export, which must be cleaned up or clearly marked incomplete. + +**Lossiness** +- **Degrade to the nearest equivalent where one exists, drop only where none + does.** A Traktor fade-in cue becomes a plain cue on a target without them; + Rekordbox memory cues fill spare hot cue slots until they run out. +- **No loss report for now** — explicitly deferred. Adapters know what they + collapsed, so it stays cheap to add. + +--- + +## 4. Landmines, earned + +**There is no stable library ID.** Export sets are specified as keyed by one, +held in a sidecar next to the user's collection — and nothing like it exists. +Today everything keys off the library's **OS path**: `prefs.get_path_mapping`, +`prefs.get_last_collection`, and `history`'s repo directory (a hash of the +resolved path). Moving a collection silently orphans all of it. Building export +sets on the path would inherit that; building the sidecar is the decided design +but is genuinely new work. Do it first — retrofitting an ID once sets exist means +migrating them. + +**The lossiness rule needs capabilities the target does not have loaded.** +`Capabilities` describes *the currently open library*, via an adapter instance +built from a real file. Export needs to know what a target platform can hold +*before* any such library exists. Either capabilities must become derivable from +a platform alone (not an instance), or exporters must carry their own static +declaration. This is exactly where a "what can the target represent?" question +will first bite, and `capabilities_for()` in each adapter currently takes a +`path`. + +**The two-platform promotion rule still applies.** A concept enters the generic +vocabulary only once **two or more** platforms have it. Export will tempt you to +add target-specific knobs to generic types; don't. Single-platform concepts stay +*preserved but not editable* — for instance Rekordbox **memory cues** are +projected and displayed and never written. + +**Rekordbox as an export TARGET is much harder than Traktor.** A Traktor export +is one XML file Konduktor already renders byte-exactly. A Rekordbox export needs +a `master.db` — SQLCipher, foreign keys into lookup tables, USN bookkeeping — plus +per-track ANLZ analysis files containing the beatgrid, plus `masterPlaylists6.xml`. +Worse, `.DAT`/`.EXT` analysis files can currently only be *modified*, never +created: `beatgrid.write_pqtz()` rebuilds the `PQTZ` tag **inside an existing +file**. Generating ANLZ from scratch is unexplored, and `PQT2` (the extended +grid) is undecoded — `pyrekordbox` names its per-beat field `unkown`. +**Strongly consider shipping Traktor as the only export target first.** + +**CDJ/USB export (`export.pdb` + ANLZ) is rejected as impractical.** It has been +re-proposed twice. Do not raise it again. + +--- + +## 5. Working agreements + +- **`./run_tests.sh` green at the end of every step.** +- **`schemas.py` and `api.ts` land in the same commit** — one contract in two + languages. +- **Verify against reality, do not infer.** The project's standing lesson, and it + has been proved right four times: Traktor cue colours, flexible grid marker + naming, whether Rekordbox reads `PQTZ` or `PQT2`, and the hot cue slot + encoding. That last one cost two rounds of wrong theory built on three + incidental data points; one deliberate probe across the full range settled it. + For export the equivalent is: **write an export, then open it in the real DJ + software** before believing it works. +- **Ben's Rekordbox library is a disposable test library** — write to it directly, + no backups needed. **His Traktor collection is real, irreplaceable data** + (8,485 entries): always work against copies. `./dev-sandbox.sh` already + encodes exactly this split and refuses to start if another server holds the + ports. +- **Capability-gate every control.** The UI must never offer an edit — or an + export target — that cannot actually be produced. This has failed twice and + both times it was a stale flag, not missing machinery. + +## 6. Suggested first steps + +1. **Decide the writer architecture** (§2) and record the decision and its + rejected alternatives, in the style of the discussion doc. +2. **Build the stable library ID sidecar** (§4) — everything else keys off it. +3. **Export Sets: model, store, API, UI.** Live references; preview computed at + export time. +4. **A Traktor exporter end to end**, with the audio copy, the pre-scan, the + space check and cancellable progress. +5. **Open the result in Traktor.** Not "the tests pass" — actually open it. +6. Only then consider a Rekordbox exporter, knowing §4's warning. + +Bulk metadata editing also remains unbuilt and unblocked; it is far smaller than +this and was deferred specifically until the adapter architecture existed. If a +shippable win is wanted sooner, that is the alternative — confirm with Ben rather +than assuming. diff --git a/.claude/handoffs/rekordbox-adapter.md b/.claude/handoffs/rekordbox-adapter.md index ec0d164..cabb0c1 100644 --- a/.claude/handoffs/rekordbox-adapter.md +++ b/.claude/handoffs/rekordbox-adapter.md @@ -1005,3 +1005,43 @@ counter move. Suite: **316 assertions**. - **`PQT2` is undecoded**, so the extended grid drifts out of step with `PQTZ` after any Konduktor grid edit. Harmless for Rekordbox itself; would need solving before any CDJ/USB export (currently rejected as out of scope). + +### The hot cue slot encoding, measured — and it was never about loops + +`djmdCue.Kind` is 1-based **and skips 4**. Established by writing a 4-beat loop +at every `Kind` from 1 to 8, ten seconds apart, and reading the pads off a real +deck: + +| `Kind` | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | +|---|---|---|---|---|---|---|---|---|---| +| pad | A | B | C | **—** | D | E | F | G | H | + +A cue at `Kind=4` occupies no pad at all; Rekordbox displays it as a memory cue. + +That single gap explains everything that had been confusing: + +- Ben's Rekordbox-authored loop on pad **F** stored `Kind=7` — correct, not an + anomaly; +- a Konduktor cue written at `Kind=4` "turned into a memory cue" — it *was* one; +- pad H stayed empty in the probe because H is `Kind=9`, and the probe stopped + at 8. + +**Loops were never the problem.** They had been disabled on the theory that an +out-point changed the slot encoding; in fact the adapter's `slot -> Kind` map was +simply wrong from pad D upward, for *every* cue type. Loops write fine now, and +`cue_types.WRITABLE_CUE_TYPES` is back to `["cue", "loop"]`. **Confirmed in +Rekordbox**: looped hot cues set in Konduktor save and display correctly. + +The lesson is the project's own standing one, and it cost two rounds of wrong +theory: the mapping was *inferred* from three incidental data points before +anyone thought to *measure* it across the whole range. One probe settled it. + +Tests now pin the exact `Kind` sequence and assert that all eight pads are +individually addressable, so a regression fails loudly instead of quietly moving +someone's cues. + +### Remaining Rekordbox gap + +Only **cover art**, which has never been investigated (`tracks.artwork` is +false; `djmdContent.ImagePath` plus separate artwork files). `PQT2` also stays +undecoded, which only matters for CDJ export — out of scope. diff --git a/CLAUDE.md b/CLAUDE.md index 1f5acf7..30b3c4d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -97,12 +97,13 @@ Two independent apps that talk over HTTP: `ContentUUID` and its mirror row's `ID` are both the **track's UUID**, an uncoloured cue is `Color=-1, ColorTableIndex=NULL`, and a loop is `Color=255, ColorTableIndex=0` with `BeatLoopSize = (beats << 16) | 1`. + **`Kind` is 1-based AND skips 4** — the bank is `1,2,3,5,6,7,8,9` for pads + A–H. Measured by writing a cue at every `Kind` 1–8 and reading the deck: a + cue at `Kind=4` lands on no pad and Rekordbox shows it as a memory cue. + Get this wrong and cues silently move to the wrong pad or vanish from the + bank. Point cues AND loops both write; `cue_types` owns the translation. **Memory cues stay preserved-but-uneditable** (Rekordbox is the only - platform with them — the two-platform promotion rule), and **saved loops - are read but not written**: verified in Rekordbox, a cue row carrying - `OutMsec` does NOT land in the hot cue slot its `Kind` names — it becomes a - memory cue — so writing one would silently create an object Konduktor - cannot then edit. `cue_types.WRITABLE_CUE_TYPES` is the narrower set. + platform with them — the two-platform promotion rule). - **Saving warns but does not block when Rekordbox is running.** `pyrekordbox.commit()` refuses outright, and its check is process-wide rather than per-file, so `RekordboxStore._commit()` suppresses that veto @@ -391,11 +392,13 @@ that number and nothing else — everything derives from it: `test_rekordbox_fidelity.py`, end to end through the API, and in Rekordbox 7 itself. Research is captured in `.claude/handoffs/rekordbox-adapter.md` §8, incl. the verified result that Rekordbox accepts Konduktor-written rows when - USNs are maintained. Remaining gaps: **saved loops** (a cue row with an - out-point does not land in the slot its `Kind` names — encoding unmeasured) and - **cover art**. **No version history on Rekordbox** — accepted scope decision, + USNs are maintained. Remaining gap: **cover art**. **No version history on Rekordbox** — accepted scope decision, see handoff §11. -- ⬜ Serato adapter; ⬜ export/conversion +- ⬜ **Export/conversion** — next up, brought forward ahead of Serato. Design is + settled in the discussion doc; current state, the architectural gap (no adapter + can create a library from nothing) and the landmines are written up in + [.claude/handoffs/export.md](.claude/handoffs/export.md). +- ⬜ Serato adapter - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging ## Write path (playlists + track metadata + prep) diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index e048108..d14b48d 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -39,7 +39,7 @@ from sqlalchemy.orm import joinedload from ...core.adapter import InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome from ...core.edit_journal import EditJournal from ...core.pathmap import PathMapping -from .cue_types import beat_loop_size, kind_for +from .cue_types import beat_loop_size, kind_for, role_and_slot log = logging.getLogger(__name__) @@ -182,7 +182,12 @@ class RekordboxStore: out: dict[str, tuple[int, int]] = {} for content_id, kind, n in rows: total, hot = out.get(str(content_id), (0, 0)) - out[str(content_id)] = (total + n, hot + (n if (kind or 0) != 0 else 0)) + # "Is this a hot cue?" must mean the same here as in the projection, + # or the count in the library table disagrees with the pads shown in + # the deck. `role_and_slot` is the single definition — it also rules + # out the reserved Kind, which occupies no pad. + is_hotcue = role_and_slot(kind)[0] == "hotcue" + out[str(content_id)] = (total + n, hot + (n if is_hotcue else 0)) return out def cues(self, track_id: str) -> list: diff --git a/backend/test_rekordbox_adapter.py b/backend/test_rekordbox_adapter.py index 9ab6b60..a909dd3 100644 --- a/backend/test_rekordbox_adapter.py +++ b/backend/test_rekordbox_adapter.py @@ -431,6 +431,20 @@ with tempfile.TemporaryDirectory() as d: check("Rekordbox has no grid lock", _raises(lambda: adapter.set_grid_lock(grid_track.id, True), Unsupported)) + print("== hot cue counting agrees with the projection ==") + # One definition of "is this a hot cue?", used by both the per-track count + # and the projection. They diverged once: the count treated the reserved + # Kind as a hot cue while the projection called it a memory cue, so the + # library table disagreed with the pads in the deck. + mismatched = [] + for t in adapter.tracks[:40]: + cues = (adapter.track_cues(t.id) or TrackCues()).cues + projected = sum(1 for c in cues if c.role == "hotcue") + if adapter.track(t.id).hotcue_count != projected: + mismatched.append(f"{t.title}: {adapter.track(t.id).hotcue_count} vs {projected}") + check("Track.hotcue_count matches the projected hot cues", + not mismatched, "; ".join(mismatched[:3])) + print("== saving warns but proceeds while Rekordbox is running ==") # pyrekordbox's own commit() refuses outright if it sees a Rekordbox process. # Konduktor's settled behaviour is to warn, not block — matching Traktor —