Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

add Albums + Tracks to the Music studio (db-primary, cover art, audio, playback)

[._.]/ Adam Eivydb452d39f7d7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5c957c7e93..73304e489b 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -11,7 +11,12 @@
## Added
-- **Music studio (Create → Music).** A new home for generating and organizing music with local OSS tools. This first cut ships **Artist** management — reusable musical personas (the audio analogue of Authors): name, genre, bio, musical style, plus a physical description + portrait style used to **generate an artist portrait** with your existing image-gen options, **upload** one, or pick from the gallery. Artists are a db-primary PostgreSQL entity (federation-ready, mirroring Authors). The Albums and Tracks tabs are stubbed for the next update, when album art and on-device music generation (Ace-Step and friends) land. Cross-peer sync for Artists is tracked separately (#1502); for now they're local-only.
+- **Music studio (Create → Music).** A new home for generating and organizing music with local OSS tools, with three tabs:
+ - **Artists** — reusable musical personas (the audio analogue of Authors): name, genre, bio, musical style, plus a physical description + portrait style used to **generate an artist portrait** with your existing image-gen options, **upload** one, or pick from the gallery.
+ - **Albums** — ordered track collections under an artist, with **cover art** you generate (1024×1024 via your image-gen options), upload, or pick from the gallery; add tracks and reorder them.
+ - **Tracks** — singles or album members with lyrics + a generation prompt and an audio file you **upload** or **attach** from the shared music library, played back inline. The generation prompt/lyrics and engine/model/duration metadata are captured now; the on-device **Generate** button (Ace-Step and friends) wires in next update.
+
+ Artists, Albums, and Tracks are db-primary PostgreSQL entities (federation-ready, mirroring Authors). Cross-peer sync for them is tracked separately (#1502); for now they're local-only.
- **Autopilot convergence rounds are now configurable.** The series autopilot re-verifies the arc (and re-reviews the manuscript) in bounded auto-resolve loops, and previously hard-stopped after 3 arc rounds / 2 editorial rounds with "did not converge after 3 rounds" — leaving no way to give a stubborn arc more attempts. You can now set **Arc verify rounds** and **Editorial rounds** (0–20, where 0 skips that gate) in Autonomous mode → **Options**; the values persist as a per-install default and are reused on **Resume**. A per-run override still wins over the saved default, which wins over the built-in floor (3 / 2). When a gate still can't auto-resolve within the limit, the pause message now says how many blocking findings remain and points you to edit the arc/manuscript or raise the limit and resume.
- Editorial Checks page now has an AI provider + model selector that configures the editorial pass. Leave it on "Default provider" to use the active/stage provider, or pick a specific provider/model to override the LLM-backed checks for that run.
diff --git a/client/src/components/music/AlbumsManager.jsx b/client/src/components/music/AlbumsManager.jsx
new file mode 100644
index 0000000000..641e29075f
--- /dev/null
+++ b/client/src/components/music/AlbumsManager.jsx
@@ -0,0 +1,404 @@
+/**
+ * AlbumsManager — manage albums (ordered track collections under an artist).
+ *
+ * Master-detail: a list of albums on the left, an editor on the right. An album
+ * carries a title, artist (via ArtistPicker), description, genre, release year,
+ * cover art (generate via image-gen / upload / gallery — same affordances as the
+ * artist portrait), and an ordered list of tracks (add from existing tracks,
+ * reorder, remove). Mirrors the Authors/Artists master-detail pattern.
+ */
+
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { Plus, Loader2, Trash2, Save, Upload, ImageIcon, Sparkles, X, ArrowUp, ArrowDown } from 'lucide-react';
+import toast from '../ui/Toast';
+import GalleryImagePicker from '../imageGen/GalleryImagePicker';
+import useMediaJobProgress from '../../hooks/useMediaJobProgress';
+import { DEFAULT_NEGATIVE_PROMPT } from '../../lib/imageGenDefaults';
+import { readFileAsBase64 } from '../../utils/fileUpload';
+import { formatTimecode } from '../../utils/formatters';
+import ArtistPicker from './ArtistPicker';
+import {
+ listAlbums, createAlbum, updateAlbum, deleteAlbum,
+ listTracks, uploadGalleryImage, generateImage,
+ ALBUM_TITLE_MAX, ALBUM_DESCRIPTION_MAX, ALBUM_GENRE_MAX, ALBUM_COVER_IMAGE_URL_MAX,
+ ALBUM_RELEASE_YEAR_MIN, ALBUM_RELEASE_YEAR_MAX,
+} from '../../services/api';
+
+const COVER_MAX_BYTES = 12 * 1024 * 1024;
+
+const emptyForm = () => ({
+ title: '', artistId: '', artist: '', description: '', genre: '', releaseYear: '', coverImageUrl: '', trackIds: [],
+});
+
+const formFromAlbum = (a) => ({
+ title: a.title || '',
+ artistId: a.artistId || '',
+ artist: a.artist || '',
+ description: a.description || '',
+ genre: a.genre || '',
+ releaseYear: a.releaseYear != null ? String(a.releaseYear) : '',
+ coverImageUrl: a.coverImageUrl || '',
+ trackIds: Array.isArray(a.trackIds) ? a.trackIds : [],
+});
+
+// Build the cover-art image-gen prompt from the album's title/genre/artist +
+// description. Album covers are square, so callers render at 1024×1024.
+const buildCoverPrompt = (f) => {
+ const bits = [
+ 'Album cover art.',
+ f.title && `Album: "${f.title.trim()}".`,
+ f.artist && `Artist: ${f.artist.trim()}.`,
+ f.genre && `Genre: ${f.genre.trim()}.`,
+ f.description && f.description.trim(),
+ ].filter(Boolean);
+ return bits.join(' ');
+};
+
+function Field({ label, hint, children }) {
+ return (
+ <label className="block">
+ <span className="block text-xs uppercase tracking-wider text-gray-500 mb-1">{label}</span>
+ {children}
+ {hint ? <span className="block text-[11px] text-gray-500 mt-1">{hint}</span> : null}
+ </label>
+ );
+}
+
+export default function AlbumsManager() {
+ const [albums, setAlbums] = useState([]);
+ const [allTracks, setAllTracks] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [selectedId, setSelectedId] = useState(null); // 'new' | id | null
+ const [form, setForm] = useState(emptyForm);
+ const [saving, setSaving] = useState(false);
+ const [confirmDelete, setConfirmDelete] = useState(false);
+ const [galleryOpen, setGalleryOpen] = useState(false);
+ const [uploadingCover, setUploadingCover] = useState(false);
+ const [startingGen, setStartingGen] = useState(false);
+ const [genJobId, setGenJobId] = useState(null);
+ const fileInputRef = useRef(null);
+ const genRequestRef = useRef(0);
+
+ const gen = useMediaJobProgress(genJobId);
+ const isGenerating = startingGen || !!genJobId;
+
+ const setCover = (url) => setForm((f) => ({ ...f, coverImageUrl: url }));
+ const clearGeneration = () => { genRequestRef.current += 1; setGenJobId(null); setStartingGen(false); };
+
+ useEffect(() => {
+ Promise.all([
+ listAlbums().catch(() => []),
+ listTracks({ silent: true }).catch(() => []),
+ ])
+ .then(([albumList, trackList]) => {
+ setAlbums(Array.isArray(albumList) ? albumList : []);
+ setAllTracks(Array.isArray(trackList) ? trackList : []);
+ })
+ .finally(() => setLoading(false));
+ }, []);
+
+ useEffect(() => {
+ if (!genJobId) return;
+ if (gen.status === 'completed' && gen.filename) {
+ setCover(gen.path || `/data/images/${gen.filename}`);
+ setGenJobId(null);
+ toast.success('Cover generated');
+ } else if (gen.status === 'failed' || gen.status === 'canceled') {
+ setGenJobId(null);
+ toast.error(gen.error || 'Cover generation failed');
+ }
+ }, [genJobId, gen.status, gen.filename, gen.path, gen.error]);
+
+ const isCreate = selectedId === 'new';
+ const selected = useMemo(
+ () => (isCreate || !selectedId ? null : albums.find((a) => a.id === selectedId) || null),
+ [albums, selectedId, isCreate],
+ );
+ const tracksById = useMemo(() => new Map(allTracks.map((t) => [t.id, t])), [allTracks]);
+ const canGenerate = !!(form.title.trim() || form.genre.trim() || form.description.trim());
+
+ const selectAlbum = (a) => {
+ setSelectedId(a.id);
+ setForm(formFromAlbum(a));
+ setConfirmDelete(false);
+ clearGeneration();
+ };
+ const startCreate = () => {
+ setSelectedId('new');
+ setForm(emptyForm());
+ setConfirmDelete(false);
+ clearGeneration();
+ };
+
+ const handleGenerateCover = async () => {
+ if (isGenerating || uploadingCover) return;
+ if (!canGenerate) { toast.error('Add a title, genre, or description to generate from'); return; }
+ const requestId = genRequestRef.current;
+ setStartingGen(true);
+ const queued = await generateImage({
+ prompt: buildCoverPrompt(form),
+ negativePrompt: DEFAULT_NEGATIVE_PROMPT,
+ width: 1024,
+ height: 1024,
+ }, { silent: true }).catch((err) => ({ error: err }));
+ if (genRequestRef.current !== requestId) return;
+ setStartingGen(false);
+ if (queued?.error) { toast.error(queued.error.message || 'Cover generation failed'); return; }
+ if (queued.jobId) { setGenJobId(queued.jobId); toast.success('Generating cover…'); return; }
+ const path = queued.path || (queued.filename ? `/data/images/${queued.filename}` : '');
+ if (path) { setCover(path); toast.success('Cover generated'); }
+ else toast.error('Cover generation returned no image');
+ };
+
+ const handleCoverFile = async (e) => {
+ const file = e.target.files?.[0];
+ if (e.target) e.target.value = '';
+ if (!file) return;
+ if (!file.type.startsWith('image/')) { toast.error('Please choose an image file'); return; }
+ if (file.size > COVER_MAX_BYTES) { toast.error(`Image exceeds ${Math.round(COVER_MAX_BYTES / 1024 / 1024)}MB`); return; }
+ setUploadingCover(true);
+ const base64 = await readFileAsBase64(file).catch(() => null);
+ if (!base64) { setUploadingCover(false); toast.error('Could not read that file'); return; }
+ const uploaded = await uploadGalleryImage(base64, { silent: true }).catch((err) => { toast.error(err.message || 'Upload failed'); return null; });
+ setUploadingCover(false);
+ if (uploaded?.path) { setCover(uploaded.path); toast.success('Cover uploaded'); }
+ };
+
+ const handleCoverPick = (item) => {
+ setGalleryOpen(false);
+ const url = item?.previewUrl || (item?.filename ? `/data/images/${item.filename}` : '');
+ if (url) setCover(url);
+ };
+
+ // Ordered track-list editing (display-only order is the trackIds array).
+ const addTrack = (trackId) => setForm((f) => (f.trackIds.includes(trackId) ? f : { ...f, trackIds: [...f.trackIds, trackId] }));
+ const removeTrack = (trackId) => setForm((f) => ({ ...f, trackIds: f.trackIds.filter((id) => id !== trackId) }));
+ const moveTrack = (idx, dir) => setForm((f) => {
+ const next = [...f.trackIds];
+ const j = idx + dir;
+ if (j < 0 || j >= next.length) return f;
+ [next[idx], next[j]] = [next[j], next[idx]];
+ return { ...f, trackIds: next };
+ });
+
+ const buildPayload = () => {
+ const yearNum = form.releaseYear.trim() === '' ? null : Number(form.releaseYear);
+ return {
+ title: form.title.trim(),
+ artistId: form.artistId,
+ artist: form.artist,
+ description: form.description,
+ genre: form.genre,
+ releaseYear: Number.isFinite(yearNum) ? yearNum : null,
+ coverImageUrl: form.coverImageUrl,
+ trackIds: form.trackIds,
+ };
+ };
+
+ const handleSave = async () => {
+ const title = form.title.trim();
+ if (!title) { toast.error('Album title is required'); return; }
+ setSaving(true);
+ const payload = buildPayload();
+ if (isCreate) {
+ const created = await createAlbum(payload).catch((err) => { toast.error(err.message || 'Failed to create album'); return null; });
+ setSaving(false);
+ if (!created) return;
+ setAlbums((prev) => [...prev, created].sort((a, b) => (a.title || '').localeCompare(b.title || '')));
+ setSelectedId(created.id);
+ toast.success(`Created "${created.title}"`);
+ } else {
+ const updated = await updateAlbum(selectedId, payload).catch((err) => { toast.error(err.message || 'Failed to save album'); return null; });
+ setSaving(false);
+ if (!updated) return;
+ setAlbums((prev) => prev.map((a) => (a.id === updated.id ? updated : a)).sort((a, b) => (a.title || '').localeCompare(b.title || '')));
+ toast.success('Saved');
+ }
+ };
+
+ const handleDelete = async () => {
+ if (!selected) return;
+ const prior = albums;
+ setAlbums((prev) => prev.filter((a) => a.id !== selected.id));
+ setSelectedId(null);
+ setConfirmDelete(false);
+ await deleteAlbum(selected.id).catch((err) => { toast.error(err.message || 'Delete failed'); setAlbums(prior); });
+ };
+
+ const availableTracks = allTracks.filter((t) => !form.trackIds.includes(t.id));
+
+ return (
+ <div>
+ <div className="flex items-center justify-between mb-4 flex-wrap gap-3">
+ <p className="text-sm text-gray-400 max-w-2xl">
+ Albums group ordered tracks under an artist, with cover art. Generate a cover from the title +
+ genre, upload one, or pick from your gallery. Add tracks from the Tracks tab and order them here.
+ </p>
+ <button
+ type="button"
+ onClick={startCreate}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium shrink-0"
+ >
+ <Plus size={16} aria-hidden="true" /> New Album
+ </button>
+ </div>
+
+ <div className="grid grid-cols-1 md:grid-cols-[260px_1fr] gap-4">
+ <div className="bg-port-card border border-port-border rounded-lg p-2">
+ {loading ? (
+ <div className="text-gray-500 text-sm p-2">Loading…</div>
+ ) : albums.length === 0 ? (
+ <div className="text-gray-500 text-sm p-2">No albums yet. Click <span className="text-port-accent">New Album</span>.</div>
+ ) : (
+ <ul className="space-y-1">
+ {albums.map((a) => (
+ <li key={a.id}>
+ <button
+ type="button"
+ onClick={() => selectAlbum(a)}
+ className={`w-full text-left px-2 py-2 rounded text-sm flex items-center gap-2 ${
+ a.id === selectedId ? 'bg-port-accent/20 text-white' : 'text-gray-300 hover:bg-port-bg'
+ }`}
+ >
+ {a.coverImageUrl ? (
+ <img src={a.coverImageUrl} alt="" className="w-8 h-8 rounded object-cover border border-port-border shrink-0" />
+ ) : (
+ <span className="w-8 h-8 rounded border border-port-border bg-port-bg flex items-center justify-center text-gray-600 shrink-0"><ImageIcon size={14} /></span>
+ )}
+ <span className="flex-1 min-w-0">
+ <span className="block truncate">{a.title}</span>
+ <span className="block text-[11px] text-gray-500 truncate">{(a.trackIds?.length || 0)} track{(a.trackIds?.length || 0) === 1 ? '' : 's'}{a.genre ? ` · ${a.genre}` : ''}</span>
+ </span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ {!isCreate && !selected ? (
+ <div className="text-gray-500 text-sm">Select an album to edit, or create a new one.</div>
+ ) : (
+ <div className="space-y-3">
+ <div className="flex gap-4 items-start">
+ {/* Cover art */}
+ <div className="shrink-0">
+ {isGenerating ? (
+ <div className="relative w-28 h-28 rounded border border-port-border bg-port-bg overflow-hidden flex items-center justify-center">
+ {gen.currentImage ? (
+ <img src={`data:image/png;base64,${gen.currentImage}`} alt="Generating cover preview" className="w-full h-full object-cover opacity-70" />
+ ) : <Loader2 size={22} className="animate-spin text-port-accent" />}
+ {gen.totalSteps ? (
+ <div className="absolute bottom-0 inset-x-0 bg-black/60 text-[9px] text-white text-center py-0.5 font-mono">{Math.round((gen.step / gen.totalSteps) * 100)}%</div>
+ ) : null}
+ </div>
+ ) : form.coverImageUrl ? (
+ <div className="relative">
+ <img src={form.coverImageUrl} alt="Album cover" className="w-28 h-28 rounded object-cover border border-port-border bg-port-bg" />
+ <button type="button" onClick={() => setCover('')} title="Remove cover" className="absolute -top-2 -right-2 p-1 rounded-full bg-port-bg border border-port-border text-gray-400 hover:text-port-error">
+ <X size={12} />
+ </button>
+ </div>
+ ) : (
+ <div className="w-28 h-28 rounded border border-dashed border-port-border bg-port-bg flex items-center justify-center text-gray-600"><ImageIcon size={24} /></div>
+ )}
+ </div>
+ <div className="flex-1 space-y-2">
+ <Field label="Title">
+ <input value={form.title} onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))} placeholder="Album title" maxLength={ALBUM_TITLE_MAX} className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white" autoFocus />
+ </Field>
+ <div className="flex items-center gap-2 flex-wrap">
+ <button type="button" onClick={handleGenerateCover} disabled={isGenerating || uploadingCover || !canGenerate} title={canGenerate ? 'Generate a cover' : 'Add a title, genre, or description first'} className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50">
+ {isGenerating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />} Generate cover
+ </button>
+ <button type="button" onClick={() => fileInputRef.current?.click()} disabled={uploadingCover || isGenerating} className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50">
+ {uploadingCover ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />} Upload
+ </button>
+ <button type="button" onClick={() => setGalleryOpen(true)} disabled={isGenerating} className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50">
+ <ImageIcon size={14} /> Gallery
+ </button>
+ <input ref={fileInputRef} type="file" accept="image/*" onChange={handleCoverFile} className="hidden" />
+ </div>
+ </div>
+ </div>
+
+ <Field label="Artist">
+ <ArtistPicker id="album-artist" value={form.artistId} name={form.artist} onChange={(artistId, artist) => setForm((f) => ({ ...f, artistId, artist }))} />
+ </Field>
+ <div className="grid grid-cols-2 gap-3">
+ <Field label="Genre">
+ <input value={form.genre} onChange={(e) => setForm((f) => ({ ...f, genre: e.target.value }))} placeholder="dream pop" maxLength={ALBUM_GENRE_MAX} className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm" />
+ </Field>
+ <Field label="Release year">
+ <input type="number" value={form.releaseYear} onChange={(e) => setForm((f) => ({ ...f, releaseYear: e.target.value }))} placeholder="2026" min={ALBUM_RELEASE_YEAR_MIN} max={ALBUM_RELEASE_YEAR_MAX} className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm" />
+ </Field>
+ </div>
+ <Field label="Description" hint="Liner notes / blurb.">
+ <textarea value={form.description} onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))} rows={3} maxLength={ALBUM_DESCRIPTION_MAX} className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm" />
+ </Field>
+
+ <Field label="Tracks" hint="Ordered — reorder with the arrows. Add from your existing tracks.">
+ {form.trackIds.length === 0 ? (
+ <p className="text-xs text-gray-500">No tracks on this album yet.</p>
+ ) : (
+ <ol className="space-y-1">
+ {form.trackIds.map((tid, idx) => {
+ const t = tracksById.get(tid);
+ return (
+ <li key={tid} className="flex items-center gap-2 px-2 py-1.5 rounded bg-port-bg border border-port-border">
+ <span className="text-[11px] text-gray-500 w-5 text-right">{idx + 1}.</span>
+ <span className="flex-1 min-w-0 truncate text-sm text-gray-200">{t ? t.title : <span className="text-gray-500 italic">(missing track)</span>}</span>
+ {t?.durationSec ? <span className="text-[11px] text-gray-500">{formatTimecode(t.durationSec)}</span> : null}
+ <button type="button" onClick={() => moveTrack(idx, -1)} disabled={idx === 0} className="p-1 text-gray-500 hover:text-white disabled:opacity-30" aria-label="Move up"><ArrowUp size={13} /></button>
+ <button type="button" onClick={() => moveTrack(idx, 1)} disabled={idx === form.trackIds.length - 1} className="p-1 text-gray-500 hover:text-white disabled:opacity-30" aria-label="Move down"><ArrowDown size={13} /></button>
+ <button type="button" onClick={() => removeTrack(tid)} className="p-1 text-gray-500 hover:text-port-error" aria-label="Remove track"><X size={13} /></button>
+ </li>
+ );
+ })}
+ </ol>
+ )}
+ {availableTracks.length > 0 ? (
+ <select
+ value=""
+ onChange={(e) => { if (e.target.value) addTrack(e.target.value); }}
+ className="mt-2 w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
+ >
+ <option value="">+ Add a track…</option>
+ {availableTracks.map((t) => (
+ <option key={t.id} value={t.id}>{t.title}</option>
+ ))}
+ </select>
+ ) : (
+ <p className="text-[11px] text-gray-500 mt-2">All your tracks are on this album. Create more in the Tracks tab.</p>
+ )}
+ </Field>
+
+ <div className="flex items-center gap-2 pt-1 flex-wrap">
+ <button type="button" onClick={handleSave} disabled={saving || !form.title.trim()} className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50">
+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
+ {isCreate ? 'Create' : 'Save'}
+ </button>
+ {!isCreate && selected ? (
+ confirmDelete ? (
+ <span className="inline-flex items-center gap-2 text-sm">
+ <span className="text-port-error">Delete this album?</span>
+ <button type="button" onClick={handleDelete} className="px-2 py-1 rounded bg-port-error/20 text-port-error hover:bg-port-error/30">Yes, delete</button>
+ <button type="button" onClick={() => setConfirmDelete(false)} className="px-2 py-1 rounded text-gray-400 hover:text-white">Cancel</button>
+ </span>
+ ) : (
+ <button type="button" onClick={() => setConfirmDelete(true)} className="inline-flex items-center gap-2 px-3 py-2 rounded-lg text-gray-400 hover:text-port-error text-sm">
+ <Trash2 size={14} /> Delete
+ </button>
+ )
+ ) : null}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ <GalleryImagePicker open={galleryOpen} onClose={() => setGalleryOpen(false)} onSelect={handleCoverPick} />
+ </div>
+ );
+}
diff --git a/client/src/components/music/ArtistPicker.jsx b/client/src/components/music/ArtistPicker.jsx
new file mode 100644
index 0000000000..92476b9099
--- /dev/null
+++ b/client/src/components/music/ArtistPicker.jsx
@@ -0,0 +1,64 @@
+/**
+ * ArtistPicker — pick an Artist persona for an album or track.
+ *
+ * Mirrors pipeline/AuthorPicker. Selecting an artist calls
+ * `onChange(artistId, artistName)` so the caller can store BOTH the FK
+ * (`artistId`) and the denormalized name (`artist`) — the name renders before
+ * the (local-only) artist record syncs. Selecting "— No artist —" calls
+ * `onChange('', '')`. Self-contained: fetches the artist list on mount.
+ */
+
+import { useEffect, useState } from 'react';
+import { Link } from 'react-router-dom';
+import { listArtists } from '../../services/api';
+
+export default function ArtistPicker({ id = 'music-artist', value, name, onChange, disabled = false }) {
+ const [artists, setArtists] = useState([]);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ let alive = true;
+ listArtists({ silent: true })
+ .then((list) => { if (alive) setArtists(Array.isArray(list) ? list : []); })
+ .catch(() => { if (alive) setArtists([]); })
+ .finally(() => { if (alive) setLoading(false); });
+ return () => { alive = false; };
+ }, []);
+
+ const handleChange = (e) => {
+ const artistId = e.target.value || '';
+ const picked = artists.find((a) => a.id === artistId);
+ onChange(artistId, picked ? picked.name : '');
+ };
+
+ // An artistId not in the fetched list (deleted persona) shouldn't silently
+ // snap to "none" — surface it so the link isn't lost.
+ const unknownLink = value && !artists.some((a) => a.id === value);
+
+ return (
+ <div>
+ <select
+ id={id}
+ value={value || ''}
+ onChange={handleChange}
+ disabled={disabled || loading}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white disabled:opacity-50"
+ >
+ <option value="">— No artist —</option>
+ {artists.map((a) => (
+ <option key={a.id} value={a.id}>{a.name}</option>
+ ))}
+ {unknownLink ? <option value={value}>{name || 'Linked artist (unavailable)'}</option> : null}
+ </select>
+ <p className="text-[11px] text-gray-500 mt-1">
+ {artists.length === 0 && !loading ? (
+ <>No artist personas yet — <Link to="/music/artists" className="text-port-accent hover:underline">create one</Link>.</>
+ ) : !value && name ? (
+ <>Unlinked artist: <span className="text-gray-400">{name}</span> — pick a persona to link it.</>
+ ) : (
+ <>Manage personas in <Link to="/music/artists" className="text-port-accent hover:underline">Artists</Link>.</>
+ )}
+ </p>
+ </div>
+ );
+}
diff --git a/client/src/components/music/TracksManager.jsx b/client/src/components/music/TracksManager.jsx
new file mode 100644
index 0000000000..6e61e0132c
--- /dev/null
+++ b/client/src/components/music/TracksManager.jsx
@@ -0,0 +1,368 @@
+/**
+ * TracksManager — manage music tracks (singles or album members).
+ *
+ * Master-detail: a list of tracks on the left, an editor on the right. A track
+ * carries a title, an artist (via ArtistPicker), lyrics + a generation prompt,
+ * and an audio file. Audio is stored in the shared music library; the editor
+ * uploads a file or attaches an existing library track, and plays it inline.
+ *
+ * On-device generation (engine/model/duration) lands in Phase 4 — for now the
+ * engine/model/duration are shown as read-only metadata on a generated track
+ * and the prompt/lyrics fields are captured so a later Generate button can use
+ * them. Mirrors the Authors/Artists master-detail pattern.
+ */
+
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { Plus, Loader2, Trash2, Save, Upload, Music2, X, Library } from 'lucide-react';
+import toast from '../ui/Toast';
+import { formatTimecode } from '../../utils/formatters';
+import ArtistPicker from './ArtistPicker';
+import {
+ listTracks, createTrack, updateTrack, deleteTrack,
+ uploadTrackAudio, attachTrackAudio, clearTrackAudio, listMusicLibrary,
+ TRACK_TITLE_MAX, TRACK_LYRICS_MAX, TRACK_PROMPT_MAX,
+} from '../../services/api';
+
+// Cap audio uploads to match the server's MUSIC_UPLOAD_MAX_BYTES (50MB).
+const AUDIO_MAX_BYTES = 50 * 1024 * 1024;
+const AUDIO_SRC = (filename) => `/data/music/${encodeURIComponent(filename)}`;
+
+const emptyForm = () => ({
+ title: '', artistId: '', artist: '', lyrics: '', prompt: '', audioFilename: '',
+});
+
+const formFromTrack = (t) => ({
+ title: t.title || '',
+ artistId: t.artistId || '',
+ artist: t.artist || '',
+ lyrics: t.lyrics || '',
+ prompt: t.prompt || '',
+ audioFilename: t.audioFilename || '',
+});
+
+function Field({ label, hint, children }) {
+ return (
+ <label className="block">
+ <span className="block text-xs uppercase tracking-wider text-gray-500 mb-1">{label}</span>
+ {children}
+ {hint ? <span className="block text-[11px] text-gray-500 mt-1">{hint}</span> : null}
+ </label>
+ );
+}
+
+export default function TracksManager() {
+ const [tracks, setTracks] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [selectedId, setSelectedId] = useState(null); // 'new' | id | null
+ const [form, setForm] = useState(emptyForm);
+ const [saving, setSaving] = useState(false);
+ const [confirmDelete, setConfirmDelete] = useState(false);
+ const [uploading, setUploading] = useState(false);
+ const [libraryOpen, setLibraryOpen] = useState(false);
+ const [library, setLibrary] = useState([]);
+ const fileInputRef = useRef(null);
+
+ useEffect(() => {
+ listTracks()
+ .then((list) => setTracks(Array.isArray(list) ? list : []))
+ .catch((err) => toast.error(err.message || 'Failed to load tracks'))
+ .finally(() => setLoading(false));
+ }, []);
+
+ const isCreate = selectedId === 'new';
+ const selected = useMemo(
+ () => (isCreate || !selectedId ? null : tracks.find((t) => t.id === selectedId) || null),
+ [tracks, selectedId, isCreate],
+ );
+ // The persisted track (for gen metadata + the audio player, which need a saved id).
+ const persisted = selected;
+
+ const selectTrack = (t) => {
+ setSelectedId(t.id);
+ setForm(formFromTrack(t));
+ setConfirmDelete(false);
+ setLibraryOpen(false);
+ };
+
+ const startCreate = () => {
+ setSelectedId('new');
+ setForm(emptyForm());
+ setConfirmDelete(false);
+ setLibraryOpen(false);
+ };
+
+ const upsertLocal = (track) => {
+ setTracks((prev) => {
+ const exists = prev.some((t) => t.id === track.id);
+ return exists ? prev.map((t) => (t.id === track.id ? track : t)) : [...prev, track];
+ });
+ };
+
+ const handleSave = async () => {
+ const title = form.title.trim();
+ if (!title) { toast.error('Track title is required'); return; }
+ setSaving(true);
+ const payload = { ...form, title };
+ if (isCreate) {
+ const created = await createTrack(payload).catch((err) => { toast.error(err.message || 'Failed to create track'); return null; });
+ setSaving(false);
+ if (!created) return;
+ upsertLocal(created);
+ setSelectedId(created.id);
+ toast.success(`Created "${created.title}"`);
+ } else {
+ const updated = await updateTrack(selectedId, payload).catch((err) => { toast.error(err.message || 'Failed to save track'); return null; });
+ setSaving(false);
+ if (!updated) return;
+ upsertLocal(updated);
+ toast.success('Saved');
+ }
+ };
+
+ const handleDelete = async () => {
+ if (!selected) return;
+ const prior = tracks;
+ setTracks((prev) => prev.filter((t) => t.id !== selected.id));
+ setSelectedId(null);
+ setConfirmDelete(false);
+ await deleteTrack(selected.id).catch((err) => { toast.error(err.message || 'Delete failed'); setTracks(prior); });
+ };
+
+ // Audio actions operate on the SAVED track (the server attaches the filename
+ // and returns the updated record). A brand-new unsaved track must be saved first.
+ const requireSaved = () => {
+ if (!persisted) { toast.error('Save the track first, then add audio'); return false; }
+ return true;
+ };
+
+ const handleAudioFile = async (e) => {
+ const file = e.target.files?.[0];
+ if (e.target) e.target.value = '';
+ if (!file || !requireSaved()) return;
+ if (file.size > AUDIO_MAX_BYTES) { toast.error(`Audio exceeds ${Math.round(AUDIO_MAX_BYTES / 1024 / 1024)}MB`); return; }
+ setUploading(true);
+ const fd = new FormData();
+ fd.append('track', file, file.name);
+ const res = await uploadTrackAudio(persisted.id, fd, { silent: true }).catch((err) => { toast.error(err.message || 'Upload failed'); return null; });
+ setUploading(false);
+ if (res?.track) {
+ upsertLocal(res.track);
+ setForm((f) => ({ ...f, audioFilename: res.track.audioFilename }));
+ toast.success('Audio uploaded');
+ }
+ };
+
+ const openLibrary = async () => {
+ if (!requireSaved()) return;
+ const res = await listMusicLibrary({ silent: true }).catch(() => null);
+ setLibrary(Array.isArray(res?.tracks) ? res.tracks : []);
+ setLibraryOpen(true);
+ };
+
+ const attachFromLibrary = async (filename) => {
+ setLibraryOpen(false);
+ const res = await attachTrackAudio(persisted.id, filename, { silent: true }).catch((err) => { toast.error(err.message || 'Attach failed'); return null; });
+ if (res?.track) {
+ upsertLocal(res.track);
+ setForm((f) => ({ ...f, audioFilename: res.track.audioFilename }));
+ toast.success('Audio attached');
+ }
+ };
+
+ const removeAudio = async () => {
+ if (!persisted) { setForm((f) => ({ ...f, audioFilename: '' })); return; }
+ const res = await clearTrackAudio(persisted.id, { silent: true }).catch((err) => { toast.error(err.message || 'Failed to clear audio'); return null; });
+ if (res?.track) {
+ upsertLocal(res.track);
+ setForm((f) => ({ ...f, audioFilename: '' }));
+ }
+ };
+
+ return (
+ <div>
+ <div className="flex items-center justify-between mb-4 flex-wrap gap-3">
+ <p className="text-sm text-gray-400 max-w-2xl">
+ Tracks are singles or album members. Set the artist, write lyrics and a generation prompt, then
+ upload an audio file or attach one from your music library. On-device generation lands next update.
+ </p>
+ <button
+ type="button"
+ onClick={startCreate}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium shrink-0"
+ >
+ <Plus size={16} aria-hidden="true" /> New Track
+ </button>
+ </div>
+
+ <div className="grid grid-cols-1 md:grid-cols-[260px_1fr] gap-4">
+ <div className="bg-port-card border border-port-border rounded-lg p-2">
+ {loading ? (
+ <div className="text-gray-500 text-sm p-2">Loading…</div>
+ ) : tracks.length === 0 ? (
+ <div className="text-gray-500 text-sm p-2">No tracks yet. Click <span className="text-port-accent">New Track</span>.</div>
+ ) : (
+ <ul className="space-y-1">
+ {tracks.map((t) => (
+ <li key={t.id}>
+ <button
+ type="button"
+ onClick={() => selectTrack(t)}
+ className={`w-full text-left px-3 py-2 rounded text-sm truncate flex items-center gap-2 ${
+ t.id === selectedId ? 'bg-port-accent/20 text-white' : 'text-gray-300 hover:bg-port-bg'
+ }`}
+ >
+ <Music2 size={13} className={t.audioFilename ? 'text-port-success shrink-0' : 'text-gray-600 shrink-0'} aria-hidden="true" />
+ <span className="flex-1 min-w-0 truncate">{t.title}</span>
+ {t.durationSec ? <span className="text-[11px] text-gray-500 shrink-0">{formatTimecode(t.durationSec)}</span> : null}
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ {!isCreate && !selected ? (
+ <div className="text-gray-500 text-sm">Select a track to edit, or create a new one.</div>
+ ) : (
+ <div className="space-y-3">
+ <Field label="Title">
+ <input
+ value={form.title}
+ onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))}
+ placeholder="Track title"
+ maxLength={TRACK_TITLE_MAX}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ autoFocus
+ />
+ </Field>
+ <Field label="Artist">
+ <ArtistPicker
+ id="track-artist"
+ value={form.artistId}
+ name={form.artist}
+ onChange={(artistId, artist) => setForm((f) => ({ ...f, artistId, artist }))}
+ />
+ </Field>
+ <Field label="Prompt" hint="Text/style prompt for generation (used by the upcoming on-device generators).">
+ <textarea
+ value={form.prompt}
+ onChange={(e) => setForm((f) => ({ ...f, prompt: e.target.value }))}
+ rows={2}
+ maxLength={TRACK_PROMPT_MAX}
+ placeholder="Warm fingerpicked folk, breathy vocals, tape hiss, 90 BPM."
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
+ />
+ </Field>
+ <Field label="Lyrics" hint="Full lyrics — also the conditioning text for lyric-aware generators (Ace-Step).">
+ <textarea
+ value={form.lyrics}
+ onChange={(e) => setForm((f) => ({ ...f, lyrics: e.target.value }))}
+ rows={6}
+ maxLength={TRACK_LYRICS_MAX}
+ placeholder={'[verse]\n…\n[chorus]\n…'}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm font-mono"
+ />
+ </Field>
+
+ {/* Generation metadata (read-only) — populated when a track is generated. */}
+ {persisted && (persisted.engine || persisted.modelId || persisted.durationSec) ? (
+ <div className="flex flex-wrap items-center gap-2 text-[11px]">
+ {persisted.engine ? <span className="px-2 py-0.5 rounded-full bg-port-bg border border-port-border text-gray-400">engine: {persisted.engine}</span> : null}
+ {persisted.modelId ? <span className="px-2 py-0.5 rounded-full bg-port-bg border border-port-border text-gray-400">model: {persisted.modelId}</span> : null}
+ {persisted.durationSec ? <span className="px-2 py-0.5 rounded-full bg-port-bg border border-port-border text-gray-400">{formatTimecode(persisted.durationSec)}</span> : null}
+ </div>
+ ) : null}
+
+ <Field label="Audio" hint="Upload an audio file or attach one from the shared music library. Save the track first.">
+ {form.audioFilename ? (
+ <div className="space-y-2">
+ <audio controls src={AUDIO_SRC(form.audioFilename)} className="w-full">
+ <track kind="captions" />
+ </audio>
+ <div className="flex items-center gap-2">
+ <span className="text-[11px] text-gray-500 truncate flex-1">{form.audioFilename}</span>
+ <button
+ type="button"
+ onClick={removeAudio}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-gray-400 hover:text-port-error text-xs"
+ >
+ <X size={12} /> Remove
+ </button>
+ </div>
+ </div>
+ ) : (
+ <div className="flex items-center gap-2 flex-wrap">
+ <button
+ type="button"
+ onClick={() => (requireSaved() ? fileInputRef.current?.click() : null)}
+ disabled={uploading}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50"
+ >
+ {uploading ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />} Upload
+ </button>
+ <button
+ type="button"
+ onClick={openLibrary}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent"
+ >
+ <Library size={14} /> From library
+ </button>
+ <input ref={fileInputRef} type="file" accept="audio/*,.mp3,.wav,.m4a,.ogg,.flac" onChange={handleAudioFile} className="hidden" />
+ </div>
+ )}
+ {libraryOpen ? (
+ <div className="mt-2 border border-port-border rounded-lg bg-port-bg max-h-48 overflow-y-auto">
+ {library.length === 0 ? (
+ <div className="text-xs text-gray-500 p-3">The music library is empty — upload a track first.</div>
+ ) : (
+ <ul className="divide-y divide-port-border">
+ {library.map((item) => (
+ <li key={item.filename}>
+ <button
+ type="button"
+ onClick={() => attachFromLibrary(item.filename)}
+ className="w-full text-left px-3 py-2 text-sm text-gray-300 hover:bg-port-card flex items-center gap-2"
+ >
+ <Music2 size={13} className="text-gray-500 shrink-0" />
+ <span className="flex-1 min-w-0 truncate">{item.label || item.filename}</span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ ) : null}
+ </Field>
+
+ <div className="flex items-center gap-2 pt-1 flex-wrap">
+ <button
+ type="button"
+ onClick={handleSave}
+ disabled={saving || !form.title.trim()}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
+ >
+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
+ {isCreate ? 'Create' : 'Save'}
+ </button>
+ {!isCreate && selected ? (
+ confirmDelete ? (
+ <span className="inline-flex items-center gap-2 text-sm">
+ <span className="text-port-error">Delete this track?</span>
+ <button type="button" onClick={handleDelete} className="px-2 py-1 rounded bg-port-error/20 text-port-error hover:bg-port-error/30">Yes, delete</button>
+ <button type="button" onClick={() => setConfirmDelete(false)} className="px-2 py-1 rounded text-gray-400 hover:text-white">Cancel</button>
+ </span>
+ ) : (
+ <button type="button" onClick={() => setConfirmDelete(true)} className="inline-flex items-center gap-2 px-3 py-2 rounded-lg text-gray-400 hover:text-port-error text-sm">
+ <Trash2 size={14} /> Delete
+ </button>
+ )
+ ) : null}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/pages/Music.jsx b/client/src/pages/Music.jsx
index 8719773c3c..e01dd6ca44 100644
--- a/client/src/pages/Music.jsx
+++ b/client/src/pages/Music.jsx
@@ -2,8 +2,9 @@
* Music studio — generate and organize music with local OSS tools.
*
* A hub for the music feature: manage **Artists** (reusable musical personas,
- * like Authors), and — landing in later updates — **Albums** and **Tracks**
- * with album art and on-device generation (Ace-Step and friends).
+ * like Authors), **Albums** (ordered track collections with cover art), and
+ * **Tracks** (singles or album members, with uploaded/attached audio). On-device
+ * generation (Ace-Step and friends) wires into the Tracks editor next update.
*
* Tabbed via URL param (`/music/:tab`) per the linkable-routes convention, so a
* tab is deep-linkable and survives reload. `tab` defaults to `artists`.
@@ -12,6 +13,8 @@
import { useParams, Navigate, Link } from 'react-router-dom';
import { Music as MusicIcon, Mic, Disc3, AudioLines } from 'lucide-react';
import ArtistsManager from '../components/music/ArtistsManager';
+import AlbumsManager from '../components/music/AlbumsManager';
+import TracksManager from '../components/music/TracksManager';
const TABS = [
{ id: 'artists', label: 'Artists', icon: Mic },
@@ -21,18 +24,6 @@ const TABS = [
const VALID = new Set(TABS.map((t) => t.id));
-function ComingSoon({ what }) {
- return (
- <div className="bg-port-card border border-port-border rounded-lg p-8 text-center">
- <p className="text-gray-300 font-medium">{what} are coming soon.</p>
- <p className="text-sm text-gray-500 mt-2 max-w-md mx-auto">
- Create an Artist first — {what.toLowerCase()} are organized under an artist, with album art and
- on-device music generation landing in the next update.
- </p>
- </div>
- );
-}
-
export default function Music() {
const { tab } = useParams();
const active = tab || 'artists';
@@ -68,8 +59,8 @@ export default function Music() {
</div>
{active === 'artists' && <ArtistsManager />}
- {active === 'albums' && <ComingSoon what="Albums" />}
- {active === 'tracks' && <ComingSoon what="Tracks" />}
+ {active === 'albums' && <AlbumsManager />}
+ {active === 'tracks' && <TracksManager />}
</div>
);
}
diff --git a/client/src/services/README.md b/client/src/services/README.md
index dcb37cbacc..1ae1441625 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -91,6 +91,8 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiUniverseBuilder.js` | Universe Builder (generate + edit + commit). |
| `apiAuthors.js` | Author personas (name, writing style, bio, headshot description/style). |
| `apiArtists.js` | Music artist personas (name, genre, bio, musical style, portrait description/style). |
+| `apiAlbums.js` | Music albums (title, artist FK + name, description, genre, release year, cover art, ordered track ids). |
+| `apiTracks.js` | Music tracks (title, album/artist FKs, lyrics, prompt, gen metadata, audio-library pointer) + shared music-library list + audio upload/attach/clear. |
| `apiWritersRoom.js` | Writers Room (folders + works + drafts, live continuation + render-preview reservation, scene-image attach). |
| `apiSharing.js` | Share buckets + federation sync. |
| `apiRounds.js` | Rounds workbench CRUD (a cappella round writing + arranging voice layers + learning tracking). |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 912151d849..a5d5f5dc3e 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -49,6 +49,8 @@ export * from './apiWritersRoom.js';
export * from './apiUniverseBuilder.js';
export * from './apiAuthors.js';
export * from './apiArtists.js';
+export * from './apiAlbums.js';
+export * from './apiTracks.js';
export * from './apiPipeline.js';
export * from './apiSharing.js';
export * from './apiRounds.js';
diff --git a/client/src/services/apiAlbums.js b/client/src/services/apiAlbums.js
new file mode 100644
index 0000000000..e01ef7c9b0
--- /dev/null
+++ b/client/src/services/apiAlbums.js
@@ -0,0 +1,30 @@
+import { request } from './apiCore.js';
+
+// ---- Music albums ----
+// Albums group ordered tracks under an artist, with cover art. `artistId` is the
+// FK; `artist` is the denormalized name (renders before the artist record syncs).
+// `options` lets a caller suppress request()'s auto-toast with `{ silent: true }`.
+export const listAlbums = (options = {}) => request('/albums', options);
+export const getAlbum = (id, options = {}) => request(`/albums/${encodeURIComponent(id)}`, options);
+export const createAlbum = (data, requestOptions = {}) => request('/albums', {
+ method: 'POST',
+ body: JSON.stringify(data),
+ ...requestOptions,
+});
+export const updateAlbum = (id, patch, requestOptions = {}) => request(`/albums/${encodeURIComponent(id)}`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+ ...requestOptions,
+});
+export const deleteAlbum = (id, requestOptions = {}) => request(`/albums/${encodeURIComponent(id)}`, {
+ method: 'DELETE',
+ ...requestOptions,
+});
+
+// Mirror server caps in server/services/albums/logic.js — bump both sides.
+export const ALBUM_TITLE_MAX = 200;
+export const ALBUM_DESCRIPTION_MAX = 4000;
+export const ALBUM_GENRE_MAX = 120;
+export const ALBUM_COVER_IMAGE_URL_MAX = 1000;
+export const ALBUM_RELEASE_YEAR_MIN = 1850;
+export const ALBUM_RELEASE_YEAR_MAX = 2200;
diff --git a/client/src/services/apiTracks.js b/client/src/services/apiTracks.js
new file mode 100644
index 0000000000..dc409c024b
--- /dev/null
+++ b/client/src/services/apiTracks.js
@@ -0,0 +1,56 @@
+import { request } from './apiCore.js';
+
+// ---- Music tracks ----
+// A track is a single song/recording — standalone or part of an album. It stores
+// a pointer (`audioFilename`) into the shared music library; the bytes are
+// uploaded/generated there. `options` lets a caller suppress request()'s
+// auto-toast with `{ silent: true }`.
+export const listTracks = (options = {}) => request('/tracks', options);
+export const getTrack = (id, options = {}) => request(`/tracks/${encodeURIComponent(id)}`, options);
+export const createTrack = (data, requestOptions = {}) => request('/tracks', {
+ method: 'POST',
+ body: JSON.stringify(data),
+ ...requestOptions,
+});
+export const updateTrack = (id, patch, requestOptions = {}) => request(`/tracks/${encodeURIComponent(id)}`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+ ...requestOptions,
+});
+export const deleteTrack = (id, requestOptions = {}) => request(`/tracks/${encodeURIComponent(id)}`, {
+ method: 'DELETE',
+ ...requestOptions,
+});
+
+// Shared music library (uploaded + generated tracks under data/music/). Used to
+// attach an existing track without re-uploading.
+export const listMusicLibrary = (options = {}) => request('/tracks/library', options);
+
+// Attach an existing library track (by stored filename) to this track.
+export const attachTrackAudio = (id, filename, requestOptions = {}) => request(`/tracks/${encodeURIComponent(id)}/audio/attach`, {
+ method: 'POST',
+ body: JSON.stringify({ filename }),
+ ...requestOptions,
+});
+
+// Clear the audio pointer (leaves the library file in place — it may be shared).
+export const clearTrackAudio = (id, requestOptions = {}) => request(`/tracks/${encodeURIComponent(id)}/audio`, {
+ method: 'DELETE',
+ ...requestOptions,
+});
+
+// Upload an audio file (FormData with a `track` file field) into the library and
+// attach it to this track. The caller builds the FormData; we pass it through as
+// the request body so the multipart boundary header is set by the browser.
+export const uploadTrackAudio = (id, formData, requestOptions = {}) => request(`/tracks/${encodeURIComponent(id)}/audio/upload`, {
+ method: 'POST',
+ body: formData,
+ ...requestOptions,
+});
+
+// Mirror server caps in server/services/tracks/logic.js — bump both sides.
+export const TRACK_TITLE_MAX = 200;
+export const TRACK_LYRICS_MAX = 20000;
+export const TRACK_PROMPT_MAX = 8000;
+export const TRACK_DURATION_MIN_SEC = 1;
+export const TRACK_DURATION_MAX_SEC = 3600;
diff --git a/server/index.js b/server/index.js
index 75bef4fab7..b86c80ac41 100644
--- a/server/index.js
+++ b/server/index.js
@@ -111,6 +111,8 @@ import writersRoomRoutes from './routes/writersRoom.js';
import universeBuilderRoutes from './routes/universeBuilder.js';
import authorsRoutes from './routes/authors.js';
import artistsRoutes from './routes/artists.js';
+import albumsRoutes from './routes/albums.js';
+import tracksRoutes from './routes/tracks.js';
import conflictJournalRoutes from './routes/conflictJournal.js';
import { initUniverseBuilderCollectionHook } from './services/universeBuilderCollectionHook.js';
import { initCatalogImageAttachHook } from './services/catalogImageAttachHook.js';
@@ -533,6 +535,8 @@ app.use('/api/writers-room', writersRoomRoutes);
app.use('/api/universe-builder', universeBuilderRoutes);
app.use('/api/authors', authorsRoutes);
app.use('/api/artists', artistsRoutes);
+app.use('/api/albums', albumsRoutes);
+app.use('/api/tracks', tracksRoutes);
app.use('/api/pipeline', pipelineRoutes);
app.use('/api/conflict-journal', conflictJournalRoutes);
app.use('/api/importer', importerRoutes);
diff --git a/server/lib/db.js b/server/lib/db.js
index 7d862eb4a3..c69a7782c8 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -973,6 +973,40 @@ async function ensureSchemaImpl() {
)`,
`CREATE INDEX IF NOT EXISTS idx_artists_live ON artists (deleted) WHERE deleted = FALSE`,
+ // Music albums (the Music studio). One row per album, the full sanitized
+ // record (title, artistId+denormalized artist, description, genre,
+ // releaseYear, coverImageUrl, ordered trackIds) in `data` JSONB. `title`
+ // mirrors a column for the live-list sort. db-primary + federation-ready
+ // (LWW merge mirrors artists), not yet registered in peerSync — local-only
+ // for now (see issue #1502). Mirrors the albums block in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS albums (
+ id TEXT PRIMARY KEY,
+ title TEXT NOT NULL,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_albums_live ON albums (deleted) WHERE deleted = FALSE`,
+
+ // Music tracks (the Music studio). One row per track, the full sanitized
+ // record (title, albumId/artistId FKs + denormalized artist, lyrics, prompt,
+ // engine/modelId/durationSec gen metadata, audioFilename pointing into the
+ // shared music library at data/music/) in `data` JSONB. `title` mirrors a
+ // column for queries. db-primary + federation-ready, not yet registered in
+ // peerSync — local-only for now (see issue #1502). Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS tracks (
+ id TEXT PRIMARY KEY,
+ title TEXT NOT NULL,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_tracks_live ON tracks (deleted) WHERE deleted = FALSE`,
+
// Pipeline series (Phase 3 Create migration, issue #1015). One row per
// series, the full sanitized record (arc/seasons/locks/covers/style) in
// `data` JSONB, moved out of data/pipeline-series/{id}/index.json
@@ -1240,7 +1274,7 @@ async function ensureSchemaImpl() {
'story_builder_sessions', 'writers_room_works', 'writers_room_folders',
'writers_room_draft_versions', 'catalog_ingredients', 'catalog_scraps',
'catalog_user_types', 'creative_director_projects', 'mood_boards',
- 'lora_training_runs', 'authors', 'artists', 'tribe_people', 'tribe_touchpoints',
+ 'lora_training_runs', 'authors', 'artists', 'albums', 'tracks', 'tribe_people', 'tribe_touchpoints',
];
for (const t of auditedTables) {
catalogDDL.push(`DROP TRIGGER IF EXISTS trg_${t}_audit ON ${t}`);
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 0188406955..e9112777dc 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -35,6 +35,8 @@ export const NAV_COMMANDS = [
{ id: 'nav.create.rounds-guide', path: '/rounds/guide', label: 'Rounds Guide', section: 'Create', aliases: ['rounds-guide', 'round-guide', 'songs-guide', 'song-guide', 'singing-guide', 'round-learning'], keywords: ['rhythm shapes', 'dirge', 'voice layers', 'harmony', 'notation', 'lead sheet', 'solfege', 'learn round', 'learn song', 'a cappella', 'singing help'] },
{ id: 'nav.create.music', path: '/music', label: 'Music', section: 'Create', aliases: ['music', 'music-studio', 'generate-music'], keywords: ['music generation', 'ace-step', 'acestep', 'musicgen', 'audioldm', 'album', 'track', 'single', 'album art', 'artist', 'song generation', 'audio', 'beat', 'producer'] },
{ id: 'nav.create.music-artists', path: '/music/artists', label: 'Music Artists', section: 'Create', aliases: ['music-artists', 'artists', 'artist', 'artist-persona', 'musician', 'band'], keywords: ['artist persona', 'musician', 'band', 'byline', 'portrait', 'genre', 'musical style', 'stage name'] },
+ { id: 'nav.create.music-albums', path: '/music/albums', label: 'Music Albums', section: 'Create', aliases: ['albums', 'album', 'music-albums', 'discography', 'lp', 'ep'], keywords: ['album', 'cover art', 'tracklist', 'release', 'discography', 'record'] },
+ { id: 'nav.create.music-tracks', path: '/music/tracks', label: 'Music Tracks', section: 'Create', aliases: ['tracks', 'track', 'music-tracks', 'singles', 'songs-audio'], keywords: ['track', 'single', 'audio', 'recording', 'lyrics', 'mp3', 'wav', 'generate track'] },
{ id: 'nav.create.sharing-conflicts', path: '/sharing/conflicts', label: 'Conflicts', section: 'Create', aliases: ['conflicts', 'sync-conflicts', 'edit-conflicts', 'conflict-journal'], keywords: ['conflict', 'overwrite', 'lost edit', 'restore', 'merge fields', 'last write wins', 'diverged', 'recover'] },
{ id: 'nav.media.loras', path: '/media/loras', label: 'LoRAs', section: 'Create', aliases: ['loras', 'lora', 'lora-manager', 'civitai'], keywords: ['lora', 'civitai', 'fine-tune', 'style adapter', 'realstagram', 'photoreal', 'flux lora'] },
{ id: 'nav.media.training', path: '/media/training', label: 'LoRA Training', section: 'Create', aliases: ['training', 'lora-training', 'train-lora', 'datasets', 'character-lora'], keywords: ['fine-tune', 'dataset', 'caption', 'dreambooth', 'character consistency', 'train', 'flux lora'] },
diff --git a/server/routes/albums.js b/server/routes/albums.js
new file mode 100644
index 0000000000..1bced12b46
--- /dev/null
+++ b/server/routes/albums.js
@@ -0,0 +1,78 @@
+/**
+ * Music album routes.
+ *
+ * GET /api/albums → Album[] (live, sorted by title)
+ * POST /api/albums → Album
+ * GET /api/albums/:id → Album
+ * PATCH /api/albums/:id → Album
+ * DELETE /api/albums/:id → { id } (soft delete)
+ *
+ * Bounds come from services/albums/logic.js so the Zod schema here and the
+ * service-layer sanitizer agree by construction. Mirrors routes/artists.js.
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import * as albums from '../services/albums/index.js';
+
+const router = Router();
+
+const titleField = z.string().trim().min(1).max(albums.TITLE_MAX);
+const artistIdField = z.string().trim().max(albums.ARTIST_ID_MAX);
+const artistNameField = z.string().trim().max(albums.ARTIST_NAME_MAX);
+const descriptionField = z.string().trim().max(albums.DESCRIPTION_MAX);
+const genreField = z.string().trim().max(albums.GENRE_MAX);
+const coverImageUrlField = z.string().trim().max(albums.COVER_IMAGE_URL_MAX);
+// null clears the year; a number is clamped server-side into the band.
+const releaseYearField = z.number().int().min(albums.RELEASE_YEAR_MIN).max(albums.RELEASE_YEAR_MAX).nullable();
+const trackIdsField = z.array(z.string().trim().max(albums.TRACK_ID_MAX)).max(albums.TRACK_IDS_MAX);
+
+const createSchema = z.object({
+ title: titleField,
+ artistId: artistIdField.optional().default(''),
+ artist: artistNameField.optional().default(''),
+ description: descriptionField.optional().default(''),
+ genre: genreField.optional().default(''),
+ releaseYear: releaseYearField.optional().default(null),
+ coverImageUrl: coverImageUrlField.optional().default(''),
+ trackIds: trackIdsField.optional().default([]),
+});
+
+const patchSchema = z.object({
+ title: titleField.optional(),
+ artistId: artistIdField.optional(),
+ artist: artistNameField.optional(),
+ description: descriptionField.optional(),
+ genre: genreField.optional(),
+ releaseYear: releaseYearField.optional(),
+ coverImageUrl: coverImageUrlField.optional(),
+ trackIds: trackIdsField.optional(),
+}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });
+
+router.get('/', asyncHandler(async (_req, res) => {
+ res.json(await albums.listAlbums());
+}));
+
+router.post('/', asyncHandler(async (req, res) => {
+ const body = validateRequest(createSchema, req.body ?? {});
+ res.status(201).json(await albums.createAlbum(body));
+}));
+
+router.get('/:id', asyncHandler(async (req, res) => {
+ const album = await albums.getAlbum(req.params.id);
+ if (!album) throw new ServerError('Album not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(album);
+}));
+
+router.patch('/:id', asyncHandler(async (req, res) => {
+ const body = validateRequest(patchSchema, req.body ?? {});
+ res.json(await albums.updateAlbum(req.params.id, body));
+}));
+
+router.delete('/:id', asyncHandler(async (req, res) => {
+ res.json(await albums.deleteAlbum(req.params.id));
+}));
+
+export default router;
diff --git a/server/routes/albums.test.js b/server/routes/albums.test.js
new file mode 100644
index 0000000000..d9285a6abf
--- /dev/null
+++ b/server/routes/albums.test.js
@@ -0,0 +1,85 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+
+vi.mock('../services/albums/index.js', () => ({
+ TITLE_MAX: 200,
+ ARTIST_ID_MAX: 80,
+ ARTIST_NAME_MAX: 120,
+ DESCRIPTION_MAX: 4000,
+ GENRE_MAX: 120,
+ COVER_IMAGE_URL_MAX: 1000,
+ TRACK_IDS_MAX: 200,
+ TRACK_ID_MAX: 80,
+ RELEASE_YEAR_MIN: 1850,
+ RELEASE_YEAR_MAX: 2200,
+ ALBUM_ID_RE: /^album-/,
+ listAlbums: vi.fn(async () => [{ id: 'album-1', title: 'Debut' }]),
+ getAlbum: vi.fn(),
+ createAlbum: vi.fn(async (input) => ({ id: 'album-new', ...input })),
+ updateAlbum: vi.fn(async (id, patch) => ({ id, ...patch })),
+ deleteAlbum: vi.fn(async (id) => ({ id })),
+}));
+
+import * as albums from '../services/albums/index.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import albumsRoutes from './albums.js';
+
+function makeApp() {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/albums', albumsRoutes);
+ app.use(errorMiddleware);
+ return app;
+}
+
+describe('albums routes', () => {
+ let app;
+ beforeEach(() => { app = makeApp(); vi.clearAllMocks(); });
+
+ it('GET / returns the album list', async () => {
+ const r = await request(app).get('/api/albums');
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual([{ id: 'album-1', title: 'Debut' }]);
+ });
+
+ it('POST / creates an album', async () => {
+ const r = await request(app).post('/api/albums').send({ title: 'Debut', genre: 'folk' });
+ expect(r.status).toBe(201);
+ expect(albums.createAlbum).toHaveBeenCalledWith(expect.objectContaining({ title: 'Debut', genre: 'folk' }));
+ expect(r.body.id).toBe('album-new');
+ });
+
+ it('POST / rejects a missing title', async () => {
+ const r = await request(app).post('/api/albums').send({ genre: 'no title' });
+ expect(r.status).toBe(400);
+ expect(albums.createAlbum).not.toHaveBeenCalled();
+ });
+
+ it('POST / rejects a garbage release year', async () => {
+ const r = await request(app).post('/api/albums').send({ title: 'X', releaseYear: 99999 });
+ expect(r.status).toBe(400);
+ });
+
+ it('GET /:id 404s when absent; returns the album when found', async () => {
+ albums.getAlbum.mockResolvedValueOnce(null);
+ expect((await request(app).get('/api/albums/album-x')).status).toBe(404);
+ albums.getAlbum.mockResolvedValueOnce({ id: 'album-1', title: 'Debut' });
+ const r = await request(app).get('/api/albums/album-1');
+ expect(r.status).toBe(200);
+ expect(r.body.title).toBe('Debut');
+ });
+
+ it('PATCH /:id rejects an empty patch; updates otherwise', async () => {
+ expect((await request(app).patch('/api/albums/album-1').send({})).status).toBe(400);
+ const r = await request(app).patch('/api/albums/album-1').send({ trackIds: ['track-2', 'track-1'] });
+ expect(r.status).toBe(200);
+ expect(albums.updateAlbum).toHaveBeenCalledWith('album-1', { trackIds: ['track-2', 'track-1'] });
+ });
+
+ it('DELETE /:id soft-deletes an album', async () => {
+ const r = await request(app).delete('/api/albums/album-1');
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual({ id: 'album-1' });
+ });
+});
diff --git a/server/routes/tracks.js b/server/routes/tracks.js
new file mode 100644
index 0000000000..7e53024222
--- /dev/null
+++ b/server/routes/tracks.js
@@ -0,0 +1,151 @@
+/**
+ * Music track routes.
+ *
+ * GET /api/tracks → Track[] (live, creation order)
+ * POST /api/tracks → Track
+ * GET /api/tracks/library → { tracks } (shared music library list)
+ * GET /api/tracks/:id → Track
+ * PATCH /api/tracks/:id → Track
+ * DELETE /api/tracks/:id → { id } (soft delete)
+ * POST /api/tracks/:id/audio/upload → Track (multipart 'track' file)
+ * POST /api/tracks/:id/audio/attach → Track (attach a library filename)
+ * DELETE /api/tracks/:id/audio → Track (clear the audio pointer)
+ *
+ * Tracks store only a pointer (`audioFilename`) into the shared music library
+ * (services/pipeline/musicLibrary.js, `data/music/`); the bytes are uploaded /
+ * generated there. Bounds come from services/tracks/logic.js. Mirrors the
+ * artists/albums routes plus the audio-attach surface from the pipeline audio
+ * stage. Deleting a track does NOT delete its library audio (it may be shared).
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import { uploadSingle } from '../lib/multipart.js';
+import * as tracks from '../services/tracks/index.js';
+import {
+ listMusicLibrary, importUploadedTrack, statMusicTrack,
+ isSupportedMusicUpload, assertSafeMusicFilename, MUSIC_UPLOAD_MAX_BYTES,
+} from '../services/pipeline/musicLibrary.js';
+
+const router = Router();
+
+const titleField = z.string().trim().min(1).max(tracks.TITLE_MAX);
+const albumIdField = z.string().trim().max(tracks.ALBUM_ID_MAX);
+const artistIdField = z.string().trim().max(tracks.ARTIST_ID_MAX);
+const artistNameField = z.string().trim().max(tracks.ARTIST_NAME_MAX);
+const lyricsField = z.string().trim().max(tracks.LYRICS_MAX);
+const promptField = z.string().trim().max(tracks.PROMPT_MAX);
+const engineField = z.string().trim().max(tracks.ENGINE_MAX);
+const modelIdField = z.string().trim().max(tracks.MODEL_ID_MAX);
+const audioFilenameField = z.string().trim().max(tracks.AUDIO_FILENAME_MAX);
+const durationField = z.number().int().min(tracks.DURATION_MIN_SEC).max(tracks.DURATION_MAX_SEC).nullable();
+
+const createSchema = z.object({
+ title: titleField,
+ albumId: albumIdField.optional().default(''),
+ artistId: artistIdField.optional().default(''),
+ artist: artistNameField.optional().default(''),
+ lyrics: lyricsField.optional().default(''),
+ prompt: promptField.optional().default(''),
+ engine: engineField.optional().default(''),
+ modelId: modelIdField.optional().default(''),
+ durationSec: durationField.optional().default(null),
+ audioFilename: audioFilenameField.optional().default(''),
+});
+
+const patchSchema = z.object({
+ title: titleField.optional(),
+ albumId: albumIdField.optional(),
+ artistId: artistIdField.optional(),
+ artist: artistNameField.optional(),
+ lyrics: lyricsField.optional(),
+ prompt: promptField.optional(),
+ engine: engineField.optional(),
+ modelId: modelIdField.optional(),
+ durationSec: durationField.optional(),
+ audioFilename: audioFilenameField.optional(),
+}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });
+
+const attachSchema = z.object({
+ filename: z.string().trim().min(1).max(tracks.AUDIO_FILENAME_MAX),
+});
+
+// Reuse the pipeline audio stage's multipart upload contract (50MB, audio MIME).
+const musicUpload = uploadSingle('track', {
+ limits: { fileSize: MUSIC_UPLOAD_MAX_BYTES },
+ fileFilter: (_req, file, cb) => {
+ if (isSupportedMusicUpload(file)) {
+ cb(null, true);
+ } else {
+ cb(new ServerError(
+ 'Unsupported audio format — accepted: MP3, WAV, M4A, OGG, FLAC',
+ { status: 400, code: 'TRACK_AUDIO_UNSUPPORTED_FORMAT' },
+ ));
+ }
+ },
+});
+
+// Load a track or 404 — shared by the audio mutation routes.
+async function requireTrack(id) {
+ const track = await tracks.getTrack(id);
+ if (!track) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
+ return track;
+}
+
+router.get('/', asyncHandler(async (_req, res) => {
+ res.json(await tracks.listTracks());
+}));
+
+// Shared music library — every uploaded/generated track sits here. The studio
+// uses it to attach an existing track to a record without re-uploading. Routed
+// before /:id so the literal `library` segment can't be read as a track id.
+router.get('/library', asyncHandler(async (_req, res) => {
+ res.json({ tracks: await listMusicLibrary() });
+}));
+
+router.post('/', asyncHandler(async (req, res) => {
+ const body = validateRequest(createSchema, req.body ?? {});
+ res.status(201).json(await tracks.createTrack(body));
+}));
+
+router.get('/:id', asyncHandler(async (req, res) => {
+ res.json(await requireTrack(req.params.id));
+}));
+
+router.patch('/:id', asyncHandler(async (req, res) => {
+ const body = validateRequest(patchSchema, req.body ?? {});
+ res.json(await tracks.updateTrack(req.params.id, body));
+}));
+
+router.delete('/:id', asyncHandler(async (req, res) => {
+ res.json(await tracks.deleteTrack(req.params.id));
+}));
+
+// Upload an audio file into the shared library and attach it to this track.
+router.post('/:id/audio/upload', musicUpload, asyncHandler(async (req, res) => {
+ await requireTrack(req.params.id);
+ if (!req.file) throw new ServerError('No audio file uploaded', { status: 400, code: 'TRACK_AUDIO_MISSING_FILE' });
+ const { filename, sizeBytes } = await importUploadedTrack(req.file.path, req.file.originalname);
+ const updated = await tracks.updateTrack(req.params.id, { audioFilename: filename });
+ res.json({ track: updated, filename, sizeBytes });
+}));
+
+// Attach an existing library track (by stored filename) to this track.
+router.post('/:id/audio/attach', asyncHandler(async (req, res) => {
+ await requireTrack(req.params.id);
+ const { filename } = validateRequest(attachSchema, req.body ?? {});
+ assertSafeMusicFilename(filename);
+ const found = await statMusicTrack(filename);
+ if (!found) throw new ServerError('Track not found in the music library', { status: 404, code: 'TRACK_AUDIO_NOT_IN_LIBRARY' });
+ res.json({ track: await tracks.updateTrack(req.params.id, { audioFilename: filename }) });
+}));
+
+// Clear the audio pointer (leaves the library file in place — it may be shared).
+router.delete('/:id/audio', asyncHandler(async (req, res) => {
+ await requireTrack(req.params.id);
+ res.json({ track: await tracks.updateTrack(req.params.id, { audioFilename: '' }) });
+}));
+
+export default router;
diff --git a/server/routes/tracks.test.js b/server/routes/tracks.test.js
new file mode 100644
index 0000000000..4608ff01bc
--- /dev/null
+++ b/server/routes/tracks.test.js
@@ -0,0 +1,121 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+
+vi.mock('../services/tracks/index.js', () => ({
+ TITLE_MAX: 200,
+ ALBUM_ID_MAX: 80,
+ ARTIST_ID_MAX: 80,
+ ARTIST_NAME_MAX: 120,
+ LYRICS_MAX: 20000,
+ PROMPT_MAX: 8000,
+ ENGINE_MAX: 60,
+ MODEL_ID_MAX: 120,
+ AUDIO_FILENAME_MAX: 256,
+ DURATION_MIN_SEC: 1,
+ DURATION_MAX_SEC: 3600,
+ TRACK_ID_RE: /^track-/,
+ listTracks: vi.fn(async () => [{ id: 'track-1', title: 'Intro' }]),
+ getTrack: vi.fn(),
+ createTrack: vi.fn(async (input) => ({ id: 'track-new', ...input })),
+ updateTrack: vi.fn(async (id, patch) => ({ id, ...patch })),
+ deleteTrack: vi.fn(async (id) => ({ id })),
+}));
+
+const lib = vi.hoisted(() => ({
+ store: new Map(),
+}));
+vi.mock('../services/pipeline/musicLibrary.js', () => ({
+ MUSIC_UPLOAD_MAX_BYTES: 50 * 1024 * 1024,
+ isSupportedMusicUpload: () => true,
+ assertSafeMusicFilename: (f) => { if (f.includes('..') || f.includes('/')) throw Object.assign(new Error('bad'), { status: 400, code: 'X' }); },
+ listMusicLibrary: vi.fn(async () => [{ filename: 'music-1.mp3', label: 'theme', sizeBytes: 10, updatedAt: '2026-05-15T00:00:00.000Z' }]),
+ importUploadedTrack: vi.fn(async () => ({ filename: 'music-up.mp3', sizeBytes: 11 })),
+ statMusicTrack: vi.fn(async (f) => (lib.store.has(f) ? { filename: f, label: f, sizeBytes: 10 } : null)),
+}));
+
+import * as tracks from '../services/tracks/index.js';
+import * as musicLibrary from '../services/pipeline/musicLibrary.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import tracksRoutes from './tracks.js';
+
+function makeApp() {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/tracks', tracksRoutes);
+ app.use(errorMiddleware);
+ return app;
+}
+
+describe('tracks routes', () => {
+ let app;
+ beforeEach(() => { app = makeApp(); vi.clearAllMocks(); lib.store.clear(); });
+
+ it('GET / returns the track list', async () => {
+ const r = await request(app).get('/api/tracks');
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual([{ id: 'track-1', title: 'Intro' }]);
+ });
+
+ it('GET /library returns the shared music library (not read as an id)', async () => {
+ const r = await request(app).get('/api/tracks/library');
+ expect(r.status).toBe(200);
+ expect(r.body.tracks[0].filename).toBe('music-1.mp3');
+ expect(tracks.getTrack).not.toHaveBeenCalled();
+ });
+
+ it('POST / creates a track', async () => {
+ const r = await request(app).post('/api/tracks').send({ title: 'Intro', engine: 'acestep' });
+ expect(r.status).toBe(201);
+ expect(tracks.createTrack).toHaveBeenCalledWith(expect.objectContaining({ title: 'Intro', engine: 'acestep' }));
+ expect(r.body.id).toBe('track-new');
+ });
+
+ it('POST / rejects a missing title', async () => {
+ expect((await request(app).post('/api/tracks').send({ engine: 'x' })).status).toBe(400);
+ expect(tracks.createTrack).not.toHaveBeenCalled();
+ });
+
+ it('PATCH /:id rejects an empty patch; updates otherwise', async () => {
+ tracks.getTrack.mockResolvedValue({ id: 'track-1', title: 'Intro' });
+ expect((await request(app).patch('/api/tracks/track-1').send({})).status).toBe(400);
+ const r = await request(app).patch('/api/tracks/track-1').send({ prompt: 'warm folk' });
+ expect(r.status).toBe(200);
+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', { prompt: 'warm folk' });
+ });
+
+ it('DELETE /:id soft-deletes a track', async () => {
+ tracks.getTrack.mockResolvedValue({ id: 'track-1', title: 'Intro' });
+ const r = await request(app).delete('/api/tracks/track-1');
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual({ id: 'track-1' });
+ });
+
+ it('POST /:id/audio/attach 404s when the track is missing', async () => {
+ tracks.getTrack.mockResolvedValueOnce(null);
+ const r = await request(app).post('/api/tracks/track-x/audio/attach').send({ filename: 'music-1.mp3' });
+ expect(r.status).toBe(404);
+ });
+
+ it('POST /:id/audio/attach 404s when the file is not in the library', async () => {
+ tracks.getTrack.mockResolvedValue({ id: 'track-1', title: 'Intro' });
+ const r = await request(app).post('/api/tracks/track-1/audio/attach').send({ filename: 'missing.mp3' });
+ expect(r.status).toBe(404);
+ expect(r.body.code).toBe('TRACK_AUDIO_NOT_IN_LIBRARY');
+ });
+
+ it('POST /:id/audio/attach attaches an existing library track', async () => {
+ tracks.getTrack.mockResolvedValue({ id: 'track-1', title: 'Intro' });
+ lib.store.set('music-1.mp3', true);
+ const r = await request(app).post('/api/tracks/track-1/audio/attach').send({ filename: 'music-1.mp3' });
+ expect(r.status).toBe(200);
+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', { audioFilename: 'music-1.mp3' });
+ });
+
+ it('DELETE /:id/audio clears the pointer', async () => {
+ tracks.getTrack.mockResolvedValue({ id: 'track-1', title: 'Intro' });
+ const r = await request(app).delete('/api/tracks/track-1/audio');
+ expect(r.status).toBe(200);
+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', { audioFilename: '' });
+ });
+});
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 37531a6e5e..719603d6a6 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -796,6 +796,40 @@ CREATE TABLE IF NOT EXISTS artists (
-- The common path is "live artists sorted by name".
CREATE INDEX IF NOT EXISTS idx_artists_live ON artists (deleted) WHERE deleted = FALSE;
+-- Music albums (the Music studio). One row per album, the full sanitized record
+-- (title, artistId + denormalized artist, description, genre, releaseYear,
+-- coverImageUrl, ordered trackIds) in `data` JSONB. `title` mirrors a column for
+-- the live-list sort. db-primary + federation-ready (LWW merge mirrors artists),
+-- not yet registered in peerSync — local-only for now (see issue #1502). Mirrors
+-- the albums block in db.js.
+CREATE TABLE IF NOT EXISTS albums (
+ id TEXT PRIMARY KEY,
+ title TEXT NOT NULL,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+);
+CREATE INDEX IF NOT EXISTS idx_albums_live ON albums (deleted) WHERE deleted = FALSE;
+
+-- Music tracks (the Music studio). One row per track, the full sanitized record
+-- (title, albumId/artistId FKs + denormalized artist, lyrics, prompt, engine/
+-- modelId/durationSec gen metadata, audioFilename pointing into the shared music
+-- library at data/music/) in `data` JSONB. `title` mirrors a column for queries.
+-- db-primary + federation-ready, not yet registered in peerSync — local-only for
+-- now (see issue #1502). Mirrors the tracks block in db.js.
+CREATE TABLE IF NOT EXISTS tracks (
+ id TEXT PRIMARY KEY,
+ title TEXT NOT NULL,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+);
+CREATE INDEX IF NOT EXISTS idx_tracks_live ON tracks (deleted) WHERE deleted = FALSE;
+
-- Pipeline series (Phase 3 Create migration, issue #1015). One row per series,
-- the full sanitized record (arc/seasons/locks/covers/style) in `data` JSONB,
-- moved out of data/pipeline-series/{id}/index.json (collectionStore). Only the
@@ -1058,6 +1092,10 @@ DROP TRIGGER IF EXISTS trg_authors_audit ON authors;
CREATE TRIGGER trg_authors_audit AFTER UPDATE OR DELETE ON authors FOR EACH ROW EXECUTE FUNCTION record_audit_log();
DROP TRIGGER IF EXISTS trg_artists_audit ON artists;
CREATE TRIGGER trg_artists_audit AFTER UPDATE OR DELETE ON artists FOR EACH ROW EXECUTE FUNCTION record_audit_log();
+DROP TRIGGER IF EXISTS trg_albums_audit ON albums;
+CREATE TRIGGER trg_albums_audit AFTER UPDATE OR DELETE ON albums FOR EACH ROW EXECUTE FUNCTION record_audit_log();
+DROP TRIGGER IF EXISTS trg_tracks_audit ON tracks;
+CREATE TRIGGER trg_tracks_audit AFTER UPDATE OR DELETE ON tracks FOR EACH ROW EXECUTE FUNCTION record_audit_log();
DROP TRIGGER IF EXISTS trg_tribe_people_audit ON tribe_people;
CREATE TRIGGER trg_tribe_people_audit AFTER UPDATE OR DELETE ON tribe_people FOR EACH ROW EXECUTE FUNCTION record_audit_log();
DROP TRIGGER IF EXISTS trg_tribe_touchpoints_audit ON tribe_touchpoints;
diff --git a/server/services/albums/db.js b/server/services/albums/db.js
new file mode 100644
index 0000000000..170f6bc5d3
--- /dev/null
+++ b/server/services/albums/db.js
@@ -0,0 +1,147 @@
+/**
+ * Music albums — PostgreSQL leaf I/O.
+ *
+ * One row per album in `albums`: the full sanitized record in `data` JSONB, with
+ * `title` + the LWW/tombstone trio mirrored into columns. Reads return `data`
+ * verbatim. Mutations run inside withTransaction + SELECT … FOR UPDATE. Mirrors
+ * `services/artists/db.js`; all mutation semantics live in logic.js.
+ */
+
+import { randomUUID } from 'crypto';
+import { query, withTransaction } from '../../lib/db.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { mirrorTimestamp } from '../../lib/pgTimestamp.js';
+import { buildAlbumRecord, applyAlbumPatch, mergeAlbumRecord } from './logic.js';
+import {
+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+} from '../../lib/conflictJournal.js';
+
+function rowToAlbum(row) {
+ return row ? row.data : null;
+}
+
+async function persist(exec, album) {
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(album.createdAt, now);
+ await exec(
+ `INSERT INTO albums (id, title, data, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7)
+ ON CONFLICT (id) DO UPDATE SET
+ title = EXCLUDED.title,
+ data = EXCLUDED.data,
+ updated_at = EXCLUDED.updated_at,
+ deleted = EXCLUDED.deleted,
+ deleted_at = EXCLUDED.deleted_at`,
+ [
+ album.id,
+ typeof album.title === 'string' ? album.title : '',
+ JSON.stringify(album),
+ createdAt,
+ mirrorTimestamp(album.updatedAt, createdAt),
+ album.deleted === true,
+ mirrorTimestamp(album.deletedAt, null),
+ ],
+ );
+ return album;
+}
+
+export async function listAlbums({ includeDeleted = false } = {}) {
+ const { rows } = includeDeleted
+ ? await query(`SELECT data FROM albums ORDER BY title ASC`)
+ : await query(`SELECT data FROM albums WHERE deleted = FALSE ORDER BY title ASC`);
+ return rows.map(rowToAlbum);
+}
+
+export async function getAlbum(id, { includeDeleted = false } = {}) {
+ const { rows } = await query(`SELECT data FROM albums WHERE id = $1`, [id]);
+ const album = rowToAlbum(rows[0]);
+ if (!album) return null;
+ return includeDeleted || !album.deleted ? album : null;
+}
+
+/** Live album ids (or all when includeDeleted) — used by tombstone GC sweeps. */
+export async function listAlbumIds({ includeDeleted = false } = {}) {
+ const { rows } = includeDeleted
+ ? await query(`SELECT id FROM albums`)
+ : await query(`SELECT id FROM albums WHERE deleted = FALSE`);
+ return rows.map((r) => r.id);
+}
+
+export async function createAlbum(input) {
+ const album = buildAlbumRecord(input, { id: `album-${randomUUID()}`, now: new Date().toISOString() });
+ if (!album) throw new ServerError('Invalid album payload', { status: 400, code: 'VALIDATION' });
+ await persist(query, album);
+ console.log(`💿 Created album: ${album.id} (${album.title})`);
+ return album;
+}
+
+export async function updateAlbum(id, patch) {
+ return withTransaction(async (client) => {
+ const sel = await client.query(`SELECT data FROM albums WHERE id = $1 FOR UPDATE`, [id]);
+ const current = rowToAlbum(sel.rows[0]);
+ if (!current || current.deleted) throw new ServerError('Album not found', { status: 404, code: 'NOT_FOUND' });
+ const next = applyAlbumPatch(current, patch);
+ if (!next) throw new ServerError('Invalid album payload', { status: 400, code: 'VALIDATION' });
+ await persist(client.query.bind(client), next);
+ return next;
+ });
+}
+
+export async function deleteAlbum(id) {
+ return withTransaction(async (client) => {
+ const sel = await client.query(`SELECT data FROM albums WHERE id = $1 FOR UPDATE`, [id]);
+ const current = rowToAlbum(sel.rows[0]);
+ if (!current || current.deleted) throw new ServerError('Album not found', { status: 404, code: 'NOT_FOUND' });
+ const now = new Date().toISOString();
+ const next = { ...current, deleted: true, deletedAt: now, updatedAt: now };
+ await persist(client.query.bind(client), next);
+ return { id };
+ });
+}
+
+/**
+ * Merge an incoming batch of album records from a peer (per-record push). LWW on
+ * `updatedAt` (tombstone-aware) via the shared `mergeAlbumRecord` decision.
+ * Federation-ready, but the album kind is not yet registered in peerSync — see
+ * issue #1502. Returns `{ applied, count }`.
+ */
+export async function mergeAlbumsFromSync(remoteAlbums, { source = { via: 'sync', peerId: null } } = {}) {
+ if (!Array.isArray(remoteAlbums)) return { applied: false, count: 0 };
+ let changed = 0;
+ for (const remote of remoteAlbums) {
+ const applied = await withTransaction(async (client) => {
+ const sel = await client.query(`SELECT data FROM albums WHERE id = $1 FOR UPDATE`, [remote?.id]);
+ const local = rowToAlbum(sel.rows[0]);
+ const { next, inserted, remoteWins, changed: didChange } = mergeAlbumRecord(local, remote);
+ if (!next) return false;
+ if (inserted) {
+ await persist(client.query.bind(client), next);
+ await setSyncBaseHash('album', next.id, contentHashForRecord('album', next));
+ return true;
+ }
+ if (!remoteWins || !didChange) return false;
+ await maybeJournalBeforeOverwrite({ kind: 'album', id: next.id, local, remote: next, source });
+ await persist(client.query.bind(client), next);
+ await setSyncBaseHash('album', next.id, contentHashForRecord('album', next));
+ return true;
+ });
+ if (applied) changed += 1;
+ }
+ await flushBaseHashes();
+ if (changed === 0) return { applied: false, count: 0 };
+ return { applied: true, count: changed };
+}
+
+/** Hard-remove tombstoned albums whose deletedAt is older than the cutoff. */
+export async function pruneTombstonedAlbums(olderThanMs) {
+ if (!Number.isFinite(olderThanMs)) return { pruned: 0 };
+ const cutoffIso = new Date(olderThanMs).toISOString();
+ const { rows } = await query(
+ `DELETE FROM albums
+ WHERE deleted = TRUE AND deleted_at IS NOT NULL AND deleted_at < $1
+ RETURNING id`,
+ [cutoffIso],
+ );
+ for (const r of rows) await deleteSyncBaseHash('album', r.id);
+ return { pruned: rows.length };
+}
diff --git a/server/services/albums/db.test.js b/server/services/albums/db.test.js
new file mode 100644
index 0000000000..b1b70e4c6e
--- /dev/null
+++ b/server/services/albums/db.test.js
@@ -0,0 +1,82 @@
+/**
+ * Postgres-backed round-trip for the music-album DB adapter. SKIPS cleanly when
+ * no test DB is reachable; runs only via `npm run test:db` against `portos_test`.
+ * Snapshots + restores the `albums` table. Mirrors artists/db.test.js.
+ */
+
+import { describe, it, expect, afterAll, beforeAll, beforeEach } from 'vitest';
+import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';
+
+let dbReady = false;
+let skipReason = '';
+{
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ await ensureSchema().catch(() => {});
+ const probe = await query(
+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'albums') AS ok`,
+ ).catch(() => ({ rows: [{ ok: false }] }));
+ if (probe.rows?.[0]?.ok) dbReady = true;
+ else skipReason = 'albums table not present';
+ }
+}
+
+if (!dbReady) console.log(`⏭️ services/albums/db.test.js skipped: ${skipReason}`);
+
+describe.skipIf(!dbReady)('albums DB adapter round-trip', () => {
+ let db;
+ let snap = [];
+ beforeAll(async () => {
+ db = await import('./db.js');
+ snap = (await query(`SELECT * FROM albums`)).rows;
+ });
+ beforeEach(async () => { await query(`DELETE FROM albums`); });
+ afterAll(async () => {
+ await query(`DELETE FROM albums`).catch(() => {});
+ for (const r of snap) {
+ await query(
+ `INSERT INTO albums (id, title, data, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1,$2,$3::jsonb,$4,$5,$6,$7) ON CONFLICT (id) DO NOTHING`,
+ [r.id, r.title, JSON.stringify(r.data), r.created_at, r.updated_at, r.deleted, r.deleted_at],
+ ).catch(() => {});
+ }
+ await close();
+ });
+
+ it('creates an album and mirrors title into the column', async () => {
+ const a = await db.createAlbum({ title: 'Debut', genre: 'folk', trackIds: ['track-1'] });
+ expect(a.id).toMatch(/^album-/);
+ const col = (await query(`SELECT title, deleted FROM albums WHERE id = $1`, [a.id])).rows[0];
+ expect(col.title).toBe('Debut');
+ expect(await db.getAlbum(a.id)).toEqual(a);
+ });
+
+ it('listAlbums excludes tombstones; update preserves absent keys', async () => {
+ const live = await db.createAlbum({ title: 'Live' });
+ const dead = await db.createAlbum({ title: 'Dead' });
+ await db.deleteAlbum(dead.id);
+ expect((await db.listAlbums()).map((a) => a.id)).toEqual([live.id]);
+ const next = await db.updateAlbum(live.id, { genre: 'jazz' });
+ expect(next.title).toBe('Live');
+ expect(next.genre).toBe('jazz');
+ });
+
+ it('mergeAlbumsFromSync: newer wins, older loses, tombstone deletes', async () => {
+ const a = await db.createAlbum({ title: 'Local' });
+ expect(await db.mergeAlbumsFromSync([{ ...a, title: 'Old', updatedAt: '2000-01-01T00:00:00.000Z' }])).toEqual({ applied: false, count: 0 });
+ expect(await db.mergeAlbumsFromSync([{ ...a, title: 'Fresh', updatedAt: '2099-01-01T00:00:00.000Z' }])).toEqual({ applied: true, count: 1 });
+ expect((await db.getAlbum(a.id)).title).toBe('Fresh');
+ await db.mergeAlbumsFromSync([{ ...a, deleted: true, deletedAt: '2099-02-01T00:00:00.000Z', updatedAt: '2099-02-01T00:00:00.000Z' }]);
+ expect(await db.getAlbum(a.id)).toBeNull();
+ });
+
+ it('pruneTombstonedAlbums removes old tombstones only', async () => {
+ const live = await db.createAlbum({ title: 'Live' });
+ const dead = await db.createAlbum({ title: 'Dead' });
+ await db.mergeAlbumsFromSync([{ ...dead, deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2099-01-01T00:00:00.000Z' }]);
+ expect((await db.pruneTombstonedAlbums(Date.parse('2030-01-01T00:00:00.000Z'))).pruned).toBe(1);
+ expect((await query(`SELECT id FROM albums`)).rows.map((r) => r.id)).toEqual([live.id]);
+ });
+});
diff --git a/server/services/albums/file.js b/server/services/albums/file.js
new file mode 100644
index 0000000000..dc4bcf3a6f
--- /dev/null
+++ b/server/services/albums/file.js
@@ -0,0 +1,125 @@
+/**
+ * Music albums — file-backed store (escape-hatch / test backend).
+ *
+ * Persists to data/albums.json (array, atomicWrite). PostgreSQL (db.js) is the
+ * default; this backend is reachable only via MEMORY_BACKEND=file or
+ * NODE_ENV=test. Mirrors `services/artists/file.js`; all mutation semantics live
+ * in logic.js so the two backends can't drift.
+ */
+
+import { join } from 'path';
+import { randomUUID } from 'crypto';
+import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { sanitizeAlbum, buildAlbumRecord, applyAlbumPatch, mergeAlbumRecord } from './logic.js';
+import {
+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+} from '../../lib/conflictJournal.js';
+
+const ALBUMS_FILE = join(PATHS.data, 'albums.json');
+
+async function loadAll() {
+ const raw = await readJSONFile(ALBUMS_FILE, []);
+ return (Array.isArray(raw) ? raw : []).map(sanitizeAlbum).filter(Boolean);
+}
+
+async function saveAll(albums) {
+ await ensureDir(PATHS.data);
+ await atomicWrite(ALBUMS_FILE, albums);
+}
+
+const byTitle = (a, b) => (a.title || '').localeCompare(b.title || '');
+
+export async function listAlbums({ includeDeleted = false } = {}) {
+ const all = await loadAll();
+ return (includeDeleted ? all : all.filter((a) => !a.deleted)).sort(byTitle);
+}
+
+export async function getAlbum(id, { includeDeleted = false } = {}) {
+ const all = await loadAll();
+ const found = all.find((a) => a.id === id);
+ if (!found) return null;
+ return includeDeleted || !found.deleted ? found : null;
+}
+
+/** Live album ids (or all when includeDeleted) — used by tombstone GC sweeps. */
+export async function listAlbumIds({ includeDeleted = false } = {}) {
+ const all = await loadAll();
+ return (includeDeleted ? all : all.filter((a) => !a.deleted)).map((a) => a.id);
+}
+
+export async function createAlbum(input) {
+ const album = buildAlbumRecord(input, { id: `album-${randomUUID()}`, now: new Date().toISOString() });
+ if (!album) throw new ServerError('Invalid album payload', { status: 400, code: 'VALIDATION' });
+ const all = await loadAll();
+ all.push(album);
+ await saveAll(all);
+ console.log(`💿 Created album: ${album.id} (${album.title})`);
+ return album;
+}
+
+export async function updateAlbum(id, patch) {
+ const all = await loadAll();
+ const idx = all.findIndex((a) => a.id === id);
+ if (idx < 0 || all[idx].deleted) throw new ServerError('Album not found', { status: 404, code: 'NOT_FOUND' });
+ const next = applyAlbumPatch(all[idx], patch);
+ if (!next) throw new ServerError('Invalid album payload', { status: 400, code: 'VALIDATION' });
+ all[idx] = next;
+ await saveAll(all);
+ return next;
+}
+
+export async function deleteAlbum(id) {
+ const all = await loadAll();
+ const idx = all.findIndex((a) => a.id === id);
+ if (idx < 0 || all[idx].deleted) throw new ServerError('Album not found', { status: 404, code: 'NOT_FOUND' });
+ const now = new Date().toISOString();
+ all[idx] = { ...all[idx], deleted: true, deletedAt: now, updatedAt: now };
+ await saveAll(all);
+ return { id };
+}
+
+/** File-backend mirror of db.js `mergeAlbumsFromSync` (LWW-per-id, tombstone-aware). */
+export async function mergeAlbumsFromSync(remoteAlbums, { source = { via: 'sync', peerId: null } } = {}) {
+ if (!Array.isArray(remoteAlbums)) return { applied: false, count: 0 };
+ const all = await loadAll();
+ const byId = new Map(all.map((a) => [a.id, a]));
+ let changed = 0;
+ for (const remote of remoteAlbums) {
+ const local = byId.get(remote?.id) || null;
+ const { next, inserted, remoteWins, changed: didChange } = mergeAlbumRecord(local, remote);
+ if (!next) continue;
+ if (inserted) {
+ byId.set(next.id, next);
+ await setSyncBaseHash('album', next.id, contentHashForRecord('album', next));
+ changed += 1;
+ continue;
+ }
+ if (!remoteWins || !didChange) continue;
+ await maybeJournalBeforeOverwrite({ kind: 'album', id: next.id, local, remote: next, source });
+ byId.set(next.id, next);
+ await setSyncBaseHash('album', next.id, contentHashForRecord('album', next));
+ changed += 1;
+ }
+ if (changed > 0) await saveAll([...byId.values()]);
+ await flushBaseHashes();
+ if (changed === 0) return { applied: false, count: 0 };
+ return { applied: true, count: changed };
+}
+
+/** Hard-remove tombstoned albums whose deletedAt is older than the cutoff. */
+export async function pruneTombstonedAlbums(olderThanMs) {
+ if (!Number.isFinite(olderThanMs)) return { pruned: 0 };
+ const all = await loadAll();
+ const survivors = [];
+ const pruned = [];
+ for (const a of all) {
+ const ms = a.deleted ? Date.parse(a.deletedAt || '') : NaN;
+ if (a.deleted && Number.isFinite(ms) && ms < olderThanMs) pruned.push(a.id);
+ else survivors.push(a);
+ }
+ if (pruned.length === 0) return { pruned: 0 };
+ await saveAll(survivors);
+ for (const id of pruned) await deleteSyncBaseHash('album', id);
+ return { pruned: pruned.length };
+}
diff --git a/server/services/albums/file.test.js b/server/services/albums/file.test.js
new file mode 100644
index 0000000000..b9ad760301
--- /dev/null
+++ b/server/services/albums/file.test.js
@@ -0,0 +1,78 @@
+/**
+ * Album file-backend store — CRUD + LWW merge outcomes.
+ *
+ * Covers the CRUD round-trip the normal (non-DB) suite exercises plus the
+ * `mergeAlbumsFromSync` LWW outcomes. The conflict-journal base-hash side
+ * effects are NOT asserted here — they depend on the album record kind being
+ * registered in syncWire/peerSync (deferred; local-only — see issue #1502).
+ * Runs against a tmpdir so it never touches real `data/`.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'albums-file-test-'));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+});
+
+const file = await import('./file.js');
+
+function reset() {
+ rmSync(join(TEST_DATA_ROOT, 'albums.json'), { force: true });
+ rmSync(join(TEST_DATA_ROOT, 'sharing'), { recursive: true, force: true });
+ rmSync(join(TEST_DATA_ROOT, 'conflict-journal'), { recursive: true, force: true });
+}
+
+const album = (id, extra = {}) => ({
+ id, title: id, artistId: '', artist: '', description: '', genre: '',
+ releaseYear: null, coverImageUrl: '', trackIds: [],
+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
+ deleted: false, deletedAt: null, ...extra,
+});
+
+beforeEach(reset);
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+describe('albums file backend — CRUD', () => {
+ it('creates, reads, updates and soft-deletes an album', async () => {
+ const created = await file.createAlbum({ title: 'Debut', genre: 'folk', trackIds: ['track-1'] });
+ expect(created.id).toMatch(/^album-/);
+ expect((await file.getAlbum(created.id)).trackIds).toEqual(['track-1']);
+
+ const updated = await file.updateAlbum(created.id, { trackIds: ['track-2', 'track-1'] });
+ expect(updated.trackIds).toEqual(['track-2', 'track-1']);
+
+ await file.deleteAlbum(created.id);
+ expect(await file.getAlbum(created.id)).toBeNull();
+ expect(await file.listAlbums()).toHaveLength(0);
+ });
+
+ it('lists live albums sorted by title', async () => {
+ await file.createAlbum({ title: 'Zenith' });
+ await file.createAlbum({ title: 'Aurora' });
+ expect((await file.listAlbums()).map((a) => a.title)).toEqual(['Aurora', 'Zenith']);
+ });
+});
+
+describe('albums file backend — mergeAlbumsFromSync (LWW outcomes)', () => {
+ it('inserts, then newer wins / older no-ops', async () => {
+ expect(await file.mergeAlbumsFromSync([album('album-1', { genre: 'v1', updatedAt: '2026-02-01T00:00:00.000Z' })]))
+ .toEqual({ applied: true, count: 1 });
+ expect(await file.mergeAlbumsFromSync([album('album-1', { genre: 'v2', updatedAt: '2026-03-01T00:00:00.000Z' })]))
+ .toEqual({ applied: true, count: 1 });
+ expect((await file.getAlbum('album-1')).genre).toBe('v2');
+ expect(await file.mergeAlbumsFromSync([album('album-1', { genre: 'stale', updatedAt: '2020-01-01T00:00:00.000Z' })]))
+ .toEqual({ applied: false, count: 0 });
+ });
+
+ it('pruneTombstonedAlbums hard-removes an old tombstone', async () => {
+ await file.mergeAlbumsFromSync([album('album-dead', { deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2020-01-01T00:00:00.000Z' })]);
+ expect(await file.pruneTombstonedAlbums(Date.parse('2030-01-01T00:00:00.000Z'))).toEqual({ pruned: 1 });
+ expect(await file.getAlbum('album-dead', { includeDeleted: true })).toBeNull();
+ });
+});
diff --git a/server/services/albums/index.js b/server/services/albums/index.js
new file mode 100644
index 0000000000..3a4ae96964
--- /dev/null
+++ b/server/services/albums/index.js
@@ -0,0 +1,106 @@
+/**
+ * Music albums — storage backend dispatcher.
+ *
+ * Albums are `db-primary` (PostgreSQL `albums` table). This thin dispatcher
+ * mirrors `services/artists/index.js`: select the backend lazily on first call.
+ * - PostgreSQL (db.js) for normal installs.
+ * - File (file.js) only via MEMORY_BACKEND=file or NODE_ENV=test.
+ *
+ * The recordEvents emits are kept so the store is federation-ready, but the
+ * album record kind is NOT yet registered in peerSync, so they are no-ops —
+ * albums are local-only until cross-peer sync is wired (see issue #1502).
+ */
+
+import { checkHealth, ensureSchema } from '../../lib/db.js';
+import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';
+
+export {
+ TITLE_MAX,
+ ARTIST_ID_MAX,
+ ARTIST_NAME_MAX,
+ DESCRIPTION_MAX,
+ GENRE_MAX,
+ COVER_IMAGE_URL_MAX,
+ TRACK_IDS_MAX,
+ TRACK_ID_MAX,
+ RELEASE_YEAR_MIN,
+ RELEASE_YEAR_MAX,
+ ALBUM_ID_RE,
+ coverImageFilename,
+} from './logic.js';
+
+let backend = null;
+let backendName = null;
+
+async function selectBackend() {
+ if (backend) return backend;
+ if (process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test') {
+ backend = await import('./file.js');
+ backendName = 'file';
+ return backend;
+ }
+ const health = await checkHealth();
+ if (!health.connected) {
+ throw new Error('Albums require PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file in .env for the unsupported file backend)');
+ }
+ await ensureSchema();
+ backend = await import('./db.js');
+ backendName = 'postgres';
+ return backend;
+}
+
+/** Name of the active backend, or null before first call (for diagnostics/tests). */
+export function getAlbumsBackendName() {
+ return backendName;
+}
+
+/** Test seam — drop the memoized backend so a suite can re-select. */
+export function _resetAlbumsBackend() {
+ backend = null;
+ backendName = null;
+}
+
+export async function listAlbums(options = {}) {
+ return (await selectBackend()).listAlbums(options);
+}
+
+export async function listAlbumIds(options = {}) {
+ return (await selectBackend()).listAlbumIds(options);
+}
+
+export async function getAlbum(id, options = {}) {
+ return (await selectBackend()).getAlbum(id, options);
+}
+
+function announceNewAlbum(id) {
+ emitRecordUpdated('album', id);
+ autoSubscribeRecordToAllPeers('album', id).catch(() => {});
+}
+
+export async function createAlbum(input) {
+ const album = await (await selectBackend()).createAlbum(input);
+ announceNewAlbum(album.id);
+ return album;
+}
+
+export async function updateAlbum(id, patch) {
+ const next = await (await selectBackend()).updateAlbum(id, patch);
+ emitRecordUpdated('album', next.id);
+ return next;
+}
+
+export async function deleteAlbum(id) {
+ const result = await (await selectBackend()).deleteAlbum(id);
+ emitRecordDeleted('album', result.id);
+ return result;
+}
+
+/** Merge an incoming batch of album records from a peer (LWW, tombstone-aware). */
+export async function mergeAlbumsFromSync(remoteAlbums, options = {}) {
+ return (await selectBackend()).mergeAlbumsFromSync(remoteAlbums, options);
+}
+
+/** Hard-remove album tombstones older than the cutoff (called by tombstone GC). */
+export async function pruneTombstonedAlbums(olderThanMs) {
+ return (await selectBackend()).pruneTombstonedAlbums(olderThanMs);
+}
diff --git a/server/services/albums/logic.js b/server/services/albums/logic.js
new file mode 100644
index 0000000000..1713064ce4
--- /dev/null
+++ b/server/services/albums/logic.js
@@ -0,0 +1,165 @@
+/**
+ * Music albums — shared mutation logic (backend-agnostic).
+ *
+ * The file backend (file.js) and the PostgreSQL backend (db.js) both import the
+ * sanitizer + record builders from here so the two backends can never drift.
+ * This module has NO I/O — pure functions only. Mirrors `services/artists/
+ * logic.js` (the persona store) with album-specific fields.
+ *
+ * An Album groups ordered tracks under an artist, with cover art:
+ * - title — album title
+ * - artistId — FK to the owning artist (`artist-…`), or '' for none
+ * - artist — denormalized artist name, so a peer/cover renders before
+ * the artist record itself has synced (mirrors series→author)
+ * - description — liner-notes blurb
+ * - genre — primary genre(s)
+ * - releaseYear — integer year, or null
+ * - coverImageUrl — optional pointer to a generated/uploaded cover image
+ * - trackIds — ordered list of track ids (`track-…`) on the album
+ *
+ * Albums are `db-primary` (PostgreSQL `albums` table). The storage layer is
+ * federation-ready (LWW merge + tombstone prune mirror authors/artists), but the
+ * cross-peer peer-sync REGISTRATION is not wired yet — see issue #1502. Until
+ * then albums are local-only.
+ */
+
+import { compareNewerWins } from '../../lib/lwwTimestamp.js';
+
+export const ALBUM_ID_RE = /^album-[A-Za-z0-9-]{1,64}$/;
+
+export const TITLE_MAX = 200;
+export const ARTIST_ID_MAX = 80;
+export const ARTIST_NAME_MAX = 120;
+export const DESCRIPTION_MAX = 4000;
+export const GENRE_MAX = 120;
+export const COVER_IMAGE_URL_MAX = 1000;
+export const TRACK_IDS_MAX = 200;
+export const TRACK_ID_MAX = 80;
+// Sane bounds for a release year — wide enough for archival reissues, narrow
+// enough to reject a fat-fingered/garbage value.
+export const RELEASE_YEAR_MIN = 1850;
+export const RELEASE_YEAR_MAX = 2200;
+
+const isStr = (v) => typeof v === 'string';
+const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');
+
+// Clamp an integer release year into the supported band; null when unparseable
+// so an album without a year stays distinct from one pinned to a bound.
+function sanitizeReleaseYear(v) {
+ if (typeof v !== 'number' || !Number.isFinite(v)) return null;
+ const y = Math.round(v);
+ if (y < RELEASE_YEAR_MIN || y > RELEASE_YEAR_MAX) return null;
+ return y;
+}
+
+// Ordered, deduped list of track ids — keeps the first occurrence's position,
+// drops blanks/non-strings, and bounds the length. Order IS the track order.
+function sanitizeTrackIds(arr) {
+ const seen = new Set();
+ return (Array.isArray(arr) ? arr : [])
+ .map((v) => trimTo(v, TRACK_ID_MAX))
+ .filter((id) => id && !seen.has(id) && seen.add(id))
+ .slice(0, TRACK_IDS_MAX);
+}
+
+/**
+ * Normalize a raw album record into the canonical stored shape. Returns null for
+ * a non-object or a record without a usable id/title (drop-on-floor contract).
+ */
+export function sanitizeAlbum(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ if (!isStr(raw.id) || !raw.id) return null;
+ const title = trimTo(raw.title, TITLE_MAX);
+ if (!title) return null;
+ const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();
+ const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;
+ const deleted = raw.deleted === true;
+ return {
+ id: raw.id,
+ title,
+ artistId: trimTo(raw.artistId, ARTIST_ID_MAX),
+ artist: trimTo(raw.artist, ARTIST_NAME_MAX),
+ description: trimTo(raw.description, DESCRIPTION_MAX),
+ genre: trimTo(raw.genre, GENRE_MAX),
+ releaseYear: sanitizeReleaseYear(raw.releaseYear),
+ // Empty string = no cover chosen; never null so the on-disk shape is stable.
+ coverImageUrl: trimTo(raw.coverImageUrl, COVER_IMAGE_URL_MAX),
+ trackIds: sanitizeTrackIds(raw.trackIds),
+ createdAt,
+ updatedAt,
+ deleted,
+ deletedAt: deleted && isStr(raw.deletedAt) && raw.deletedAt.trim() ? raw.deletedAt : null,
+ };
+}
+
+/**
+ * Resolve an album's `coverImageUrl` to the bare gallery-image filename under
+ * `data/images/` for a future peer-sync asset transfer. Returns null when
+ * there's nothing local to ship. Mirrors artists' portraitImageFilename.
+ */
+export function coverImageFilename(coverImageUrl) {
+ if (!isStr(coverImageUrl)) return null;
+ const url = coverImageUrl.trim();
+ if (!url) return null;
+ if (/^(https?:|data:|blob:)/i.test(url)) return null;
+ let name = url;
+ const imagesPrefix = '/data/images/';
+ if (url.startsWith(imagesPrefix)) name = url.slice(imagesPrefix.length);
+ else if (url.startsWith('/')) return null;
+ name = name.split(/[?#]/)[0];
+ const base = name.split('/').pop();
+ return base || null;
+}
+
+/** Build a fresh album record from create input. */
+export function buildAlbumRecord(input, { id, now }) {
+ return sanitizeAlbum({
+ id,
+ title: input.title,
+ artistId: input.artistId || '',
+ artist: input.artist || '',
+ description: input.description || '',
+ genre: input.genre || '',
+ releaseYear: input.releaseYear ?? null,
+ coverImageUrl: input.coverImageUrl || '',
+ trackIds: input.trackIds || [],
+ createdAt: now,
+ updatedAt: now,
+ deleted: false,
+ deletedAt: null,
+ });
+}
+
+// The user-authored fields a partial patch may overwrite. `id`, the LWW/
+// tombstone trio, and `createdAt` are server-owned / structural.
+const PATCHABLE = [
+ 'title', 'artistId', 'artist', 'description', 'genre', 'releaseYear', 'coverImageUrl', 'trackIds',
+];
+
+/**
+ * LWW merge decision for one incoming album record against the local copy.
+ * Mirrors mergeArtistRecord. Returns `{ next, inserted, remoteWins, changed }`.
+ */
+export function mergeAlbumRecord(local, remoteRaw) {
+ const remote = sanitizeAlbum(remoteRaw);
+ if (!remote) return { next: null, inserted: false, remoteWins: false, changed: false };
+ if (!local) return { next: remote, inserted: true, remoteWins: true, changed: true };
+ const remoteWins = compareNewerWins(remote.updatedAt, local.updatedAt);
+ const next = remoteWins ? remote : local;
+ const changed = JSON.stringify(next) !== JSON.stringify(local);
+ return { next, inserted: false, remoteWins, changed };
+}
+
+/**
+ * Apply a partial patch onto an existing record. Only keys PRESENT in `patch`
+ * overwrite — absent preserves, present-empty clears (per CLAUDE.md). Bumps
+ * updatedAt.
+ */
+export function applyAlbumPatch(current, patch = {}) {
+ const next = { ...current };
+ for (const key of PATCHABLE) {
+ if (key in patch) next[key] = patch[key];
+ }
+ next.updatedAt = new Date().toISOString();
+ return sanitizeAlbum(next);
+}
diff --git a/server/services/albums/logic.test.js b/server/services/albums/logic.test.js
new file mode 100644
index 0000000000..6d8523e085
--- /dev/null
+++ b/server/services/albums/logic.test.js
@@ -0,0 +1,94 @@
+import { describe, it, expect } from 'vitest';
+import {
+ sanitizeAlbum, buildAlbumRecord, applyAlbumPatch, mergeAlbumRecord, coverImageFilename,
+ TITLE_MAX, DESCRIPTION_MAX, RELEASE_YEAR_MIN, RELEASE_YEAR_MAX, TRACK_IDS_MAX,
+} from './logic.js';
+
+describe('albums logic', () => {
+ describe('sanitizeAlbum', () => {
+ it('drops records without an id or title', () => {
+ expect(sanitizeAlbum(null)).toBeNull();
+ expect(sanitizeAlbum({})).toBeNull();
+ expect(sanitizeAlbum({ id: 'album-1' })).toBeNull();
+ expect(sanitizeAlbum({ id: 'album-1', title: ' ' })).toBeNull();
+ });
+
+ it('trims fields and normalizes the shape', () => {
+ const a = sanitizeAlbum({
+ id: 'album-1',
+ title: ` ${'t'.repeat(TITLE_MAX + 50)} `,
+ artistId: ' artist-9 ',
+ artist: ' Nova ',
+ description: ` ${'d'.repeat(DESCRIPTION_MAX + 10)} `,
+ genre: ' dream pop ',
+ releaseYear: 2025,
+ coverImageUrl: ' /data/images/cover.png ',
+ trackIds: ['track-1', 'track-2'],
+ });
+ expect(a.title.length).toBe(TITLE_MAX);
+ expect(a.artistId).toBe('artist-9');
+ expect(a.artist).toBe('Nova');
+ expect(a.description.length).toBe(DESCRIPTION_MAX);
+ expect(a.genre).toBe('dream pop');
+ expect(a.releaseYear).toBe(2025);
+ expect(a.coverImageUrl).toBe('/data/images/cover.png');
+ expect(a.trackIds).toEqual(['track-1', 'track-2']);
+ });
+
+ it('clamps a garbage release year to null', () => {
+ expect(sanitizeAlbum({ id: 'album-1', title: 'X', releaseYear: 99999 }).releaseYear).toBeNull();
+ expect(sanitizeAlbum({ id: 'album-1', title: 'X', releaseYear: RELEASE_YEAR_MIN - 1 }).releaseYear).toBeNull();
+ expect(sanitizeAlbum({ id: 'album-1', title: 'X', releaseYear: 'soon' }).releaseYear).toBeNull();
+ expect(sanitizeAlbum({ id: 'album-1', title: 'X', releaseYear: RELEASE_YEAR_MAX }).releaseYear).toBe(RELEASE_YEAR_MAX);
+ });
+
+ it('dedupes trackIds keeping first position, drops blanks, and bounds the length', () => {
+ const a = sanitizeAlbum({
+ id: 'album-1', title: 'X',
+ trackIds: ['track-2', '', ' ', 'track-1', 'track-2', 42],
+ });
+ expect(a.trackIds).toEqual(['track-2', 'track-1']);
+ const many = sanitizeAlbum({ id: 'album-1', title: 'X', trackIds: Array.from({ length: TRACK_IDS_MAX + 10 }, (_, i) => `track-${i}`) });
+ expect(many.trackIds).toHaveLength(TRACK_IDS_MAX);
+ });
+ });
+
+ describe('applyAlbumPatch', () => {
+ const base = buildAlbumRecord({ title: 'Debut', genre: 'folk' }, { id: 'album-1', now: '2026-06-14T00:00:00.000Z' });
+
+ it('overwrites present keys and preserves absent ones', () => {
+ const next = applyAlbumPatch(base, { title: 'Debut (Remastered)' });
+ expect(next.title).toBe('Debut (Remastered)');
+ expect(next.genre).toBe('folk');
+ });
+
+ it('applies an intentional clear and reorders trackIds', () => {
+ const next = applyAlbumPatch(base, { genre: '', trackIds: ['track-3', 'track-1'] });
+ expect(next.genre).toBe('');
+ expect(next.trackIds).toEqual(['track-3', 'track-1']);
+ });
+ });
+
+ describe('mergeAlbumRecord (LWW)', () => {
+ const local = buildAlbumRecord({ title: 'Local' }, { id: 'album-1', now: '2026-06-01T00:00:00.000Z' });
+ it('inserts when no local counterpart', () => {
+ const r = mergeAlbumRecord(null, { ...local, title: 'Remote' });
+ expect(r.inserted).toBe(true);
+ expect(r.next.title).toBe('Remote');
+ });
+ it('newer remote wins; older loses', () => {
+ expect(mergeAlbumRecord(local, { ...local, title: 'New', updatedAt: '2099-01-01T00:00:00.000Z' }).remoteWins).toBe(true);
+ expect(mergeAlbumRecord(local, { ...local, title: 'Old', updatedAt: '2000-01-01T00:00:00.000Z' }).remoteWins).toBe(false);
+ });
+ });
+
+ describe('coverImageFilename', () => {
+ it('returns the basename for a gallery path; null for external/non-image', () => {
+ expect(coverImageFilename('/data/images/cover.png')).toBe('cover.png');
+ expect(coverImageFilename('cover.png?v=2')).toBe('cover.png');
+ expect(coverImageFilename('https://example.com/x.png')).toBeNull();
+ expect(coverImageFilename('/data/videos/x.mp4')).toBeNull();
+ expect(coverImageFilename('')).toBeNull();
+ });
+ });
+});
diff --git a/server/services/tracks/db.js b/server/services/tracks/db.js
new file mode 100644
index 0000000000..a348cb93ce
--- /dev/null
+++ b/server/services/tracks/db.js
@@ -0,0 +1,147 @@
+/**
+ * Music tracks — PostgreSQL leaf I/O.
+ *
+ * One row per track in `tracks`: the full sanitized record in `data` JSONB, with
+ * `title` + the LWW/tombstone trio mirrored into columns. Reads return `data`
+ * verbatim. Mutations run inside withTransaction + SELECT … FOR UPDATE. Mirrors
+ * `services/albums/db.js`; all mutation semantics live in logic.js.
+ */
+
+import { randomUUID } from 'crypto';
+import { query, withTransaction } from '../../lib/db.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { mirrorTimestamp } from '../../lib/pgTimestamp.js';
+import { buildTrackRecord, applyTrackPatch, mergeTrackRecord } from './logic.js';
+import {
+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+} from '../../lib/conflictJournal.js';
+
+function rowToTrack(row) {
+ return row ? row.data : null;
+}
+
+async function persist(exec, track) {
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(track.createdAt, now);
+ await exec(
+ `INSERT INTO tracks (id, title, data, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7)
+ ON CONFLICT (id) DO UPDATE SET
+ title = EXCLUDED.title,
+ data = EXCLUDED.data,
+ updated_at = EXCLUDED.updated_at,
+ deleted = EXCLUDED.deleted,
+ deleted_at = EXCLUDED.deleted_at`,
+ [
+ track.id,
+ typeof track.title === 'string' ? track.title : '',
+ JSON.stringify(track),
+ createdAt,
+ mirrorTimestamp(track.updatedAt, createdAt),
+ track.deleted === true,
+ mirrorTimestamp(track.deletedAt, null),
+ ],
+ );
+ return track;
+}
+
+export async function listTracks({ includeDeleted = false } = {}) {
+ const { rows } = includeDeleted
+ ? await query(`SELECT data FROM tracks ORDER BY created_at ASC`)
+ : await query(`SELECT data FROM tracks WHERE deleted = FALSE ORDER BY created_at ASC`);
+ return rows.map(rowToTrack);
+}
+
+export async function getTrack(id, { includeDeleted = false } = {}) {
+ const { rows } = await query(`SELECT data FROM tracks WHERE id = $1`, [id]);
+ const track = rowToTrack(rows[0]);
+ if (!track) return null;
+ return includeDeleted || !track.deleted ? track : null;
+}
+
+/** Live track ids (or all when includeDeleted) — used by tombstone GC sweeps. */
+export async function listTrackIds({ includeDeleted = false } = {}) {
+ const { rows } = includeDeleted
+ ? await query(`SELECT id FROM tracks`)
+ : await query(`SELECT id FROM tracks WHERE deleted = FALSE`);
+ return rows.map((r) => r.id);
+}
+
+export async function createTrack(input) {
+ const track = buildTrackRecord(input, { id: `track-${randomUUID()}`, now: new Date().toISOString() });
+ if (!track) throw new ServerError('Invalid track payload', { status: 400, code: 'VALIDATION' });
+ await persist(query, track);
+ console.log(`🎵 Created track: ${track.id} (${track.title})`);
+ return track;
+}
+
+export async function updateTrack(id, patch) {
+ return withTransaction(async (client) => {
+ const sel = await client.query(`SELECT data FROM tracks WHERE id = $1 FOR UPDATE`, [id]);
+ const current = rowToTrack(sel.rows[0]);
+ if (!current || current.deleted) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
+ const next = applyTrackPatch(current, patch);
+ if (!next) throw new ServerError('Invalid track payload', { status: 400, code: 'VALIDATION' });
+ await persist(client.query.bind(client), next);
+ return next;
+ });
+}
+
+export async function deleteTrack(id) {
+ return withTransaction(async (client) => {
+ const sel = await client.query(`SELECT data FROM tracks WHERE id = $1 FOR UPDATE`, [id]);
+ const current = rowToTrack(sel.rows[0]);
+ if (!current || current.deleted) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
+ const now = new Date().toISOString();
+ const next = { ...current, deleted: true, deletedAt: now, updatedAt: now };
+ await persist(client.query.bind(client), next);
+ return { id };
+ });
+}
+
+/**
+ * Merge an incoming batch of track records from a peer (per-record push). LWW on
+ * `updatedAt` (tombstone-aware) via the shared `mergeTrackRecord` decision.
+ * Federation-ready, but the track kind is not yet registered in peerSync — see
+ * issue #1502. Returns `{ applied, count }`.
+ */
+export async function mergeTracksFromSync(remoteTracks, { source = { via: 'sync', peerId: null } } = {}) {
+ if (!Array.isArray(remoteTracks)) return { applied: false, count: 0 };
+ let changed = 0;
+ for (const remote of remoteTracks) {
+ const applied = await withTransaction(async (client) => {
+ const sel = await client.query(`SELECT data FROM tracks WHERE id = $1 FOR UPDATE`, [remote?.id]);
+ const local = rowToTrack(sel.rows[0]);
+ const { next, inserted, remoteWins, changed: didChange } = mergeTrackRecord(local, remote);
+ if (!next) return false;
+ if (inserted) {
+ await persist(client.query.bind(client), next);
+ await setSyncBaseHash('track', next.id, contentHashForRecord('track', next));
+ return true;
+ }
+ if (!remoteWins || !didChange) return false;
+ await maybeJournalBeforeOverwrite({ kind: 'track', id: next.id, local, remote: next, source });
+ await persist(client.query.bind(client), next);
+ await setSyncBaseHash('track', next.id, contentHashForRecord('track', next));
+ return true;
+ });
+ if (applied) changed += 1;
+ }
+ await flushBaseHashes();
+ if (changed === 0) return { applied: false, count: 0 };
+ return { applied: true, count: changed };
+}
+
+/** Hard-remove tombstoned tracks whose deletedAt is older than the cutoff. */
+export async function pruneTombstonedTracks(olderThanMs) {
+ if (!Number.isFinite(olderThanMs)) return { pruned: 0 };
+ const cutoffIso = new Date(olderThanMs).toISOString();
+ const { rows } = await query(
+ `DELETE FROM tracks
+ WHERE deleted = TRUE AND deleted_at IS NOT NULL AND deleted_at < $1
+ RETURNING id`,
+ [cutoffIso],
+ );
+ for (const r of rows) await deleteSyncBaseHash('track', r.id);
+ return { pruned: rows.length };
+}
diff --git a/server/services/tracks/db.test.js b/server/services/tracks/db.test.js
new file mode 100644
index 0000000000..fc81c53eb5
--- /dev/null
+++ b/server/services/tracks/db.test.js
@@ -0,0 +1,72 @@
+/**
+ * Postgres-backed round-trip for the music-track DB adapter. SKIPS cleanly when
+ * no test DB is reachable; runs only via `npm run test:db` against `portos_test`.
+ * Snapshots + restores the `tracks` table. Mirrors albums/db.test.js.
+ */
+
+import { describe, it, expect, afterAll, beforeAll, beforeEach } from 'vitest';
+import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';
+
+let dbReady = false;
+let skipReason = '';
+{
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ await ensureSchema().catch(() => {});
+ const probe = await query(
+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'tracks') AS ok`,
+ ).catch(() => ({ rows: [{ ok: false }] }));
+ if (probe.rows?.[0]?.ok) dbReady = true;
+ else skipReason = 'tracks table not present';
+ }
+}
+
+if (!dbReady) console.log(`⏭️ services/tracks/db.test.js skipped: ${skipReason}`);
+
+describe.skipIf(!dbReady)('tracks DB adapter round-trip', () => {
+ let db;
+ let snap = [];
+ beforeAll(async () => {
+ db = await import('./db.js');
+ snap = (await query(`SELECT * FROM tracks`)).rows;
+ });
+ beforeEach(async () => { await query(`DELETE FROM tracks`); });
+ afterAll(async () => {
+ await query(`DELETE FROM tracks`).catch(() => {});
+ for (const r of snap) {
+ await query(
+ `INSERT INTO tracks (id, title, data, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1,$2,$3::jsonb,$4,$5,$6,$7) ON CONFLICT (id) DO NOTHING`,
+ [r.id, r.title, JSON.stringify(r.data), r.created_at, r.updated_at, r.deleted, r.deleted_at],
+ ).catch(() => {});
+ }
+ await close();
+ });
+
+ it('creates a track and mirrors title into the column', async () => {
+ const t = await db.createTrack({ title: 'Intro', engine: 'acestep', audioFilename: 'music-1.mp3' });
+ expect(t.id).toMatch(/^track-/);
+ const col = (await query(`SELECT title FROM tracks WHERE id = $1`, [t.id])).rows[0];
+ expect(col.title).toBe('Intro');
+ expect(await db.getTrack(t.id)).toEqual(t);
+ });
+
+ it('listTracks excludes tombstones; update preserves absent keys', async () => {
+ const live = await db.createTrack({ title: 'Live' });
+ const dead = await db.createTrack({ title: 'Dead' });
+ await db.deleteTrack(dead.id);
+ expect((await db.listTracks()).map((t) => t.id)).toEqual([live.id]);
+ const next = await db.updateTrack(live.id, { prompt: 'warm' });
+ expect(next.title).toBe('Live');
+ expect(next.prompt).toBe('warm');
+ });
+
+ it('mergeTracksFromSync: newer wins, older loses', async () => {
+ const t = await db.createTrack({ title: 'Local' });
+ expect(await db.mergeTracksFromSync([{ ...t, title: 'Old', updatedAt: '2000-01-01T00:00:00.000Z' }])).toEqual({ applied: false, count: 0 });
+ expect(await db.mergeTracksFromSync([{ ...t, title: 'Fresh', updatedAt: '2099-01-01T00:00:00.000Z' }])).toEqual({ applied: true, count: 1 });
+ expect((await db.getTrack(t.id)).title).toBe('Fresh');
+ });
+});
diff --git a/server/services/tracks/file.js b/server/services/tracks/file.js
new file mode 100644
index 0000000000..47a908f1cb
--- /dev/null
+++ b/server/services/tracks/file.js
@@ -0,0 +1,126 @@
+/**
+ * Music tracks — file-backed store (escape-hatch / test backend).
+ *
+ * Persists to data/tracks.json (array, atomicWrite). PostgreSQL (db.js) is the
+ * default; this backend is reachable only via MEMORY_BACKEND=file or
+ * NODE_ENV=test. Mirrors `services/albums/file.js`; all mutation semantics live
+ * in logic.js so the two backends can't drift.
+ */
+
+import { join } from 'path';
+import { randomUUID } from 'crypto';
+import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { sanitizeTrack, buildTrackRecord, applyTrackPatch, mergeTrackRecord } from './logic.js';
+import {
+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+} from '../../lib/conflictJournal.js';
+
+const TRACKS_FILE = join(PATHS.data, 'tracks.json');
+
+async function loadAll() {
+ const raw = await readJSONFile(TRACKS_FILE, []);
+ return (Array.isArray(raw) ? raw : []).map(sanitizeTrack).filter(Boolean);
+}
+
+async function saveAll(tracks) {
+ await ensureDir(PATHS.data);
+ await atomicWrite(TRACKS_FILE, tracks);
+}
+
+// Tracks list in creation order (the album's trackIds drive display order).
+const byCreated = (a, b) => (a.createdAt || '').localeCompare(b.createdAt || '');
+
+export async function listTracks({ includeDeleted = false } = {}) {
+ const all = await loadAll();
+ return (includeDeleted ? all : all.filter((t) => !t.deleted)).sort(byCreated);
+}
+
+export async function getTrack(id, { includeDeleted = false } = {}) {
+ const all = await loadAll();
+ const found = all.find((t) => t.id === id);
+ if (!found) return null;
+ return includeDeleted || !found.deleted ? found : null;
+}
+
+/** Live track ids (or all when includeDeleted) — used by tombstone GC sweeps. */
+export async function listTrackIds({ includeDeleted = false } = {}) {
+ const all = await loadAll();
+ return (includeDeleted ? all : all.filter((t) => !t.deleted)).map((t) => t.id);
+}
+
+export async function createTrack(input) {
+ const track = buildTrackRecord(input, { id: `track-${randomUUID()}`, now: new Date().toISOString() });
+ if (!track) throw new ServerError('Invalid track payload', { status: 400, code: 'VALIDATION' });
+ const all = await loadAll();
+ all.push(track);
+ await saveAll(all);
+ console.log(`🎵 Created track: ${track.id} (${track.title})`);
+ return track;
+}
+
+export async function updateTrack(id, patch) {
+ const all = await loadAll();
+ const idx = all.findIndex((t) => t.id === id);
+ if (idx < 0 || all[idx].deleted) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
+ const next = applyTrackPatch(all[idx], patch);
+ if (!next) throw new ServerError('Invalid track payload', { status: 400, code: 'VALIDATION' });
+ all[idx] = next;
+ await saveAll(all);
+ return next;
+}
+
+export async function deleteTrack(id) {
+ const all = await loadAll();
+ const idx = all.findIndex((t) => t.id === id);
+ if (idx < 0 || all[idx].deleted) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
+ const now = new Date().toISOString();
+ all[idx] = { ...all[idx], deleted: true, deletedAt: now, updatedAt: now };
+ await saveAll(all);
+ return { id };
+}
+
+/** File-backend mirror of db.js `mergeTracksFromSync` (LWW-per-id, tombstone-aware). */
+export async function mergeTracksFromSync(remoteTracks, { source = { via: 'sync', peerId: null } } = {}) {
+ if (!Array.isArray(remoteTracks)) return { applied: false, count: 0 };
+ const all = await loadAll();
+ const byId = new Map(all.map((t) => [t.id, t]));
+ let changed = 0;
+ for (const remote of remoteTracks) {
+ const local = byId.get(remote?.id) || null;
+ const { next, inserted, remoteWins, changed: didChange } = mergeTrackRecord(local, remote);
+ if (!next) continue;
+ if (inserted) {
+ byId.set(next.id, next);
+ await setSyncBaseHash('track', next.id, contentHashForRecord('track', next));
+ changed += 1;
+ continue;
+ }
+ if (!remoteWins || !didChange) continue;
+ await maybeJournalBeforeOverwrite({ kind: 'track', id: next.id, local, remote: next, source });
+ byId.set(next.id, next);
+ await setSyncBaseHash('track', next.id, contentHashForRecord('track', next));
+ changed += 1;
+ }
+ if (changed > 0) await saveAll([...byId.values()]);
+ await flushBaseHashes();
+ if (changed === 0) return { applied: false, count: 0 };
+ return { applied: true, count: changed };
+}
+
+/** Hard-remove tombstoned tracks whose deletedAt is older than the cutoff. */
+export async function pruneTombstonedTracks(olderThanMs) {
+ if (!Number.isFinite(olderThanMs)) return { pruned: 0 };
+ const all = await loadAll();
+ const survivors = [];
+ const pruned = [];
+ for (const t of all) {
+ const ms = t.deleted ? Date.parse(t.deletedAt || '') : NaN;
+ if (t.deleted && Number.isFinite(ms) && ms < olderThanMs) pruned.push(t.id);
+ else survivors.push(t);
+ }
+ if (pruned.length === 0) return { pruned: 0 };
+ await saveAll(survivors);
+ for (const id of pruned) await deleteSyncBaseHash('track', id);
+ return { pruned: pruned.length };
+}
diff --git a/server/services/tracks/file.test.js b/server/services/tracks/file.test.js
new file mode 100644
index 0000000000..e88c3d4794
--- /dev/null
+++ b/server/services/tracks/file.test.js
@@ -0,0 +1,70 @@
+/**
+ * Track file-backend store — CRUD + LWW merge outcomes.
+ *
+ * Covers the CRUD round-trip + `mergeTracksFromSync` LWW outcomes. Conflict-
+ * journal side effects are NOT asserted (track kind not yet registered in
+ * syncWire/peerSync — deferred, local-only; see issue #1502). tmpdir-backed.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'tracks-file-test-'));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+});
+
+const file = await import('./file.js');
+
+function reset() {
+ rmSync(join(TEST_DATA_ROOT, 'tracks.json'), { force: true });
+ rmSync(join(TEST_DATA_ROOT, 'sharing'), { recursive: true, force: true });
+ rmSync(join(TEST_DATA_ROOT, 'conflict-journal'), { recursive: true, force: true });
+}
+
+const track = (id, extra = {}) => ({
+ id, title: id, albumId: '', artistId: '', artist: '', lyrics: '', prompt: '',
+ engine: '', modelId: '', durationSec: null, audioFilename: '',
+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
+ deleted: false, deletedAt: null, ...extra,
+});
+
+beforeEach(reset);
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+describe('tracks file backend — CRUD', () => {
+ it('creates, reads, updates and soft-deletes a track', async () => {
+ const created = await file.createTrack({ title: 'Intro', audioFilename: 'music-1.mp3' });
+ expect(created.id).toMatch(/^track-/);
+ expect((await file.getTrack(created.id)).audioFilename).toBe('music-1.mp3');
+
+ const updated = await file.updateTrack(created.id, { audioFilename: '' });
+ expect(updated.audioFilename).toBe('');
+
+ await file.deleteTrack(created.id);
+ expect(await file.getTrack(created.id)).toBeNull();
+ expect(await file.listTracks()).toHaveLength(0);
+ });
+});
+
+describe('tracks file backend — mergeTracksFromSync (LWW outcomes)', () => {
+ it('inserts, then newer wins / older no-ops', async () => {
+ expect(await file.mergeTracksFromSync([track('track-1', { prompt: 'v1', updatedAt: '2026-02-01T00:00:00.000Z' })]))
+ .toEqual({ applied: true, count: 1 });
+ expect(await file.mergeTracksFromSync([track('track-1', { prompt: 'v2', updatedAt: '2026-03-01T00:00:00.000Z' })]))
+ .toEqual({ applied: true, count: 1 });
+ expect((await file.getTrack('track-1')).prompt).toBe('v2');
+ expect(await file.mergeTracksFromSync([track('track-1', { prompt: 'stale', updatedAt: '2020-01-01T00:00:00.000Z' })]))
+ .toEqual({ applied: false, count: 0 });
+ });
+
+ it('pruneTombstonedTracks hard-removes an old tombstone', async () => {
+ await file.mergeTracksFromSync([track('track-dead', { deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2020-01-01T00:00:00.000Z' })]);
+ expect(await file.pruneTombstonedTracks(Date.parse('2030-01-01T00:00:00.000Z'))).toEqual({ pruned: 1 });
+ expect(await file.getTrack('track-dead', { includeDeleted: true })).toBeNull();
+ });
+});
diff --git a/server/services/tracks/index.js b/server/services/tracks/index.js
new file mode 100644
index 0000000000..08b69f612b
--- /dev/null
+++ b/server/services/tracks/index.js
@@ -0,0 +1,107 @@
+/**
+ * Music tracks — storage backend dispatcher.
+ *
+ * Tracks are `db-primary` (PostgreSQL `tracks` table). This thin dispatcher
+ * mirrors `services/albums/index.js`: select the backend lazily on first call.
+ * - PostgreSQL (db.js) for normal installs.
+ * - File (file.js) only via MEMORY_BACKEND=file or NODE_ENV=test.
+ *
+ * The recordEvents emits are kept so the store is federation-ready, but the
+ * track record kind is NOT yet registered in peerSync, so they are no-ops —
+ * tracks are local-only until cross-peer sync is wired (see issue #1502).
+ */
+
+import { checkHealth, ensureSchema } from '../../lib/db.js';
+import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';
+
+export {
+ TITLE_MAX,
+ ALBUM_ID_MAX,
+ ARTIST_ID_MAX,
+ ARTIST_NAME_MAX,
+ LYRICS_MAX,
+ PROMPT_MAX,
+ ENGINE_MAX,
+ MODEL_ID_MAX,
+ AUDIO_FILENAME_MAX,
+ DURATION_MIN_SEC,
+ DURATION_MAX_SEC,
+ TRACK_ID_RE,
+ trackAudioFilename,
+} from './logic.js';
+
+let backend = null;
+let backendName = null;
+
+async function selectBackend() {
+ if (backend) return backend;
+ if (process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test') {
+ backend = await import('./file.js');
+ backendName = 'file';
+ return backend;
+ }
+ const health = await checkHealth();
+ if (!health.connected) {
+ throw new Error('Tracks require PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file in .env for the unsupported file backend)');
+ }
+ await ensureSchema();
+ backend = await import('./db.js');
+ backendName = 'postgres';
+ return backend;
+}
+
+/** Name of the active backend, or null before first call (for diagnostics/tests). */
+export function getTracksBackendName() {
+ return backendName;
+}
+
+/** Test seam — drop the memoized backend so a suite can re-select. */
+export function _resetTracksBackend() {
+ backend = null;
+ backendName = null;
+}
+
+export async function listTracks(options = {}) {
+ return (await selectBackend()).listTracks(options);
+}
+
+export async function listTrackIds(options = {}) {
+ return (await selectBackend()).listTrackIds(options);
+}
+
+export async function getTrack(id, options = {}) {
+ return (await selectBackend()).getTrack(id, options);
+}
+
+function announceNewTrack(id) {
+ emitRecordUpdated('track', id);
+ autoSubscribeRecordToAllPeers('track', id).catch(() => {});
+}
+
+export async function createTrack(input) {
+ const track = await (await selectBackend()).createTrack(input);
+ announceNewTrack(track.id);
+ return track;
+}
+
+export async function updateTrack(id, patch) {
+ const next = await (await selectBackend()).updateTrack(id, patch);
+ emitRecordUpdated('track', next.id);
+ return next;
+}
+
+export async function deleteTrack(id) {
+ const result = await (await selectBackend()).deleteTrack(id);
+ emitRecordDeleted('track', result.id);
+ return result;
+}
+
+/** Merge an incoming batch of track records from a peer (LWW, tombstone-aware). */
+export async function mergeTracksFromSync(remoteTracks, options = {}) {
+ return (await selectBackend()).mergeTracksFromSync(remoteTracks, options);
+}
+
+/** Hard-remove track tombstones older than the cutoff (called by tombstone GC). */
+export async function pruneTombstonedTracks(olderThanMs) {
+ return (await selectBackend()).pruneTombstonedTracks(olderThanMs);
+}
diff --git a/server/services/tracks/logic.js b/server/services/tracks/logic.js
new file mode 100644
index 0000000000..7d4c9b7a55
--- /dev/null
+++ b/server/services/tracks/logic.js
@@ -0,0 +1,156 @@
+/**
+ * Music tracks — shared mutation logic (backend-agnostic).
+ *
+ * The file backend (file.js) and the PostgreSQL backend (db.js) both import the
+ * sanitizer + record builders from here so the two backends can never drift.
+ * This module has NO I/O — pure functions only. Mirrors `services/albums/
+ * logic.js` with track-specific fields.
+ *
+ * A Track is a single song/recording — standalone or part of an album:
+ * - title — track title
+ * - albumId — FK to the owning album (`album-…`), or '' for a single
+ * - artistId — FK to the performing artist (`artist-…`), or '' for none
+ * - artist — denormalized artist name (renders before the artist syncs)
+ * - lyrics — full lyrics (also the conditioning text for lyric-aware
+ * generators like Ace-Step)
+ * - prompt — the text/style prompt used (or to use) for generation
+ * - engine — music-gen engine id the audio came from (e.g. 'acestep'),
+ * or '' for an uploaded track
+ * - modelId — model within that engine, or ''
+ * - durationSec — clip length in seconds, or null
+ * - audioFilename — the music-library filename under data/music/ (the bytes),
+ * or '' when no audio is attached yet
+ *
+ * Tracks are `db-primary` (PostgreSQL `tracks` table). The audio bytes live in
+ * the shared music library (services/pipeline/musicLibrary.js, `data/music/`);
+ * a track stores only the filename pointer. The storage layer is federation-
+ * ready, but cross-peer sync is not wired yet — see issue #1502 (local-only).
+ */
+
+import { compareNewerWins } from '../../lib/lwwTimestamp.js';
+
+export const TRACK_ID_RE = /^track-[A-Za-z0-9-]{1,64}$/;
+
+export const TITLE_MAX = 200;
+export const ALBUM_ID_MAX = 80;
+export const ARTIST_ID_MAX = 80;
+export const ARTIST_NAME_MAX = 120;
+export const LYRICS_MAX = 20000;
+export const PROMPT_MAX = 8000;
+export const ENGINE_MAX = 60;
+export const MODEL_ID_MAX = 120;
+export const AUDIO_FILENAME_MAX = 256;
+// A track clip's usable duration band — wide enough for a long-form generation,
+// bounded so a garbage value can't poison the record.
+export const DURATION_MIN_SEC = 1;
+export const DURATION_MAX_SEC = 3600;
+
+const isStr = (v) => typeof v === 'string';
+const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');
+
+function sanitizeDuration(v) {
+ if (typeof v !== 'number' || !Number.isFinite(v)) return null;
+ const s = Math.round(v);
+ if (s < DURATION_MIN_SEC || s > DURATION_MAX_SEC) return null;
+ return s;
+}
+
+/**
+ * Normalize a raw track record into the canonical stored shape. Returns null for
+ * a non-object or a record without a usable id/title (drop-on-floor contract).
+ */
+export function sanitizeTrack(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ if (!isStr(raw.id) || !raw.id) return null;
+ const title = trimTo(raw.title, TITLE_MAX);
+ if (!title) return null;
+ const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();
+ const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;
+ const deleted = raw.deleted === true;
+ return {
+ id: raw.id,
+ title,
+ albumId: trimTo(raw.albumId, ALBUM_ID_MAX),
+ artistId: trimTo(raw.artistId, ARTIST_ID_MAX),
+ artist: trimTo(raw.artist, ARTIST_NAME_MAX),
+ lyrics: trimTo(raw.lyrics, LYRICS_MAX),
+ prompt: trimTo(raw.prompt, PROMPT_MAX),
+ engine: trimTo(raw.engine, ENGINE_MAX),
+ modelId: trimTo(raw.modelId, MODEL_ID_MAX),
+ durationSec: sanitizeDuration(raw.durationSec),
+ // Empty string = no audio attached yet; never null so the shape is stable.
+ audioFilename: trimTo(raw.audioFilename, AUDIO_FILENAME_MAX),
+ createdAt,
+ updatedAt,
+ deleted,
+ deletedAt: deleted && isStr(raw.deletedAt) && raw.deletedAt.trim() ? raw.deletedAt : null,
+ };
+}
+
+/**
+ * The bare music-library filename for a track's audio (already a basename), or
+ * null when no audio is attached. Tracks store the filename directly (not a
+ * URL), so this is mostly an existence/trim guard for the future asset pipeline.
+ */
+export function trackAudioFilename(audioFilename) {
+ const name = trimTo(audioFilename, AUDIO_FILENAME_MAX);
+ if (!name) return null;
+ // Defense-in-depth: never let a path-ish value through as an asset basename.
+ if (name.includes('/') || name.includes('\\') || name.includes('..')) return null;
+ return name;
+}
+
+/** Build a fresh track record from create input. */
+export function buildTrackRecord(input, { id, now }) {
+ return sanitizeTrack({
+ id,
+ title: input.title,
+ albumId: input.albumId || '',
+ artistId: input.artistId || '',
+ artist: input.artist || '',
+ lyrics: input.lyrics || '',
+ prompt: input.prompt || '',
+ engine: input.engine || '',
+ modelId: input.modelId || '',
+ durationSec: input.durationSec ?? null,
+ audioFilename: input.audioFilename || '',
+ createdAt: now,
+ updatedAt: now,
+ deleted: false,
+ deletedAt: null,
+ });
+}
+
+// The user-authored fields a partial patch may overwrite. `id`, the LWW/
+// tombstone trio, and `createdAt` are server-owned / structural.
+const PATCHABLE = [
+ 'title', 'albumId', 'artistId', 'artist', 'lyrics', 'prompt', 'engine', 'modelId', 'durationSec', 'audioFilename',
+];
+
+/**
+ * LWW merge decision for one incoming track record against the local copy.
+ * Mirrors mergeAlbumRecord. Returns `{ next, inserted, remoteWins, changed }`.
+ */
+export function mergeTrackRecord(local, remoteRaw) {
+ const remote = sanitizeTrack(remoteRaw);
+ if (!remote) return { next: null, inserted: false, remoteWins: false, changed: false };
+ if (!local) return { next: remote, inserted: true, remoteWins: true, changed: true };
+ const remoteWins = compareNewerWins(remote.updatedAt, local.updatedAt);
+ const next = remoteWins ? remote : local;
+ const changed = JSON.stringify(next) !== JSON.stringify(local);
+ return { next, inserted: false, remoteWins, changed };
+}
+
+/**
+ * Apply a partial patch onto an existing record. Only keys PRESENT in `patch`
+ * overwrite — absent preserves, present-empty clears (per CLAUDE.md). Bumps
+ * updatedAt.
+ */
+export function applyTrackPatch(current, patch = {}) {
+ const next = { ...current };
+ for (const key of PATCHABLE) {
+ if (key in patch) next[key] = patch[key];
+ }
+ next.updatedAt = new Date().toISOString();
+ return sanitizeTrack(next);
+}
diff --git a/server/services/tracks/logic.test.js b/server/services/tracks/logic.test.js
new file mode 100644
index 0000000000..6015e12770
--- /dev/null
+++ b/server/services/tracks/logic.test.js
@@ -0,0 +1,75 @@
+import { describe, it, expect } from 'vitest';
+import {
+ sanitizeTrack, buildTrackRecord, applyTrackPatch, mergeTrackRecord, trackAudioFilename,
+ TITLE_MAX, LYRICS_MAX, DURATION_MIN_SEC, DURATION_MAX_SEC,
+} from './logic.js';
+
+describe('tracks logic', () => {
+ describe('sanitizeTrack', () => {
+ it('drops records without an id or title', () => {
+ expect(sanitizeTrack(null)).toBeNull();
+ expect(sanitizeTrack({})).toBeNull();
+ expect(sanitizeTrack({ id: 'track-1' })).toBeNull();
+ expect(sanitizeTrack({ id: 'track-1', title: ' ' })).toBeNull();
+ });
+
+ it('trims fields and normalizes the shape', () => {
+ const t = sanitizeTrack({
+ id: 'track-1',
+ title: ` ${'t'.repeat(TITLE_MAX + 50)} `,
+ albumId: ' album-9 ',
+ artistId: ' artist-9 ',
+ artist: ' Nova ',
+ lyrics: ` ${'l'.repeat(LYRICS_MAX + 10)} `,
+ prompt: ' warm folk ',
+ engine: ' acestep ',
+ modelId: ' ace-v1 ',
+ durationSec: 180,
+ audioFilename: ' music-abc.mp3 ',
+ });
+ expect(t.title.length).toBe(TITLE_MAX);
+ expect(t.albumId).toBe('album-9');
+ expect(t.artistId).toBe('artist-9');
+ expect(t.artist).toBe('Nova');
+ expect(t.lyrics.length).toBe(LYRICS_MAX);
+ expect(t.engine).toBe('acestep');
+ expect(t.modelId).toBe('ace-v1');
+ expect(t.durationSec).toBe(180);
+ expect(t.audioFilename).toBe('music-abc.mp3');
+ });
+
+ it('clamps a garbage duration to null', () => {
+ expect(sanitizeTrack({ id: 'track-1', title: 'X', durationSec: 0 }).durationSec).toBeNull();
+ expect(sanitizeTrack({ id: 'track-1', title: 'X', durationSec: DURATION_MAX_SEC + 1 }).durationSec).toBeNull();
+ expect(sanitizeTrack({ id: 'track-1', title: 'X', durationSec: 'long' }).durationSec).toBeNull();
+ expect(sanitizeTrack({ id: 'track-1', title: 'X', durationSec: DURATION_MIN_SEC }).durationSec).toBe(DURATION_MIN_SEC);
+ });
+ });
+
+ describe('applyTrackPatch', () => {
+ const base = buildTrackRecord({ title: 'Intro', lyrics: 'la la' }, { id: 'track-1', now: '2026-06-14T00:00:00.000Z' });
+ it('overwrites present keys, preserves absent, applies clear', () => {
+ const next = applyTrackPatch(base, { title: 'Intro (Reprise)', lyrics: '' });
+ expect(next.title).toBe('Intro (Reprise)');
+ expect(next.lyrics).toBe('');
+ });
+ });
+
+ describe('mergeTrackRecord (LWW)', () => {
+ const local = buildTrackRecord({ title: 'Local' }, { id: 'track-1', now: '2026-06-01T00:00:00.000Z' });
+ it('inserts / newer-wins / older-loses', () => {
+ expect(mergeTrackRecord(null, { ...local, title: 'R' }).inserted).toBe(true);
+ expect(mergeTrackRecord(local, { ...local, title: 'New', updatedAt: '2099-01-01T00:00:00.000Z' }).remoteWins).toBe(true);
+ expect(mergeTrackRecord(local, { ...local, title: 'Old', updatedAt: '2000-01-01T00:00:00.000Z' }).remoteWins).toBe(false);
+ });
+ });
+
+ describe('trackAudioFilename', () => {
+ it('returns a bare filename, null for blank or path-ish input', () => {
+ expect(trackAudioFilename('music-abc.mp3')).toBe('music-abc.mp3');
+ expect(trackAudioFilename('')).toBeNull();
+ expect(trackAudioFilename('../escape.mp3')).toBeNull();
+ expect(trackAudioFilename('sub/dir.mp3')).toBeNull();
+ });
+ });
+});