178 KiB
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.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 importtraktor_nml_utilsorkonduktor.adapters(test_layering.pyenforces 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— theLibraryAdapter/LibraryDriverprotocols and the error tree (NotFound→ 404,InvalidCommand→ 400,Unsupported→ 422), mapped to status codes once inmain.pyrather than per route.move_playlist(node_id, parent_id, index)(sidebar drag and drop,POST /api/playlists/move) moves any tree node;indexcounts the new parent's children WITHOUT the node, and it returns the node's id AFTER the move — a Traktor folder's / smart playlist's id is its path, so it changes (playlists keep their UUID, so export sets never need retargeting). Gated per node onPlaylistNode.can_move. Traktor refuses a folder or smart playlist landing beside a namesake (as rename does); Rekordbox renumbersSeqitself (pyrekordbox's version cannot move to the top level) and keepsmasterPlaylists6.xml'sParentIdin step; OneLibrary renumberssequenceNofrom 0, and the pdb follows at Save.POST /api/playlists/{id}/addtakesduplicates:skip/add/ask(nothing changes, the count comes back so the UI can ask and resend);addonly wherecapabilities.playlists.duplicates— Traktor only, since OneLibrary'splaylist_contentis keyed on (playlist, content) and rekordbox's tolerance of a repeat is unmeasured. An optionalindexinserts among the CURRENT entries (a drop between a table's rows); folder add (playlist_index) and device import (into_playlist_index) take the same.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 genericTracks. 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, andretarget()when a path remap changes track ids. Recordingbeforekeeps undo cheap later.registry.py— adapter selection bycan_open()probe, not extension (Rekordbox is a.db, Serato is a directory).audio_tags.py,pathmap.py— format-agnostic helpers.grid_edit.py(ReplaceGridCommands) — the marker-level grid commands (add / move-with-clamp / retempo / delete) for a store whose one primitive isreplace_grid: Rekordbox's and OneLibrary's, whose grids are per-beat lists. Traktor keeps its own, companion-aware versions.relocate.py— auto path remapping's search (seerelocation.py). Fixes ONE thing: a stored prefix changed and the layout under it did not (a collection built on Windows with the SSD asX:, opened on a Mac where it is/Volumes/MiniSSD— the real case, 8,359 of 8,365 found). It SAMPLES ~50 tracks per group against each candidate root (drives, home, Music), dropping leading folders at the shallowest level that hits, and verifies the winner over the WHOLE group — it never walks a drive. At least one folder must survive the drop (a bare filename at a drive root is a coincidence), and a runner-up resolving ≥50% of the winner's count makes the group ambiguous — a drive and its backup clone are a question, not a ranking. Which groups to search is the adapter's call (unresolved_path_groups()): only volumes in which NO track resolves, so a few deleted files never prompt.structure.py+auto_hotcues.py— Auto Hotcues (the deck's ✨ Auto button →AutoCueDialog→POST /api/tracks/cue/auto). The user binds each slot to an EVENT (first_beat,intro_end,build_n,drop_n,breakdown_nfor n ≤ 3,outro,last_beat) plus an offset in BEATS;structure.analysefinds the events,auto_hotcues.planresolves the template and reports an outcome per slot (placed/not_found/out_of_range/occupied/protected/duplicate) — "this track has no third drop" is an answer, not a silent gap. One cue per beat: a slot landing on a beat that already has a cue — one KEPT in the bank (the grid cue, a hand-placed cue, within a quarter beat) or a new one in a lower slot — is aduplicateof that slot. A replaced cue frees its beat only if its replacement is placed, which is circular, soplaniterates to a fixpoint. How it finds them:- Everything is per bar ON THE TRACK'S GRID, bar 1 = the first marker (Traktor's convention). Bar-1 detection from audio was tried: it never beat that rule, because DJ tracks start on a downbeat.
- Per-bar kick / bass / loudness / brightness + MFCC, then an exact DP segmentation whose boundary price depends on bar position (cheap on ×8, dearer on ×4, very dear elsewhere) — the phrase bias lives in the objective, not in a snap afterwards.
- A drop is a high section entered from a low one, not a loud one: a house intro is often as loud as its drop. A breakdown is where a drop ends when another drop follows; the end of the last one is the outro's.
- Kick is the grid detector's sharp low-band onset, NOT on- vs off-beat
energy (a house bassline lives on the off-beat), and "high" does not
require a kick (drum & bass has none on every beat).
Measured against the phrase analysis Rekordbox stores for 12 local
"High"-mood tracks (PSSI; the previous detector's cues scored below a cue
every 16 bars): drops 81% on the exact bar (22/27), breakdowns 80%
(12/15), outro 42% within 4 bars —
backend/bench_structure.pyreruns it. Rekordbox's own "Up" spans the whole pre-drop groove where a DJ's build is the last 8–16 bars, so build scores against it are not meaningful. Halftime tracks inherit the grid's octave: at 174 a "bar" is half a musical bar.
grid_detect.py— beatgrid detection (the deck's Analyze button,POST /api/tracks/grid/auto). Fits ONE constant tempo + anchor to the whole track rather than tracking beats:librosa.beat.beat_track, which it replaced, quantises tempo to 23 ms frames and can only return 117.45 / 123.05 / 129.20 / 136.00 between 115 and 140 BPM. Timing comes from a 1–8 kHz attack band, and which attack is the beat from whether a kick's low end follows it — each band alone lost a real track to an off-beat hat or a syncopated bassline. Positions are in the decoded audio's time base (libsndfile = CoreAudio to the sample on MP3). Rekordbox's and Traktor's clocks both differ from it, per FILE (an MP3's header, an M4A's edit list), and are deliberately NOT corrected here but at each adapter boundary —adapters/rekordbox/timebase.py,adapters/traktor/timebase.py.backend/bench_grid_detect.pyscores it against any library's single-marker grids and reports that constant separately from detection error (29 Rekordbox references: old 1/29 BPMs, new 27/29). Either half can be HELD — the Analyze dialog's BPM / Grid ticks:bpm=keeps that tempo (no search, no round snap, no re-octave) and finds only the phase;anchor=detects the tempo and returns the anchor untouched,drift_msthen measuring how well the kept anchor fits.bench_grid_detect.py --hold bpm|anchorscores each alone (2026-10-04, 15 local refs: phase given the right BPM 15/15; tempo given the right anchor 14/15, the same miss as full analysis).grid_plan.py— what an analysis does to one track's grid, as one pure function (plan_grid→GridStep) so the batch, the dialog's counts and the tests agree. BPM+Grid = full, an existing grid replaced only with Replace ticked; BPM alone keeps the first marker's anchor; Grid alone keeps its BPM (else the track's TEMPO). With ONE tick, Replace does not apply (adjusting is the point) and a track with nothing to keep is analysed in full; a flexible grid is skipped, never flattened; locked is always skipped.main._analyse_gridwrites each through the hand-edit command for the same thing —set_grid_marker_bpm(0)/move_grid_marker(0)— so companions, marker names and time bases behave as for a hand edit.loudness.py— loudness measurement, the Mastering columns (decided 2026-10-19, the discussion): integrated LUFS (BS.1770-4 / R128 gating), LRA (Tech 3342), true peak (4x oversampled below 96 kHz), PLR (= true peak − LUFS) and RMS = the DR meter's convention: power in non-overlapping 3 s blocks, channels averaged, the mean of the LOUDEST 20%, AES17 sine-referenced (a full-scale sine reads 0 dB, a square +3) — unweighted, so beside LUFS it shows bass weight, and a long intro does not pull it down. It decodes on its OWN, at the file's rate and channels: the analysis decode (mono 22.05 kHz) cannot serve BS.1770 (it sums channel POWERS) nor true peak. Streams in chunks from per-100 ms sums, so memory stays at seconds of audio; ~1 s per track. Matches FFmpeg'sebur128(in PyAV's wheel —test_loudness.pyuses it as the reference meter) to 0.01 LU; on an inter-sample peak it is closer to exact than FFmpeg's interpolator. Mixed In Key, the requester's reference, shows no RMS or LUFS at all (researched), so nothing was matched.VERSIONbumps make stored values stale.key_detect.py+key_model.npz— musical key detection: a small CNN (Korzeniowski & Widmer 2017 — five 5x5 convs, a per-frame dense layer over the WHOLE pitch axis, since a key is not pitch-invariant, logits averaged over time), an ensemble of three, run in NUMPY — torch only trains it (backend/train_key_model.py, engine venv), the backend never imports it. Input is a 7-octave CQT at 36 bins/octave (C1–C8); the net sees C2–C7, the spare octaves are for pitch-shift augmentation. Trained on GiantSteps MTG, scored on the separate GiantSteps key set (bench_key_detect.py): 69.4% exact, 83.4% harmonically mixable; key templates (Krumhansl/Temperley/KeyFinder/EDM) topped out at 49.5% on the same features. ~0.6 s per track beside the decode. Always returns a key for music (confidence tracks accuracy, but even the lowest band is ~10x chance); None only for silence / under 5 s. The datasets are NOT on the machine by default — fetch steps are in the training script.musical_key.py— the generic key (Camelot wheel 1-12 + mode) and the three notations libraries STORE:camelot(8A),open_key(1m — Traktor's default, Open Key n = Camelot n+7) andmusical(Am, spelt as rekordbox spells its own rows: flats for Db/Eb/Ab/Bb, F#).parseaccepts all three (and "Amin", "F# minor"), because a library holds what imported tags said: a rekordbox stick's key table had "12A" beside "Abm".stem_file.py+tag_copy.py— writing a native-instruments STEM file (Convert to Stems). AnipodMP4 with five AAC stereo 44.1 kHz streams (mix, drums, bass, synths, vox), streams 1-4disposition0, muxed IN LOCKSTEP, plus amoov/udta/stemJSON box appended in place (moov is last, so only two sizes change). Each stream encodes on its own thread (PyAV releases the GIL in FFmpeg; ~3x faster withaac, 104 → 35 s for a 5-minute track's real stems) while ONE thread muxes in the single-threaded order, so the file is byte-identical; every codec is opened and the header written before a worker starts, since the firstmux()would otherwise open codecs a worker is using.aac_coder=fastwas measured and rejected: 3-4x faster per stream, but it drops whole 8-20 kHz bands for moments (twoloop: never). The separation is a CALLBACK — the backend never imports torch; the engine (below) supplies it, the tests a fake. Measured traps: FFmpeg's resampler upmixes mono at -3 dB, so mono is duplicated by hand; resampling does not move time; both encoders (aac_aton macOS,aacelsewhere) are timing-exact but decode up to ~2 frames LONGER, so length checks allow 0..2048 samples and the duration reported is the source's; AAC pre-echo fools threshold onsets, so alignment is checked by cross-correlation. Two JSON literals: the box exactly as the commercial files hold it and<STEMS>exactly as Traktor writes it — they differ in key order AND float digits (Traktor's 16 digits do not round-trip the same double; both are the same float32), so neither is derived from the other.tag_copycarries every canonical tag (ID3 / Vorbis / MP4 -> MP4, incl.tmpoand freeforminitialkey, the atoms the user's commercial stems use) and the cover, opening the target asMP4explicitly because the batch writes*.konduktor-partialfiles thataudio_tags.write_coverwould refuse by suffix.places.py— where a person keeps things on THIS computer: the user's own folders (viaplatformdirs— hardcoding is wrong on every OS differently:~/VideosisMovieson macOS, Linux's are user-configurable localised XDG dirs, and Windows Known Folders are routinely relocated by OneDrive) and mounted volumes. The mount scanner lives here rather than in the OneLibrary adapter, where it grew: "where does this OS mount things" is not adapter knowledge, the file browser needs the same answer, and two scanners would drift.is_boot_volume()compares st_dev against/, not the name, because macOS lists the startup disk in/Volumesnext to real removable media andMacintosh HDis only its default name.is_os_housekeeping()names what an OS writes into a folder by itself (.Spotlight-V100,.Trashes,._*,System Volume Information, …), so the export's "is this folder empty?" check does not refuse a stick's root just because a Mac has mounted it once.drives()splits drives intolocal(the boot disk at/, never its/Volumesalias, plus internal drives perdiskutil, cached per mount) andexternal— anything uncertain is external, so a stick is never presented as a safe place to reference tracks from; mounted.dmgs are dropped.is_hidden()reads macOS's hidden FLAG (as Finder does), not a list of names.folder.py— a folder of loose audio files read as a read-only source (FolderSource), for the sidebar's Files trees. NOT a registered driver:can_open("any directory")would make every folder a library to the picker. This folder only (the tree reaches subfolders), track id = absolute path, tags read once per folder mtime byFolderScanner— which is also the audio route's gatekeeper: only a file a scan found is streamed, so/api/folder/tracks/audiocannot read an arbitrary path. Tagged keys are deliberately dropped (every notation there is). The listed suffixes are the collection'stracks.audio_formatscapability. A stem file lists asmedia_kind: "stem"(itsstembox, read at scan time).
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".apply_stem_swapsis Convert to Stems' library side (genericStemSwap/StemSwapResultincore/adapter.py, gated ontracks.stem_convertible; Rekordbox/OneLibrary refuse): all swaps are validated before any applies. "repoint" moves the entry to the stem file (id changes; playlists follow asTYPE="STEM"); "add" deep-copies it (plus its pending tag fields and staged art, so Save still writes them to the new file). Either sets<STEMS>(the literal fromcore/stem_file), INFO bitrate/playtime/playtime_float/filesize(KB), VOLUMEID only where it still names the volume, and KEEPS AUDIO_ID (_KEEP_AUDIO_ID_ON_STEM: measured in Traktor 4.5 — cleared, Traktor re-analyses on load and re-measures a hand-set grid's BPM; kept, it touches nothing). Every START shifts by the time-base difference, the old offset read fromStemSwap.original_audio— the original's bytes where they are NOW (parked, under a non-audio name, sotimebase.offset_ms(..., suffix=)takes the original's suffix). Read from the old path it would be 0 and every cue ~51 ms late (test_stem_swap.pypins that failure). An anchor pushed below 0 moves forward by whole beats with its companion; a hotcue there clamps to 0 and is reported. The journal records scopestem(nottrack/add, which would exclude the entry from the tag sync).adapter.py(TraktorAdapter) — owns the store and theTrackIndexbuilt 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.timebase.py— Traktor's clock vs the decoded audio. Traktor decodes MP3 naively (ignores the LAME gapless fields, decodes the Xing/Info header frame as audio), so on an MP3 WITH a header every stored position sitssamples_per_frame + encoder_delay + 529samples (2257 = ~51 ms at 44.1 kHz, 47 ms at 48 kHz) later than the decoded audio; header-less MP3s and every other format are 0. Measured in Traktor 4.5 with blinded cues in both directions (kit 4, in the stem-conversion discussion log). The store ADDS it at its four seconds→START writes (time_offset_ms),projection.to_track_cuesSUBTRACTS it, and a read is never clamped at 0: Traktor anchors grids inside the header frame, and clamping would move them on the next write-back (buildBeatGridkeeps negative starts for the same reason). A file that cannot be read gets 0 and is not cached. The header itself is read bycore/mp3_gapless.py, which skips the ID3v2 tag first — a check that did not once misread every real MP3 as header-less.
adapters/rekordbox/— track metadata, playlists and hot cues writable; the beatgrid still read-only (milestones 2 and 3a). Also home toanlz_writer.py, which BUILDS analysis files from nothing — Pioneer's format, not one product's, so the OneLibrary exporter borrows it the same way it already borrowsbeatgrid.master.dbis SQLCipher-encrypted SQLite, read viapyrekordbox. Every mutating command raisesUnsupportedandcapabilities()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
PQTZtag listing EVERY BEAT.beatgrid.pycollapses 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'supdate_len(). Only.DAT'sPQTZis written..EXTholds a second "extended" grid (PQT2) whose per-beat bytepyrekordboxitself callsunkown, 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 fromPQTZ, leaves a Konduktor-written.DATuntouched, and is unbothered by the stale.EXT(which would matter only for CDJ export — out of scope). It does not reconciledjmdContent.BPM, so the adapter maintains that column itself, mirroring the first marker exactly as Traktor's<TEMPO>does. Grid edits are buffered untilsave()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 — soTrack.grid_marker_countcarries a documented approximation (1 when the track has a BPM) thattrack_cues()corrects. - Cues live in two places that must agree:
djmdCuerows and a JSON mirror incontentCue.Cues(+rb_cue_count). Rekordbox stampsrb_local_usnoncontentCue, 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/OutFrameare the position in frames at 150 fps, a cue'sContentUUIDand its mirror row'sIDare both the track's UUID, an uncoloured cue isColor=-1, ColorTableIndex=NULL, and a loop isColor=255, ColorTableIndex=0withBeatLoopSize = (beats << 16) | 1.Kindis 1-based AND skips 4 — the bank is1,2,3,5,6,7,8,9for pads A–H. Measured by writing a cue at everyKind1–8 and reading the deck: a cue atKind=4lands 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_typesowns the translation. Memory cues are editable (add_memory_cue/rename_/set_memory_cue_color/delete_memory_cue, addressed byCuePoint.id=djmdCue.ID; decided and MEASURED 2026-10-16, kit M1 in the discussion):Kind=0, no ANLZ write, at most 10 per track (rekordbox stops storing the 11th SILENTLY, so the store refuses it with a reason), and a colour of their OWN — 8 colours (memory_palette.py, display RGB sampled from rekordbox's menu), the 0-based code inColorwithColorTableIndexNULL (the opposite of a hot cue),-1never coloured, 255 after "No Color", and an unnamed memory LOOP hasComment=''._sync_content_cuewrites the mirror in ROW order (rowid), as rekordbox does — not by position. A cue on the reservedKind=4is shown as a memory cue but is not one, so it is not editable. Hot cue colour is writable (set_cue_color,PATCH /api/tracks/cue/color) frompalette.SWATCHES— all 16 of rekordbox's swatches, MEASURED (the teal-green, 0x13 #00FF30, came last: rekordbox wrote it as its default for a hot cue added on a stick); a pick must be an exact swatch (swatch_code), unlike the exporter's nearest-huecode_for. Not a breach of the promotion rule: Rekordbox, OneLibrary and Serato all colour cues — Traktor is the odd one out, by type only, so it reportscolor="none". The colour belongs to the PAD:set_cuewith no colour keeps the slot's existing code, so rename, type change and an Auto Hotcues Replace keep it; only Delete or "Default" clear it. Both columns go throughRekordboxStore._apply_color(coloured: code +Color=-1; uncoloured loop:255/0; uncoloured cue:-1/NULL). An unknown code projects as no colour but stays on the row. Uncoloured cues still DRAW in Konduktor's type colours, not rekordbox's green/orange defaults (decided 2026-10-01: those defaults are unmeasured). - Saving warns but does not block when Rekordbox is running.
pyrekordbox.commit()refuses outright, and its check is process-wide rather than per-file, soRekordboxStore._commit()suppresses that veto and logs instead — otherwise a temp copy could not be written while the user had a different library open. djmdCue.Kindis 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-issuedusnon 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 andsave()commits — which maps onto Konduktor's "edit in memory, Save writes to disk" model exactly, sincepyrekordbox'scommit()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/remixerare foreign keys into lookup tables, so a write is find-or-create (pyrekordbox'sadd_*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/mixare absent fromeditable_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 andmaster.dbcannot be replaced.AppStatecloses the previous adapter when opening a new library.
- 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
adapters/onelibrary/— editable when opened as THE library; read-only when browsed from the sidebar's Devices (read_only=True, causebrowsing). The cross-vendor USB export format (AlphaTheta + Algoriddim + Native Instruments), read by CDJ-class hardware. Editing is landing in steps toward parity with the Rekordbox adapter — track metadata, playlists, hot cues and the beatgrid, and theexport.pdbrebuild done and VERIFIED in rekordbox 7 (both library views matched); adding/removing tracks done (checked in rekordbox too) and the UI ("Open for editing…" on a Devices row) — all VERIFIED in rekordbox 7 on a real stick (2026-10-01) — decided in the editing discussion, which also holds what rekordbox 7 was MEASURED writing when it edits a stick (no update counter moves, thecuetable stays empty, a new playlist goes on top). The store never opens the database ON the drive: it works on a copy in app-data and Save writes it back whole — fingerprint check (refuses if another app wrote the stick since open), backup to app-data, temp file beside the database, stale-wal/-shmdeleted, rename — then writes edited text fields into the audio files' tags as rekordbox does (not the rating). Cue tags are read by Konduktor's ownrekordbox/anlz_file.py, NOT pyrekordbox: rekordbox writes COMPACT cue entries when it edits (48 / 44 bytes, export: 88), and pyrekordbox's parser raised on the 44-byte one and lost the whole.EXT. Cue and grid edits rewrite only the cue LISTS they touch, and inside them only the entries they touch (anlz_file.raw_entrieskeeps the rest as rekordbox wrote them), held as edited in-memory copies of the.DAT/.EXTthat every read serves, written at Save BEFORE the database (temp + rename, fingerprinted, backed up). Each rule reproduces rekordbox's own measured edit byte for byte: a recolour changes only thePCP2colour bytes (palette code- RGB — rekordbox draws the CODE, so
cues.colorispalette, like master.db); a new pad is APPENDED to its lists; a grid edit rewritesPQTZ, BLANKS.EXT'sPQT2(anlz_writer.blank_pqt2), clears every loop's beat length to 0/0, leaves.2EXalone, and setsbpmx100from the first marker. A pad keeps its colour and (unless given one) its name through a move or retype. An.EXTwithoutPCO2gets both lists seeded from itsPCOBs on the first edit — readers preferPCO2, so a one-pad list would hide the rest. A track with no analysis files refuses cue/grid edits. Memory cues are editable the way rekordbox 7 edits them on a stick (kit M2; rekordbox's own bytes arefixtures/onelibrary-memory-edits):memory_cues.pydoes the list edits — ONLY the analysis files change (the database and both pdbs keep every row); the.DATPCOBmemory list PREPENDS a new cue and is relinked as a whole (status 0, bytes 24–27 = prev/next list index,anlz_writer.relinked_memory_pcpts), the.EXTPCO2memory list APPENDS it in rekordbox's compact 44-byte form; colour =PCP2byte 28, 1-based (memory_palette.anlz_byte), name = thePCP2comment, which grows the entry by its length; cap 10. The id is content-derived (cues.memory_cue_id: stored time, kind, loop end), the same in both lists. When rekordbox rewrites a.DATit also re-sorts the untouched hotPCOBascending; Konduktor changes only the list it edits.device_library.pykeeps the stick's legacyexport.pdbin step at every Save (rekordbox's own edits let its playlists drift — measured). The stick's own pdb is EDITED (pdb.PdbEditor), not regenerated: ids are mirrored from OneLibrary (rekordbox exports both from the same ids), only the tracks / lookup / playlist tables are candidates, a table is rewritten only if a row changed, an unchanged row keeps rekordbox's bytes, and a changed track row is the old row with the edited fields overwritten — so phrase strings,masterDbIdhalves and play counts survive. A track row ends at its last string (pdb.track_extent), NOT at the next row: rekordbox's heap holds stale tails between rows. Keys and artwork are mirrored too (pdb artwork row =a<n>.jpgbeside OneLibrary'sb<n>); history andexportExt.pdbare untouched. Adding and removing tracks (tracks.places_audio: the LIBRARY places added audio, so the importer asksplace_audioinstead of the user, and the routes check space ataudio_home()): a file already on the stick is used in place, anything else is copied toContents/<Artist>/<Album>/(rekordbox's layout:UnknownArtist/UnknownAlbum, file names cut to 48 characters) via<stick>/.konduktor-incoming/, playable from there until Save moves it into place; Discard deletes it, and a crashed session's incoming folder is cleared on the next EDITABLE open (never a browsing one). Each added track is decoded once and gets the OneLibrary exporter's own.DAT/.EXT/.2EX(OneLibraryExporter.anlz_filesbuilds bytes rather than writing) and art (art_files), held in memory and written at Save; hot cues replay throughset_cue, memory cues (and a hot cue with no free pad) cross as memory cues. The row copies a rekordbox stick row column for column (search columns NULL, no counters) andproperty.numberOfContentsfollows. Removing deletes every row naming the track (playlist entries renumbered from 1) and, AFTER the database is saved, its audio, analysis files and unshared artwork, pruning emptied folders. The adapter re-projects after every save, since Save moves files.save.managed_by_exportis set when the drive's root carries an export set's.konduktor-export.json, and SaveBar warns that the next export run replaces edits made in place. Full research, incl. the schema, is in .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.pyscans mount points rather than probing fixed paths, andlayout.pyowns the on-drive layout (PIONEER/rekordbox/exportLibrary.db, analysis underPIONEER/USBANLZ/P0<xx>/<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, notcontent_id, which rekordbox renumbers from 1 on every re-export. - Cues are NOT in the
cuetable, which rekordbox exports empty; they are in the ANLZ files.PCOBis split by pad (.DATholds 1–3,.EXTholds 4 and up — reading only the.DATsilently loses pads D–H), andPCO2in the.EXTholds the complete set plus RGB colour and comments.PCO2wins,PCOBis the fallback, both merge across files first. - The slot numbering differs from
master.db.djmdCue.Kindis a sparse bank that skips 4; ANLZhot_cueis a dense 1-based index (pad D isKind5 buthot_cue4), 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_timeis0xFFFFFFFF(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 bytrack_cues(). ThePQTZbeatgrid 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.
- RGB — rekordbox draws the CODE, so
- A stem file ADDED to a Traktor collection (folder add, import, the
Traktor exporter — all
TraktorStore.add_entry) gets<STEMS>rendered from its OWN box bystem_file.traktor_stems_json(keys sorted, compact, whole floats as integers, else 16 significant digits) — measured to give Traktor's value for every local stem file and to re-render all 3,678 in the big collection unchanged, though every one of those is NI's default layout. Without it the entry read as plain audio (Type column, playlistTYPE="TRACK") while the deck, which reads the file, played stems. Rekordbox and OneLibrary have no such element, so their projections takemedia_kindfrom the FILE (stem_file.is_stem_file, only.m4a/.mp4opened, ~0.7 ms each, cached per path inRekordboxStore.is_stem) — the same mismatch otherwise: Type said audio while the deck played stems. importer.pyalso serves the folder add:reference=Trueadds each file where it is (nothing to copy or roll back), and every planned file the destination already points at (matched onaudio_path, never the displayfilepath) maps to its EXISTING id instead of being added again.PrepStriptakesorigin(collection/device/folder), recorded with the deck's track inApp— the deck follows its TRACK's library, not the view's, so browsing elsewhere cannot point it at endpoints that do not know the track.trackAudioUrl/trackCuesForinapi.tsare the one place that choice is made.stems/— Convert to Stems around the file itself.engine_manager.py: the engine version THIS build needs (engine.json) and the pinned weights (weights.json, a copy ofengine/weights.jsona test keeps equal). Installs under app-data (Windows: a SHORT%LOCALAPPDATA%\Konduktor\enginefor the 260-char limit); an install counts only after every part's hash, the archive's, AND the unpacked engine starting and naming the expected version (probe) —installed.jsonis written last. One engine at a time; CUDA offered only for driver r580+ and capability 7.5+ (nvidia-smi). Side-loading (offline) verifies against the release manifest, cached once seen.download.py: resumable (Range, restarts if ignored), SHA-verified, certifi TLS (a frozen macOS Python has no CA store).engine_process.py: oneserveper batch — progress, cancel-by-message, crash reported with the engine's stderr tail, raw work files deleted as read, a Windows Job Object andkeep_awake(caffeinate / SetThreadExecutionState). Routes:GET /api/stems/engine,POST .../install(astem-engine-installjob in bytes, engine + weights),POST .../sideload,DELETE.convert.py— the batch (POST /api/tracks/stems/previewand/convert, astem-conversionjob inBATCH_JOBS, exclusive with the engine install and import). The collection is UNTOUCHED while tracks convert (hours, on a big batch): each becomes a verified<target>.konduktor-partial, so edits made meanwhile carry over and Cancel only deletes new files. One short END STEP underSTATE.mutationthen publishes each (a rename that refuses to overwrite: link+unlink on POSIX), parks each original in Replace mode (.<name>.<ext>.konduktor-parked, same folder, hidden on Windows, retried while Windows holds it open) and swaps every entry at once. Skips (reported, not failed): already a stem file BY CONTENT, missing file, target exists (never overwritten), two sources onto one (case-folded) target, a target the collection names; disk space is preflighted per volume (both copies coexist until Save) and for the work folder. Replace implies repoint; destination mode mirrors the tree (full path, volume first, when the tracks share no folder) and may repoint or add (+ existing / new playlist).pending.py— the ledger of conversions awaiting Save (per library id, atomic):AppState._saveCOMMITS (deletes parked originals, retargets export sets — inside_save, so import and remap saves count too),discard()and opening another library RESTORE, and_openRECOVERS a crash before the missing-files check (parked originals would look missing): each item decided by whether the SAVED library names the stem file. Every step works from what is on disk, never the recorded state alone; only a stem file the batch PUBLISHED is ever deleted; an uncommitted verified stem file is kept under its partial name and REUSED by the next batch converting the same (unchanged) source. While conversions are pending or running, remap-paths, path mapping, relocation, import, folder add, history restore and reload answer 409 (_require_no_pending_stems): each would save or drop the swap./api/statereportspending_stems,stem_job,stem_recovery.stream_cache.py— stem PLAYBACK. A browser decodes only an MP4's FIRST audio stream (the mix), so each stem is served as a file of its own: the three audio routes (collection /source/folder) take?stem=0..3, and/api/…/tracks/stemsreport[{name, color}]read from the FILE (stem_file.stem_layout: the box, and enough streams — never the library's<STEMS>, which plain MP3s carry).stem_file.extract_streamCOPIES packets into anipodMP4 — measured bit-identical to decoding the stream in place, edit list and priming (1024 / 2112) intact, on commercial stems too, so stems stay sample-locked to the mix and the cues. Cached in app-data keyed by path + size + mtime, LRU under 2 GB, written partial → rename; ~0.1 s per stem uncached.app_state.py— the one loaded library, and the version-history commit.discard()(POST /api/discard, SaveBar's "Discard changes…", the quit prompt's Discard) drops every unsaved edit through the adapter's ownreload, NOTopen— reopening would re-run the missing-files check and forget this session's relocation answers. The route stops (and WAITS for) running batches first, as library open does (_stop_batches), or a batch would keep writing into the reloaded library. Rekordbox's reload is a real discard (RekordboxStore.discard): session rolled back and closed with its engine, buffered ANLZ grids and journal cleared — before, it opened a second connection and stayed "dirty". A reentrantmutationlock serialises open / save / discard (and, next, a stem batch's swap step). History is app-level: the adapter returns the bytes it wrote plus a summary, andAppState.save()versions them. Every write path must go through it. Where it is versioned is the open library'sservices(services.py):LocalServicesis the history repo in this computer's app-data, keyed by path (what it always was); a remote library's live on its server. Routes reach history throughSTATE.services/STATE.restore_version, never thehistorymodule withSTATE.path.open_hooksrun at the end of every open (and restore) — how the server re-applies its configured path mapping.- Remote libraries (decided 2026-10-01/02 —
the discussion):
the whole library on the user's NAS, a Konduktor SERVER in a container
holding it, the desktop app opening it as "Remote". Three pieces:
remote_protocol.py— the wire contract BOTH sides import: theLibraryAdapterprotocol itself as RPC (RPCtable,MUTATINGflag,EXCLUDEDwith a reason for every member that does not travel —test_remote_protocol.pyfails on a protocol member that is neither), args/results (de)serialised by pydanticTypeAdapters built from the protocol's own hints (a misspelt argument is refused, not defaulted),API_VERSION(same major, server minor ≥ client's), the lease (LEASE_SECONDS120 /HEARTBEAT_SECONDS15),WireNewTrackand the prepared-analysis.npzpacking. Bytes never travel as JSON.server/—python -m konduktor.server(the container's command;server/Dockerfile,compose.yaml,.env.example). NOTmain.pybehind a password.config.pyreads the env (KONDUKTOR_PLATFORMchecked against the file,_LIBRARY,_CONTENT,_USERNAME,_PASSWORD,_PATH_MAP"stored => here; …") and fails fast with one line.app.py: HTTP Basic on every route;/v1/hello,session/*,rpc/{method}(every answer carriesrevplus the tracks itchanged/removed),audio(Range),art,upload(into a folder CONFINED to the content folder — resolve thenis_relative_to, so neither..nor a symlink escapes — never overwriting,-2suffixes, per-session so a cancel deletes only its own),fs/list|space,folder/tracks|audio|leads(the content folder as a Files tree: tags via the sharedFolderScanner, file facts,held= file → the library's id; audio only for a file a listing returned, confined;leads= the analysis lead per file, None unless the platform analyses),save,discard,history,export-sets, and the stems routes below. Capabilities are the adapter's plustracks.audio_destination="library",reference=False,paths.remappable=False,overwrite_risk="none".session.py: ONE holder; a 409 names who holds it (machine, since, running batch) andtakeoverreplaces it; the old token is 423 from then on; a lapsed lease is renewed silently for the SAME client if nobody took it. Unsaved edits are the native model's, not the session's: the next holder inherits them andpending_edits(last_editor+ the adapter's optionaledit_summary()) asks them to save or discard. A container restart loses them — accepted. Lightweight by decision: the server never decodes audio — its image shipsrequirements-server.txtwithout librosa / scikit-learn / PyAV, andtest_layering.pychecks importing it pulls none in (stem_file._audio_stream_countcountssountraks when PyAV is absent). With a path mapping configured the server calls the adapter's optionalset_write_stored_paths(True): a file added (or a stem file swapped in) through the mapping is written in the library's STORED form (pathmap.stored_form), so the collection keeps one convention and still opens where it was made.adapters/remote/— the client, imports no platform adapter.RemoteAdapterIS aLibraryAdapter: the frontend, export, import and batches never learn a library is remote. It mirrors the projection in a localTrackIndex(same query code), folds each command'schangedinto it, and re-fetches on anyrevgap.audio_pathdownloads into the sharedcache.py(keyed by the server'sAudioFacts— path, size, mtime — partial-then-rename, LRU underremoteCacheBytes, the recently used never evicted); anything that needs only a file's IDENTITY asks the new protocol memberaudio_facts, which never downloads (exporter.plan,importer._existing_files).client.pytries the address that last worked, then the others (primary → fallback) on CONNECT failures only, and maps status codes back onto the adapter error classes (423 →SessionLost, unreachable →Unavailable, 503 inmain.py).session.pyheartbeats (reporting the running batch) and movesconnected / reconnecting / offline / taken_over; anything but connected/reconnecting makescapabilities()read-only with causetaken_over/offline, and a 423 on any command flips it at once; taken over cancels this computer's batches (_on_remote_change).config.py: saved remotes in prefs (remotes, plus a stableremoteClientId), passwords in the OS keychain viakeyring(use_password_storeis the test seam).services.py: history, export sets (exports.use_store, keyed byremote:<server id>so nothing on this computer is mistaken for the server's) and the stems ledger (RemotePending) all on the server. Imports UPLOAD (importer.uploads_audio→upload_audio, cleaned up on failure; free space from the server) into a folder the user picks on the server; Rekordbox's add analysis — waveform, grid AND key — is computed HERE (core/add_analysis.preparewith the lead the upload reports, sent asNewTrack.analysis). The content folder browsed like a drive (decided 2026-10-10,folder.py):/api/fs/driveslists the server FIRST (kind: "server", pathserver:) while a remote is open, and the ordinary Files routes (/api/fs/folders,/api/folder/*) takeserver:+ the path ON THE SERVER — so the folder view, deck and add dialog need no second set of routes, and a server path is never taken for the same path here.RemoteAdapter.folder_listingremembers what was listed (ServerFiles, a read-only source);folder_audiodownloads into the shared cache by the same facts as a library track's. Adding one is IN PLACE (on_library_host→importer.plan_on_host+run(reference=True)): nothing uploaded, nothing asked; files the library holds map to their ids; where the server reports a lead the file is fetched and analysed here, as an upload is. Server paths go back to the server in its own spelling (_server_paths), neverstr(Path(…)), which rewrites them on Windows. Convert to Stems (stems/remote_convert.py): the server plans (/v1/stems/plan, itsconvert.plan), this computer downloads, separates and encodes, uploads each verified file (/v1/stems/stage, sha-256 checked, kept on the server as a LEFTOVER), and the server runs the ordinaryconvert._end_stepunder its mutation lock with its own ledger (/v1/stems/publish). Cancel abandons this run's uploads; a takeover cannot, so they stay and the next run reuses them. The preview addstransfer(download / upload / measured speed) and space lines for both machines. UI: the picker's platform list ends with Remote (selects: "remote") →RemotePicker(saved remotes; the form saves only afterhandshake— a wrong password or version refuses, an unreachable fallback alone does not; the in-use → Take over and the leftover-edits Save / Discard / Decide-later prompts happen before the library shows).Apppolls['state']every 5 s for a remote (remoteinEditState), re-reads capabilities on a change and toasts it;StatusBarshows the connection.FileBrowser/FolderPickertakelisting="library"for the server's folders; Import / Add Files / Convert to Stems use it whentracks.audio_destination === 'library'(folders remembered per remote:remoteImportFolders,remoteStemFolders). Settings → Remote audio is the cache. Path remapping hides onpaths.remappable === false.
library_id.py— a stable identity for a library that survives it being moved. Everything else keys off the OS path (historyhashes it,prefsstores it), which is fine for things a user shrugs at losing and NOT fine for export sets, which are curated work holding references into one library. Two halves, only the first authoritative: a hidden.konduktor-library.jsonsidecar beside the library, which moves with it, plus a disposablelibraries.jsonindex in app-data. The id is random — deriving it from the path defeats the point and from the contents would change on every save. The sidecar is keyed by filename, because one folder can hold two libraries and a single id per folder would hand both the same identity. A removable library gets no sidecar (writing to a user's USB stick for Konduktor's bookkeeping is not a trade worth making) and falls back to a path-derived id thatis_durable()reports honestly. Writing beside the library is not a new intrusion — saves already createbackups/there.exports.py— export sets: a named, persisted slice of the library bound to a destination and one or more target platforms (targets, never empty; a set saved with the old singletargetloads as a one-item list). The targets share the destination and ONE copy of the audio — their layouts (collection.nml;PIONEER/…;master.db+share/…) do not collide. Konduktor's OWN data, never written into the user's library (a Traktor collection has nowhere to put it, and it would live in a file Traktor rewrites). Three rules shape it: references are LIVE (a set stores playlist ids, resolved at export time, soresolve()is computed on every call and NEVER cached); a playlist is removable only as a whole (a live reference plus per-track removal needs an exclusion list, i.e. hidden state silently deciding what a future export contains); and it is keyed bylibrary_id, not path.resolve()dedupes across playlists and loose tracks — one track, one file copy — and SURFACES what is gone rather than dropping it, because a gig stick quietly missing four tracks is this feature's worst failure.retarget()follows ids through a path remap, which/api/library/remap-pathscalls with a before/after snapshot.relocation.py— the open-time missing-files check.AppState.open()starts aRelocationCheckthread (after the saved mapping is applied, so a volume it fixes is not asked about);GET /api/library/relocationserves the proposals untilPOSTanswers them (no mappings = Not now), then serves nothing — "ask once per open" lives here, not in the UI, which would re-ask on every refetch. Answers are session-only (set_session_mappings, applied inTraktorStore._resolveBENEATH the saved mapping and only for a file not found as stored): never written to the library, which would change every Traktor track id, nor to prefs, so a reopen asks again. Only a mapping the search proposed is accepted. Traktor only for now; Rekordbox/OneLibrary return no groups.RelocateDialogalways asks — found volumes ticked, ambiguous ones a radio with nothing preselected, missing ones "Not connected" with a "Map by hand…" link toPathMappingDialog; no backdrop-click dismiss.loudness_store.py— where loudness lives: Konduktor's own store, keyed by the audio file's PATH (SQLite in app-data; stdlib, so the server has it too) — never the library, never file tags (a measurement can be redone from the audio, and nothing but Konduktor would read a tag). Size + mtime are recorded but are NOT the key: a changed file keeps its value, shown STALE (dimmed, still sorted on, offered for re-analysis), because a changed mtime almost always means another app rewrote the tags.AppState._saverefreshes the facts of every file Konduktor itself just tagged, so its own writes never stale a value;/api/library/remap-pathsremaps the keys. Written AT ONCE, outside the edit/Save cycle — never dirty, survives Discard.STATE.loudnessis this computer's store, or for a remote libraryRemoteLoudnessStore(the SERVER's:/v1/loudness/get,PUT /v1/loudness— session required, nottouched).main._loud_target(origin, id)picks source + store per id: collection = the library's; device / Files folder = this computer's; a folder id that is not a listed file falls back to the collection (a folder view's held rows)./api/loudnessserves a list's values throughaudio_facts(never downloads); Analyze's Loudness tick and/api/tracks/loudness(the deck where no grid can be written) measure, for ANY origin — BPM / Grid / Key stay collection-only (400 otherwise). Convert to Stems RE-measures a stem file whose original was measured (AAC can move the true peak; never carried over):convert.stem_loudnessafter the build, stored at publish by the shared_end_step— remotely, the value rides/v1/stems/stage.prefs.py— persisted user prefs (userprefs.jsonin the per-OS app-data dir). Last-opened collection (global AND per-platform), library column layout, prep-deck zoom, import destination. Best-effort, but every read-modify-write holds_LOCKand every write is atomic (paths.write_json): the UI sends several PATCHes at once on launch, and unlocked, with a truncating write, a reader caught the file empty and wrote back only its own key — wiping every pref, the column layout included. A file that will not parse is moved touserprefs.json.corrupt, never silently overwritten. New helpers that read then write must take the lock.schemas.py— HTTP request bodies + envelopes; re-exportscore.model.main.py— thin FastAPI routes (all under/api), talking only to the adapter. Starts unloaded; the library is chosen at runtime viaPOST /api/library/open(data routes 409 until then).GET /api/capabilitiesfeeds the UI's gating;GET /api/fs/listpowers the file browser;GET/PATCH /api/prefspersist UI prefs. SettingKONDUKTOR_NMLauto-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 — reportsselects,removableandfound, 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) and/api/fs/places(the browser's sidebar — the user's folders, then drives, plus that platform's own location when it keeps one at a fixed path; a place that does not exist is omitted, never disabled, since a greyed-out Music folder reads as breakage where its absence reads as an accurate description of the machine)./api/library/openchecksexists(), notis_file()— which shapes are valid iscan_open()'s business, and a OneLibrary library is a drive.prefskeeps last-opened per platform: offering a Rekordboxmaster.dbto someone who just chose Traktor is an offer that cannot be taken.
-
engine/— the stem engine, a separate program (konduktor_engine, Python 3.12, torch 2.14 + demucs 4.1 pinned inengine/requirements.txt) that imports nothing fromkonduktor, built and released on its OWN channel.core.pyloads htdemucs_ft from a LOCAL weights folder — never online: the weights' licence rules out shipping them, so the app downloads them, pinned by revision + SHA-256 inengine/weights.json(fetch_weights.pyfor CI/dev). Seeded — and demucs draws its random shift from PYTHON'srandom, not torch's, so both are seeded or no two runs match.serve.py: one process per batch, the model loaded once; JSON requests on stdin, JSON-line replies on a private copy of stdout (sys.stdoutpoints at stderr, since torch prints), one lock for writes from two threads. A reader THREAD ends the process the moment stdin closes — the backend dies without killing children, and torch keeps the main thread busy.cancelraises from the progress callback and keeps the model loaded; CUDA OOM falls back to CPU for that track; the process lowers its own priority.inforeports the CUDA card, capability and the build's arch list, which is how the app decides whether to offer the CUDA engine.- Frozen as a PyInstaller onedir (
konduktor-engine.spec; onefile would re-extract ~500 MB per launch),torch/includeand the HF client dropped: macOS arm64 = 164 MB download / 550 MB unpacked, runs after a tar round trip (ad-hoc signature intact).test_engine.pypins the protocol (reproducible seed, cancel, stdin-EOF exit) and, with--frozen, that the frozen build separates BIT-FOR-BIT like the unfrozen code (CPU). package.py→ tar.gz (zip loses exec bits on macOS), split under GitHub's 2 GiB asset cap, per-part SHA-256; symlinks are archived as links and not double-counted..github/workflows/engine.ymlbuilds macos-arm64, windows-x64-cpu and windows-x64-cuda (torch cu130: Turing–Blackwell, driver r580+; older cards get the CPU engine), runs the golden test on CPU (runners have no GPU), checks Windows path length, and on anengine-v*tag publishesprerelease/ NOT latest with anengine-manifest.json.backend/dev_stems.py(dev only) converts files with the real writer through an unfrozen engine, and can swap them into a collection.
-
frontend/— React + TypeScript + Vite. A dark, virtualized track explorer. Entry: frontend/src/App.tsx.api.ts— typed client + all API types. Generic, not Traktor-shaped: cue types are the stringscue/fade_in/fade_out/load/loop, a cue has arole(hotcue/memory) and a nullableslot, andeditable+readonly_reasonsay whether the adapter will accept a command on it — gate oneditable, never on a platform-specific reason likegrid_marker. Keep in lockstep withcore/model.py; land both in the same commit.lib/capabilities.tsx—useCaps()overGET /api/capabilities. The app does not render until capabilities resolve, so no first frame can offer an edit the adapter would reject. Containers calluseCaps(); 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/—FileBrowser(the one file browser: places rail + path bar + listing,mode: 'file' | 'directory'. Deliberately NOT the chrome or the confirm footer — its two callers frame it very differently, one as a step inside a full-screen card and one as a modal over the import dialog, and a shared wrapper would put a modal inside a modal.pathis controlled, because the caller needs to know where you are standing to label its footer;useFsListing()is exported so the caller reads the RESOLVED path through the same query key rather than being told it by an effect. The rail navigates, never selects — one click there must not be able to open a library or commit an import destination. It polls, because drives come and go while a dialog is open, and the volatile Drives group is LAST so an appearing drive cannot shift the rows above a moving cursor),ExportsSection+ExportDialog(exports in the sidebar — each a named, persisted slice of the library bound to a destination. An export expands to show its referenced playlists, whose counts come fromcontentsrecomputed on every read, because the references are LIVE. Two deliberate omissions: a referenced playlist has no per-track remove — that would need an exclusion list, i.e. hidden state deciding future exports — and an export's views passTrackTablenoonRemove/reorder— in a playlist those act on the user's REAL playlist: same pixels, opposite meaning. Removal from an export is on the context menu, and only on its root view. Adding is not gated on the library being writable, since an export set is Konduktor's own data.ExportDialogshows unsupported targets disabled with a reason rather than hiding them),DevicesSection(every drive, polled from/api/fs/drives: external ones under Devices, the computer's own under an expandable Local Storage. A drive carrying a OneLibrary library opens as a device as before, and EVERY drive has a lazily-fetched Files tree; clicking a folder is thefoldersource kind — its audio in the ordinary table, with files the collection already holds checked off in the # column (TrackTable'smarked). A held file's row IS the collection track (decided 2026-10-10:main._folder_rows;FolderTracks.filesmaps its collection id back to the folder id that adding takes): it shows the collection's key/rating/cues/plays, loads into the deck as origincollection(loadTrack), edits inline and from the menu, and drops onto a playlist directly. The table runs on the COLLECTION's capabilities; a LOOSE row's edit — inline (TableMeta.mayEdit, asked before the editor opens), rating, Edit Tags / Analyze / Auto Hotcues / Stems — asks to add it first (askToAdd), and in the deck it stays read-only (not_in_library). A browsed device is read-only (causebrowsing); "Open for editing…" — the drive row's right-click menu, and a button while browsing a device whose caps saybrowsing— opens it as THE library via App'sopenForEditing(unsaved-edits confirm, source closed, library opened). Capped at 40% of the sidebar and self-scrolling so a deep tree gives way before the playlists do) +AddFilesDialog(copy vs. leave in place is asked every time with nothing preselected — the answer depends on the drive — and warns that a referenced file on an external drive goes missing on unplug. A playlist/export target adds to the collection first and says so; it runs throughimporter.run(reference=…, into_playlist=…). A library withtracks.places_audio(a stick) is the exception: no question and no destination — the dialog STATES how many files are copied and how many stay in place (platformCopy.placedAudioSummary), andImportDialogdrops its destination folder the same way),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.selectsdecides 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 withforcePickernever 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. Creating is right-click only: a folder's menu offers New Playlist / New Folder inside it, empty space below the rows creates at the top level, and the new node is named in place (Esc or an empty name creates nothing). Rename/Delete are on the same menu and the row's hover buttons, which share one set of actions. Drag and drop (lib/drag.tsx, below): a row is a drag source and a drop target with ZONES — a playlist's upper/lower half is before/after; a folder's top/bottom quarter before/after and its middle INTO (appended), except the bottom quarter of an OPEN folder, which is "first inside"; the empty space below the rows is "end of the top level". Never into the dragged node's own subtree, and a drop that would change nothing shows no indicator. Holding over a collapsed folder opens it after 0.6 s (tracks too, so nested playlists are reachable). Tracks dropped on a playlist go throughlib/addTracks.ts— shared with the context menu's "Add to" — which ASKS about duplicates where the platform can hold them (decided: ask each time), and Cmd (Ctrl on Windows;lib/modKey.ts) moves them out of the editable playlist they came from. A device's or Files folder's tracks openImportDialog(trackIds+target) /AddFilesDialogwith the target filled in (onAddForeign), so copy-vs-reference is still asked. Export rows take the collection's tracks and any playlist/folder (as "Add to export" does). A Traktor folder's id is its PATH of names, so thePATCH/DELETEplaylist routes take a:pathparam, a folder name may not contain/, and renaming onto a sibling folder's name is refused),QuitGuard(mounted inmain.tsx: the desktop shell PREVENTS window close / Cmd+Q and emitskonduktor://quit-requested; this acks it (quit_ack— the shell quits anyway after ~2 s without one, so a hung page cannot trap the user), quits (quit_now) when nothing is unsaved, else asks Save · Discard · Cancel; the sidecar is killed only atRunEvent::Exit, after the answer; browser dev getsbeforeunload),StartupGate(mounted inmain.tsxaround everything butAmbientBackdrop: the shell opens the window AT ONCE and starts the sidecar beside it, so nothing that calls the API mounts untilbackend_status/konduktor://backendsays ready, which is whensetApiBasegets the sidecar's address. MeanwhileStartupScreenshows the icon with a generated waveform scrolling under a fixed playhead, a "first launch takes longer" note after 6 s, Quit / Keep waiting after 90 s, and if the sidecar exits its last 30 output lines with Copy details / Quit / Try again (backend_restart). The shell has no timeout of its own. Before ready it answers quit requests itself — nothing can be unsaved — and stops at ready so it never racesQuitGuard),SaveBar(+ "Discard changes…" when dirty, and the settings gear beside it, whose menu (or?anywhere) opensShortcutsDialog— a KEYBOARD MAP (decided 2026-10-15): keys lit in the colour of what they do, a caption explaining the key pointed at or pressed (pressing explains, it never acts: a capture-phase listener keeps the deck's and table's keys from firing), holding or picking ⇧ / Cmd-Ctrl relights it with that layer, mouse gestures listed beneath. It shrinks to fit the dialog and drops the words on the keys when too small. Its content islib/shortcuts.ts, written out BY HAND, so a new or changed shortcut inPrepStrip/TrackTablemust be added there too — andAppSettings("Konduktor Settings…": app-level prefs, each with its default inAPP_SETTING_DEFAULTSand read throughuseAppSetting; todayexpandPlaylistFoldersandexportRootFolder, both default off — the latter read by the backend atrun_exportand passed down asExportPayload.root_folder— andtimeReadoutDecimals(0–3, default 1: the deck's ELAPSED / REMAIN, truncated, never rounded). The Sidebar holds folder open state as per-id overrides of that setting, reset on a new library or a change of the setting, and carried to the new ids when a rename/move changes a folder's path id)),Toolbar(search/filters; columns are chosen by right-clicking the table header),TrackTable(the one track list — All Tracks, playlists, exports and devices. TanStack Table + virtualized grid; per-row play button, configurable columns, header sorting, inline double-click editing, and Finder-style row selection — click / Cmd-Ctrl+click / Shift+click over the SORTED rows, ↑/↓ (Shift extends), Cmd/Ctrl+A, Esc, Enter (load + play the highlighted row, winning over a focused button); shortcuts stand down while anaria-modaldialog orrole="menu"is open, so new dialogs needaria-modal="true". Right-click acts on the whole selection; single-track items are hidden for a multi-selection. A view with a manual order passesreorder(drag rows — the whole selection moves as a block — with an insertion line and edge auto-scroll);enabledis false while a sort or filter is active, so a partial or re-sorted order can never overwrite the real entry list.onRemovewires Delete/Backspace;positionsmakes the # column show playlist positions. Playlists gate both on the node's owncan_reorder, so smart playlists get neither. Row reorder is hand-rolled, not dnd-kit sortable: a SortableContext around the virtualizer loops on its flushSync-driven measurement — which is why playlists were once a separate, non-virtualizedPlaylistTable. Fixed 44 px rows make the drop index just pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns. Every table's rows are a DRAG SOURCE throughlib/drag.tsx(a selected row carries the selection, the payload'sleadis the row grabbed,dragFromsays whose ids they are and which editable playlist a Cmd/Ctrl-drag leaves — a Cmd/Ctrl press arms a drag, and stays a toggle-click if it never moves); the in-table reorder is just the table's own drop target.)lib/drag.tsx— drag and drop across the window (decided 2026-10-06, the discussion): ONE gesture, the TARGET decides what it means. Pointer events, NOT HTML5 DnD — Tauri's webview captures native drag events for file drops on Windows. A source callsbeginDragpast a 6 px threshold (usePressToDragfor plain elements); targets register withuseDropTarget({ hint, label, onDrop })and are found byelementFromPointthen up the ancestors, the innermost whosehintis non-null winning, so a target declines a spot by returning null. A module-level store read through narrowuseSyncExternalStoreselectors: a move re-renders only the target under the pointer and the ghost (DragLayer, mounted in main.tsx), never the table. Esc cancels (before every other Esc handler); the click after a drop is swallowed;data-drag-scroll="<top inset>"makes an element scroll at a 20 px edge after a 250 ms dwell — any less and the first/last visible row could not be dropped on. Targets: playlist + export rows (Sidebar, ExportsSection), the tree's zones, the table's reorder, and the DECK (App), which loads the grabbed row paused, in its own origin. An open editable playlist's TABLE (and its empty / no-match state) also takes files and Files/device rows (TrackTable.foreignDrop,drag.isForeign; decided 2026-10-17): the add dialog opens with the playlist as target at the insertion line — appended while sorted/filtered — and both add dialogs offer "Also add to " (usePlaylistToggle), ticked every time, never remembered; unticked = the collection only. Wherever a playlist is the target, the sidebar's drop included. Files from Finder / Explorer (decided 2026-10-13) ride the same store as afilespayload:lib/fileDrop.tsfeeds Tauri'sonDragDropEvent(real paths; a plain browser has none, so no file drop there) throughnativeDragStart/Move/End, refused at enter while anaria-modaldialog is open or no library is loaded. A playlist/export row opensAddFilesDialogwith its target, ONE audio file on the deck loads it to listen to, anywhere else (App's root target, with a window overlay) adds to the collection — or says why the library cannot.POST /api/folder/droppedresolves the paths first (FolderScanner.dropped: folders RECURSIVELY, capped atMAX_DROPPED; single files held apart from the folder cache so a partial listing never hides a folder's other files from the sidebar) and makes each file addable and playable through the folder routes. Copy vs in place is asked as for a browsed folder; the add preview counts external-drive files PER FILE (removable_count/removable_drives, a drop can mix drives) andin_destination.ConvertStemsDialog(Convert to Stems, one dialog — decided: Where = Replace the originals (its option STATES that Save deletes them, since the choice is remembered and may be preselected) or Save to a folder; In the collection = point at the stem file / add as new tracks + playlist (folder mode only); a live preview fromPOST /api/tracks/stems/preview— N to convert, skipped ▸ with reasons, a time estimate from measured real-time factors, space; the engine download INLINE, offering the GPU engine whennvidiais set, which keeps running if the dialog closes (App shows it in the status bar). Every option persists asstemConvert),StemReportDialog(the Details behind a finished run's toast — every skipped/failed track with its reason),StemsSettings(Settings → Stems: engine status / download / install from a folder / remove, compute devicestemDevice, the remembered defaults, originals awaiting Save). App follows a finished run's{old: new}ids with the deck and the selection, picks a running conversion back up from/api/state.stem_jobafter a reload, and reportsstem_recoveryonce. The menu item is shown DISABLED with a reason (MenuItem.title— renderedaria-disabled, notdisabled, since browsers show no tooltip on a disabled button) where the platform cannot play stem files as stems. SaveBar adds "Saving deletes N original files" while conversions are pending (decided: the consequence is shown where Save is pressed).Toasttakes an optionalaction;StatusJob.unit: 'bytes'shows a download in MB. Every background job's status-bar entry reads label + count · a bar SPLIT horizontally when the job reports per-item progress (top = the current item'sfraction, 0-100 %; bottom = the whole job, (done + fraction) / total, so 99 % into the first of two tracks reads ~50 %) — a single bar otherwise; two colours in one bar was tried and read as confusing · itsstatus("separating 41 %") at its natural width · the item's name LAST (the only part that truncates; full name on hover). The section is a FIXED width (560 px; the view name on the left gives way instead) and everything BEFORE the bar is fixed (count sized for its largest value, "cancelling…" as a status, not a label), so neither a long name nor a phase change moves the bar. The status deliberately has no fixed slot: it is after the bar, and a slot left a gap before the name.Job.fraction/statuscome fromJobHandle.progress(fraction=, status=)and reset wheneverdoneadvances; a stem conversion maps decode / separate / encode onto a track's 0-1 by measured shares.AnalyzeDialog(the context menu's Analyze…, decided 2026-10-04: BPM / Grid / Key / Loudness ticks, remembered asanalyzeWhat(a tick that was disabled keeps its saved value), BPM / Grid / Key each disabled with a reason where they cannot be stored (gridWhy/keyWhy: a device, loose files, a read-only library). Loudness is never disabled, so the item is offered for ANY selection, with the selection'sorigin(2026-10-19); where loudness is all that can be done it is pre-ticked. The Replace questions (loudness: "Measure again") are inside the dialog, never a second popup, and never remembered: the grid's only when BPM AND Grid are ticked, since with one tick adjusting the grid is the point. Every count and the "Analyze N" button come from/api/tracks/analyze/preview, i.e. the backend's ownplan_grid. The finished job's toast says what was written and skipped, by reason. The deck's one-click Analyze writes the key too, and App hands the deck the fresh copy of its track whenever the view it came from refetches — the deck otherwise held a load-time snapshot, so neither an analysed key nor an Edit Tags change reached it),AutoCueDialog(the Auto Hotcues slot template: event + beat offset per slot, a per-slot Replace tick for occupied slots — never remembered, since overwriting is a decision about THIS track — and the template itself persisted asautoCueTemplatein userprefs. Also has a batch mode for the context menu: same template, but it starts a job viaonRun, and each tick reads "Replace" and applies to every track in the batch. A Replace RENAMES the slot's cue —set_hotcuekeeps the old name only when called without one, which is what a hand move does),ContextMenu(supports▸submenus, section headings, separators and checkbox items that toggle without closing — the header row's right-click column chooser uses those; "Add to" lists playlists + exports and acts on the whole selection; in an editable playlist "Set Position…" (SetPositionDialog,lib/playlistOrder.ts) moves the selection as ONE block so its first track lands at #N — allowed while sorted/filtered, unlike drag, because it reorders the FULL entry list. While the table is sorted the dialog asks the block's Order: "As sorted" (default; the menu's ids arrive in VIEW order, so the sort is written into the playlist and survives clearing it) or playlist order; "Remove ▸" holds From this playlist / From this export / Grids / Hotcues / From collection, each behind aConfirmDialog— as is the playlist Delete key. Enter confirms unless a button has focus, so Tab-to-Cancel + Enter cancels) +EditTagsDialog(right-click → multi-field metadata + album-art edit),StatusBar,RatingStars(read-only, or click-to-set when givenonChange),Toast,UpdateDialog(UpdateCheck, mounted inmain.tsxbesideAppso it shows even on the picker screen: on startup lists recent GitHub releases and takes the newest non-draft, non-prereleasev…tag — NOT/releases/latest, since the stem engine publishesengine-v*releases in the same repo — and, if its tag's semver part is newer than__APP_VERSION__— build-number-b<N>bumps don't count — shows an update dialog with the release's "What's Changed" bullets; "Skip this version" persistsskippedUpdateVersionto userprefs via/api/prefs; check failures are silent. In the desktop app, Update installs it (decided 2026-10-16, the discussion):update_download(lib.rs, tauri-plugin-updater) reads THAT release'slatest.json, downloads with progress in the dialog, verifies the signature and STAGES the package in app-cache;update_restartthen quits through the ordinary quit request, so QuitGuard asks about unsaved edits. The package is installed inexit_now, only AFTER the sidecar is killed — on macOS the running backend lazily loads native libraries from inside the bundle being replaced, on Windows its.exeis locked (the shell waits until it can open it for writing) — then the app relaunches. Cancel in QuitGuard keeps it staged (konduktor://update-deferred) and the next ordinary quit installs it without relaunching. On macOS a bundle run from the DMG, translocated, or in a folder the user cannot write is refused BEFORE downloading (the updater's own admin-password fallback runs on the main thread, which the quit path may hold). Any failure shows its reason + "Open release page" (the old Download, still the button in a plain browser); an install that failed at exit is written tofailed.jsonand reported by the next launch (update_take_failure). The updater's crate is built WITHOUT itszipfeature — only for v1-style zipped Windows installers, and every zip 4.x is yanked.- Stem playback (decided 2026-09-30): a stem FILE always loads its four
stems (
trackStemsFor/trackStemUrlinapi.ts) and the deck plays their SUM, as Traktor's stem deck does — the mix stream is never decoded, which also saves a full-length buffer.PlaybackEngine.loadtakes several buffers: one source + gain each, all started at ONE scheduled context time (so they stay sample-locked through seeks and loops), mute/solo as ramped gains, never a restart.ScratchEngine.loadStemskeeps ONE summed copy of the audible stems (not four), re-summed in slices on a mute change.analyzeStemsreturns the overview's three-band columns (of the sum) plus one amplitude lane per stem, each normalised to its own 99.5th percentile but never below 5% of the loudest (a silent stem stays silent).MainWaveformdraws the lanes in the file's own colours with a mute button at each lane's left edge (click = mute, Cmd/Ctrl-click = solo); Q W E R mute stems 1-4, Shift+ solos. Solo is not a mode: it SETS the mutes (every other stem muted), so each stem stays freely mutable after it; soloing the one stem still playing unmutes all. Mutes reset per track. Memory is the cost: ~140 MB per stem for 6 minutes, i.e. the same four buffers as the file holds streams, and no more. - Prep strip (DJ deck across the top of the window):
PrepStripowns it, in three rows. Header: cover, title/artist · album · genre, a Read-only badge, the readout well (ELAPSED / REMAIN to tenths, KEY, andBpmReadout— click to type an exact BPM; with no grid, a typed or tapped BPM CREATES one at the playhead, and Set grid on a track with no BPM opens the readout to ask rather than failing), SNAP, Analyze, Auto hotcues. Waveforms:MainWaveform(scrolling; zoom +/− in its corner and Cmd/Ctrl+scroll, 0.25–64 s across, owned byPrepStripso it survives track switches and persists; a toggle under the zoom buttons draws the RAW signal instead of bars —lib/rawWave.ts, below; persisted asmainWaveRaw) overOverviewWaveform, which frames the main view's visible range around the playhead (it takessecPerViewfor exactly that). Controls: play, CUE,LoopControls, then (wherecues.memory_cues) the Hot / Mem switch (ModeSwitch, the same component as BEAT / MAN), thenHotcueBar,MemoryCueStrip(Mem) OR — in Grid mode —GridEditStrip, thenTempoControls(±0.01 / ±0.25, ÷2 ×2, tap, lock) and the Grid toggle. The row is a container and gives way in stages instead of overlapping: each pad queries its own width and drops its name below 4rem (the bank never goes belowPAD_MINper pad), then the tempo group folds intoTempoFold's portalled popover, then Grid keeps only its icon. The two row breakpoints are measured widths — move them if controls are added to the row. Every grid control acts on the marker governing the playhead, since a beatgrid is a marker list and there is no separate marker selection; see "Beatgrid" below.- One size for loops AND beat jump (
beatSize, 1/32–32, persisted asbeatSize; the oldbeatJumpBeatspref is read once on upgrade).LoopControlshas a BEAT / MAN switch: BEAT shows− size +(the size key sets or clears a loop of that length; −/+ halve/double, resizing an engaged beat loop from its locked start), MAN shows IN / OUT / toggle. The armed IN point is React STATE (loopInPoint), not a ref, because the IN button (lit "armed") and the waveform (drawLoopIn: a green IN line plus a dashed band to the playhead — the loop OUT would make now) both show it. OUT closes an armed IN, or with a manual loop already set moves its end to the playhead. A loop that is switched off stays drawn as a dim outline (drawLoop(…, idle)), so the toggle shows what it would restore. ‹ › (and ←/→) MOVE an engaged loop by its own length, Traktor-style, and only jump the playhead when no loop is engaged. The move sets the new loop BEFORE seeking:PlaybackEngine.seekhonours the loop in force, so seeking first wraps the playhead back into the old loop. - Memory cues (decided 2026-10-16, the discussion):
Mem mode replaces the pads with
MemoryCueStrip— chips in TIME order, scrolling sideways, labelled by name elsem:ss.s, after a + Memory button (at the snapped playhead, or the engaged loop as a memory loop; disabled with the reason pastmax_memory_cues). Clicking a chip is CDJ CALL, not a trigger: jump there and make it the CUE point (paused stays paused), a memory loop engaging as a loop pad does (enterCue). Right-click: Type (point types, where the platform has more than one — Traktor;set_memory_cue_type, a loop is not retyped), Colour (memory_palette), Rename… (the sharedRenameField), Delete — no move (rekordbox has none: a move is delete + add). An uncoloured memory cue draws in its TYPE colour, exactly as a hot cue does (cueColor/core/cue_colors.effective_color). Digit keys stay on hot cues. The mode persists ascueBankMode. - Hotcue edits live on the pad's right-click menu (type as one-click
choices, a colour swatch grid + Default where
cues.colorispalette—ContextMenu'sswatchesitem, Rename…, Delete); there is no standalone type dropdown or delete button. Rename re-sets the slot with its own start/type/length plus the new name, sinceset_cuereplaces a slot. A non-editable cue gets the same menu disabled, not no menu. Prep libs live insrc/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.
- One size for loops AND beat jump (
capabilities.writableis 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_causesays which kind (platform_incomplete/cloud_synced) andplatformCopy.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'sonEditField(inline edit + click-to-rate go inert), the "Edit Tags…" context item,Sidebar's new-playlist button, and all 12PrepStripedit 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 readcues.hotcue_slots), the cue-type dropdown (cues.types), the cue colour swatches (cues.color === 'palette'+cues.palette; afreeplatform gets no picker yet), 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 the context menu's "Add to" — each on its OWN flag, since a platform may allow renaming but not deleting. Memory cues: the deck's Hot / Mem toggle shows oncues.memory_cues, + Memory refuses pastcues.max_memory_cues, and a memory cue's swatches arecues.memory_palettewherecues.memory_colorispalette(its own 8, notpalette's 16). Track colour (decided 2026-10-17, the discussion): shown as the Type column's icon inTrack.color_hex; set from the context menu's Colour ▸ (swatches fromtracks.colors, + No Color, the whole selection,PATCH /api/tracks/color) — nowhere else.Track.coloris a neutral NAME (TrackColor: pink red orange yellow green aqua blue purple), which is what crosses platforms; each adapter'strack_palette.pymaps its codes to it BY NAME, not hue: TraktorINFO@COLOR1-7 = Red Orange Yellow Green Blue Violet(purple) Magenta(pink), measured (kit T1), no file tag; rekordboxColorID/ OneLibrarycolor_id/ pdbcolor_id1-8 = Pink… Purple, 0 none. Traktor's Blue LOOKS like rekordbox's Aqua but crosses as Blue (the name is the DJ's category); aqua arriving in Traktor becomes Blue. Unmeasured: what Traktor leaves after "None" (Konduktor removes the attribute). Carried but deliberately unused until a second adapter exists:slot_labels: 'letter',loops: 'separate_bank'.
-
lib/trackColumns.tsx— single source of truth for the library table's columns (defs, default widths/visibility/order, the Columns-menu list, the inlineInlineEditcell, and theTableMeta.onEditFieldaugmentation). The five Mastering columns (LUFS, RMS, True Peak, LRA, PLR; hidden by default) sit in the header chooser's first submenu (COLUMN_MENU'sgroup); cells carry their unit (formatLoudness), stale = dimmed with a tooltip. Their accessor returnsundefinedwhen unmeasured withsortUndefined: 'last'— TanStack sortsnullas 0, which would rank every unmeasured track loudest.Track.loudnessis NOT the backend's: App joins/api/loudnessinto the rows (['loudness', origin, hash of ids]), only while a Mastering column is visible; analyses invalidate['loudness'].- 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 insrc/index.css— see "Theme" below. Library column layout (visibility/order/width) persists touserprefs.jsonviaGET/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 inPrepStripfrom the shared['prefs']query). Continuously-changing prefs (columns, zoom,beatSize) are written through ONE debounced writer,lib/prefs.ts(usePrefsWriter/queuePrefs): changes merge into one PATCH, sent in order, and the queue outlives unmounts;QuitGuardcallsflushPrefs()before quitting. Do not give a new pref its own timer.
- Data flow: the whole library is fetched once (
Commands
./dev.sh # start both servers (see README for one-time setup)
.\dev.ps1 # the same on Windows (BUILDING-WINDOWS.md)
# 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 ...
# A Konduktor SERVER (a remote library) from source — configured by env, see
# server/.env.example; the container runs the same command:
KONDUKTOR_PLATFORM=traktor KONDUKTOR_LIBRARY=/path/collection.nml \
KONDUKTOR_CONTENT=/path/music KONDUKTOR_USERNAME=dj KONDUKTOR_PASSWORD=pw \
python -m konduktor.server # listens on :8765
docker build -f server/Dockerfile -t konduktor-server . # from the repo root
# 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<ENTRY>(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_gridleaves no companion debris (I); companion cues are ordinary editable hotcues — move/retype/delete work and never touch the grid marker (J); and real flexible grids in the collection project correctly (K); and removing a track from the collection drops its<ENTRY>and its PRIMARYKEYs from exactly the playlists that held it — the only ADDED lines are theENTRIES=recounts, every other playlist byte-identical (L); and a path remap rewrites locations + playlist keys localized (H1/H2), re-keys the entry index so earlier tag edits still reach the file (H3), and is refused with nothing changed when it would give two ENTRYs one primary key — onto a staying track's path, or two differently-keyed entries for one file — which the preview reports first, while a chain (A onto B's old path, B onward) and a pre-existing duplicate are allowed, each track's staged art and edits following the TRACK (H4). Andset_key(N): on a keyed entry only its INFO and MUSICAL_KEY lines change; an unkeyed one gains the KEY attribute and one<MUSICAL_KEY>between LOUDNESS and CUE_V2 in Traktor's layout; the encoding matches the real collection; a Camelot collection gets Camelot; an ADDED Pioneer key ("Abm") lands as "6m"; and the key tag reaches TKEY /initialkeyin MP3, FLAC and M4A. Andmove_playlist(O): the COLLECTION is untouched, a move round-trips and moving back is byte-identical; a folder moves with its subtree and answers its new path id; into its own descendant / beside a namesake is refused with nothing changed; a smart playlist moves by its path id; a no-op is not dirty. And memory cues (P): add / rename / delete change only that<ENTRY>'s cue lines, in Traktor's shape (HOTCUE="-1",n.n.), add + delete round-trips byte for byte, new cues (hot ones too) are INSERTED by START, and a pad + memory cue at one START project once, as the pad. And>/ quotes in attribute values (Q): Traktor leaves>raw, and an empty element holding one (4.5's default "Recently added" query$IMPORTDATE >= MONTHS_AGO(1), a comment, a file name) once came back self-closed (/>, which Traktor never writes); a value containingname='x'once came back with a bare"(malformed). Both were in the fork'sformat_traktor_layout, fixed there (2026-10-16). And track colour (R):set_track_colorchanges one line, that entry's<INFO>, withCOLORlast as Traktor writes it; aqua is stored as Blue; clearing restores the original bytes; and a Traktor 4.5 collection holding coloured tracks (when on the machine) renders byte-identically. 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; plus the drag-and-drop routes:/add's threeduplicatesmodes (askchanges nothing and counts) and/api/playlists/move(path id answered, 400 into itself, 404 unknown).test_timebase.py— Traktor's MP3 time base:mp3_gaplesson generated MP3s (header found after a 1 MB ID3 tag; header-less has none), the offset in samples (2257 at 44.1 and 48 kHz, 0 header-less / WAV / missing), every write path adding it and the projection removing it, a grid anchored inside the header frame reading negative and round-tripping byte for byte, and — when kit 4 is on the machine — Traktor's own hand-placed cues reading back onto the kick. Then the same for rekordbox's clock: the per-file offsets (MP3 header, header-less, 48 kHz, FFmpeg and Apple AAC priming, the unreadable fallback), negative beats dropped with bar numbering kept, and rekordbox's own hand-placed kit-4 cues read back frommaster.db.test_stem_file.py— the stem writer on generated sources with a FAKE engine: both JSON literals byte-exact against the user's commercial files and collection (skipped when absent) and float32-equal; mono not 3 dB quieter; 48 kHz resampling does not move time; MP3 and FLAC through both encoders give five streams with only the mix enabled, no shift (cross-correlation), the bitrate rule (256 floor, lossless 320), every tag + cover;verifyrefuses a shifted, truncated or box-less file; a raising checkpoint cancels. The threaded encode is byte-identical to a single-threaded reference (with each encoder present), reports progress 0 → 1, and a cancel or a failing encoder thread leaves no thread running.test_stem_swap.py—apply_stem_swapson a temp copy of the real collection with a generated MP3 (with header) and a real stem file: prep reads back at the same decoded second while its START moves by the 2257- sample offset read from the PARKED file (and the 51 ms error reading the old path would cause); outside the ENTRY only its PRIMARYKEYs change (TYPE STEM); save round-trip; anchor-before-0 moves a whole beat with its companion, a hotcue clamps and is reported; "add" appends, keeps the original, joins a playlist, carries pending tag fields; clashes refused with nothing changed.test_engine_manager.py— the engine manager and process against a LOCAL Range-aware server and a FAKE engine script (no network, no torch): resume, restart when Range is ignored, checksum refusal, cancel keeps the.part; install from split parts with byte progress and a probe; a wrong-version engine or corrupt part leaves nothing installed; side-load and weights verified; the CUDA offer's driver/capability floors; the process relays progress, cancels without dying, reports a crash with its reason, keeps the Mac awake; the routes (install job in bytes, 409 while one runs, remove).test_stems_batch.py— the Convert to Stems batch through the routes with the FAKE engine (stem_test_support.py, shared withtest_engine_manager.py), on temp collections pointed at generated MP3s: skips with reasons (an existing target is never overwritten); Replace parks, swaps at the end, leaves the saved file untouched, keeps prep in decoded time and 409s the blocked routes; Save deletes parked originals and retargets an export set; Discard and switching library restore; Cancel leaves no file; one bad track fails alone; destination+add mirrors into a new playlist; crash recovery restores (or finishes a committed save) and a re-run REUSES the kept stem files without calling the engine.test_stem_playback.py— stem playback's backend half on a generated stem file (fake stems = distinct scalings of the mix): the layout is read from the FILE (an MP3 whose entry carries<STEMS>has none); each served stem is its own MP4, bit-identical to that stream in place and the RIGHT stem; out-of-range / non-stem requests 404; the cache reuses, follows an edited file, evicts LRU but never what it just wrote; the folder origin serves too and lists the file as a stem track; a stem file ADDED from a folder gets<STEMS>and aTYPE="STEM"playlist key, the MP3 beside it neither. On a Rekordbox copy, an added stem file projects as a stem track (also after a reopen) and the deck is offered its stems.test_traktor_adapter.py— the generic layer: one parse per open, the projection refreshing after every command family, cue-type translation, capabilities, andset_analysed_gridvsreplace_grid.test_save_fidelitycovers 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 andagentRegistry.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, andmove_playlist(E2) changes onlydjmdPlaylistrows + the counter withSeq1..n in both parents. And removing a track deletes exactly the rows Rekordbox 7 deletes (measured 2026-10-01 by diffing a removal made in Rekordbox itself:djmdContent,djmdCue,contentCue,contentFile,djmdMixerParam,djmdSongPlaylist— DELETED, neverrb_local_deleted; the playlist row untouched, later entries renumbered) plus, after the commit, its ANLZ files and their emptied folder. Artwork is left (unmeasured:_m/_ssizes are not incontentFile), and a track in a table that was empty when measured (Sampler, History, Tag List, My Tag, …) is refused with nothing changed. And adding tracks (J) on generated kick-track MP3s: a raisingcheckpointcancels before the library is touched; nothing reaches disk before save; afterwards only INSERTs (plus the counter) into the tables Rekordbox writes for a new track, the row filled from the file and stamped with the library's device, onecontentFileper analysis file +artwork.jpgwhose Hash is the MD5; a plain file gets Konduktor's grid ON the kick, a source's grid, hot cue (pad, colour), loop and memory cue cross as themselves; and removing it deletes its analysis files.test_folders.pydrives the same through/api/folder/addon a Rekordbox copy, and a non-addable library 422s. Andset_key(K): a key the library has changes exactly the track row and the counter, pointing at its OWN row (found by meaning, not name); a missing key adds onedjmdKeyrow as rekordbox creates its own — its spelling,SeqNULL, its own USN (so through the ORM; a raw insert is left unstamped) — which the nextset_keyreuses. And memory cues (G2): M1's measured row shapes (point:Color -1, CTI NULL; loop:255/0,Comment ''), colour inColor(Blue 6) with CTI NULL, No Color = 255, the mirror in ROW order, rename touching onlyComment(+ the USN pyrekordbox stamps on every cue write — rekordbox's own leave it NULL, and it has accepted ours), the 11th refused with nothing changed, delete removing the row outright.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 againstfixtures/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, thePCOB/PCO2merge, and — cross-checked against the same cues inmaster.db— the dense ANLZ slot numbering, which is the thing most likely to be silently wrong. Also readsfixtures/onelibrary/rekordbox-edited/(a stick after rekordbox itself edited it: compact cue entries) and pins browsing vs editable mode. It opens a temp COPY of the fixture — a stray save once rewrote the checked-in one.test_onelibrary_fidelity.py— the row-level diff for OneLibrary writes, on a temp copy of the fixture: nothing reaches the drive before Save, a no-op save changes zero rows, a title edit exactlycontent.title(no counter, as rekordbox), dates asYYYY-MM-DDtext, lookups found-or-created withnameForSearchNULL, a new playlist on top with siblings shifted, entries from 1, a move changing only parent +sequenceNo(0..n-1 in both parents); and the stick hazards — another app's write refused, an unplugged drive keeps the edits, stale-shmdeleted, the backup holds the old rows, the drive never held open, file tags written (title yes, rating no). Andset_key: an existing key changes onlycontent.key_idand reaches TKEY as the stick names it; a missing one adds a key row in rekordbox's spelling; on Goober, "12A" projects a key and setting 12A reuses that row.test_onelibrary_anlz.py— cue and grid edits in the ANLZ files. First against rekordbox's own edit of the same thing (fixtures/onelibrary-goober/after/): a recolour'sPCO2and a grid edit's blankedPQT2and cleared loop beats are rekordbox's bytes exactly, and the newPQTZkeeps the marker where it was (rekordbox's own halving moved its anchor 6 ms; within 10 ms). Then fidelity on the demo drive: nothing on the drive before Save, only the touched tags change (in place, order kept), a moved pad keeps colour and name, swatches only, a same-tempo marker collapses (a per-beat grid has no markers), another app's ANLZ write refused, an.EXTwith noPCO2keeps every pad, a track with no analysis files refuses. And memory cues against rekordbox's own edits (fixtures/onelibrary-memory-edits): add a cue, add a loop, add up to 10, recolour, comment and delete, each replayed withmemory_cuesonbefore/and equal toafter/tag for tag (the.DAThot list compared as a set — rekordbox re-sorts it); then through the adapter on the demo drive: palette, cap, NotFound, nothing before Save, and Save changing only the two memory lists.test_onelibrary_pdb.py— the Device Library rebuild on Goober's ownexport.pdb: every track row reads (rows end at their last string; stale heap tails ignored), a no-op rebuild returns None and a no-op save leaves the file byte-identical (ids are mirrored), an edit changes only the edited fields, a new playlist and a reorder reach it, every untouched table andexportExt.pdbstay byte-identical, another app's pdb write is refused, and a stick without one never gets one.test_onelibrary_tracks.py— adding and removing throughimporter.runon Goober: placement (in place on the stick, elseContents/<Artist>/<Album>/, Unknown*, FAT-safe names, 48 chars, suffixed on collision), the prep crossing (pad + colour + name, memory cues, a taken pad -> memory, a detected grid), the row's shape, art as a/b pairs, the Device Library rows; a cancel mid-copy, a Discard and a crash leave nothing; removal deletes rows at once and files only at Save, renumbers playlists and prunes empty folders.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 arrive as Traktor memory cues (HOTCUE="-1"; one on a pad's START shows once, as the pad), a hot cue displaced with no spare pad becomes a memory cue instead of being dropped, 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. And the route with chosentrack_ids+into_playlist+export_id(a device drop): only that track, into the playlist and the export, no drive folder made.test_grid_detect.py— beatgrid detection on synthetic audio, so the tempo and first beat are known rather than borrowed from another analyser: exact integer and non-integer BPMs, the 125 BPM the old detector could not return, octave choice, and the loud off-beat hat and syncopated bassline that each fooled one band on real music. Holding either half: a held BPM comes back untouched (never snapped or re-octaved, a wrong one reports drift) with the phase still found through the hat/bass traps; a held anchor comes back untouched with the tempo detected, an off-beat one reported as drift. Andplan_grid's every rule. Accuracy on REAL music isbench_grid_detect.py's job (not inrun_tests.sh: it needs audio).test_key_detect.py— key detection on SYNTHETIC cadences in all 24 keys (I-IV-V-I / i-iv-V-i — a pop I-V-vi-IV is fairly called minor by an EDM model), loudness / sample-rate invariance, None for silence, and the numpy convolution against a direct implementation. Accuracy on real music isbench_key_detect.py's job (GiantSteps + any folder of key-tagged files).test_loudness.py— loudness measurement on GENERATED signals against FFmpeg'sebur128through PyAV (integrated ±0.1 LU, LRA ±0.3, true peak ±0.2 dB, 44.1/48 kHz, mono), the standard's anchors (a -23 dBFS 1 kHz stereo sine = -23.0 LUFS; an inter-sample peak = -6.02 dBTP), RMS's definition (a full-scale sine 0.0, a square +3.01, a long quiet intro moves nothing), silence / under 3 s = None, chunked feeding equals one pass, and real files at their own rate and channels.test_loudness_store.py— the store (stale on facts or version, remap with the new path winning, concurrent writers) and the routes on generated FLACs: a Files folder measured with BPM refused, preview counts = the run's, skip unless Replace, a touched file stale with its value kept, the deck route, the same file's value seen from the collection, a Save's own tag write not staling it, Discard keeping it, a remap carrying it, a device's undecodable stubs reported per track.test_stems_batch.py/test_remote_stems.pypin the stem re-measure,test_remote_adapter.pythe server-side store (423 without the session, 503 once taken over).test_auto_hotcues.py— Auto Hotcues in three layers:structure.analyseon SYNTHETIC audio with known sections (the intro with a kick is not a drop; no breakdown after the last drop),plan's outcomes and beat-counted offsets (across a tempo change), and the ROUTE end to end on a temp copy of the real collection — the previous implementation's route returned 500 on every call for a week while its helper's tests passed.test_grid_batch.py— batch analysis from the context menu, bothjobs.pyjobs shown in the status bar: Analyze… (BPM / Grid / Key) (POST /api/tracks/grid/auto-batch) and Auto Hotcues… (POST /api/tracks/cue/auto-batch, one template for every track). Pins the batch-only decisions: locked grids are skipped always, existing grids unlessreplace_existing; a hotcue batch analyses a grid FIRST where there is none and never touches an existing one, and a ticked Replace applies to every track; a failing track is reported not fatal; one batch at a time ACROSS both kinds (a grid run would move the beats a hotcue run is placing cues on); a cancel KEEPS finished tracks (unsaved edits like any other) and still returns its result; opening another library cancels the run. Each shares its helper (_analyse_grid,_place_auto_cues) with the deck's single-track button. Also BPM alone / Grid alone through_analyse_gridon a real Traktor copy: the detector is asked to hold the right half, BPM alone retempos the marker in place with its beat-1 cue untouched, Grid alone moves it (cue dragged along) at the same tempo, and a TEMPO-only track gets one marker at it. And Analyze (POST /api/tracks/analyze+/analyze/preview, the dialog's BPM / Grid / Key;grid/auto-batchis now an alias of it with BPM+Grid): nothing ticked 400s; Key alone sets keyless tracks, skips keyed ones unlessreplace_key, never touches a grid; the preview's counts match the run's (BPM alone: single grids adjusted, flexible skipped, bare in full); a skipped track is never decoded and grid+key share ONE decode; a grid that cannot be fitted still gets its key; the deck's Analyze writes the key too and never fails on it. The decode ismain._decode_for_analysis(the seam the fakes replace);test_key_detect.pyruns the route once with the REAL decode and detectors on a generated F-minor 124 BPM WAV.test_bulk_remove.py— the context menu's Remove ▸ routes (/api/tracks/grid/clear,/api/tracks/cue/clear,/api/tracks/remove): locked grids are kept, clearing hotcues empties the whole bank (loops and the grid's beat-1 cue too) but never the grid, a removed track leaves the projection AND its playlists while its audio file is untouched, removal is gated ontracks.removable, and all three are refused while a batch analysis runs.remove_tracksis the protocol's only DESTROYING verb for tracks; Traktor and Rekordbox implement it, OneLibrary (read-only) refuses. The journal records it astrack/remove, NOT an edit — otherwise history would read "edited 40 tracks".test_folders.py— the Files trees and adding loose files, through the routes, on generated FLACs and a temp copy of the collection: a folder lists only the visible audio DIRECTLY in it; the audio route refuses anything a scan did not find; a file the collection already points at is never added twice (on Traktor that would be two ENTRYs sharing a primary key — a corrupt collection) but still reaches the playlist/export it was headed for; "copy" points the entry at the copy and "reference" at the original. And a DROP (/api/folder/dropped): folders recursively minus hidden ones, dropped non-audio counted as skipped, only what was dropped becomes streamable, the folder's own listing stays whole, the cap, held files as their collection track, and the preview's per-file external-drive count andin_destination.test_picker.py— the picker's routes. Pins the scoping, because the bug it replaced was invisible:/api/library/optionsflattened 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, that every offered place exists, that the boot volume is not offered as a drive, and that the adapter and the browser share ONE mount scanner. 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_prefs.py—userprefs.jsonunder concurrent writes: 200 bursts of simultaneous patches (plus a reader) keep every key and every patch; the last-collection and path-mapping helpers lose nothing either; an unreadable file is moved aside, not overwritten. Against the old unlocked code it fails on the first trial.test_exports.py— export sets against a temp copy of the real collection. Pins the things that would fail SILENTLY: a live reference picks up a playlist edited AFTER curation; contents dedupe across playlists and loose tracks; a deleted playlist or track is surfaced, not dropped; sets are per-library; two sets sharing a destination are caught (an export clears its destination, so the second would wipe the first); and deleting a set never touches its folder.test_export.py— writing a Traktor collection from NOTHING. There is no original here, so the guarantee differs fromtest_save_fidelity.py's: the result must be a collection Traktor would have written. Pins the skeleton, and above all that<LOCATION>is volume-relative — an export writing host paths would work perfectly on the machine that made it and resolve to nothing at the gig. Also that a flexible multi-marker grid and hot-cue PADS survive, each grid keeps its source's lock, loose tracks get their "Other" playlist, and re-exporting into the same folder replaces rather than appends. Lock beatgrids (the run's option): a new set locks by default and remembers being told not to; on, every exported track WITH a grid is locked (never one without — Traktor would never give it a grid), written as Traktor 4.5 writes it (LOCK="1"thenLOCK_MODIFICATION_TIME, ISO, UTC);test_export_pioneer.pypins the Rekordbox Library'sAnalysed233 vs 105. It then runs a real export end to end (the source library is built with the exporter itself, so its LOCATIONs point at audio that exists) and pins the safety rules with teeth: a folder Konduktor did NOT write is refused, andrun()refuses a blocked plan even when called directly; a re-export replaces its own files and leaves the user's alone; a cancel leaves no library file and no audio at all, including the file being written; a missing source file is skipped rather than fatal. And the incremental re-export: an unchanged re-export copies and decodes NOTHING (same inodes), an edited source and a copy tampered with on the stick are each re-copied alone, a moved shared root renames kept copies instead of copying, a cancelled re-export keeps them and the folder stays ours, and the analysis cache round-trips exactly.test_export_pioneer.py— the two Pioneer targets against the same contract. Harder than Traktor's in a way that test cannot cover: each writes a database PLUS per-track analysis files, so "the library" is no longer one path, and the prep survives a real change of representation rather than a re-render. Pins the three crossings that fail SILENTLY — the key is CONVERTED not copied, hot cues keep their PAD across the dense-vs-sparse slot difference, and a flexible multi-tempo grid survives expansion to per-beat and collapse back. Both are read back with Konduktor's own adapters, which is the strongest check short of the hardware: the reader was written against real rekordbox output.test_relocate.py— auto path remapping:relocate.searchon temp folders (drive-letter change, clone = ambiguous, partial copy loses, bare filename is no match, dropped home folders), then the Traktor path through the routes on a collection re-homed toX:/E:: a resolving volume is never asked about, nothing applies before the answer and only a proposed mapping does, the collection and prefs are untouched, a reopen asks again, and a saved manual mapping's volume is left out.test_library_id.py— the property no other suite covers: a library that moves keeps its identity. Also that two libraries in one folder stay two, a removable library is never written beside, an unwritable location falls back rather than failing, andpaths.write_jsonis atomic (curated user work, soprefs.py's best-effort "any I/O error degrades to no prefs" is NOT adequate).test_discard.py— discarding unsaved edits through the route: the edit is gone, the file and version history untouched, relocation answers and the saved path mapping survive, the adapter object is the same (a reload, not a reopen), and a running batch has stopped by the time discard returns; on Rekordbox (temp copy, skipped when absent) the library is clean afterwards and a later save writes nothing that was thrown away; read-only libraries 409.test_remote_protocol.py— pure: everyLibraryAdaptermember is an RPC or excluded with a reason, every command isMUTATING, args/results survive JSON by the protocol's types (tuples, dataclasses,None), a misspelt or missing argument is refused, a prepared analysis crosses intact, the version rule.test_remote_server.py— the server's own routes on a temp copy of the collection with a FAKE clock: config refusals, 401s, one computer at a time (423 without the token, 409 naming the holder and its batch, takeover kills the old token, an expired lease frees it, the same client renews), leftover edits named, save + history on the server, discard, confinement (.., symlinks), uploads never overwrite and delete only their own, Range audio.test_remote_adapter.py— END TO END: a real server in a thread, the app's routes opening it. Handshake refusals, fallback, the mirror, Save touching only the edited<ENTRY>THROUGH the trip, one download per file, Analyze on the cached copy, export (and a re-export copying nothing), an upload stored in the mapping's stored form, takeover → read-only at once, reopening names the holder and the edits left, leaving releases. And the content folder as a drive: listed first, confined, held files ticked off, auditioned with one download, an add IN PLACE (no upload, the held one not added twice, both into the playlist, analysed here when the server reports a lead).test_remote_stems.py— Convert to Stems on a remote with the FAKE engine: the plan's transfer and two-machine space, Replace parks and swaps ON THE SERVER (saved file untouched until Save, which deletes the parked original), Discard restores, Cancel deletes only this run's uploads, a takeover's uploads are reused without the engine.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 sharepyrekordbox: the rule is "no adapter reaches for a rival vendor's library", and a shared dependency is not a breach. Also:adapters/remoteimports no platform adapter, and importingkonduktor.serverpulls in no librosa / scikit-learn / torch / numba / PyAV.
Also validate the backend interactively at http://localhost:8000/docs and the
frontend at http://localhost:5173.
Critical gotchas — read these
traktor-nml-utilsMUST come from GitHub, not PyPI. PyPI's3.1.0is stale and cannot parse Traktor Pro 4 (NML v20) files — its strict parser dies on the v4<GRID>element insideCUE_V2.requirements.txtpins a GitHub commit (v4.0.0). Do not "simplify" this to a plain PyPI pin.pyrekordboxis now the same situation: PyPI's latest (0.4.4) has noonelibrarymodule, which is the OneLibrary (exportLibrary.db) reader (OneLibraryclass;devicelib_plus/DeviceLibraryPlusbefore upstream's rename), normasterdb(formerlydb6, now removed upstream;tables→models,BLOBinmasterdb.database). Both GitHub deps are pinned to a COMMIT, never bare master: thedevicelib_plus→onelibraryrename reached CI's fresh install while dev venvs kept the old commit, and a release shipped that could not export or read OneLibrary while every local test passed. Move a pin on purpose, with./run_tests.sh. PyAV: open files for reading throughcore/pyav.open_input, neverav.opendirectly. PyAV 18 refuses a file with non-UTF-8 tags unless givenmetadata_errors="ignore"; PyAV 19 removed that keyword. CI installs fresh (it got 19) while a dev venv keeps what it had (18), so code passing the keyword passed every local test and shipped a release whose deck played every stem track as the mix.requirements.txtcapsav<20: checkpyav.pybefore raising it.- The collection is real, irreplaceable data — protect it. Every save
writes a timestamped
.bakfirst (into abackups/folder next to the collection). When testing writes, pointKONDUKTOR_NMLat a COPY. Warn the user to close Traktor before saving (it overwritescollection.nmlon exit). - 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.pyenforces this. - The desktop sidecar is a PyInstaller ONEDIR folder — never go back to
onefile. A onefile binary unpacked ~390 native libraries into a NEW temp
folder on every launch, and macOS (XProtect / syspolicyd) checks each library
it has not seen before as it is dlopen()ed, keyed per FILE: the window
appeared only after ~10 s on every launch (measured 2026-10-12: 95 s to load
them all fresh, 1 s once seen). As a folder in the app they are checked
once; a launch is ~0.5 s.
build_sidecar.*stagessrc-tauri/binaries/konduktor-sidecar/;lib.rsspawns<resources>/sidecar/konduktor-sidecar[.exe]. On macOS it is bundled bytauri.macos.conf.json'sbundle.macOS.files, NOTbundle.resources: the resource copier follows symlinks, turning PyInstaller's 37 library aliases (_internal/libavcodec… -> av/.dylibs/…,Python.framework'sVersions/Current) into second copies a library could be loaded twice from. Windows has no such links and usesresources(tauri.windows.conf.json).
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.iduses this. - Rating =
RANKING / 51, giving 0–5 stars (_rating_stars). - Key = two fields.
INFO@KEYis the display text Traktor shows and tags files with, in the user's notation (Open Key"10m"in the real collection);<MUSICAL_KEY VALUE>is the analysed key, pitch class + 12 for minor (12= C minor =10m; 6,628 of 6,641 entries carrying both agree). 1,354 entries have ONLYMUSICAL_KEY— analysed, never given text — soprojection.entry_keyfalls back to it (rendered Open Key).set_keyandadd_entrywrite BOTH, the text in the collection's majority notation (TraktorStore.key_notation(); an empty collection — an export — takes a Traktor-native source's own, so Traktor→Traktor keeps the user's). - Track colour =
INFO@COLOR, 1-7 in the Color menu's order (Red … Magenta), the LAST attribute of<INFO>; collection-only (_COLLECTION_ONLY_FIELDS). Seetrack_palette.py. - Beatgrid = an ORDERED LIST of markers, never a single BPM + anchor.
Traktor stores each as a
CUE_V2 TYPE="4"with its own<GRID BPM>child (flexible beatgrids, 3.4+);<TEMPO BPM>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<GRID>child, order bySTART— 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 (exceptplace_grid_companion, used only by Auto Grid). They are not locked: Traktor 4 keeps a beatgrid without one, so a companion is an ordinary hotcue the user may move, retype or delete — doing so simply ends the pairing (it is no longer a white cue on a marker), and the grid is untouched. Grid edits still drag or delete a companion that is still paired. The#FFFFFFtest 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.pyis the single shared definition of all of this. - Memory cues are
CUE_V2s on no pad (HOTCUE="-1") WITHOUT a<GRID>— a grid marker is alsoHOTCUE="-1", and the<GRID>child is the only test (projection.is_memory_cue). Measured in Traktor 4.5 (kit M3, 2026-10-16): any type, no limit, drawn on the waveform, reached with the cue panel's ‹ ›, a name shown in the cue panel, and a Konduktor-written one kept byte for byte. MAP puts a pad on one and leaves the memory cue at the same START; Traktor draws ONE marker, so the projection shows the pad only. Their id is content-derived (m:<START>:<TYPE>:<LEN>:<n>). Traktor keepsCUE_V2sorted by START, so the store INSERTS new cues in place (_insert_cue) rather than appending.
- Marker NAME is not a discriminator (
- Playlist tree: recurse
nml.playlists.node.subnodes.node. A node's.typeisFOLDER,PLAYLIST, orSMARTLIST. Smart playlists are rule-based and have no static entry list.PlaylistNode.idis the playlist's stableUUID; folders use a synthetic path idfld:<name>/<name>, smart playlistssl:<path>. - Model classes use single-capital names:
Entrytype,Primarykeytype,CueV2Type.Entrytypeis 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-*/well/accent/gold/mint/pinktokens and the material classes fromindex.css(see "Theme"). Icons come fromlib/icons.tsx, never emoji; a platform's own mark comes fromlib/platformIcons.tsx(<PlatformIcon platform=…>— single-colour marks redrawn from each platform's app icon, masks keyed byuseIdsince one page can show a mark twice). That file is a lookup of display ASSETS by platform id, not platform branching; an unknown id falls back to a generic mark, so a new adapter needs no change there to appear. Keepapi.tstypes aligned withschemas.py. - Never
window.confirm/alert/prompt. They cannot be themed, they block the event loop (a playing deck stutters), and under Tauri they read as a web page. Useawait askConfirm({ title, body, confirmLabel, tone? })fromlib/confirm.tsx— same one-line shape asconfirm(), rendered as the themedConfirmDialogby theConfirmHostmounted once inmain.tsx.toneisdanger(default, pink) orprimary. Components that already hold dialog state may still renderConfirmDialogdirectly.
Theme — "dark liquid glass"
Floating frosted panels (12 px gutters) over a drifting wash of colour sampled from the loaded track's cover art. Colour is reserved for MEANING — cue types, key, playhead, the one primary action; chrome stays neutral. The rules that are easy to break:
ink-900…ink-600are translucent WHITE overlays, not greys, so they read on any panel. Onlyink-950is opaque: it is the dark text on light buttons and the page base. Recessed things (inputs, waveforms, readouts, progress tracks) usewell/ the.wellclass — neverbg-ink-950.- Materials are classes in
index.css:.glass(panel),.glass-overlay(menus, dialogs, toasts — denser),.well,.btn-glass,.btn-primary(white→accent pill, one per view),.is-selected. The rim light is a::before, so these setposition: relative; Tailwind'sfixed/absoluteutilities win because utilities outrank the components layer. - Never put
backdrop-filter(orfilter/transform) on an element that can contain a popup. It makes that element the containing block for everyposition: fixeddescendant, so a context menu or dialog opened inside it is placed relative to the panel, not the window — the sidebar's playlist menu opened far from the cursor..glass's blur and tint therefore live on its::after(z-index -1 underisolation: isolate), not on the panel. - Every overlay renders through
createPortal(…, document.body)— all dialogs,ContextMenuandToast. Each.glasspanel is a stacking context (isolation), so an overlay rendered INSIDE one can never rise above a neighbouring panel, whatever its z-index: New Export (from the sidebar) sat behind the library, and the deck's Auto Hotcues dialog behind both. One z scale, set on the overlay's root: dialogsz-50, a dialog opened from a dialog (FolderPicker)z-[60], menusz-[70], toastsz-[80]. A new overlay that skips the portal will look fine when opened fromAppand break the first time a panel opens it. Small popovers anchored to a control inside a scrolling list should open the sharedContextMenuinstead (as the playlist row's "Add to export" does) — a popover inside the list is clipped by it. - A
.glass/.glass-overlaybox must never be the element that scrolls. Its tint, blur and rim are pseudo-elements sized to the box, so they scroll away with the first screenful and leave later content on bare background (the column chooser's last items did). Give the glass frameoverflow-hiddenand scroll an inner element — as every dialog andContextMenudo. - Keep backdrop blurs on SHORT elements small (the table's sticky header uses 8 px). Chrome silently skips a large backdrop blur on a thin strip — 12 px and up left the rows under the ~33 px header perfectly sharp, with the computed style still reporting the blur, so nothing looks wrong in DevTools.
- The accent is
oklch(0.8 0.11 var(--accent-hue))— the cover's hue at a FIXED lightness and chroma, so dark text on it keeps its contrast whatever is loaded.lib/ambient.tssets--accent-hueand--amb-1..4on<html>; they are@property-registered so a track change glides, and nothing in React state depends on them (no re-render on a track change). The art is fetched as a blob →createImageBitmap, because a cross-origin<img>(the API under Tauri) taints the canvas. A device track, or greyscale art, gets the default. AmbientBackdropis mounted inmain.tsx, behind the picker too; so no root container may set an opaque background, or the glass has nothing behind it.- Canvas drawing glows instead of outlining (
cues.ts): a black outline on glass reads as a gap in the waveform. The playhead isdrawPlayhead, shared by both waveforms. - The table's Cues column draws one dot per occupied slot from
Track.hotcues(HotcueChip: slot, type, colour), which every adapter projects with the SAME slot test itstrack_cues()uses, so the dots cannot disagree with the pads. OneLibrary fills it lazily, likehotcue_count. - Python 3.14 note: pin dependencies loosely enough to get prebuilt wheels
(older
pydantic-corepins 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. To release a new version, bump
that number and nothing else — everything derives from it:
- Tauri / installers —
tauri.conf.jsonsets"version": "../package.json", so the.dmg/.exenames + bundle version come frompackage.json. - Backend API —
konduktor/__init__.py_read_version()readspackage.json(dev:<repo>/frontend/package.json; frozen sidecar: bundled at the PyInstaller root viasys._MEIPASS, added inkonduktor-sidecar.spec).main.pyuses this for the FastAPIversion. Falls back to"0.0.0"if not found (cosmetic, must never crash startup). - Frontend / update check —
vite.config.tsbakes it in at build time as the__APP_VERSION__global (declared insrc/vite-env.d.ts);UpdateCheckcompares it against the latest GitHub release tag on startup. - CI release —
.github/workflows/build.ymlreads it withjq .version frontend/package.jsonand tags each pushv<version>-b<run_number>(release nameKonduktor v<version>-b<run_number>). The-b<N>suffix keeps every push's tag/release unique. Each release also carries its files under user-facing names, laid out by.github/scripts/release_assets.py:Konduktor-<v>-macOS.dmg,Konduktor-<v>-Windows-Setup.exe(also the Windows update package),Konduktor-<v>-app-updater.tar.gz(the macOS update package) and the in-app updater'slatest.json(version= package.json's, each platform's URL + signature inlined; the name is fixed — the app asks for it by name). The notes open with a "Download" section linking the two installers, above the PR's patch notes or GitHub's generated ones; the update dialog reads only "What's Changed" and skips "Download" when falling back.bundle.createUpdaterArtifactssigns those with the updater key: the repo secretsTAURI_SIGNING_PRIVATE_KEY/_PASSWORD, public half intauri.conf.jsonplugins.updater.pubkey. Losing the private key means installed copies can never update themselves again — it is backed up outside the repo. A local build without it passes--config src-tauri/tauri.unsigned.conf.json(build.ps1does so itself). - NOT a source:
src-tauri/Cargo.tomlversionis 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, Cmd/Ctrl+↑/↓ = loop/jump size). 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: writing cover art (reading works: the file's embedded art, else Rekordbox's ownImagePathcopy undershare/). 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_tracksis 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", whichtest_import.pychecks on rendered bytes — exactly one line changes, the one carrying<COLLECTION ENTRIES="N">, whose count the store now maintains. The store creates a bareENTRYand the cues/grid are written by replaying the ordinary commands, so an import inheritsreplace_grid's companion handling and tests instead of growing a second implementation.AUDIO_IDandLOUDNESSare 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. Rekordbox implements it too (2026-10-01; gated ontracks.addable, which the folder menu, the folder header and the device Import button read from the COLLECTION's capabilities). Unlike Traktor it must ANALYSE: a Rekordbox grid and waveform live in the ANLZ files, without which Rekordbox shows neither grid nor cues. Soadd_tracksdecodes each file once (waveform.decode→analyse_samples+grid_detect), in a first phase that may be cancelled throughcheckpointbefore the library is touched; a file with no grid of its own gets Konduktor's (decided: arrive ready to prep), and one with no key of its own a detected key (key_detect.with_detected_key, from the same decode; OneLibrary too). ThenRekordboxStore.add_trackwrites the row the way Rekordbox's own add was MEASURED to (file facts,DateCreatedfrom the file's birth time, this library's device) and the grid/cues replay throughreplace_grid/set_cue/add_memory_cue— memory cues and colours cross as themselves, a hot cue with no free pad becomes a memory cue. Its ANLZ files and artwork (NewTrack.art, else the file's embedded cover) are held until save and written BEFORE the grids and commit, thencontentFilerows hash what was written (_m/_sunlisted, as Rekordbox does); a failed save removes them. Key, mixer gain and phrases are Rekordbox's own analysis and are not written. The row and file builders live inadapters/rekordbox/new_content.py, shared with the Rekordbox Library exporter.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
CapabilitiesContextfor 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 soSaveBarstill 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 stay memory cues (Traktor'sHOTCUE="-1"; until 2026-10-16 they were promoted to spare pads), a hot cue whose pad is taken moves to a spare pad, else becomes a memory cue; cue colour is dropped (Traktor derives it from type). Into Rekordbox / OneLibrary only the first 10 memory cues cross (rekordbox's cap).
- ✅ OneLibrary adapter — reading and editing done, at parity with the
Rekordbox adapter (2026-10-01, decisions).
A OneLibrary USB drive opens, projects, browses and searches: tracks,
playlists, hot cues, memory cues, loops and flexible beatgrids. Done: track
metadata (+ file tags), playlists, hot cues and the beatgrid (in the ANLZ
files, each rule matching rekordbox's measured edit), the
export.pdbrebuild on save, adding/removing tracks (the library places the audio), Save via a working copy, and "Open for editing…" on a Devices row — all verified in rekordbox 7. Same gaps as Rekordbox: cover-art writing, stem conversion. All format research — including the schema, which has no public spec — is in .claude/handoffs/onelibrary-adapter.md. - 🟡 Export/conversion — in progress. Both the design AND the user flow
are settled; see
the export discussion doc,
whose 2026-09-23 section is the current one, plus
.claude/handoffs/export.md for the landmines.
An export is a named, persisted object in the sidebar carrying its name,
target platform and destination; tracks and playlists are added to it; an
Export button copies the audio and writes the library. Settled: Traktor-only
target for v1, source is whatever library is loaded, mirror the source
folder structure (so filename collisions cannot happen), playlists are live
links removable only as a whole, re-export clears the destination first,
cancel rolls back, key notation mirrors the source, no whole-library
export. Grids were first left unlocked, and that went wrong: an exported
Traktor entry has no
AUDIO_ID(Traktor's analysis fingerprint, which cannot be computed), so Traktor re-analyses it on its first load — re-measuring the BPM (a 174 track came back as 87) and drifting the grid. So the run dialog has Lock beatgrids (decided 2026-10-19;ExportSet.lock_grids, default on, sent with the run and remembered on the set; shown where a target'sPlatformOption.locks_grids). It rides on the genericTrackCues.grid_locked(exporter._locked), the flag a source's own lock already arrives in, so off still carries each track's own lock; Traktor writesLOCK+LOCK_MODIFICATION_TIME(UTC), the Rekordbox Library sets bit 0x80 ofdjmdContent.Analysed(105 -> 233, measured by locking tracks in rekordbox 7). The stick formats carry NO lock: rekordbox 7's own device export of two locked tracks left OneLibraryanalysedBitsand the pdb'su5at 41, as on every unlocked track (measured on Hardy, 2026-10-19), so neither stick exporter setslocks_grids. The Rekordbox ADAPTER does not yet read or write that bit (grid.lockablestays false). Verified against the real collection: Traktor storesVOLUME="Hardy"plus a volume-relativeDIR, never a host path — so a USB export is portable by construction, and the.nmlcannot be written until the destination is known. Also settled: loose tracks land in an "Other" playlist, playlist folders are preserved — at the exported library's TOP LEVEL by default; theexportRootFoldersetting (ExportPayload.root_folder) nests the whole tree, Other included, in one folder named after the export, in all four writers (decided 2026-10-12: the export is a library of its own, so the wrapper was one more click at the gig), and the export is a standalonecollection.nmlthe user swaps into a Traktor install — so it needs the full skeleton, verified from the real file:<NML VERSION="20">,<HEAD>,<COLLECTION ENTRIES>,<SETS ENTRIES="0">,<PLAYLISTS>wrapping a$ROOTFOLDER node with aSUBNODES COUNT, and<INDEXING><SORTING_INFO PATH="$COLLECTION">. There is no<MUSICFOLDERS>element, so it is not required. Safety: "clear the destination first" plus "the user picks the destination" is a folder-deletion hazard, so an export writes a.konduktor-export.jsonmanifest and refuses to clear any folder that lacks one — Konduktor only ever deletes what Konduktor wrote. All three targets are now writable from nothing (2026-09-23). The UI needed no change at all —/api/export-targetsreads the exporter registry, so registering one is what makes a platform selectable. Three things were measured rather than assumed, each contradicting the handoff's expectation:- ANLZ analysis files CAN be created from scratch. The handoff called this
unexplored and a likely blocker.
adapters/rekordbox/anlz_writer.pybuilds them; both Pioneer targets need one per track. Two traps:AnlzTag.contentis a construct Switch (pass the structure, not bytes), and the cue-entry structsAnlzCuePoint/AnlzCuePoint2cannot be built at all — each declares"type"twice, once as a magicConstand once as the cue kind, so parsing works (the second overwrites) and building cannot. Cue entries are therefore packed by hand, and the whole FILE is assembled here too, becauseAnlzFile.build()re-builds every tag through those same structs. Base.metadata.create_all()does NOT reproduce Rekordbox's schema. The ORM models 37 tables where a realmaster.dbhas 47, and marks columns NOT NULL that Rekordbox leaves nullable (agentRegistry.id_1caught it). Sofixtures/rekordbox/schema.sqlis the real DDL, plusseed.sqlfor the scaffolding rowsadd_contentrequires —djmdDevice/djmdPropertyare deliberately NOT in the fixture, since they carry the machine's name and UUIDs; those are generated fresh per export.- The two Pioneer key blobs are different.
masterdb's key andonelibrary's are not the same string; mixing them up yields a database Rekordbox cannot open.adapters/onelibrary/export.pywrites a whole drive (PIONEER/rekordbox/ exportLibrary.dbfrom the checked-in DDL, plus ANLZ underPIONEER/USBANLZ/, paths drive-relative). What rekordbox needs was MEASURED — by stripping tags from a rekordbox-written stick one at a time and loading each track in rekordbox 7 (goober, 2026-09-27): a.DATmust carryPVBRAND the preview waveform (PWAV/PWV2) or rekordbox shows NEITHER the grid NOR the hot cues, even when those tags are rekordbox's own bytes. It follows theanalysisDataFilePathcolumn (theP0xx/xxxxxxxxnames need not match its own path hash, which is no standard hash of the path), and the.EXTwaveforms and whole.2EXonly affect drawing. So every export decodes each track once (core/waveform.py, ~1.5 s each via librosa — CoreAudio for AAC on macOS; an undecodable file gets a flat preview) andPVBRis 400 zeros plus the MP3's length in samples. Both Pioneer exporters write the full seven-tag.DAT; themaster.dbtarget's need is inferred, not measured. Progress and cancel reach the writer throughExportPayload.checkpoint. pyrekordbox accepting an ANLZ file proves nothing: its parser ignoreslen_headerand the constants (a 12-bytePCPTheader round-tripped perfectly; real: 28). The cue tags are therefore pinned byte-for-byte against the fixture's rekordbox-written files (test_export_pioneer.py): both files always, every list always (hot + memoryPCOBin each, hot + memoryPCO2in the.EXT, empty ones included), hot cues highest pad first, the1000/1constants inPCP2.fixtures/onelibrary/seed.sqlholds rekordbox's browse scaffolding (menuItem/category/sort/color), like the Rekordbox target's.fileTypefollows the suffix (a.stem.m4ais 4, M4A), bitrate is written in kbps — the genericTrack.bitrateis bits per second (the table divides by 1000; the Pioneer readers multiply) — and a staleexportLibrary.db-wal/-shmis deleted before writing, because Rekordbox leaves both on a stick it mounted and SQLite replays a leftover WAL into a new database. A Pioneer grid can start mid-bar (Motorola opens on beat 3):markers_from_beatsputs the first marker on the first DOWNBEAT — the generic first marker is bar 1 — andbeats_from_markerswrites the lead-in beats back, numbered as they were; before this every bar of such a track landed two beats early, on import to Traktor as well as on export. Rekordbox's clock runs behind the decoded audio by the start padding it does not trim, which depends on the FILE: an MP3 with a Xing/Info header 1105 samples (~25 ms; rekordbox skips the header frame, unlike Traktor), a header-less MP3 0, an M4A its edit list's priming (1024 from FFmpeg, 2112 from Apple — rekordbox ignores the edit list), lossless 0. Measured with blinded cues in rekordbox 7 (kit 4, 2026-09-30); it replaced a fixed 1105 that was 25 ms wrong on header-less MP3s and 22 ms on Apple AAC. The file is read (core/mp3_gapless.py,core/mp4_edit.py); one that cannot be read falls back to 1105. A position before the decoded audio (a Traktor grid anchored in the header frame) clamps to 0 on write, andbeats_from_markersdrops beats before 0 while keeping the rest's bar numbering. The OneLibrary fixture's demo MP3s are 12-byte stubs, so the fixture tests exercise only the fallback —test_timebase.pycovers the per-file rule. The generic model is the decoded time base, soadapters/rekordbox/timebase.pyis applied at EVERY Pioneer boundary: both exporters add it, the OneLibrary reader and the Rekordbox adapter subtract it on read and add it on write (set_cue,set_cue_type, grid save). Without it every cue sat 25 ms early in rekordbox. Drawn waveforms (.EXTPWV3/PWV5,.2EXPWV7/PWV6/PWVC) are generated from one decode (core/waveform.py: 150 frames/s, bands split at 200 Hz / 2.5 kHz) with constants fitted to rekordbox's own files for 12 local tracks and checked on 5 held-out ones (per-band correlation 0.77-0.96). Every column split goes throughwaveform.even_slices, nevernp.array_split: the latter gives the firstn % kchunks an extra frame, so overview column k held LATER audio than its position — up to ~1.8 s by column 420 of 1200, back to 0 at the end. Rekordbox drew such an overview a bar ahead of the playhead mid-track (test_export_pioneer.pypins a burst landing in its own column). rekordbox 7's SONG LIST drawsPWV6— and only whencontent.contentLinkis set. Both measured by bisecting a rekordbox-written stick: removing a track'sPWV6emptied its row (removingPWV4changed nothing), and blanking itscontentLinkalone turned the row plain blue with a "?" beside CUE — what every Konduktor-exported row showed while the exporter left it NULL. It now writes rekordbox's 788224 (besideanalysedBits41; meaning unknown).masterDbId/masterContentIddo NOT matter, so no link to a rekordbox collection is claimed.PWV4is still written (every rekordbox file has it); its low/mid/high bytes cannot be matched per column (b4/b5 are sampled at one instant: column-to-column correlation 0.05/0.16), so each byte is a QUANTILE MAP fitted to rekordbox's distribution (_PWV4_MAPS); smoothed, it tracks rekordbox's at 0.5-0.99. A very loud master draws smaller than in rekordbox, whose PWV4 keeps some absolute level. rekordbox reads 200+ covers from oneArtwork/00001folder (verified on a 207-track export). Decoding is PyAV first (FFmpeg in its wheel: AAC on every OS; measured to start on the same sample as librosa) with librosa as fallback. Cue colour on export is what Konduktor SHOWS (core/cue_colors.py, mirroringlib/cues.ts): a stored colour, else the type's — blue cue, green loop — because "unset" makes rekordbox draw its own defaults (green/orange). rekordbox draws a hot cue from its palette CODE (PCP2byte 44, before the RGB;djmdCue.ColorTableIndexin master.db), not the RGB —adapters/rekordbox/palette.pyholds the 16-swatch table MEASURED from a rekordbox 7 export (the teal-green, 0x13 #00FF30, measured later from a rekordbox-edited stick). Type colours map by intent (cue -> light blue 0x05, loop -> green 0x16), anything else to the nearest hue; the palette has NO white, so a grid companion is code 0 + RGB white (what rekordbox draws for it: unverified). The Artwork (adapters/rekordbox/artwork.py, Pillow), measured on a rekordbox 7 export:PIONEER/Artwork/00001/{a,b}<n>.jpgat 80 px and_mat 240 px,abyte-identical tob, baseline JPEG q85 4:2:0, non-square art LETTERBOXED onto black (a crop or stretch is visibly wrong);image.pathnames thebfile andcontent.image_idpoints at it; one image per track, never shared. The runner carries each cover asExportTrack.artfromLibraryAdapter.cover_art— not re-read from the copied file, since a library's art is not always embedded. The OneLibrary READER now servescover_arttoo (the_mfile). How rekordbox itself splits a large library acrossArtwork/000NNfolders is unknown; one folder of 207 was verified to load in full. Themaster.dbtarget was opened in a real Rekordbox 7 (2026-09-27, by swapping an export into~/Library/Pioneer/rekordboxwith a full backup): it accepts the library, keeps our tracks/cues/analysis untouched, and shows grids, cues and the playlist tree. Two things it needed: amasterPlaylists6.xmlbesidemaster.db(written as a skeleton BEFORE the DB is opened, so pyrekordbox registers each playlist in it), anddjmdContent.ContentLink— a bit field: NULL = blue song-list preview + "?", any value = coloured, 0x200000 clears the "?", and the real library's 0x3D060E adds a badge claiming analysis we do not write, so the exporter uses 0x2C060E. Parity with the OneLibrary target is done and verified in Rekordbox 7: cue colours (palette code indjmdCue.ColorTableIndex,Color-1 — coloured loops included), memory cues (store.add_memory_cue, the same write as the adapter's memory-cue edit: colour inColorfrom the memory palette, the first 10 per track), and artwork (share/PIONEER/Artwork/<uuid[:3]>/<uuid[3:]>/artwork.jpgfit to 800 px plus_m240 /_s80 letterboxed,ImagePath-> artwork.jpg). The exporter writes cues throughstore.set_cue/add_memory_cue, which share_write_cuewith every adapter edit, so thecontentCuemirror stays in step. Two Rekordbox targets, named for what they are: "Rekordbox Library" (export.py, a COMPUTERmaster.db— Rekordbox never reads one from a stick) and "Rekordbox Export" (device_export.py, platformrekordbox_export: a stick's legacy Device Library,PIONEER/rekordbox/export.pdb+exportExt.pdb, what Rekordbox lists as "Device Library" and pre-OneLibrary players read).pdb.pyreads and writes the DeviceSQL format — no public spec; the layout is crate-digger's, CONFIRMED byte for byte against a real rekordbox 7 device export (every row re-encodes identically; a data page rebuilt from its rows is identical). It writes from rekordbox's OWN empty device library (fixtures/rekordbox/device/, the fixed colour/column/menu tables) and follows rekordbox's page allocation (a table's first data page is its reserved candidate; further pages and the new candidate come from next-unused). The track row'sbitmaskis 0xC0700 = OneLibrary'scontentLink;u3/u4are the halves of rekordbox'smasterDbIdand stay 0. A table's HEADER page is not empty: it indexes its data (first data page; for tracks, playlist tree and history an entry per data page,page << 3 | 3if it has room) and the history row counts the tracks — left as in the empty template, Rekordbox 7 said "Device library is corrupted". It shares the stick's analysis files anda<n>.jpgartwork with the OneLibrary target — the same paths, and whichever target runs second REUSES what the first just wrote, so a two-format stick costs one decode per track. A target with no reader is listed by/api/export-targetsfrom the exporter registry;LibraryExporter. display_namenames a target where one platform has two.adapters/rekordbox/export.pywrites amaster.dband replays cues through the ordinaryRekordboxAdapter.set_cue, so it inherits_sync_content_cue, the sparseKindbank and their tests rather than redefining them; its ANLZ files go under ashare/directory besidemaster.db, which is whatAnalysisDataPathis rooted at — write them at the library root and the grid silently reads back empty. Key notation crosses via the wheel, never by copying the string:projection.render_key()is the inverse ofparse_key, shared by both Pioneer targets, so Traktor's"10m"becomes"Cm"rather than a literal"10m"in a Pioneer library. Both are nowcore/musical_key; until 2026-10-04render_keyspelt with SHARPS ("G#m", "D#", "C#m") where rekordbox's own rows say "Abm", "Eb", "Dbm" — measured from the key rows rekordbox 7 created in the local library. In-place writes (set_key, adds) find a key row by MEANING, so a library's existing "12A" or "G#m" row is reused, never duplicated. Caveat:djmdContent.FolderPathis an ABSOLUTE host path, so unlike Traktor and OneLibrary a Rekordbox export is not portable by copying the folder. Still unwritten and documented as unknown: OneLibrary's waveform tags and thecuetable's MPEG seek columns. Step 5 done:exporter.py— plan, mirrored copy, manifest, rollback — onjobs.py, plusPOST /api/exports/{id}/previewand/run, and theExportRunDialog. Multi-target (2026-09-27): audio is copied once, then each target'swrite()runs in turn over it; ANY failure undoes everything, earlier targets' libraries included — and files a failing writer never got to report, via a snapshot of the destination taken before the first write. The manifest listslibraries(plural; the oldlibrarykey is still cleared). Audio lives underContents/, so a music folder with a top-levelPIONEER/or amaster.dbcannot land on a library's path. An exporter's staticdrive_root(OneLibrary: a CDJ looks forPIONEER/only at a stick's root) surfaces asPlatformOption.drive_rootand the preview'snot_drive_root— a warning, not a block, since the other targets are valid in any folder. Three properties it is built around: audio is copied FIRST and the library written LAST, so a cancel leaves no library file and its absence is what marks an export unfinished; rollback registers each file BEFORE writing it, so the in-flight copy is cleaned up too; and the manifest (.konduktor-export.json) means clearing removes exactly what the last export wrote, so a file the user put in the folder survives a re-export. Audio mirrors the source tree relative tocommon_dir_prefix— mirroring absolute paths would put the user's home directory on the stick, and relative paths make filename collisions impossible. A destination Konduktor did not write is refused, not confirmed: there is no "do it anyway". Incremental re-export (2026-09-28): the manifest'saudiomap records, per copy, the SOURCE's path/size/mtime and the COPY's size/mtime as read back (FAT32 rounds mtimes, so they are never assumed equal). A copy is kept when all four match — no checksums: hashing the copy means reading it back over USB, about the cost of copying it. Copies are matched by SOURCE path, since adding a track from another folder movescommon_dir_prefixand every destination path with it; a kept copy that moved is RENAMED (two-phase via.konduktor-moving/, since one's new path can be another's old one). Order: old libraries and unkept files go, kept copies move, a manifest listing every path the run may leave is written (crash-safe), new copies land as*.konduktor-partialand are renamed in, libraries last. A failed run with kept files REWRITES the manifest around them rather than deleting it — else the folder would be refused as not ours. Pioneer waveform decoding is cached on the drive too (core/analysis_cache.py,.konduktor-cache/, keyed by the same source facts + the lead +waveform.ANALYSIS_VERSION— bump that whenanalyse()changes); exporters reach it throughExportTrack.waveform(), neverwaveform.analyse()directly. The Rekordbox Library target's ANLZ paths are a fresh UUID per export, which is why the MEASUREMENT is cached rather than old ANLZ files reused by path. Step 4 done:core/export.py(theLibraryExporterprotocol, its own registry, and the strictly-genericExportPayload— so a Rekordbox collection exports to Traktor with no exporter knowing Rekordbox exists) andadapters/traktor/export.py. The writer creates then replays: it writes a minimal valid NML skeleton, opens aTraktorAdapteron it and populates it with the ordinary commands. That amends the original design note, which rejected create-then-replay on the grounds that the write target must always be a native model parsed from a real file — here it literally is, a skeleton Konduktor just wrote, and the alternative was a second definition of "Track + cues + grid → ENTRY" that would drift fromadd_entryand inherit none of its tests. Exporters declare static capabilities: no instance, no path, because the library being described does not exist yet. Steps 1–3 done:library_id.py;exports.py+ 10 routes +api.ts; and the UI (ExportsSection,ExportDialog, export views inApp, "Add to" on the track context menu and each sidebar playlist row). Next:core/exporter.py+ the Traktor writer, and the export run itself on top ofjobs.pyandimporter.py's copy machinery — there is no Export button yet, since nothing can be written. Note the OneLibrary work already demonstrated creating anexportLibrary.dbfrom nothing, andfixtures/onelibrary/schema.sqlis the DDL to do it with.
- ANLZ analysis files CAN be created from scratch. The handoff called this
unexplored and a likely blocker.
- ✅ Drag and drop (2026-10-06) — tracks onto playlists / exports / the
deck, playlists around the tree and onto exports; see
lib/drag.tsxand the Sidebar under Architecture. - ✅ Remote libraries (2026-10-02) — a Konduktor server in a container
(TrueNAS) holds a Traktor or Rekordbox library; the app opens it as
"Remote": browse, prep, edit, Save (versioned on the server), export sticks,
import by upload, Convert to Stems — all with analysis and separation on the
laptop. One computer at a time, with takeover. See "Remote libraries" under
Architecture. Not yet: verified on a real TrueNAS (the image is published by
CI's
server-imagejob), a web UI served by the server (decided: not now). - ⬜ 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 fromtraktor_nml_utils)._render()inplaylist_store.pyis the single place this happens. - Playlists: keyed by stable
UUID; folders by synthetic path id (fld:<name>/<name>). PRIMARYKEYTYPEisSTEMif the track has a STEMS child (CollectionService.stem_keys, resolved viaentries_for), elseTRACK. - Track metadata:
set_track_metadata(track_id, fields)edits only the SAFE set — title, artist, album, genre, label, remixer, producer, mix, release_date, comment, comment2, rating (0–5 stars →RANKING = stars*51).comment2is Traktor's "Comment 2", stored inINFO@RATING— free text despite the name, unrelated to the stars — and it is collection-only: Traktor writes no file tag for it, so_sync_file_tagsskips it too. 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 aCUE_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_typechanges just the type;delete_hotcueremoves a slot. (The adapter exposes these generically asset_cue/set_cue_type/delete_cue, taking acue_typeSTRING —cue,fade_in,fade_out,load,loop— which the Traktor adapter maps to the integers below.) A grid marker's companion cue is an ordinary hotcue to these commands (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; keepsTEMPO),place_grid_companion.set_lock(track_id, locked)togglesLOCK. 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 viafile_tags(mutagen; ID3/MP4/FLAC/AIFF, WAV skipped) — best-effort (reportsfile-not-foundif the drive isn't mounted,.nmlstill saves). Frame/atom-level writes preserve everything else (verified: cover art, BPM, key, and Traktor STEM atoms all survive)..nmlis 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 callsservice.replace_track()so the change shows immediately (the two models aren't yet consolidated). POST /api/savealways 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
<audio> element can't do reverse/arbitrary-rate scratch or seamless loops).
playbackEngine.ts— anAudioBufferSourceNodewith astartOffset/startedAtposition model;getPosition()reads the AudioContext clock (high-res → smooth playhead). Seamless loops via nativeloopStart/loopEnd;setLoop()re-anchors position so enabling/disabling a loop doesn't desync.scratchEngine.ts— a persistent (idle-silent)ScriptProcessorNodethat, while dragging the main waveform, plays PCM at a position gliding toward the cursor, then coasts with inertia on release.- CRITICAL gotcha: playing an
AudioBuffer"acquires the content" in Firefox and detaches anygetChannelData()views held elsewhere. The scratch engine therefore copies the PCM inload()(never holds the playback buffer's views). Playback and scratch also run on separateAudioContexts — sharing one goes silent after a source has played. waveform.ts— decodes once (buffer reused by both engines, no re-decode), splits into 3 bands viaOfflineAudioContextbiquads, and paints them as three layers, not one blended colour per column: bass (orange) first and tallest, then mids (violet) and highs (cyan) with ascreenblend — no green, matching Traktor's Spectrum. Each band is normalised to its own 99.5th percentile and then EXPANDED (bass steepest): dance music holds its bass near full scale for whole sections, so a linear map draws a solid orange wall instead of the kick pulse. The main view draws 2 px bars with a 1 px gap, binned in track space so bars scroll rather than flicker.rawWave.ts— the raw waveform (decided 2026-10-15, the discussion): the bars' ~7 ms columns of unsigned band energy hide where a kick starts, so the main view can draw the signal itself as a thin line, after Traktor at full zoom. Its own toggle (under the zoom buttons), NOT tied to Grid mode — tried first, changed after use. Shape exact, colour approximate: the tint is the bar palette weighted by the ~7 ms band columns, lerped, mixed in OKLab with the CHROMA restored (bandColour) — a plain RGB mean of orange/violet/cyan lands near grey and read as mud; chosen from five variants rendered on real tracks; the scale is fixed by the track's loudest sample (no per-view gain, so nothing pumps while scrolling). Each pixel is a min→max stroke stretched to touch its neighbour's, so it reads as an envelope zoomed out and a line zoomed in with no switch-over. Data: min/max per 32 samples summarised at load (~4 MB / 6 min) for wide views; below 128 samples a pixel, the visible window read straight from theAudioBuffer(copyFromChannel— no full-length mono copy). Bins sit on a track-space grid like the bars'. A stem track's lanes each draw their own raw line, in the stem's colour, each at its own peak floored at 5% of the loudest. Measured in WKWebView: 0.3 ms a frame at 0.25 s, ~5 ms at 64 s.decodeAlign.ts— the deck's decode vs the grid's time base. Positions are in the backend's PyAV decode; the deck decodes withdecodeAudioData. Measured 2026-10-15 with click files: identical on every format and engine EXCEPT a header-less MP3 under WebKit (the macOS app), decoded 529 samples (12 ms) EARLY — CoreAudio trims the decoder delay with no header to say so; FFmpeg (and Chromium/WebView2) do not. Invisible under bars, a 12 ms miss on the raw line. The engine's offset is MEASURED once per session by decoding a built-in 2.7 KB header-less MP3 (decodeProbe.ts, click at a known FFmpeg sample), and a header-less MP3's buffer (mp3HeaderFrame, a port ofcore/mp3_gapless.parsebehind an is-it-an-MP3 gate) is padded by it indecodeUrl— so playback, scratch and both waveforms move together. Not measured: a header without a trusted encoder-delay field; Edge on a real Windows machine (Chromium on macOS matched).cues.ts— canvas drawers for cue markers (type-colored), the active loop band, the beatgrid (per-segment white beats/brighter downbeats, plus marker lines — gold for the one governing the playhead, accent otherwise, with the active segment tinted), and the floating CUE point (gold). The main waveform's playhead is red; both waveforms share these.beatgrid.ts— theBeatGridmodel (buildBeatGrid→BeatGrid | null). Unit-tested (npm run test, vitest);beatgrid.test.tspins the property that a single-marker grid is algebraically identical to the old single-BPM math, which is what protects the 99.98% of tracks with a constant tempo.- Prep edits go straight to the prep endpoints above; after each edit the
endpoint refreshes the read model (
service.replace_track()) so cue/grid counts update live, and the frontend invalidates the relevant queries.