# CLAUDE.md Guidance for working in this repo. Read before making changes. ## What this is **Konduktor** — a library-management and track-preparation tool for **Native Instruments Traktor** (Pro 4 / NML v20), built on the `traktor-nml-utils` library. The user is a DJ; the goal is a polished, multiplatform web app for browsing the collection, editing playlists, and preparing tracks (metadata, cover art, and audio prep: playback, waveform, beatgrid, cues/hotcues, loops) — a lightweight alternative to heavy Traktor, later possibly wrapped in Tauri and given a mobile version. ## Architecture Two independent apps that talk over HTTP: - **`backend/`** — Python + FastAPI. Entry point: [backend/konduktor/main.py](backend/konduktor/main.py). **Architecture: projection + command replay.** The generic model is a *read projection*; edits are strictly-generic commands that a per-platform **adapter** replays onto its **retained native model**, which stays the write target. The generic model is NEVER serialized back over a library — that is what preserves byte-exact saves, and it is the only model that works for formats you cannot regenerate (a Rekordbox SQLite row, a Serato tag inside an audio file). Traktor is currently the only adapter; see `.claude/discussions/` for the decision log. - `core/` — **platform-independent. Must not import `traktor_nml_utils` or `konduktor.adapters`** (`test_layering.py` enforces this). This is the contract a Rekordbox or Serato adapter will be written against. - `model.py` — the generic model (`Track`, `CuePoint`, `GridMarker`, `TrackCues`, `PlaylistNode`, `Facets`, `Stats`, …). Served straight to HTTP. - `adapter.py` — the `LibraryAdapter` / `LibraryDriver` protocols and the error tree (`NotFound` → 404, `InvalidCommand` → 400, `Unsupported` → 422), mapped to status codes once in `main.py` rather than per route. - `capabilities.py` — `Capabilities`: what the loaded library can persist, so the UI can gate controls instead of branching on the platform. - `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over generic `Track`s. Shared so "sort by artist" cannot mean different things on different platforms behind one UI. - `edit_journal.py` (`EditJournal`) — every edit this session at **field resolution** (`track/set/genre`, `cue/add/slot:1`, `grid/marker-bpm/marker:0`). Drives the file-tag sync, the version-history message, and `retarget()` when a path remap changes track ids. Recording `before` keeps undo cheap later. - `registry.py` — adapter selection by **`can_open()` probe**, not extension (Rekordbox is a `.db`, Serato is a directory). - `audio_tags.py`, `pathmap.py`, `auto_hotcues.py` — format-agnostic helpers. - `adapters/traktor/` — everything that knows NML exists. - `store.py` (`TraktorStore`) — the retained native model: owns the parsed dataclass NML, applies every edit, renders + saves. See "Write path". - `adapter.py` (`TraktorAdapter`) — owns the store **and** the `TrackIndex` built from it, so projection and native model cannot drift. Translates the generic cue vocabulary to Traktor's integers (the only place that mapping exists). **Every mutating command returns its refreshed projection** — a forgotten refresh would be a silently stale UI no byte test would catch. - `projection.py` — native → generic (`to_track`, `to_track_cues`). - `driver.py`/`discovery.py` — `can_open`, default-location detection, restore. - `beatgrid.py`, `locations.py`, `capabilities.py` — Traktor's grid/companion rules, LOCATION ↔ OS path conversion, and its capability set. - `adapters/rekordbox/` — **track metadata, playlists and hot cues writable; the beatgrid still read-only** (milestones 2 and 3a). `master.db` is SQLCipher-encrypted SQLite, read via `pyrekordbox`. Every mutating command raises `Unsupported` and `capabilities()` advertises nothing as editable, so the UI never offers an edit. Three things differ from Traktor and are the reason this adapter is not a copy of it: - **The beatgrid is NOT in the database, and is written to ONE tag of ONE file.** There is no grid table at all; it lives in per-track ANLZ analysis files as a `PQTZ` tag listing EVERY BEAT. `beatgrid.py` collapses those into the generic marker list on read and expands them back on write. `write_pqtz()` rebuilds the entry list directly — `pyrekordbox`'s own setters refuse to change the NUMBER of beats, which every real edit does — then calls the tag's `update_len()`. **Only `.DAT`'s `PQTZ` is written.** `.EXT` holds a second "extended" grid (`PQT2`) whose per-beat byte `pyrekordbox` itself calls `unkown`, so writing it would mean guessing at bytes in data with no version history. Verified in Rekordbox 7: it reads the grid AND the deck's BPM from `PQTZ`, leaves a Konduktor-written `.DAT` untouched, and is unbothered by the stale `.EXT` (which would matter only for CDJ export — out of scope). It does **not** reconcile `djmdContent.BPM`, so the adapter maintains that column itself, mirroring the first marker exactly as Traktor's `` does. Grid edits are **buffered until `save()`** so ANLZ file writes obey the same "edit in memory, Save writes to disk" contract as everything else; `save()` writes the files BEFORE committing the database, so a failed file write leaves nothing committed. `store.anlz_grid()` parses them **lazily** — ~1.4 ms each, i.e. ~12 s for a library of 8,500 if done at open — so `Track.grid_marker_count` carries a documented approximation (1 when the track has a BPM) that `track_cues()` corrects. - **Cues live in two places** that must agree: `djmdCue` rows and a JSON mirror in `contentCue.Cues` (+ `rb_cue_count`). Rekordbox stamps `rb_local_usn` on `contentCue`, never on the cue rows. Every cue write ends in `_sync_content_cue()`, which rebuilds the mirror from the rows — leaving it stale is this platform's version of Traktor's companion-cue desync. Field conventions are read off a real library, not guessed: `InFrame`/`OutFrame` are the position in frames at **150 fps**, a cue's `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). - **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 and logs instead — otherwise a temp copy could not be written while the user had a different library open. - **`djmdCue.Kind` is an OPAQUE slot id**: 0 = memory cue, N = hot cue slot N. Pads A and C store 1 and 3, but the 6th pad stored 7 — so the slot→letter mapping is NOT a plain index and is deliberately left to the UI. Writes are refused outright on a **cloud-synced** library (detected by a server-issued `usn` on any row): a bad sync state would propagate to the user's other machines, and there is no version history here to undo it. Every command passes through `_require_writable()` so a command added later cannot forget that check. Edits accumulate in the SQLAlchemy session and `save()` commits — which maps onto Konduktor's "edit in memory, Save writes to disk" model exactly, since `pyrekordbox`'s `commit()` is what assigns Rekordbox's USNs. A real Rekordbox 7 was verified to accept a library written this way, display the edit, leave the row alone, and continue from the counter it was left at. `artist`/`album`/`genre`/`label`/`remixer` are **foreign keys into lookup tables**, so a write is find-or-create (pyrekordbox's `add_*` RAISES on an existing name) followed by a **flush + expire** — without which the ORM re-reads the stale relationship and a successful edit projects as a no-op. `producer`/`mix` are absent from `editable_fields`: Rekordbox has no column for them and its Composer is a different field. `close()` disposes the SQLAlchemy engine, not just the session — otherwise the OS file handle stays open and `master.db` cannot be replaced. `AppState` closes the previous adapter when opening a new library. - `adapters/onelibrary/` — **read-only.** The cross-vendor USB export format (AlphaTheta + Algoriddim + Native Instruments), read by CDJ-class hardware. Built as the source half of a future "import a stick into Traktor" feature. Full research, incl. the schema, is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md); the four things that make it unlike the Rekordbox adapter: - **The library is a REMOVABLE DRIVE, not a file in a known place.** So `discovery.py` scans mount points rather than probing fixed paths, and `layout.py` owns the on-drive layout (`PIONEER/rekordbox/exportLibrary.db`, analysis under `PIONEER/USBANLZ/P0/<8 hex>/`). Every stored path is **drive-relative with a leading slash** — `/Contents/…/x.mp3` — which is NOT an absolute host path: joining it naively discards the mount point and silently yields `/Contents/…`, which looks like an empty drive rather than a path bug. `DriveLayout.resolve()` is the only place that join happens. A track's id is that drive-relative path, not `content_id`, which rekordbox renumbers from 1 on every re-export. - **Cues are NOT in the `cue` table**, which rekordbox exports empty; they are in the ANLZ files. `PCOB` is **split by pad** (`.DAT` holds 1–3, `.EXT` holds 4 and up — reading only the `.DAT` silently loses pads D–H), and `PCO2` in the `.EXT` holds the complete set plus RGB colour and comments. `PCO2` wins, `PCOB` is the fallback, both merge across files first. - **The slot numbering differs from `master.db`.** `djmdCue.Kind` is a sparse bank that skips 4; ANLZ `hot_cue` is a **dense 1-based index** (pad D is `Kind` 5 but `hot_cue` 4), and 0 means memory cue. Measured by aligning the same five cues in both representations. Reuse the Rekordbox mapping here and every cue from pad D on lands one pad too far along. Times are **ms**, not 150 fps frames; `loop_time` is `0xFFFFFFFF` (not 0) when there is no loop. - **Analysis files are parsed lazily** — `.DAT` ~2 ms but `.EXT` ~23 ms, so eager parsing would cost ~23 s on a 1,000-track drive. Cue and marker counts are therefore approximate in the library table and corrected by `track_cues()`. The `PQTZ` beatgrid is the same tag as Rekordbox's, and the collapse rule is **shared by import** rather than copied — two definitions of "when does a tempo change start a marker" would drift silently. - `app_state.py` — the one loaded library, and the **version-history commit**. History is app-level: the adapter returns the bytes it wrote plus a summary, and `AppState.save()` versions them. Every write path must go through it. - `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data dir). Last-opened collection (global AND per-platform), library column layout, prep-deck zoom, import destination. Best-effort. - `schemas.py` — HTTP request bodies + envelopes; re-exports `core.model`. - `main.py` — thin FastAPI routes (all under `/api`), talking only to the adapter. Starts **unloaded**; the library is chosen at runtime via `POST /api/library/open` (data routes 409 until then). `GET /api/capabilities` feeds the UI's gating; `GET /api/fs/list` powers the file browser; `GET`/`PATCH /api/prefs` persist UI prefs. Setting `KONDUKTOR_NML` auto-loads on startup (dev/tests). The picker's three routes are all **scoped by `?platform=`**, because it asks which platform first: `/api/platforms` (the pre-load equivalent of capabilities — reports `selects`, `removable` and `found`, sorted so a menu does not reshuffle between launches), `/api/library/options` (that platform's detections + its own last-opened) and `/api/fs/list` (that platform's suffixes; a directory-selecting platform contributes none, so its browse shows folders only). `/api/library/open` checks `exists()`, **not `is_file()`** — which shapes are valid is `can_open()`'s business, and a OneLibrary library is a drive. `prefs` keeps last-opened **per platform**: offering a Rekordbox `master.db` to someone who just chose Traktor is an offer that cannot be taken. - **`frontend/`** — React + TypeScript + Vite. A dark, virtualized track explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx). - `api.ts` — typed client + all API types. **Generic, not Traktor-shaped**: cue types are the strings `cue`/`fade_in`/`fade_out`/`load`/`loop`, a cue has a `role` (`hotcue`/`memory`) and a nullable `slot`, and `editable` + `readonly_reason` say whether the adapter will accept a command on it — gate on `editable`, never on a platform-specific reason like `grid_marker`. Keep in lockstep with `core/model.py`; land both in the same commit. - `lib/capabilities.tsx` — `useCaps()` over `GET /api/capabilities`. The app does not render until capabilities resolve, so no first frame can offer an edit the adapter would reject. Containers call `useCaps()`; presentational leaves take plain values as props. **No component branches on the platform.** - `lib/platformCopy.ts` — composes user-facing wording from the *facts* the adapter supplies (`app_name`, `library_label`, `overwrite_risk`), so "Close Traktor before saving — it overwrites collection.nml on exit" stays specific without being hard-coded. Never put finished sentences in the API. - `components/` — `CollectionPicker` (**two steps: which PLATFORM, then which library** — Automatic / Open last / Find manually, the last revealing a file browser. The platform comes first because every later answer depends on it: asked the other way round, "Automatic" had to guess ACROSS platforms and did it by adapter registration order, so a plugged-in stick could be opened as the user's collection. Scoping removes that by construction rather than by ranking candidates better. Nothing is remembered between launches — the platform list is where every session starts. `selects` decides whether the browser offers files or a folder to confirm, because a library is a file on some platforms and a DIRECTORY on others), `Sidebar` (a header naming the open library, which is also the only way to switch to another one — the picker used to be a one-way door with `forcePicker` never set, so changing library meant restarting; switching confirms first when there are unsaved edits, since the adapter holds them in a native model that opening another library replaces — plus the playlist tree + create/rename/delete), `SaveBar`, `Toolbar` (search/filters + `ColumnsMenu`), `TrackTable` (All Tracks — TanStack Table + **virtualized** grid; per-row play button, configurable columns, inline double-click editing) and `PlaylistTable` (playlists — same columns/cells/play/inline-edit via shared `HeaderRow`/ `RowCells`/`PlayButton`, so the two views look identical, PLUS dnd-kit drag-to-reorder + a remove button, header sorting disabled so the manual order stands; `canReorder` is false while a filter/search is active so a partial order can't overwrite the full entry list). `PlaylistTable` is non-virtualized (playlists are small) and feeds `useReactTable` a **stable** empty `sorting` array (`NO_SORTING`): a controlled `state.sorting` that's a fresh `[]` each render with no `onSortingChange` makes TanStack Table re-sync its internal state every commit → infinite re-render loop. Keep that reference stable. `SelectionBar` (bulk add-to-playlist), `ContextMenu` + `EditTagsDialog` (right-click → multi-field metadata + album-art edit), `StatusBar`, `RatingStars` (read-only, or click-to-set when given `onChange`), `Toast`, `UpdateDialog` (`UpdateCheck`, mounted in `main.tsx` beside `App` so it shows even on the picker screen: on startup fetches the latest GitHub release and, if its tag's **semver part** is newer than `__APP_VERSION__` — build-number `-b` bumps don't count — shows an update dialog with the release's "What's Changed" bullets; Download opens the release page in the system browser via `@tauri-apps/plugin-shell` `open` — falls back to `window.open` outside Tauri; "Skip this version" persists `skippedUpdateVersion` to userprefs via `/api/prefs`; all failures are silent). - **Prep strip** (DJ deck across the top of the window): `PrepStrip` owns it — transport (play/pause, CUE), two waveforms (`MainWaveform` scrolling+zoomable — its zoom is owned by `PrepStrip` so it survives track switches and persists, `OverviewWaveform` whole-track), `LoopControls`, `HotcueBar`, `GridControls` (BPM readout/editor, fine ±0.01 / coarse ±0.25 BPM nudge, /2·×2, tap tempo, marker nudge, add/delete marker, lock, delete grid (confirmed) — all on the marker **governing the playhead**, since a beatgrid is a marker list and there is no separate marker selection; see "Beatgrid" below). Prep libs live in `src/lib/`: `playbackEngine.ts` (Web Audio, seamless loops), `scratchEngine.ts` (drag-to-scratch), `waveform.ts` (frequency-colored analysis + paint), `beatgrid.ts` (the marker-list beat math — every beat/bar/snap/jump calculation goes through it), `cues.ts` (draw cues/loop/beatgrid/cue-point). See "Prep engine" below. - **`capabilities.writable`** is the library-level gate, and it is deliberately NOT the same as every per-feature flag being false: "the platform has no such feature" and "this library cannot be written at all" look identical to a UI that only sees per-feature flags, and silently inert controls read as a bug. `readonly_cause` says which kind (`platform_incomplete` / `cloud_synced`) and `platformCopy.readOnlyNotice()` words it — the two need very different sentences, since one is a roadmap gap and the other a permanent refusal that protects the user's other machines. Gated on it: `SaveBar` (replaces the save button with the reason), `App`'s `onEditField` (inline edit + click-to-rate go inert), the "Edit Tags…" context item, `Sidebar`'s new-playlist button, and all 12 `PrepStrip` edit handlers (which report the reason rather than firing a request the adapter would refuse — the deck stays fully usable for listening, and shows a "Read-only" badge). - Capability-gated today: hotcue bank size (`HotcueBar`, the auto-cue guard and the digit shortcuts all read `cues.hotcue_slots`), the cue-type dropdown (`cues.types`), the rating scale (`tracks.rating_max`), the grid Lock button (`grid.lockable`). Per-node playlist flags (`can_rename`, `can_delete`, `can_add_tracks`) gate the sidebar and `SelectionBar` — each on its OWN flag, since a platform may allow renaming but not deleting. Carried but deliberately unused until a second adapter exists: `slot_labels: 'letter'`, `palette`, `loops: 'separate_bank'`, and memory-cue *editing* (one-platform features stay preserved-but-uneditable). - `lib/trackColumns.tsx` — single source of truth for the library table's columns (defs, default widths/visibility/order, the Columns-menu list, the inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation). - Data flow: the whole library is fetched once (`/api/tracks?limit=20000`); filtering and sorting happen **client-side** for instant interaction. Edits apply in-memory (server holds them) and the sidebar **Save to Traktor** button flushes to disk. Styling is Tailwind v4 with tokens in `src/index.css`. Library column layout (visibility/order/width) persists to `userprefs.json` via `GET`/`PATCH /api/prefs` (debounced; hydrated on launch, merged against defaults so newly-added columns still appear). The prep deck's main-waveform zoom persists the same way (`mainZoomSec`, hydrated in `PrepStrip` from the shared `['prefs']` query). ## Commands ```bash ./dev.sh # start both servers (see README for one-time setup) # Backend cd backend && source .venv/bin/activate uvicorn konduktor.main:app --reload --port 8000 # point at another file: KONDUKTOR_NML=/path/to/collection.nml uvicorn ... # Frontend cd frontend npm run dev # dev server (proxies /api -> :8000) npm run build # tsc -b && vite build — run this to typecheck npm run test # vitest — unit tests for src/lib/beatgrid.ts ``` **Tests:** `cd backend && ./run_tests.sh` (runs against a temp copy of the real collection). **ALWAYS run this before changing anything in the save / serialization path.** It enforces: - `test_save_fidelity.py` — a no-op save is byte-identical (A); a playlist edit changes only that playlist's block (B); a **track-metadata edit changes only that ``** (C); a **hotcue create is localized + round-trips** with START stored in ms (D); a **grid-marker edit is localized + round-trips** (E); **flexible (multi-marker) grids** add/move/delete reversibly, `delete_grid` leaves no companion debris (I); **companion cues are protected** from hotcue commands (J); and real flexible grids in the collection project correctly (K). The guard that catches serialization regressions like the lxml reformatting bug. - `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays Traktor-valid, backup-first, COLLECTION byte-identical, original untouched. - `test_traktor_adapter.py` — the **generic layer**: one parse per open, the projection refreshing after every command family, cue-type translation, capabilities, and `set_analysed_grid` vs `replace_grid`. `test_save_fidelity` covers the store and its bytes; without this the adapter layer would be untested. - `test_rekordbox_adapter.py` — the second adapter against the same contract: cue/grid/key translation as pure units (they need no library), then the projection, playlist tree, capabilities and the refusal of all 21 commands against a **temp copy** of the local Rekordbox library. Skips cleanly when no Rekordbox is installed, so it is safe on any machine. - `test_rekordbox_fidelity.py` — the **row-level analogue of the byte diff**: a full table dump before/after, compared row by row (a byte diff is meaningless against SQLite). Asserts a no-op save changes zero rows; a one-field edit changes exactly two — the track and `agentRegistry.localUpdateCount` — with the counter up by one and the edited row stamped with it; edits are invisible on disk until save; and playlist create/fill/rename/delete round-trip. - `test_onelibrary_adapter.py` — the third adapter against the same contract. Unlike the Rekordbox tests it needs **nothing installed and nothing plugged in**: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export trimmed to fixture size (its README says what was removed; the database is untouched). So the expected values are checked against bytes *rekordbox* wrote, not bytes Konduktor wrote. Pins the drive-relative path resolution, the `PCOB`/`PCO2` merge, and — cross-checked against the same cues in `master.db` — the dense ANLZ slot numbering, which is the thing most likely to be silently wrong. - `test_import.py` — the import feature end to end: a drive's tracks into a temp copy of the real collection. Asserts the prep survives (hot cues keep their PAD, memory cues fill spare ones, the flexible grid crosses intact, no companion cue is invented), that the existing 8,485 entries render byte-identically, that the job registry runs/fails/cancels, and that a cancelled import leaves **no orphaned audio and an untouched collection**. - `test_picker.py` — the picker's routes. Pins the scoping, because the bug it replaced was invisible: `/api/library/options` flattened every driver's detections and returned `[0]`, so a plugged-in USB stick could be offered as the user's collection and nothing failed — it just opened the wrong library. Also pins that a drive is named the same whichever of its two valid paths was opened. Needs nothing installed: every assertion is about the SHAPE of the answer, and prefs are redirected to a temp file so a test can never rewrite the user's last-opened library. - `test_layering.py` — `core/` imports nothing platform-specific, and no adapter imports another platform's library (checked on real imports via AST, so merely naming a platform in a comment is fine). Rekordbox and OneLibrary deliberately **share** `pyrekordbox`: the rule is "no adapter reaches for a rival vendor's library", and a shared dependency is not a breach. Also validate the backend interactively at `http://localhost:8000/docs` and the frontend at `http://localhost:5173`. ## Critical gotchas — read these 1. **`traktor-nml-utils` MUST come from GitHub, not PyPI.** PyPI's `3.1.0` is stale and **cannot parse Traktor Pro 4 (NML v20)** files — its strict parser dies on the v4 `` element inside `CUE_V2`. `requirements.txt` pins the GitHub `master` (v4.0.0). Do not "simplify" this to a plain PyPI pin. **`pyrekordbox` is now the same situation**: PyPI's latest (0.4.4) has no `devicelib_plus`, which is the OneLibrary (`exportLibrary.db`) reader, so `requirements.txt` pins the GitHub master. That upgrade renamed `db6` → `masterdb` and `tables` → `models` and moved `BLOB` out of `db6.database`; the Rekordbox adapter uses the new names. `db6` still works as a deprecated alias and is **removed in 0.6.0**. 2. **The collection is real, irreplaceable data — protect it.** Every save writes a timestamped `.bak` first (into a `backups/` folder next to the collection). When testing writes, point `KONDUKTOR_NML` at a COPY. Warn the user to close Traktor before saving (it overwrites `collection.nml` on exit). 3. **Never re-serialize with lxml.** lxml reformats the whole file (collapses empty tags, drops float precision) → thousands of noise lines. The ONLY safe render is the library's own pipeline (see "Write path"), which reproduces Traktor's byte-exact layout so a no-op save is byte-identical and only edited objects diff. `test_save_fidelity.py` enforces this. ## Data model notes - **Track primary key** = `f"{location.volume}{location.dir}{location.file}"`, e.g. `Macintosh HD/:Music/:one.mp3`. This is how playlist entries (`PRIMARYKEY.KEY`) join to collection tracks. `Track.id` uses this. - **Rating** = `RANKING / 51`, giving 0–5 stars (`_rating_stars`). - **Key** is Traktor's display key string, e.g. `"10m"` (Open Key notation). - **Beatgrid = an ORDERED LIST of markers**, never a single BPM + anchor. Traktor stores each as a `CUE_V2 TYPE="4"` with its own `` child (flexible beatgrids, 3.4+); `` mirrors the **first marker by START**. A constant-tempo track is simply a list of length one, so this is the model for every track. Two rules verified against the real 8485-entry collection — get these wrong and you corrupt grids: - **Marker NAME is not a discriminator** (`AutoGrid` ×7888, `n.n.` ×64, `Beat Marker` ×14, `Unnamed` ×4). Identify by the `` child, order by `START` — never by name or document order. - **Companion cues are conventional, not structural.** Traktor usually pairs a marker with a white (`COLOR="#FFFFFF"`) `TYPE="0"` cue at the same position, which occupies a **real hotcue slot** — but 60 of 7970 markers have none. Konduktor follows them, keeps them in sync, and **never invents one** (except `place_grid_companion`, used only by Auto Grid). The `#FFFFFF` test is load-bearing: 49 uncoloured cues and 18 *loops* also sit within 1 ms of a marker and must not be dragged or deleted. `backend/konduktor/beatgrid.py` is the single shared definition of all of this. - **Playlist tree**: recurse `nml.playlists.node.subnodes.node`. A node's `.type` is `FOLDER`, `PLAYLIST`, or `SMARTLIST`. Smart playlists are rule-based and have no static entry list. `PlaylistNode.id` is the playlist's stable `UUID`; folders use a synthetic path id `fld:/`, smart playlists `sl:`. - Model classes use single-capital names: `Entrytype`, `Primarykeytype`, `CueV2Type`. `Entrytype` is shared by collection entries and playlist entries. ## Conventions - Backend: type hints, Pydantic models for all responses, keep query logic in `collection_service.py` (routes stay thin). - Frontend: functional components, TanStack Query for fetching, Tailwind utility classes with the `ink-*`/`accent`/`gold`/`mint`/`pink` tokens from `index.css`. Keep `api.ts` types aligned with `schemas.py`. - Python 3.14 note: pin dependencies loosely enough to get prebuilt wheels (older `pydantic-core` pins force a from-source Rust build that fails). ## Versioning **There is ONE source of truth for the app version: the `version` field in [frontend/package.json](frontend/package.json).** To release a new version, bump that number and nothing else — everything derives from it: - **Tauri / installers** — `tauri.conf.json` sets `"version": "../package.json"`, so the `.dmg`/`.exe` names + bundle version come from `package.json`. - **Backend API** — `konduktor/__init__.py` `_read_version()` reads `package.json` (dev: `/frontend/package.json`; frozen sidecar: bundled at the PyInstaller root via `sys._MEIPASS`, added in `konduktor-sidecar.spec`). `main.py` uses this for the FastAPI `version`. Falls back to `"0.0.0"` if not found (cosmetic, must never crash startup). - **Frontend / update check** — `vite.config.ts` bakes it in at build time as the `__APP_VERSION__` global (declared in `src/vite-env.d.ts`); `UpdateCheck` compares it against the latest GitHub release tag on startup. - **CI release** — `.github/workflows/build.yml` reads it with `jq .version frontend/package.json` and tags each push `v-b` (release name `Konduktor v-b`). The `-b` suffix keeps every push's tag/release unique. - **NOT a source**: `src-tauri/Cargo.toml` `version` is inert Rust crate metadata (Tauri uses the config's `../package.json`); don't treat it as the app version. ## Roadmap - ✅ Phase 1 — backend core + read-only API - ✅ Phase 2 — track explorer UI - ✅ Phase 3 — playlist editing/creation + safe (backup-first, surgical) saves - ✅ Runtime collection picker (in-app file browser) - ✅ Track metadata editing (right-click → Edit Tags dialog, plus inline double-click cell editing + click-to-set rating stars) with embedded file-tag & cover-art writing - ✅ Configurable library columns (show/hide, drag-reorder, resize) + auto-detect collection picker (Automatic / last-opened / manual), persisted to `userprefs.json` - ✅ Track prep — audio playback, frequency-colored scrolling waveform, scratch, beatgrid display + editing, cue/hotcue create/jump/delete, loops; keyboard shortcuts (Space = play/pause, 1–8 = hotcues, Shift+1–8 = delete). See "Prep engine". - ✅ Track prep Tier 2 — cue-point fine editing / audio export polish - ✅ Flexible beatgrids — the grid is a marker list end to end (marker-level commands, piecewise beat math, playhead-derived marker editing). Step 1 of the multi-platform plan in `.claude/discussions/`. - ✅ Generic model + adapter interface (Traktor as the only adapter) — step 2 of the multi-platform plan. Backend, wire format and UI are all generic; nothing above `adapters/traktor/` knows what Traktor is. - 🟡 Rekordbox adapter — **read + metadata/playlist/hot-cue/beatgrid writes done** (milestones 1–3). A Rekordbox library opens, projects, browses and accepts track metadata, playlist, hot cue and beatgrid edits — including flexible multi-tempo grids, confirmed rendering correctly in Rekordbox 7 — verified row-by-row by `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 gap: **cover art**. **No version history on Rekordbox** — accepted scope decision, see handoff §11. - ✅ **Import a OneLibrary stick into Traktor** — done end to end. A plugged-in drive appears under **Devices** in the sidebar, browses in the ordinary table and deck (audio streams off the stick so a track can be auditioned before importing), and imports into the loaded collection: audio copied, cues and flexible beatgrids translated, playlists recreated in a folder named after the drive. Verified in Traktor 4.5 itself. Three pieces worth knowing: - **`add_tracks` is the protocol's only CREATING verb** (`core/adapter.py`, `NewTrack`). Everywhere else the write target was parsed from a real file, which is what makes the byte-fidelity guarantee hold; here the rule becomes "an added entry must not perturb any existing one", which `test_import.py` checks on rendered bytes — exactly one line changes, the one carrying ``, whose count the store now maintains. The store creates a bare `ENTRY` and the cues/grid are written by **replaying the ordinary commands**, so an import inherits `replace_grid`'s companion handling and tests instead of growing a second implementation. `AUDIO_ID` and `LOUDNESS` are left empty — they are Traktor's own analysis outputs and cannot be computed; **verified that Traktor loads and plays such entries** and re-analyses them. - **`jobs.py` + `importer.py`** — the app's first long-running operation. Thread per job, polling, cooperative cancel; deliberately not asyncio or SSE. **Ordering is the safety property**: audio copies first and the library is written last, so a cancel leaves the collection untouched and removes what it copied (including the file being written — cleaning up only COMPLETED copies left debris the retry then suffixed around). Export will reuse this. - **The UI gates itself through capabilities, not conditions.** Browsing a device swaps the `CapabilitiesContext` for the device's own read-only set, so inline editing, Edit Tags, rating stars and all 12 deck handlers go inert with **no component learning what a device is**. The Sidebar sits outside that swap so `SaveBar` still saves collection edits. While a device's capabilities load the fallback is read-only, never the collection's — guessing "writable" for one frame would offer an edit bound for the wrong library. Lossiness follows the settled rule: memory cues become hot cues in spare pads (earliest first), cue colour is dropped (Traktor derives it from type). - 🟡 OneLibrary adapter — **read-only, done**. A OneLibrary USB drive opens, projects, browses and searches: tracks, playlists, hot cues, memory cues, loops and flexible beatgrids. Built as the readable SOURCE half of a future **"import a OneLibrary stick into a Traktor library"** feature, which is the motivating use case. Everything unknown about the format is on the write side (the `cue` table's MPEG seek columns, the waveform tags a CDJ draws from, the update counters), so read-only is a deliberate boundary rather than an unfinished one. All research — including the schema, which has no public spec — is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md). - ⬜ **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). Note the OneLibrary work already demonstrated creating an `exportLibrary.db` from nothing, and `fixtures/onelibrary/schema.sql` is the DDL to do it with. - ⬜ Serato adapter - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging ## Write path (playlists + track metadata + prep) `PlaylistStore` edits the **traktor-nml-utils dataclass model** in memory and, on `save()`, renders the WHOLE model and writes it (backup-first, into a `backups/` folder next to the collection). Whole-file render is proven byte-identical for unedited content, so only the objects you actually changed diff — no COLLECTION splicing needed. - **The render MUST use the library's pipeline** (do NOT use lxml — see gotcha 3): `XmlSerializer().render(nml)` → `restore_traktor_float_format(s, nml)` → `format_traktor_layout(s)` (both funcs imported from `traktor_nml_utils`). `_render()` in `playlist_store.py` is the single place this happens. - **Playlists**: keyed by stable `UUID`; folders by synthetic path id (`fld:/`). PRIMARYKEY `TYPE` is `STEM` if the track has a STEMS child (`CollectionService.stem_keys`, resolved via `entries_for`), else `TRACK`. - **Track metadata**: `set_track_metadata(track_id, fields)` edits only the SAFE set — title, artist, album, genre, label, remixer, producer, mix, release_date, comment, rating (0–5 stars → `RANKING = stars*51`). Path, BPM and key are intentionally NOT editable via metadata (path = identity; BPM/key are audio/grid — BPM is edited through the grid path below). This is the set the Edit Tags dialog AND the inline table editing (double-click cell, click rating stars) both write. - **Track prep** (also `PlaylistStore`, same render/save pipeline): `set_hotcue(track_id, slot, start_sec, type, length_sec)` creates/replaces a `CUE_V2` (types 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop; START/LEN stored in **ms**; a loop hotcue carries LEN); `set_hotcue_type` changes just the type; `delete_hotcue` removes a slot. (The adapter exposes these generically as `set_cue`/`set_cue_type`/`delete_cue`, taking a `cue_type` STRING — `cue`, `fade_in`, `fade_out`, `load`, `loop` — which the Traktor adapter maps to the integers below.) Hotcue commands **refuse a slot held by a grid marker's companion cue** (see "Beatgrid"). Beatgrid commands are marker-level: `add_grid_marker` (inherits the governing tempo when no BPM is given), `move_grid_marker` (clamped between its neighbours, drags the companion), `set_grid_marker_bpm` (also serves ×2 / ÷2, which retempo the governing marker like every other tempo control), `delete_grid_marker`, `replace_grid` (Auto Grid and the deck's Reset), `delete_grid` (markers **and** companions; keeps `TEMPO`), `place_grid_companion`. `set_lock(track_id, locked)` toggles `LOCK`. Invariants D/E/I/J prove hotcue + grid edits are localized and round-trip. - **Embedded file tags + cover art**: on save, for each edited track, `_sync_file_tags()` writes the changed fields (and staged cover art) into the audio file via `file_tags` (mutagen; ID3/MP4/FLAC/AIFF, WAV skipped) — best-effort (reports `file-not-found` if the drive isn't mounted, `.nml` still saves). Frame/atom-level writes preserve everything else (verified: cover art, BPM, key, and Traktor STEM atoms all survive). `.nml` is the source of truth; Traktor caches its own cover thumbnail so it may need a manual "Import Cover Art" to show replaced art. - Reads come from `CollectionService`; after a metadata edit the endpoint calls `service.replace_track()` so the change shows immediately (the two models aren't yet consolidated). - `POST /api/save` always writes (backup-first); no write gate. Endpoints: `POST/PATCH/DELETE /api/playlists[...]`, `PUT .../entries` (replace), `POST .../add` (append); `PATCH /api/tracks` (metadata); `GET/PUT /api/tracks/art` (cover art); `GET /api/tracks/audio` (Range-aware stream for playback/analysis); `GET /api/tracks/cues`, `POST/PATCH/DELETE /api/tracks/cue`, `POST/PATCH/DELETE /api/tracks/grid/marker`, `PUT /api/tracks/grid` (replace), `DELETE /api/tracks/grid`, `PATCH /api/tracks/lock` (prep); `POST /api/save`. - Tests: `backend/run_tests.sh` → `test_save_fidelity.py` + `test_phase3.py` (both run against a temp copy). Run before touching the save/serialization path. ## Prep engine (frontend) The prep strip plays every track through the **Web Audio API** (a plain `