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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
add Music studio with db-primary Artist personas (mirrors Authors)
[._.]/ Adam Eivy67e68e1b4256
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d3cd1a09bb..5c957c7e93 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -11,6 +11,8 @@## 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.+- **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.- App **Automation** tabs now show a banner when scheduled automation is globally paused, with a one-click **Resume**. Manually clicking **Run** on a task now bypasses the global pause — the pause only stops scheduled/autonomous spawning, not explicit user triggers.diff --git a/client/src/App.jsx b/client/src/App.jsxindex 9d0517519c..f8aa4e94c1 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -48,6 +48,7 @@ const LoraDatasetDetail = lazyWithReload(() => import('./pages/LoraDatasetDetailconst UniverseBuilder = lazyWithReload(() => import('./pages/UniverseBuilder'));const Universes = lazyWithReload(() => import('./pages/Universes'));const Authors = lazyWithReload(() => import('./pages/Authors'));+const Music = lazyWithReload(() => import('./pages/Music'));const Catalog = lazyWithReload(() => import('./pages/Catalog'));const Rounds = lazyWithReload(() => import('./pages/Rounds'));const RoundEditor = lazyWithReload(() => import('./pages/RoundEditor'));@@ -320,6 +321,8 @@ export default function App() {<Route path="story-builder/:storyId" element={<Navigate to="idea" replace />} /><Route path="story-builder/:storyId/:step" element={<StoryBuilder />} /><Route path="authors" element={<Authors />} />+ <Route path="music" element={<Music />} />+ <Route path="music/:tab" element={<Music />} /><Route path="pipeline" element={<Pipeline />} /><Route path="pipeline/editorial-checks" element={<PipelineEditorialChecks />} /><Route path="pipeline/series/:seriesId" element={<PipelineSeries />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 0222ed425b..fe15e6f0fc 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -204,6 +204,7 @@ const navItems = [{ to: '/importer', label: 'Importer', icon: FileInput },{ to: '/media', label: 'Media Gen', icon: Layers },{ to: '/mood-boards', label: 'Mood Boards', icon: Palette },+ { to: '/music', label: 'Music', icon: Mic },{ to: '/rounds', label: 'Rounds', icon: Music },{ to: '/pipeline', label: 'Series Pipeline', icon: WorkflowIcon, dynamic: 'pipelineSeries' },{ to: '/sharing', label: 'Sharing', icon: Share2 },diff --git a/client/src/components/music/ArtistsManager.jsx b/client/src/components/music/ArtistsManager.jsxnew file mode 100644index 0000000000..13cc94d2f6--- /dev/null+++ b/client/src/components/music/ArtistsManager.jsx@@ -0,0 +1,471 @@+/**+ * ArtistsManager — manage reusable music-artist personas (the Music studio's+ * analogue of the Authors page). Master-detail: a selectable list on the left,+ * an editor on the right. An Artist carries a name, genre, bio, musical style,+ * plus a physical description + portrait style used to generate (or upload) an+ * artist portrait. Mirrors pages/Authors.jsx — same portrait+ * generate/upload/gallery affordances, reusing the image-gen pipeline.+ */++import { useEffect, useMemo, useRef, useState } from 'react';+import { Plus, Loader2, Trash2, Save, Upload, ImageIcon, Sparkles, X } 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 {+ listArtists, createArtist, updateArtist, deleteArtist, uploadGalleryImage, generateImage,+ ARTIST_NAME_MAX, ARTIST_GENRE_MAX, ARTIST_BIO_MAX, ARTIST_MUSICAL_STYLE_MAX,+ ARTIST_PHYSICAL_DESCRIPTION_MAX, ARTIST_PORTRAIT_STYLE_MAX, ARTIST_PORTRAIT_IMAGE_URL_MAX,+} from '../../services/api';++// Cap portrait uploads so the base64 round-trip stays small.+const PORTRAIT_MAX_BYTES = 12 * 1024 * 1024;++const emptyForm = () => ({+ name: '', genre: '', bio: '', musicalStyle: '', physicalDescription: '', portraitStyle: '', portraitImageUrl: '',+});++const formFromArtist = (a) => ({+ name: a.name || '',+ genre: a.genre || '',+ bio: a.bio || '',+ musicalStyle: a.musicalStyle || '',+ physicalDescription: a.physicalDescription || '',+ portraitStyle: a.portraitStyle || '',+ portraitImageUrl: a.portraitImageUrl || '',+});++// Build the image-gen prompt for an artist portrait from the persona's physical+// description (the subject) and portrait style (the art direction). Either field+// alone is enough to render; both are folded into one prompt.+const buildPortraitPrompt = (f) => {+ const desc = (f.physicalDescription || '').trim();+ const style = (f.portraitStyle || '').trim();+ const subject = desc ? `Music artist portrait. ${desc}` : 'Music artist promotional portrait.';+ return style ? `${subject} ${style}` : subject;+};++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 ArtistsManager() {+ const [artists, setArtists] = useState([]);+ const [loading, setLoading] = useState(true);+ // selectedId === 'new' is create mode; a real id is edit mode; null is idle.+ const [selectedId, setSelectedId] = useState(null);+ const [form, setForm] = useState(emptyForm);+ const [saving, setSaving] = useState(false);+ const [confirmDelete, setConfirmDelete] = useState(false);+ const [galleryOpen, setGalleryOpen] = useState(false);+ const [uploadingPortrait, setUploadingPortrait] = useState(false);+ const [startingGen, setStartingGen] = useState(false);+ const [genJobId, setGenJobId] = useState(null);+ const fileInputRef = useRef(null);+ // Bumped on every artist switch / new-artist so a stale generate response+ // can't write the wrong persona's portrait (mirrors Authors' genRequestRef).+ const genRequestRef = useRef(0);++ const gen = useMediaJobProgress(genJobId);+ const isGenerating = startingGen || !!genJobId;++ const setPortrait = (url) => setForm((f) => ({ ...f, portraitImageUrl: url }));+ const clearGeneration = () => { genRequestRef.current += 1; setGenJobId(null); setStartingGen(false); };++ useEffect(() => {+ if (!genJobId) return;+ if (gen.status === 'completed' && gen.filename) {+ setPortrait(gen.path || `/data/images/${gen.filename}`);+ setGenJobId(null);+ toast.success('Portrait generated');+ } else if (gen.status === 'failed' || gen.status === 'canceled') {+ setGenJobId(null);+ toast.error(gen.error || 'Portrait generation failed');+ }+ }, [genJobId, gen.status, gen.filename, gen.path, gen.error]);++ const handleGeneratePortrait = async () => {+ if (isGenerating || uploadingPortrait) return;+ if (!form.physicalDescription.trim() && !form.portraitStyle.trim()) {+ toast.error('Add a physical description or portrait style to generate from');+ return;+ }+ const requestId = genRequestRef.current;+ setStartingGen(true);+ const queued = await generateImage({+ prompt: buildPortraitPrompt(form),+ negativePrompt: `${DEFAULT_NEGATIVE_PROMPT}, extra limbs, nsfw, nude`,+ width: 768,+ height: 1024,+ }, { silent: true }).catch((err) => ({ error: err }));+ if (genRequestRef.current !== requestId) return;+ setStartingGen(false);+ if (queued?.error) {+ toast.error(queued.error.message || 'Portrait generation failed');+ return;+ }+ if (queued.jobId) {+ setGenJobId(queued.jobId);+ toast.success('Generating portrait…');+ return;+ }+ const path = queued.path || (queued.filename ? `/data/images/${queued.filename}` : '');+ if (path) {+ setPortrait(path);+ toast.success('Portrait generated');+ } else {+ toast.error('Portrait generation returned no image');+ }+ };++ const handlePortraitFile = 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 > PORTRAIT_MAX_BYTES) {+ toast.error(`Image exceeds ${Math.round(PORTRAIT_MAX_BYTES / 1024 / 1024)}MB`);+ return;+ }+ setUploadingPortrait(true);+ const base64 = await readFileAsBase64(file).catch(() => null);+ if (!base64) { setUploadingPortrait(false); toast.error('Could not read that file'); return; }+ // Route through the gallery (`/data/images/`) so the stored portrait URL+ // rides the image asset path (matches Authors' headshot upload).+ const uploaded = await uploadGalleryImage(base64, { silent: true }).catch((err) => {+ toast.error(err.message || 'Upload failed');+ return null;+ });+ setUploadingPortrait(false);+ if (uploaded?.path) {+ setPortrait(uploaded.path);+ toast.success('Portrait uploaded');+ }+ };++ const handlePortraitPick = (item) => {+ setGalleryOpen(false);+ const url = item?.previewUrl || (item?.filename ? `/data/images/${item.filename}` : '');+ if (url) setPortrait(url);+ };++ useEffect(() => {+ listArtists()+ .then((list) => setArtists(Array.isArray(list) ? list : []))+ .catch((err) => toast.error(err.message || 'Failed to load artists'))+ .finally(() => setLoading(false));+ }, []);++ const isCreate = selectedId === 'new';+ const selected = useMemo(+ () => (isCreate || !selectedId ? null : artists.find((a) => a.id === selectedId) || null),+ [artists, selectedId, isCreate],+ );+ const canGenerate = !!(form.physicalDescription.trim() || form.portraitStyle.trim());++ const selectArtist = (a) => {+ setSelectedId(a.id);+ setForm(formFromArtist(a));+ setConfirmDelete(false);+ clearGeneration();+ };++ const startCreate = () => {+ setSelectedId('new');+ setForm(emptyForm());+ setConfirmDelete(false);+ clearGeneration();+ };++ const handleSave = async () => {+ const name = form.name.trim();+ if (!name) { toast.error('Artist name is required'); return; }+ setSaving(true);+ const payload = { ...form, name };+ if (isCreate) {+ const created = await createArtist(payload).catch((err) => {+ toast.error(err.message || 'Failed to create artist');+ return null;+ });+ setSaving(false);+ if (!created) return;+ setArtists((prev) => [...prev, created].sort((a, b) => (a.name || '').localeCompare(b.name || '')));+ setSelectedId(created.id);+ toast.success(`Created "${created.name}"`);+ } else {+ const updated = await updateArtist(selectedId, payload).catch((err) => {+ toast.error(err.message || 'Failed to save artist');+ return null;+ });+ setSaving(false);+ if (!updated) return;+ setArtists((prev) => prev+ .map((a) => (a.id === updated.id ? updated : a))+ .sort((a, b) => (a.name || '').localeCompare(b.name || '')));+ toast.success('Saved');+ }+ };++ const handleDelete = async () => {+ if (!selected) return;+ const prior = artists;+ setArtists((prev) => prev.filter((a) => a.id !== selected.id));+ setSelectedId(null);+ setConfirmDelete(false);+ await deleteArtist(selected.id).catch((err) => {+ toast.error(err.message || 'Delete failed');+ setArtists(prior);+ });+ };++ 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">+ Artist personas are reusable across albums and tracks — the byline plus the genre, musical+ style, bio, and the physical description + style used to generate (or upload) an artist portrait.+ </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 Artist+ </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>+ ) : artists.length === 0 ? (+ <div className="text-gray-500 text-sm p-2">No artists yet. Click <span className="text-port-accent">New Artist</span>.</div>+ ) : (+ <ul className="space-y-1">+ {artists.map((a) => (+ <li key={a.id}>+ <button+ type="button"+ onClick={() => selectArtist(a)}+ className={`w-full text-left px-3 py-2 rounded text-sm truncate ${+ a.id === selectedId ? 'bg-port-accent/20 text-white' : 'text-gray-300 hover:bg-port-bg'+ }`}+ >+ {a.name}+ {a.genre ? <span className="block text-[11px] text-gray-500 truncate">{a.genre}</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 an artist to edit, or create a new one.</div>+ ) : (+ <div className="space-y-3">+ <Field label="Name">+ <input+ value={form.name}+ onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}+ placeholder="Nova Vale"+ maxLength={ARTIST_NAME_MAX}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ autoFocus+ />+ </Field>+ <Field label="Genre" hint="Primary genre(s) — e.g. 'indie folk, dream pop'.">+ <input+ value={form.genre}+ onChange={(e) => setForm((f) => ({ ...f, genre: e.target.value }))}+ placeholder="indie folk, dream pop"+ maxLength={ARTIST_GENRE_MAX}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </Field>+ <Field label="Musical style" hint="Voice / production / instrumentation notes — fed into music-gen prompts.">+ <textarea+ value={form.musicalStyle}+ onChange={(e) => setForm((f) => ({ ...f, musicalStyle: e.target.value }))}+ rows={4}+ maxLength={ARTIST_MUSICAL_STYLE_MAX}+ placeholder="Warm fingerpicked guitar, breathy close-mic vocals, tape saturation, sparse reverb."+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </Field>+ <Field label="Bio" hint="About-the-artist blurb.">+ <textarea+ value={form.bio}+ onChange={(e) => setForm((f) => ({ ...f, bio: e.target.value }))}+ rows={4}+ maxLength={ARTIST_BIO_MAX}+ placeholder="Nova Vale is a songwriter working at the seam of folk and ambient…"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </Field>+ <Field label="Physical description" hint="Subject of the portrait — appearance, age, expression, wardrobe.">+ <textarea+ value={form.physicalDescription}+ onChange={(e) => setForm((f) => ({ ...f, physicalDescription: e.target.value }))}+ rows={3}+ maxLength={ARTIST_PHYSICAL_DESCRIPTION_MAX}+ placeholder="Androgynous figure, late 20s, cropped platinum hair, vintage band tee, calm gaze."+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </Field>+ <Field label="Portrait style" hint="Art / photography direction for the portrait render.">+ <textarea+ value={form.portraitStyle}+ onChange={(e) => setForm((f) => ({ ...f, portraitStyle: e.target.value }))}+ rows={3}+ maxLength={ARTIST_PORTRAIT_STYLE_MAX}+ placeholder="Moody film photograph, neon backlight, grainy 35mm, shallow depth of field."+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </Field>+ <Field label="Portrait image" hint="Optional — generate from the description + style, upload a photo, pick one from your gallery, or paste a URL.">+ <div className="flex items-start gap-3">+ {isGenerating ? (+ <div className="relative w-20 h-20 rounded border border-port-border bg-port-bg overflow-hidden flex items-center justify-center shrink-0">+ {gen.currentImage ? (+ <img+ src={`data:image/png;base64,${gen.currentImage}`}+ alt="Generating portrait preview"+ className="w-full h-full object-cover opacity-70"+ />+ ) : (+ <Loader2 size={20} className="animate-spin text-port-accent" aria-hidden="true" />+ )}+ {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.portraitImageUrl ? (+ <div className="relative shrink-0">+ <img+ src={form.portraitImageUrl}+ alt="Artist portrait"+ className="w-20 h-20 rounded object-cover border border-port-border bg-port-bg"+ />+ <button+ type="button"+ onClick={() => setPortrait('')}+ title="Remove portrait"+ 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-20 h-20 rounded border border-dashed border-port-border bg-port-bg flex items-center justify-center text-gray-600 shrink-0">+ <ImageIcon size={20} aria-hidden="true" />+ </div>+ )}+ <div className="flex-1 space-y-2">+ <div className="flex items-center gap-2 flex-wrap">+ <button+ type="button"+ onClick={handleGeneratePortrait}+ disabled={isGenerating || uploadingPortrait || !canGenerate}+ title={canGenerate+ ? 'Generate a portrait from the description + style'+ : 'Add a physical description or portrait style 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+ </button>+ <button+ type="button"+ onClick={() => fileInputRef.current?.click()}+ disabled={uploadingPortrait || 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"+ >+ {uploadingPortrait ? <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} /> Choose from gallery+ </button>+ <input+ ref={fileInputRef}+ type="file"+ accept="image/*"+ onChange={handlePortraitFile}+ className="hidden"+ />+ </div>+ <input+ value={form.portraitImageUrl}+ onChange={(e) => setPortrait(e.target.value)}+ disabled={isGenerating}+ placeholder="/images/… or https://…"+ maxLength={ARTIST_PORTRAIT_IMAGE_URL_MAX}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm disabled:opacity-50"+ />+ </div>+ </div>+ </Field>++ <div className="flex items-center gap-2 pt-1 flex-wrap">+ <button+ type="button"+ onClick={handleSave}+ disabled={saving || !form.name.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 artist?</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={handlePortraitPick}+ />+ </div>+ );+}diff --git a/client/src/pages/Music.jsx b/client/src/pages/Music.jsxnew file mode 100644index 0000000000..8719773c3c--- /dev/null+++ b/client/src/pages/Music.jsx@@ -0,0 +1,75 @@+/**+ * 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).+ *+ * Tabbed via URL param (`/music/:tab`) per the linkable-routes convention, so a+ * tab is deep-linkable and survives reload. `tab` defaults to `artists`.+ */++import { useParams, Navigate, Link } from 'react-router-dom';+import { Music as MusicIcon, Mic, Disc3, AudioLines } from 'lucide-react';+import ArtistsManager from '../components/music/ArtistsManager';++const TABS = [+ { id: 'artists', label: 'Artists', icon: Mic },+ { id: 'albums', label: 'Albums', icon: Disc3 },+ { id: 'tracks', label: 'Tracks', icon: AudioLines },+];++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';+ // Unknown tab → redirect to the default rather than render an empty shell.+ if (!VALID.has(active)) return <Navigate to="/music/artists" replace />;++ return (+ <div>+ <div className="flex items-center gap-3 mb-4">+ <MusicIcon className="w-6 h-6 text-port-accent" />+ <h1 className="text-2xl font-bold text-white">Music</h1>+ </div>++ <div className="flex items-center gap-1 mb-6 border-b border-port-border">+ {TABS.map((t) => {+ const Icon = t.icon;+ const isActive = t.id === active;+ return (+ <Link+ key={t.id}+ to={`/music/${t.id}`}+ className={`inline-flex items-center gap-2 px-4 py-2 text-sm font-medium border-b-2 -mb-px ${+ isActive+ ? 'border-port-accent text-white'+ : 'border-transparent text-gray-400 hover:text-white'+ }`}+ >+ <Icon size={15} aria-hidden="true" />+ {t.label}+ </Link>+ );+ })}+ </div>++ {active === 'artists' && <ArtistsManager />}+ {active === 'albums' && <ComingSoon what="Albums" />}+ {active === 'tracks' && <ComingSoon what="Tracks" />}+ </div>+ );+}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 1fb3c3a13f..912151d849 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -48,6 +48,7 @@ export * from './apiMediaJobs.js';export * from './apiWritersRoom.js';export * from './apiUniverseBuilder.js';export * from './apiAuthors.js';+export * from './apiArtists.js';export * from './apiPipeline.js';export * from './apiSharing.js';export * from './apiRounds.js';diff --git a/client/src/services/apiArtists.js b/client/src/services/apiArtists.jsnew file mode 100644index 0000000000..4f981df437--- /dev/null+++ b/client/src/services/apiArtists.js@@ -0,0 +1,32 @@+import { request } from './apiCore.js';++// ---- Music artists ----+// Reusable musical personas (the Music studio's analogue of Authors): name,+// genre, bio, musical style, plus a physical description + portrait style used+// to generate an artist portrait. `options` lets a caller suppress request()'s+// auto-toast with `{ silent: true }`.+export const listArtists = (options = {}) => request('/artists', options);+export const getArtist = (id, options = {}) => request(`/artists/${encodeURIComponent(id)}`, options);+export const createArtist = (data, requestOptions = {}) => request('/artists', {+ method: 'POST',+ body: JSON.stringify(data),+ ...requestOptions,+});+export const updateArtist = (id, patch, requestOptions = {}) => request(`/artists/${encodeURIComponent(id)}`, {+ method: 'PATCH',+ body: JSON.stringify(patch),+ ...requestOptions,+});+export const deleteArtist = (id, requestOptions = {}) => request(`/artists/${encodeURIComponent(id)}`, {+ method: 'DELETE',+ ...requestOptions,+});++// Mirror server caps in server/services/artists/logic.js — bump both sides.+export const ARTIST_NAME_MAX = 120;+export const ARTIST_GENRE_MAX = 120;+export const ARTIST_BIO_MAX = 4000;+export const ARTIST_MUSICAL_STYLE_MAX = 4000;+export const ARTIST_PHYSICAL_DESCRIPTION_MAX = 2000;+export const ARTIST_PORTRAIT_STYLE_MAX = 2000;+export const ARTIST_PORTRAIT_IMAGE_URL_MAX = 1000;diff --git a/server/index.js b/server/index.jsindex 70e9f6ec5c..75bef4fab7 100644--- a/server/index.js+++ b/server/index.js@@ -110,6 +110,7 @@ import moodBoardRoutes from './routes/moodBoard.js';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 conflictJournalRoutes from './routes/conflictJournal.js';import { initUniverseBuilderCollectionHook } from './services/universeBuilderCollectionHook.js';import { initCatalogImageAttachHook } from './services/catalogImageAttachHook.js';@@ -531,6 +532,7 @@ app.use('/api/mood-boards', moodBoardRoutes);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/pipeline', pipelineRoutes);app.use('/api/conflict-journal', conflictJournalRoutes);app.use('/api/importer', importerRoutes);diff --git a/server/lib/db.js b/server/lib/db.jsindex aac38098f3..7d862eb4a3 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -954,6 +954,25 @@ async function ensureSchemaImpl() {)`,`CREATE INDEX IF NOT EXISTS idx_authors_live ON authors (deleted) WHERE deleted = FALSE`,+ // Music artists (the Music studio's persona store — analogue of authors).+ // One row per artist, the full sanitized record (name, genre, bio,+ // musicalStyle, physicalDescription, portraitStyle, portraitImageUrl) in+ // `data` JSONB. `name` mirrors a column for the live-list sort; the LWW/+ // tombstone trio is populated FROM the record body. Artists are db-primary+ // and federation-ready (LWW merge mirrors authors), but the artist record+ // kind is not yet registered in peerSync — local-only for now (see issue #1502).+ // Mirrors the artists block in init-db.sql.+ `CREATE TABLE IF NOT EXISTS artists (+ id TEXT PRIMARY KEY,+ name 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_artists_live ON artists (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@@ -1221,7 +1240,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', 'tribe_people', 'tribe_touchpoints',+ 'lora_training_runs', 'authors', 'artists', '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.jsindex a5cc6dc910..0188406955 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -33,6 +33,8 @@ export const NAV_COMMANDS = [{ id: 'nav.create.story-builder', path: '/story-builder', label: 'Story Builder', section: 'Create', aliases: ['story-builder', 'storybuilder', 'guided', 'new-story', 'story-wizard'], keywords: ['idea', 'universe', 'arc', 'reader map', 'guided', 'wizard', 'linear', 'lock', 'front door', 'episode', 'series'] },{ id: 'nav.create.rounds', path: '/rounds', label: 'Rounds', section: 'Create', aliases: ['rounds', 'round', 'songs', 'song', 'a-cappella', 'acappella', 'sing'], keywords: ['round', 'song', 'lyrics', 'melody', 'harmony', 'dirge', 'ballad', 'a cappella', 'vocal', 'choir', 'singing', 'arrangement', 'quodlibet', '500 miles'] },{ 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.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/artists.js b/server/routes/artists.jsnew file mode 100644index 0000000000..7137a73503--- /dev/null+++ b/server/routes/artists.js@@ -0,0 +1,75 @@+/**+ * Music artist routes.+ *+ * GET /api/artists → Artist[] (live, sorted by name)+ * POST /api/artists → Artist+ * GET /api/artists/:id → Artist+ * PATCH /api/artists/:id → Artist+ * DELETE /api/artists/:id → { id } (soft delete)+ *+ * The Music studio's persona store — mirrors routes/authors.js. Bounds come from+ * services/artists/logic.js so the Zod schema here and the service-layer+ * sanitizer agree by construction.+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import * as artists from '../services/artists/index.js';++const router = Router();++const nameField = z.string().trim().min(1).max(artists.NAME_MAX);+const genreField = z.string().trim().max(artists.GENRE_MAX);+const bioField = z.string().trim().max(artists.BIO_MAX);+const musicalStyleField = z.string().trim().max(artists.MUSICAL_STYLE_MAX);+const physicalDescriptionField = z.string().trim().max(artists.PHYSICAL_DESCRIPTION_MAX);+const portraitStyleField = z.string().trim().max(artists.PORTRAIT_STYLE_MAX);+const portraitImageUrlField = z.string().trim().max(artists.PORTRAIT_IMAGE_URL_MAX);++const createSchema = z.object({+ name: nameField,+ genre: genreField.optional().default(''),+ bio: bioField.optional().default(''),+ musicalStyle: musicalStyleField.optional().default(''),+ physicalDescription: physicalDescriptionField.optional().default(''),+ portraitStyle: portraitStyleField.optional().default(''),+ portraitImageUrl: portraitImageUrlField.optional().default(''),+});++const patchSchema = z.object({+ name: nameField.optional(),+ genre: genreField.optional(),+ bio: bioField.optional(),+ musicalStyle: musicalStyleField.optional(),+ physicalDescription: physicalDescriptionField.optional(),+ portraitStyle: portraitStyleField.optional(),+ portraitImageUrl: portraitImageUrlField.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 artists.listArtists());+}));++router.post('/', asyncHandler(async (req, res) => {+ const body = validateRequest(createSchema, req.body ?? {});+ res.status(201).json(await artists.createArtist(body));+}));++router.get('/:id', asyncHandler(async (req, res) => {+ const artist = await artists.getArtist(req.params.id);+ if (!artist) throw new ServerError('Artist not found', { status: 404, code: 'NOT_FOUND' });+ res.json(artist);+}));++router.patch('/:id', asyncHandler(async (req, res) => {+ const body = validateRequest(patchSchema, req.body ?? {});+ res.json(await artists.updateArtist(req.params.id, body));+}));++router.delete('/:id', asyncHandler(async (req, res) => {+ res.json(await artists.deleteArtist(req.params.id));+}));++export default router;diff --git a/server/routes/artists.test.js b/server/routes/artists.test.jsnew file mode 100644index 0000000000..a342b63957--- /dev/null+++ b/server/routes/artists.test.js@@ -0,0 +1,89 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++vi.mock('../services/artists/index.js', () => ({+ NAME_MAX: 120,+ GENRE_MAX: 120,+ BIO_MAX: 4000,+ MUSICAL_STYLE_MAX: 4000,+ PHYSICAL_DESCRIPTION_MAX: 2000,+ PORTRAIT_STYLE_MAX: 2000,+ PORTRAIT_IMAGE_URL_MAX: 1000,+ ARTIST_ID_RE: /^artist-/,+ listArtists: vi.fn(async () => [{ id: 'artist-1', name: 'Nova' }]),+ getArtist: vi.fn(),+ createArtist: vi.fn(async (input) => ({ id: 'artist-new', ...input })),+ updateArtist: vi.fn(async (id, patch) => ({ id, ...patch })),+ deleteArtist: vi.fn(async (id) => ({ id })),+}));++import * as artists from '../services/artists/index.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import artistsRoutes from './artists.js';++function makeApp() {+ const app = express();+ app.use(express.json());+ app.use('/api/artists', artistsRoutes);+ app.use(errorMiddleware);+ return app;+}++describe('artists routes', () => {+ let app;+ beforeEach(() => {+ app = makeApp();+ vi.clearAllMocks();+ });++ it('GET / returns the artist list', async () => {+ const r = await request(app).get('/api/artists');+ expect(r.status).toBe(200);+ expect(r.body).toEqual([{ id: 'artist-1', name: 'Nova' }]);+ });++ it('POST / creates an artist', async () => {+ const r = await request(app).post('/api/artists').send({ name: 'Nova', genre: 'indie folk' });+ expect(r.status).toBe(201);+ expect(artists.createArtist).toHaveBeenCalledWith(expect.objectContaining({ name: 'Nova', genre: 'indie folk' }));+ expect(r.body.id).toBe('artist-new');+ });++ it('POST / rejects a missing name', async () => {+ const r = await request(app).post('/api/artists').send({ genre: 'no name' });+ expect(r.status).toBe(400);+ expect(artists.createArtist).not.toHaveBeenCalled();+ });++ it('GET /:id returns 404 when absent', async () => {+ artists.getArtist.mockResolvedValueOnce(null);+ const r = await request(app).get('/api/artists/artist-missing');+ expect(r.status).toBe(404);+ });++ it('GET /:id returns the artist when found', async () => {+ artists.getArtist.mockResolvedValueOnce({ id: 'artist-1', name: 'Nova' });+ const r = await request(app).get('/api/artists/artist-1');+ expect(r.status).toBe(200);+ expect(r.body.name).toBe('Nova');+ });++ it('PATCH /:id rejects an empty patch', async () => {+ const r = await request(app).patch('/api/artists/artist-1').send({});+ expect(r.status).toBe(400);+ expect(artists.updateArtist).not.toHaveBeenCalled();+ });++ it('PATCH /:id updates an artist', async () => {+ const r = await request(app).patch('/api/artists/artist-1').send({ name: 'Nova Star' });+ expect(r.status).toBe(200);+ expect(artists.updateArtist).toHaveBeenCalledWith('artist-1', { name: 'Nova Star' });+ });++ it('DELETE /:id soft-deletes an artist', async () => {+ const r = await request(app).delete('/api/artists/artist-1');+ expect(r.status).toBe(200);+ expect(r.body).toEqual({ id: 'artist-1' });+ });+});diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 8834c4c40e..37531a6e5e 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -777,6 +777,25 @@ CREATE TABLE IF NOT EXISTS authors (-- The common path is "live authors sorted by name".CREATE INDEX IF NOT EXISTS idx_authors_live ON authors (deleted) WHERE deleted = FALSE;+-- Music artists (the Music studio's persona store — analogue of authors). One+-- row per artist, the full sanitized record (name, genre, bio, musicalStyle,+-- physicalDescription, portraitStyle, portraitImageUrl) in `data` JSONB. `name`+-- mirrors a column for the live-list sort; the LWW/tombstone trio is populated+-- FROM the record body. Artists are db-primary and federation-ready (LWW merge+-- mirrors authors), but the artist record kind is not yet registered in peerSync+-- — local-only for now (see issue #1502). Mirrors the artists block in db.js.+CREATE TABLE IF NOT EXISTS artists (+ id TEXT PRIMARY KEY,+ name 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+);+-- The common path is "live artists sorted by name".+CREATE INDEX IF NOT EXISTS idx_artists_live ON artists (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@@ -1037,6 +1056,8 @@ DROP TRIGGER IF EXISTS trg_lora_training_runs_audit ON lora_training_runs;CREATE TRIGGER trg_lora_training_runs_audit AFTER UPDATE OR DELETE ON lora_training_runs FOR EACH ROW EXECUTE FUNCTION record_audit_log();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_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/artists/db.js b/server/services/artists/db.jsnew file mode 100644index 0000000000..b7de3d525f--- /dev/null+++ b/server/services/artists/db.js@@ -0,0 +1,149 @@+/**+ * Music artists — PostgreSQL leaf I/O.+ *+ * One row per artist in `artists`: the full sanitized record in `data` JSONB,+ * with `name` + the LWW/tombstone trio mirrored into columns for the queries the+ * service runs. Reads return `data` verbatim. Mutations run inside+ * withTransaction + SELECT … FOR UPDATE. Mirrors `services/authors/db.js`; all+ * mutation semantics live in logic.js (shared with file.js) so the two backends+ * can't drift.+ */++import { randomUUID } from 'crypto';+import { query, withTransaction } from '../../lib/db.js';+import { ServerError } from '../../lib/errorHandler.js';+import { mirrorTimestamp } from '../../lib/pgTimestamp.js';+import { buildArtistRecord, applyArtistPatch, mergeArtistRecord } from './logic.js';+import {+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,+} from '../../lib/conflictJournal.js';++function rowToArtist(row) {+ return row ? row.data : null;+}++async function persist(exec, artist) {+ const now = new Date().toISOString();+ const createdAt = mirrorTimestamp(artist.createdAt, now);+ await exec(+ `INSERT INTO artists (id, name, data, created_at, updated_at, deleted, deleted_at)+ VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7)+ ON CONFLICT (id) DO UPDATE SET+ name = EXCLUDED.name,+ data = EXCLUDED.data,+ updated_at = EXCLUDED.updated_at,+ deleted = EXCLUDED.deleted,+ deleted_at = EXCLUDED.deleted_at`,+ [+ artist.id,+ typeof artist.name === 'string' ? artist.name : '',+ JSON.stringify(artist),+ createdAt,+ mirrorTimestamp(artist.updatedAt, createdAt),+ artist.deleted === true,+ mirrorTimestamp(artist.deletedAt, null),+ ],+ );+ return artist;+}++export async function listArtists({ includeDeleted = false } = {}) {+ const { rows } = includeDeleted+ ? await query(`SELECT data FROM artists ORDER BY name ASC`)+ : await query(`SELECT data FROM artists WHERE deleted = FALSE ORDER BY name ASC`);+ return rows.map(rowToArtist);+}++export async function getArtist(id, { includeDeleted = false } = {}) {+ const { rows } = await query(`SELECT data FROM artists WHERE id = $1`, [id]);+ const artist = rowToArtist(rows[0]);+ if (!artist) return null;+ return includeDeleted || !artist.deleted ? artist : null;+}++/** Live artist ids (or all when includeDeleted) — used by tombstone GC sweeps. */+export async function listArtistIds({ includeDeleted = false } = {}) {+ const { rows } = includeDeleted+ ? await query(`SELECT id FROM artists`)+ : await query(`SELECT id FROM artists WHERE deleted = FALSE`);+ return rows.map((r) => r.id);+}++export async function createArtist(input) {+ const artist = buildArtistRecord(input, { id: `artist-${randomUUID()}`, now: new Date().toISOString() });+ if (!artist) throw new ServerError('Invalid artist payload', { status: 400, code: 'VALIDATION' });+ await persist(query, artist);+ console.log(`🎤 Created music artist: ${artist.id} (${artist.name})`);+ return artist;+}++export async function updateArtist(id, patch) {+ return withTransaction(async (client) => {+ const sel = await client.query(`SELECT data FROM artists WHERE id = $1 FOR UPDATE`, [id]);+ const current = rowToArtist(sel.rows[0]);+ if (!current || current.deleted) throw new ServerError('Artist not found', { status: 404, code: 'NOT_FOUND' });+ const next = applyArtistPatch(current, patch);+ if (!next) throw new ServerError('Invalid artist payload', { status: 400, code: 'VALIDATION' });+ await persist(client.query.bind(client), next);+ return next;+ });+}++export async function deleteArtist(id) {+ return withTransaction(async (client) => {+ const sel = await client.query(`SELECT data FROM artists WHERE id = $1 FOR UPDATE`, [id]);+ const current = rowToArtist(sel.rows[0]);+ if (!current || current.deleted) throw new ServerError('Artist 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 artist records from a peer (per-record push). LWW+ * on `updatedAt` (tombstone-aware) via the shared `mergeArtistRecord` decision.+ * Federation-ready: this is wired identically to authors, but the artist kind is+ * not yet registered in peerSync — see issue #1502. Returns `{ applied, count }`.+ */+export async function mergeArtistsFromSync(remoteArtists, { source = { via: 'sync', peerId: null } } = {}) {+ if (!Array.isArray(remoteArtists)) return { applied: false, count: 0 };+ let changed = 0;+ for (const remote of remoteArtists) {+ const applied = await withTransaction(async (client) => {+ const sel = await client.query(`SELECT data FROM artists WHERE id = $1 FOR UPDATE`, [remote?.id]);+ const local = rowToArtist(sel.rows[0]);+ const { next, inserted, remoteWins, changed: didChange } = mergeArtistRecord(local, remote);+ if (!next) return false;+ if (inserted) {+ await persist(client.query.bind(client), next);+ await setSyncBaseHash('artist', next.id, contentHashForRecord('artist', next));+ return true;+ }+ if (!remoteWins || !didChange) return false;+ await maybeJournalBeforeOverwrite({ kind: 'artist', id: next.id, local, remote: next, source });+ await persist(client.query.bind(client), next);+ await setSyncBaseHash('artist', next.id, contentHashForRecord('artist', 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 artists whose deletedAt is older than the cutoff. */+export async function pruneTombstonedArtists(olderThanMs) {+ if (!Number.isFinite(olderThanMs)) return { pruned: 0 };+ const cutoffIso = new Date(olderThanMs).toISOString();+ const { rows } = await query(+ `DELETE FROM artists+ WHERE deleted = TRUE AND deleted_at IS NOT NULL AND deleted_at < $1+ RETURNING id`,+ [cutoffIso],+ );+ for (const r of rows) await deleteSyncBaseHash('artist', r.id);+ return { pruned: rows.length };+}diff --git a/server/services/artists/db.test.js b/server/services/artists/db.test.jsnew file mode 100644index 0000000000..ffc78cb189--- /dev/null+++ b/server/services/artists/db.test.js@@ -0,0 +1,134 @@+/**+ * Postgres-backed round-trip for the music-artist DB adapter.+ *+ * Like the other `*.db.test.js` suites, needs a live PostgreSQL with the schema+ * applied; SKIPS cleanly when no test DB is reachable (the `query()` backstop in+ * lib/db.js refuses row writes to the real `portos` DB under the test runner, so+ * these DELETE/INSERT statements can NEVER corrupt real data — this suite only+ * runs via `npm run test:db` against `portos_test`).+ *+ * Snapshots + restores the `artists` table so a developer's real personas+ * survive the run even on the test DB. Mirrors authors/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 = 'artists') AS ok`,+ ).catch(() => ({ rows: [{ ok: false }] }));+ if (probe.rows?.[0]?.ok) dbReady = true;+ else skipReason = 'artists table not present';+ }+}++if (!dbReady) console.log(`⏭️ services/artists/db.test.js skipped: ${skipReason}`);++describe.skipIf(!dbReady)('artists DB adapter round-trip', () => {+ let db;+ let snap = [];+ beforeAll(async () => {+ db = await import('./db.js');+ snap = (await query(`SELECT * FROM artists`)).rows;+ });++ beforeEach(async () => { await query(`DELETE FROM artists`); });++ afterAll(async () => {+ await query(`DELETE FROM artists`).catch(() => {});+ for (const r of snap) {+ await query(+ `INSERT INTO artists (id, name, 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.name, JSON.stringify(r.data), r.created_at, r.updated_at, r.deleted, r.deleted_at],+ ).catch(() => {});+ }+ await close();+ });++ it('creates an artist and mirrors name into the queryable column', async () => {+ const a = await db.createArtist({ name: 'Nova', genre: 'dream pop' });+ expect(a.id).toMatch(/^artist-/);+ const col = (await query(`SELECT name, deleted FROM artists WHERE id = $1`, [a.id])).rows[0];+ expect(col.name).toBe('Nova');+ expect(col.deleted).toBe(false);+ expect(await db.getArtist(a.id)).toEqual(a);+ });++ it('listArtists excludes tombstones; getArtist returns null for a deleted id', async () => {+ const live = await db.createArtist({ name: 'Live' });+ const dead = await db.createArtist({ name: 'Dead' });+ await db.deleteArtist(dead.id);+ const ids = (await db.listArtists()).map((a) => a.id);+ expect(ids).toEqual([live.id]);+ expect(await db.getArtist(dead.id)).toBeNull();+ expect((await db.getArtist(dead.id, { includeDeleted: true })).deleted).toBe(true);+ });++ it('updateArtist bumps updatedAt and applies a partial patch (absent keys preserved)', async () => {+ const a = await db.createArtist({ name: 'Original', bio: 'keep me' });+ const next = await db.updateArtist(a.id, { name: 'Renamed' });+ expect(next.name).toBe('Renamed');+ expect(next.bio).toBe('keep me');+ expect(new Date(next.updatedAt).getTime()).toBeGreaterThanOrEqual(new Date(a.updatedAt).getTime());+ });++ describe('mergeArtistsFromSync (LWW)', () => {+ it('inserts a brand-new remote artist verbatim', async () => {+ const remote = {+ id: 'artist-remote-1', name: 'Peer Artist', genre: 'ambient', bio: '',+ musicalStyle: 'lush', physicalDescription: '', portraitStyle: '', portraitImageUrl: '',+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',+ deleted: false, deletedAt: null,+ };+ expect(await db.mergeArtistsFromSync([remote])).toEqual({ applied: true, count: 1 });+ expect(await db.getArtist('artist-remote-1')).toEqual(remote);+ });++ it('newer remote updatedAt overwrites local (LWW); older loses', async () => {+ const a = await db.createArtist({ name: 'Local' });+ const older = { ...a, name: 'Stale', updatedAt: '2000-01-01T00:00:00.000Z' };+ expect(await db.mergeArtistsFromSync([older])).toEqual({ applied: false, count: 0 });+ expect((await db.getArtist(a.id)).name).toBe('Local');+ const newer = { ...a, name: 'Fresh', updatedAt: '2099-01-01T00:00:00.000Z' };+ expect(await db.mergeArtistsFromSync([newer])).toEqual({ applied: true, count: 1 });+ expect((await db.getArtist(a.id)).name).toBe('Fresh');+ });++ it('a newer remote tombstone deletes a live local record', async () => {+ const a = await db.createArtist({ name: 'Doomed' });+ const tombstone = { ...a, deleted: true, deletedAt: '2099-01-01T00:00:00.000Z', updatedAt: '2099-01-01T00:00:00.000Z' };+ expect(await db.mergeArtistsFromSync([tombstone])).toEqual({ applied: true, count: 1 });+ expect(await db.getArtist(a.id)).toBeNull();+ });+ });++ describe('pruneTombstonedArtists', () => {+ it('hard-removes tombstones older than the cutoff, keeps newer + live', async () => {+ const live = await db.createArtist({ name: 'Live' });+ const oldDead = await db.createArtist({ name: 'OldDead' });+ const newDead = await db.createArtist({ name: 'NewDead' });+ await db.mergeArtistsFromSync([+ { ...oldDead, deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2099-01-01T00:00:00.000Z' },+ { ...newDead, deleted: true, deletedAt: '2099-01-01T00:00:00.000Z', updatedAt: '2099-01-02T00:00:00.000Z' },+ ]);+ const { pruned } = await db.pruneTombstonedArtists(Date.parse('2030-01-01T00:00:00.000Z'));+ expect(pruned).toBe(1);+ const remaining = (await query(`SELECT id FROM artists ORDER BY id`)).rows.map((r) => r.id);+ expect(remaining.sort()).toEqual([live.id, newDead.id].sort());+ });++ it('is a no-op for a non-finite cutoff', async () => {+ await db.createArtist({ name: 'X' });+ expect(await db.pruneTombstonedArtists(NaN)).toEqual({ pruned: 0 });+ });+ });+});diff --git a/server/services/artists/file.js b/server/services/artists/file.jsnew file mode 100644index 0000000000..44f241a9e9--- /dev/null+++ b/server/services/artists/file.js@@ -0,0 +1,125 @@+/**+ * Music artists — file-backed store (escape-hatch / test backend).+ *+ * Persists to data/artists.json (array, atomicWrite). PostgreSQL (db.js) is the+ * default; this backend is reachable only via MEMORY_BACKEND=file or+ * NODE_ENV=test. Mirrors `services/authors/file.js`; all mutation semantics live+ * in logic.js so this backend and the PG backend 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 { sanitizeArtist, buildArtistRecord, applyArtistPatch, mergeArtistRecord } from './logic.js';+import {+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,+} from '../../lib/conflictJournal.js';++const ARTISTS_FILE = join(PATHS.data, 'artists.json');++async function loadAll() {+ const raw = await readJSONFile(ARTISTS_FILE, []);+ return (Array.isArray(raw) ? raw : []).map(sanitizeArtist).filter(Boolean);+}++async function saveAll(artists) {+ await ensureDir(PATHS.data);+ await atomicWrite(ARTISTS_FILE, artists);+}++const byName = (a, b) => (a.name || '').localeCompare(b.name || '');++export async function listArtists({ includeDeleted = false } = {}) {+ const all = await loadAll();+ return (includeDeleted ? all : all.filter((a) => !a.deleted)).sort(byName);+}++export async function getArtist(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 artist ids (or all when includeDeleted) — used by tombstone GC sweeps. */+export async function listArtistIds({ includeDeleted = false } = {}) {+ const all = await loadAll();+ return (includeDeleted ? all : all.filter((a) => !a.deleted)).map((a) => a.id);+}++export async function createArtist(input) {+ const artist = buildArtistRecord(input, { id: `artist-${randomUUID()}`, now: new Date().toISOString() });+ if (!artist) throw new ServerError('Invalid artist payload', { status: 400, code: 'VALIDATION' });+ const all = await loadAll();+ all.push(artist);+ await saveAll(all);+ console.log(`🎤 Created music artist: ${artist.id} (${artist.name})`);+ return artist;+}++export async function updateArtist(id, patch) {+ const all = await loadAll();+ const idx = all.findIndex((a) => a.id === id);+ if (idx < 0 || all[idx].deleted) throw new ServerError('Artist not found', { status: 404, code: 'NOT_FOUND' });+ const next = applyArtistPatch(all[idx], patch);+ if (!next) throw new ServerError('Invalid artist payload', { status: 400, code: 'VALIDATION' });+ all[idx] = next;+ await saveAll(all);+ return next;+}++export async function deleteArtist(id) {+ const all = await loadAll();+ const idx = all.findIndex((a) => a.id === id);+ if (idx < 0 || all[idx].deleted) throw new ServerError('Artist 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 `mergeArtistsFromSync` (LWW-per-id, tombstone-aware). */+export async function mergeArtistsFromSync(remoteArtists, { source = { via: 'sync', peerId: null } } = {}) {+ if (!Array.isArray(remoteArtists)) 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 remoteArtists) {+ const local = byId.get(remote?.id) || null;+ const { next, inserted, remoteWins, changed: didChange } = mergeArtistRecord(local, remote);+ if (!next) continue;+ if (inserted) {+ byId.set(next.id, next);+ await setSyncBaseHash('artist', next.id, contentHashForRecord('artist', next));+ changed += 1;+ continue;+ }+ if (!remoteWins || !didChange) continue;+ await maybeJournalBeforeOverwrite({ kind: 'artist', id: next.id, local, remote: next, source });+ byId.set(next.id, next);+ await setSyncBaseHash('artist', next.id, contentHashForRecord('artist', 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 artists whose deletedAt is older than the cutoff. */+export async function pruneTombstonedArtists(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('artist', id);+ return { pruned: pruned.length };+}diff --git a/server/services/artists/file.test.js b/server/services/artists/file.test.jsnew file mode 100644index 0000000000..12e4371b6e--- /dev/null+++ b/server/services/artists/file.test.js@@ -0,0 +1,105 @@+/**+ * Artist file-backend store — CRUD + LWW merge outcomes.+ *+ * Covers the CRUD round-trip on the file backend (which the normal, non-DB suite+ * exercises) and the `mergeArtistsFromSync` LWW outcomes (insert / newer-wins /+ * older-loses / tombstone), asserted via getArtist/listArtists.+ *+ * NOTE: the conflict-journal base-hash + journaling SIDE EFFECTS that authors'+ * file.test.js asserts are intentionally NOT covered here — they depend on the+ * artist record kind being registered in syncWire/peerSync (cross-peer sync),+ * which is deferred (artists are local-only for now — see issue #1502). When that+ * registration lands, this suite should grow the base-hash/journaling assertions+ * to mirror authors. 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(), 'artists-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, 'artists.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 artist = (id, extra = {}) => ({+ id, name: id, genre: '', bio: '', musicalStyle: '', physicalDescription: '',+ portraitStyle: '', portraitImageUrl: '',+ 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('artists file backend — CRUD', () => {+ it('creates, reads, updates and soft-deletes an artist', async () => {+ const created = await file.createArtist({ name: 'Nova', genre: 'dream pop' });+ expect(created.id).toMatch(/^artist-/);+ expect((await file.getArtist(created.id)).genre).toBe('dream pop');++ const updated = await file.updateArtist(created.id, { genre: 'shoegaze' });+ expect(updated.genre).toBe('shoegaze');++ await file.deleteArtist(created.id);+ expect(await file.getArtist(created.id)).toBeNull();+ expect(await file.getArtist(created.id, { includeDeleted: true })).toBeTruthy();+ expect(await file.listArtists()).toHaveLength(0);+ });++ it('lists live artists sorted by name', async () => {+ await file.createArtist({ name: 'Zephyr' });+ await file.createArtist({ name: 'Aria' });+ const names = (await file.listArtists()).map((a) => a.name);+ expect(names).toEqual(['Aria', 'Zephyr']);+ });+});++describe('artists file backend — mergeArtistsFromSync (LWW outcomes)', () => {+ it('inserts a remote artist with no local counterpart', async () => {+ const res = await file.mergeArtistsFromSync([artist('artist-1', { bio: 'inserted' })]);+ expect(res).toEqual({ applied: true, count: 1 });+ expect((await file.getArtist('artist-1')).bio).toBe('inserted');+ });++ it('a newer remote wins; an older remote is a no-op', async () => {+ await file.mergeArtistsFromSync([artist('artist-1', { bio: 'v1', updatedAt: '2026-02-01T00:00:00.000Z' })]);++ const newer = await file.mergeArtistsFromSync([artist('artist-1', { bio: 'v2', updatedAt: '2026-03-01T00:00:00.000Z' })]);+ expect(newer).toEqual({ applied: true, count: 1 });+ expect((await file.getArtist('artist-1')).bio).toBe('v2');++ const older = await file.mergeArtistsFromSync([artist('artist-1', { bio: 'stale', updatedAt: '2020-01-01T00:00:00.000Z' })]);+ expect(older).toEqual({ applied: false, count: 0 });+ expect((await file.getArtist('artist-1')).bio).toBe('v2');+ });++ it('a newer remote tombstone soft-deletes the live local record', async () => {+ await file.mergeArtistsFromSync([artist('artist-1', { bio: 'live', updatedAt: '2026-01-01T00:00:00.000Z' })]);+ await file.mergeArtistsFromSync([+ artist('artist-1', { deleted: true, deletedAt: '2026-05-01T00:00:00.000Z', updatedAt: '2026-05-01T00:00:00.000Z' }),+ ]);+ expect(await file.getArtist('artist-1')).toBeNull();+ expect(await file.getArtist('artist-1', { includeDeleted: true })).toBeTruthy();+ });++ it('pruneTombstonedArtists hard-removes an old tombstone', async () => {+ await file.mergeArtistsFromSync([+ artist('artist-dead', { deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2020-01-01T00:00:00.000Z' }),+ ]);+ const res = await file.pruneTombstonedArtists(Date.parse('2030-01-01T00:00:00.000Z'));+ expect(res).toEqual({ pruned: 1 });+ expect(await file.getArtist('artist-dead', { includeDeleted: true })).toBeNull();+ });+});diff --git a/server/services/artists/index.js b/server/services/artists/index.jsnew file mode 100644index 0000000000..264e449319--- /dev/null+++ b/server/services/artists/index.js@@ -0,0 +1,106 @@+/**+ * Music artists — storage backend dispatcher.+ *+ * Artists are `db-primary` (PostgreSQL `artists` table). This thin dispatcher+ * mirrors `services/authors/index.js`: select the backend lazily on first call+ * so route imports + tests work regardless of boot ordering.+ *+ * - PostgreSQL (db.js) for normal installs.+ * - File (file.js) only via MEMORY_BACKEND=file or NODE_ENV=test.+ *+ * The recordEvents emits below are kept so the store is federation-ready, but+ * the artist record kind is NOT yet registered in peerSync, so they are no-ops+ * (autoSubscribeRecordToAllPeers ignores unregistered kinds) — artists 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 {+ NAME_MAX,+ GENRE_MAX,+ BIO_MAX,+ MUSICAL_STYLE_MAX,+ PHYSICAL_DESCRIPTION_MAX,+ PORTRAIT_STYLE_MAX,+ PORTRAIT_IMAGE_URL_MAX,+ ARTIST_ID_RE,+ portraitImageFilename,+} 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('Artists 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 getArtistsBackendName() {+ return backendName;+}++/** Test seam — drop the memoized backend so a suite can re-select. */+export function _resetArtistsBackend() {+ backend = null;+ backendName = null;+}++export async function listArtists(options = {}) {+ return (await selectBackend()).listArtists(options);+}++export async function listArtistIds(options = {}) {+ return (await selectBackend()).listArtistIds(options);+}++export async function getArtist(id, options = {}) {+ return (await selectBackend()).getArtist(id, options);+}++function announceNewArtist(id) {+ emitRecordUpdated('artist', id);+ autoSubscribeRecordToAllPeers('artist', id).catch(() => {});+}++export async function createArtist(input) {+ const artist = await (await selectBackend()).createArtist(input);+ announceNewArtist(artist.id);+ return artist;+}++export async function updateArtist(id, patch) {+ const next = await (await selectBackend()).updateArtist(id, patch);+ emitRecordUpdated('artist', next.id);+ return next;+}++export async function deleteArtist(id) {+ const result = await (await selectBackend()).deleteArtist(id);+ emitRecordDeleted('artist', result.id);+ return result;+}++/** Merge an incoming batch of artist records from a peer (LWW, tombstone-aware). */+export async function mergeArtistsFromSync(remoteArtists, options = {}) {+ return (await selectBackend()).mergeArtistsFromSync(remoteArtists, options);+}++/** Hard-remove artist tombstones older than the cutoff (called by tombstone GC). */+export async function pruneTombstonedArtists(olderThanMs) {+ return (await selectBackend()).pruneTombstonedArtists(olderThanMs);+}diff --git a/server/services/artists/logic.js b/server/services/artists/logic.jsnew file mode 100644index 0000000000..af65b407c9--- /dev/null+++ b/server/services/artists/logic.js@@ -0,0 +1,145 @@+/**+ * Music artists — 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 in+ * how an artist record is shaped, trimmed, or patched. This module has NO I/O —+ * pure functions only. It deliberately mirrors `services/authors/logic.js`: an+ * Artist is the music studio's analogue of an Author persona.+ *+ * An Artist is a reusable musical persona used as a track/album byline and as+ * the prompt source for generating a portrait + music:+ * - name — display / stage name+ * - genre — primary genre(s), e.g. "indie folk, dream pop"+ * - bio — about-the-artist blurb+ * - musicalStyle — voice / production notes fed into music-gen prompts+ * (the audio analogue of an author's writingStyle)+ * - physicalDescription — subject description for the portrait render+ * - portraitStyle — art/photography direction for the portrait render+ * - portraitImageUrl — optional pointer to a generated/chosen portrait+ *+ * Artists are `db-primary` (PostgreSQL `artists` table). The storage layer is+ * federation-ready (LWW merge + tombstone prune mirror authors), but the cross-+ * peer peer-sync REGISTRATION (schemaVersions / peerSync / syncWire / tombstone+ * GC) is not wired yet — see issue #1502. Until then artists are local-only, like+ * the Rounds workbench.+ */++import { compareNewerWins } from '../../lib/lwwTimestamp.js';++export const ARTIST_ID_RE = /^artist-[A-Za-z0-9-]{1,64}$/;++export const NAME_MAX = 120;+export const GENRE_MAX = 120;+export const BIO_MAX = 4000;+export const MUSICAL_STYLE_MAX = 4000;+export const PHYSICAL_DESCRIPTION_MAX = 2000;+export const PORTRAIT_STYLE_MAX = 2000;+export const PORTRAIT_IMAGE_URL_MAX = 1000;++const isStr = (v) => typeof v === 'string';+const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');++/**+ * Normalize a raw artist record into the canonical stored shape. Returns null+ * for a non-object or a record without a usable id/name (mirrors the other+ * sanitizers' "drop on the floor" contract so a malformed import can't land).+ */+export function sanitizeArtist(raw) {+ if (!raw || typeof raw !== 'object') return null;+ if (!isStr(raw.id) || !raw.id) return null;+ const name = trimTo(raw.name, NAME_MAX);+ if (!name) 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,+ name,+ genre: trimTo(raw.genre, GENRE_MAX),+ bio: trimTo(raw.bio, BIO_MAX),+ musicalStyle: trimTo(raw.musicalStyle, MUSICAL_STYLE_MAX),+ physicalDescription: trimTo(raw.physicalDescription, PHYSICAL_DESCRIPTION_MAX),+ portraitStyle: trimTo(raw.portraitStyle, PORTRAIT_STYLE_MAX),+ // Empty string = no portrait chosen; never null so the on-disk shape is stable.+ portraitImageUrl: trimTo(raw.portraitImageUrl, PORTRAIT_IMAGE_URL_MAX),+ createdAt,+ updatedAt,+ deleted,+ deletedAt: deleted && isStr(raw.deletedAt) && raw.deletedAt.trim() ? raw.deletedAt : null,+ };+}++/**+ * Resolve an artist's `portraitImageUrl` to the bare gallery-image filename that+ * lives under `data/images/` — the unit a future peer-sync asset pipeline can+ * hash + transfer. Returns null when there's nothing local to ship (empty,+ * external URL, or a non-image path). Mirrors authors' headshotImageFilename.+ */+export function portraitImageFilename(portraitImageUrl) {+ if (!isStr(portraitImageUrl)) return null;+ const url = portraitImageUrl.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; // some other absolute path → not a gallery image+ name = name.split(/[?#]/)[0];+ const base = name.split('/').pop();+ return base || null;+}++/** Build a fresh artist record from create input. */+export function buildArtistRecord(input, { id, now }) {+ return sanitizeArtist({+ id,+ name: input.name,+ genre: input.genre || '',+ bio: input.bio || '',+ musicalStyle: input.musicalStyle || '',+ physicalDescription: input.physicalDescription || '',+ portraitStyle: input.portraitStyle || '',+ portraitImageUrl: input.portraitImageUrl || '',+ createdAt: now,+ updatedAt: now,+ deleted: false,+ deletedAt: null,+ });+}++// The user-authored scalar fields a partial patch may overwrite. `id`, the+// LWW/tombstone trio, and `createdAt` are server-owned / structural.+const PATCHABLE = [+ 'name', 'genre', 'bio', 'musicalStyle', 'physicalDescription', 'portraitStyle', 'portraitImageUrl',+];++/**+ * LWW merge decision for one incoming artist record against the local copy.+ * Mirrors mergeAuthorRecord: sanitize remote (drop-on-floor), insert when no+ * local counterpart, else newer `updatedAt` wins (tombstone-aware). Returns+ * `{ next, inserted, remoteWins, changed }`.+ */+export function mergeArtistRecord(local, remoteRaw) {+ const remote = sanitizeArtist(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 — an absent key preserves the current value, a present empty-string+ * applies the clear (distinguish-absent-vs-empty per CLAUDE.md). Bumps updatedAt.+ */+export function applyArtistPatch(current, patch = {}) {+ const next = { ...current };+ for (const key of PATCHABLE) {+ if (key in patch) next[key] = patch[key];+ }+ next.updatedAt = new Date().toISOString();+ return sanitizeArtist(next);+}diff --git a/server/services/artists/logic.test.js b/server/services/artists/logic.test.jsnew file mode 100644index 0000000000..440afaaff5--- /dev/null+++ b/server/services/artists/logic.test.js@@ -0,0 +1,148 @@+import { describe, it, expect } from 'vitest';+import {+ sanitizeArtist, buildArtistRecord, applyArtistPatch,+ mergeArtistRecord, portraitImageFilename,+ NAME_MAX, MUSICAL_STYLE_MAX,+} from './logic.js';++describe('artists logic', () => {+ describe('sanitizeArtist', () => {+ it('drops records without an id or name', () => {+ expect(sanitizeArtist(null)).toBeNull();+ expect(sanitizeArtist({})).toBeNull();+ expect(sanitizeArtist({ id: 'artist-1' })).toBeNull();+ expect(sanitizeArtist({ id: 'artist-1', name: ' ' })).toBeNull();+ });++ it('trims fields to their caps and normalizes the shape', () => {+ const a = sanitizeArtist({+ id: 'artist-1',+ name: ` ${'n'.repeat(NAME_MAX + 50)} `,+ musicalStyle: ` ${'w'.repeat(MUSICAL_STYLE_MAX + 10)} `,+ genre: ' indie folk ',+ bio: ' blurb ',+ physicalDescription: ' desc ',+ portraitStyle: ' studio ',+ portraitImageUrl: ' /img.png ',+ });+ expect(a.id).toBe('artist-1');+ expect(a.name.length).toBe(NAME_MAX);+ expect(a.musicalStyle.length).toBe(MUSICAL_STYLE_MAX);+ expect(a.genre).toBe('indie folk');+ expect(a.bio).toBe('blurb');+ expect(a.physicalDescription).toBe('desc');+ expect(a.portraitStyle).toBe('studio');+ expect(a.portraitImageUrl).toBe('/img.png');+ expect(a.deleted).toBe(false);+ expect(a.deletedAt).toBeNull();+ });++ it('clears deletedAt when not deleted', () => {+ const a = sanitizeArtist({ id: 'artist-1', name: 'X', deleted: false, deletedAt: '2020-01-01' });+ expect(a.deletedAt).toBeNull();+ });+ });++ describe('buildArtistRecord', () => {+ it('builds a fresh record with timestamps', () => {+ const now = '2026-06-14T00:00:00.000Z';+ const a = buildArtistRecord({ name: 'Nova' }, { id: 'artist-9', now });+ expect(a.id).toBe('artist-9');+ expect(a.name).toBe('Nova');+ expect(a.createdAt).toBe(now);+ expect(a.updatedAt).toBe(now);+ expect(a.musicalStyle).toBe('');+ });+ });++ describe('applyArtistPatch', () => {+ const base = buildArtistRecord({ name: 'Nova', bio: 'old bio' }, { id: 'artist-1', now: '2026-06-14T00:00:00.000Z' });++ it('overwrites present keys and preserves absent ones', () => {+ const next = applyArtistPatch(base, { name: 'Nova Star' });+ expect(next.name).toBe('Nova Star');+ expect(next.bio).toBe('old bio');+ });++ it('applies an intentional clear (present empty string)', () => {+ const next = applyArtistPatch(base, { bio: '' });+ expect(next.bio).toBe('');+ });++ it('bumps updatedAt', () => {+ const next = applyArtistPatch(base, { name: 'Nova Star' });+ expect(next.updatedAt >= base.updatedAt).toBe(true);+ });+ });++ describe('mergeArtistRecord (federation-ready LWW)', () => {+ const local = buildArtistRecord({ name: 'Local' }, { id: 'artist-1', now: '2026-06-01T00:00:00.000Z' });++ it('inserts when there is no local counterpart', () => {+ const remote = { ...local, name: 'Remote' };+ const r = mergeArtistRecord(null, remote);+ expect(r.inserted).toBe(true);+ expect(r.changed).toBe(true);+ expect(r.next.name).toBe('Remote');+ });++ it('drops a malformed remote (returns null next)', () => {+ const r = mergeArtistRecord(local, { id: 'artist-1', name: '' });+ expect(r.next).toBeNull();+ expect(r.changed).toBe(false);+ });++ it('newer remote updatedAt wins', () => {+ const remote = { ...local, name: 'Fresh', updatedAt: '2099-01-01T00:00:00.000Z' };+ const r = mergeArtistRecord(local, remote);+ expect(r.remoteWins).toBe(true);+ expect(r.next.name).toBe('Fresh');+ });++ it('older remote loses (local wins, no change)', () => {+ const remote = { ...local, name: 'Stale', updatedAt: '2000-01-01T00:00:00.000Z' };+ const r = mergeArtistRecord(local, remote);+ expect(r.remoteWins).toBe(false);+ expect(r.changed).toBe(false);+ expect(r.next.name).toBe('Local');+ });++ it('unparseable remote updatedAt never overrides a valid local', () => {+ const remote = { ...local, name: 'Garbage', updatedAt: 'not-a-date' };+ const r = mergeArtistRecord(local, remote);+ expect(r.remoteWins).toBe(false);+ expect(r.next.name).toBe('Local');+ });++ it('a newer remote tombstone overwrites a live local record', () => {+ const remote = { ...local, deleted: true, deletedAt: '2099-01-01T00:00:00.000Z', updatedAt: '2099-01-01T00:00:00.000Z' };+ const r = mergeArtistRecord(local, remote);+ expect(r.remoteWins).toBe(true);+ expect(r.next.deleted).toBe(true);+ });+ });++ describe('portraitImageFilename', () => {+ it('returns the basename for a gallery mount path', () => {+ expect(portraitImageFilename('/data/images/abc123.png')).toBe('abc123.png');+ });+ it('returns a bare filename unchanged', () => {+ expect(portraitImageFilename('abc123.png')).toBe('abc123.png');+ });+ it('strips a querystring/hash', () => {+ expect(portraitImageFilename('/data/images/abc.png?v=2')).toBe('abc.png');+ });+ it('returns null for external URLs (receiver fetches those itself)', () => {+ expect(portraitImageFilename('https://example.com/x.png')).toBeNull();+ expect(portraitImageFilename('data:image/png;base64,AAAA')).toBeNull();+ });+ it('returns null for a non-image absolute path', () => {+ expect(portraitImageFilename('/data/videos/x.mp4')).toBeNull();+ });+ it('returns null for empty / non-string input', () => {+ expect(portraitImageFilename('')).toBeNull();+ expect(portraitImageFilename(null)).toBeNull();+ expect(portraitImageFilename(undefined)).toBeNull();+ });+ });+});