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
refactor: route-contract parity and rounds/jsonExtract consolidation
[._.]/ Adam Eivy2938d6710256
diff --git a/client/src/pages/SongBook.jsx b/client/src/pages/SongBook.jsxindex 78007f2384..cc842e8c78 100644--- a/client/src/pages/SongBook.jsx+++ b/client/src/pages/SongBook.jsx@@ -7,7 +7,7 @@* the play/edit viewer lives at /songbook/:id and import at /songbook/import.** Filters live in URL search params (?stage=&instrument=&tag=&q=) so a- * filtered view is linkable (Catalog.jsx pattern). Stage flips PUT just the+ * filtered view is linkable (Catalog.jsx pattern). Stage flips PATCH just the* stage field and update local state reactively — no refetch.*/@@ -70,7 +70,7 @@ export default function SongBook() {.catch((err) => toast.error(err?.message || 'Failed to delete song')),), [confirmDelete]);- // Stage flip: PUT just the stage (defaults-free partial) then merge the+ // Stage flip: PATCH just the stage (defaults-free partial) then merge the// server record into local state. No custom catch toast — the request// helper owns the error toast (single layer).const onStageChange = useCallback((id, stage) => {diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsxindex 84562cdc80..9cca5d3464 100644--- a/client/src/pages/SongBookViewer.jsx+++ b/client/src/pages/SongBookViewer.jsx@@ -18,7 +18,7 @@* source link — plus the attachments section (synced meta, machine-local* bytes → "not on this machine" when absent).* - EDIT (?mode=edit): metadata form + font-mono content textarea with format- * select and live preview. Saves are explicit (single PUT). The whole+ * select and live preview. Saves are explicit (single PATCH). The whole* `content` object is always sent — the server fills nested content* defaults, so `{ content: { text } }` alone would reset format to 'tab'.*@@ -116,7 +116,7 @@ export default function SongBookViewer() {const [song, setSong] = useState(null);// URL-backed instrument view (?view=guitar|ukulele|piano). Render-only —- // never PUT back to the record. Defaults to the song's own instrument+ // never PATCHed back to the record. Defaults to the song's own instrument// (bass/voice/other map to guitar), so the param stays off the URL for the// song's natural view and deep links like ?view=piano stay shareable.const [instrumentView, setInstrumentView] = useDrawerTab(@@ -279,7 +279,7 @@ export default function SongBookViewer() {// --- Mutationsconst onStageChange = useCallback((stage) => {- // PUT just the stage (defaults-free partial). Helper toast owns the error+ // PATCH just the stage (defaults-free partial). Helper toast owns the error// UI (no custom catch toast → no silent).updateSong(id, { stage }).then((updated) => {diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsxindex 6e82249f68..b44227ac75 100644--- a/client/src/pages/SongBookViewer.test.jsx+++ b/client/src/pages/SongBookViewer.test.jsx@@ -443,7 +443,7 @@ K: o - - - - - o -`;await waitFor(() => expect(api.updateSong).toHaveBeenCalled());const [, patch] = api.updateSong.mock.calls[0];expect(patch.title).toBe('Renamed Song');- // The WHOLE content object goes in the PUT (format would otherwise reset).+ // The WHOLE content object goes in the PATCH (format would otherwise reset).expect(patch.content).toEqual({ format: 'tab', text: SHEET });// attachments is server-managed — never sent.expect('attachments' in patch).toBe(false);diff --git a/client/src/services/apiRounds.js b/client/src/services/apiRounds.jsindex b51568ac02..da9c9351d4 100644--- a/client/src/services/apiRounds.js+++ b/client/src/services/apiRounds.js@@ -15,7 +15,7 @@ export const createRound = (body = {}, options) =>request('/rounds', { method: 'POST', body: JSON.stringify(body), ...options });export const updateRound = (id, patch, options) =>- request(`/rounds/${enc(id)}`, { method: 'PUT', body: JSON.stringify(patch), ...options });+ request(`/rounds/${enc(id)}`, { method: 'PATCH', body: JSON.stringify(patch), ...options });export const deleteRound = (id, options) =>request(`/rounds/${enc(id)}`, { method: 'DELETE', ...options });@@ -66,7 +66,7 @@ export const cancelReferenceAudioImport = (jobId, options = {}) =>// MuScriptor sidecar. Kickoff returns { jobId, model } (503 with an install// hint when the runtime isn't provisioned); progress streams over SSE; the// terminal `complete` frame carries the { filename } the caller persists on the-// reference (via the normal PUT on Save, same as the audio import above).+// reference (via the normal PATCH on Save, same as the audio import above).export const transcribeReferenceMidi = (filename, model, options = {}) =>request('/rounds/reference-audio/transcribe-midi', {method: 'POST', body: JSON.stringify(model ? { filename, model } : { filename }), ...options,diff --git a/client/src/services/apiSongbook.js b/client/src/services/apiSongbook.jsindex 199f7074fe..7ca09ce333 100644--- a/client/src/services/apiSongbook.js+++ b/client/src/services/apiSongbook.js@@ -8,7 +8,7 @@ import { request } from './apiCore.js';// Server contract notes (server/routes/brainSongbook.js):// - POST / and POST /:id/attachments return 201 with the created record /// `{ attachment }` in the body.-// - PUT is a defaults-free partial, BUT a nested `content` object fills inner+// - PATCH is a defaults-free partial, BUT a nested `content` object fills inner// defaults — callers must always send the WHOLE content object// ({ format, text }), never `{ content: { text } }` alone (format would// reset to 'tab'). Never send `attachments` (server-managed; stripped).@@ -27,10 +27,10 @@ export const getSong = (id, options) => request(`/brain/songbook/${enc(id)}`, opexport const createSong = (body = {}, options) =>request('/brain/songbook', { method: 'POST', body: JSON.stringify(body), ...options });-// Defaults-free partial PUT — also the stage chip-flip path+// Defaults-free partial PATCH — also the stage chip-flip path// (`updateSong(id, { stage })`).export const updateSong = (id, patch, options) =>- request(`/brain/songbook/${enc(id)}`, { method: 'PUT', body: JSON.stringify(patch), ...options });+ request(`/brain/songbook/${enc(id)}`, { method: 'PATCH', body: JSON.stringify(patch), ...options });export const deleteSong = (id, options) =>request(`/brain/songbook/${enc(id)}`, { method: 'DELETE', ...options });diff --git a/server/lib/README.md b/server/lib/README.mdindex daa817b3bc..e8bdff55b7 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -48,6 +48,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `pipelineValidation.js` | Creative-production pipeline schemas (Writers Room works/folders/live-mode/drafts, story-bible character/place/object, editorial checks, storyboard shots/scenes, prompt-stage config, issue-list query). || `postValidation.js` | MeatSpace POST (Power On Self Test) schemas — drill config (incl. adaptive toggle), drill generation/scoring, sessions, memory builder, training log. || `privacyValidation.js` | Privacy Center schemas — PII Vault (issue #2140): vault record create/update (partial PUT), list query, UUID params; the vault type/status vocabularies + the sensitive-type (`ssn`/`passport`/`drivers_license`/`financial_account`) `useForScans` hard-false rule and per-type scan defaults. Trusted Organizations registry (issue #2141): org create/update (partial PUT), list query, UUID params, and the replace-set holdings schema. Data-broker database + case ledger (issue #2144): broker list/case-list query filters, the scan-start + refresh action bodies, and the `PRIVACY_BROKER_CASE_STATES` vocabulary. |+| `roundsValidation.js` | Rounds workbench shape bounds + pure record sanitizers (sections, layers, recordings, pitch analysis, references, progress) — `sanitizeRound(raw, builtinIds)` and the length/count limits shared with routes/rounds.js. || `socketValidation.js` | Socket event payload schemas. || `storyBuilderValidation.js` | Unified Story Builder session/step schemas. || `telegramValidation.js` | Telegram bot config + test schemas. |diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex 3a1e2d45c9..91ccf6c597 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -628,7 +628,7 @@ export const songInputSchema = z.object({notes: z.string().max(5000).optional().default('')});-// PUT /api/brain/songbook/:id — defaults-free partial. partialWithoutDefaults+// PATCH /api/brain/songbook/:id — defaults-free partial. partialWithoutDefaults// only strips top-level defaults (see the zodCompat docstring): a// present-but-partial `content` object would still inflate its inner defaults// — `{ content: { text } }` resetting format to 'tab', `{ content: { format } }`diff --git a/server/lib/index.js b/server/lib/index.jsindex f4ea6668b5..df528ba9e6 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -37,6 +37,7 @@ export * as peerSyncValidation from './peerSyncValidation.js';export * as pipelineValidation from './pipelineValidation.js';export * as postValidation from './postValidation.js';export * as privacyValidation from './privacyValidation.js';+export * as roundsValidation from './roundsValidation.js';export * as socketValidation from './socketValidation.js';export * as storyBuilderValidation from './storyBuilderValidation.js';export * as telegramValidation from './telegramValidation.js';diff --git a/server/lib/roundsValidation.js b/server/lib/roundsValidation.jsnew file mode 100644index 0000000000..050d31998c--- /dev/null+++ b/server/lib/roundsValidation.js@@ -0,0 +1,408 @@+/**+ * Rounds record sanitization — shape bounds + pure sanitize helpers for the+ * a cappella rounds workbench (services/rounds.js). Extracted so the service+ * keeps only seed data + CRUD while the validation vocabulary lives with the+ * other *Validation lib modules.+ *+ * The bounds are shared with routes/rounds.js#roundInputSchema (via the+ * service's re-exports) — sanitize-on-read and validate-at-the-boundary agree+ * by construction. The rhythm-shape and layer id vocabularies mirror+ * client/src/lib/songCraft.js; unknown ids are accepted (free-text fallback)+ * so a client on a newer/older songCraft revision can't 400.+ *+ * Pure/side-effect-free: no I/O, no module state. `sanitizeRound` takes the+ * caller's built-in id set as an argument so this module doesn't depend on the+ * service's seed data.+ */++import { randomUUID } from 'crypto';++// --- Shape bounds (shared with routes/rounds.js#roundInputSchema) -------------+export const TITLE_MAX_LENGTH = 200;+export const ARTIST_MAX_LENGTH = 200;+export const KEY_MAX_LENGTH = 24;+export const FIELD_MAX_LENGTH = 4000; // lyrics body / general notes+export const SCORE_MAX_LENGTH = 8000; // sheet-music notation (lead-sheet DSL)+export const SCORE_PARTS_MAX = 12; // harmony variations of the sheet music+export const LABEL_MAX_LENGTH = 120; // section + layer labels+export const PART_MAX_LENGTH = 60; // layer voice (e.g. "Bass")+export const ID_MAX_LENGTH = 60; // rhythm-shape / layer ids+export const TEMPO_MIN = 20;+export const TEMPO_MAX = 320;+export const SECTIONS_MAX = 60;+export const LAYERS_MAX = 24;+export const RECORDINGS_MAX = 64; // saved vocal takes for layered playback+export const REFERENCES_MAX = 12; // reference links/videos (e.g. TikTok)+export const PARTNERS_MAX = 12; // partner-song ids (rounds sung together)+export const URL_MAX_LENGTH = 512; // uploaded-file path/url+// Reference-audio analysis (#2106): labeled time ranges on a reference's+// attached audio ("0:00–0:14 melody alone"). Bounded so a hand-edited file+// can't balloon a reference; a layered TikTok build rarely has more than a+// handful of voice entrances.+export const REF_SEGMENTS_MAX = 24; // labeled time ranges per reference+// Per-take pitch analysis (#1027). The pitch track is a DOWNSAMPLED tuner trace+// kept for replay/training so it isn't recomputed on every open; bound it so a+// long take can't bloat data/rounds.json. `accuracy.perNote` mirrors the+// color-match grade-per-note array (#1025), bounded the same way a score can't+// be arbitrarily long.+export const PITCH_TRACK_MAX = 4000; // downsampled tuner samples per take+export const PER_NOTE_GRADES_MAX = 2000; // per-note color-match grades per take+// Training progress (#1028). `progress.history` maps a training scope (a+// section id or the whole-song sentinel) to a bounded array of graded attempts.+// Mirrors client/src/lib/songProgress.js HISTORY_MAX (kept window per scope) and+// caps the number of distinct scopes so a hand-edited file can't balloon the+// record. An attempt is `{ percentInTune, graded, at }`.+export const PROGRESS_HISTORY_MAX = 50; // attempts kept per scope+export const PROGRESS_SCOPES_MAX = 80; // distinct training scopes tracked+// Valid color-match grades — mirrors client/src/lib/colorMatch.js GRADE. An+// unrecognized grade is dropped (a newer/older client vocabulary can't 400 or+// poison the persisted array).+export const RECORDING_GRADES = ['in-tune', 'close', 'off', 'missed', 'pending'];++// Trim a string field, returning '' for non-strings. Mirrors the+// absent-vs-empty rule in CLAUDE.md: callers decide whether '' clears.+const trimField = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');++// Clamp an integer tempo into the supported band; null when unparseable so a+// song without a tempo stays distinct from one pinned to a bound.+const sanitizeTempo = (v) => {+ if (typeof v !== 'number' || !Number.isFinite(v)) return null;+ return Math.max(TEMPO_MIN, Math.min(TEMPO_MAX, Math.round(v)));+};++// One lyric/structure section ({ id, label, lyrics }). Label defaults from the+// id when blank so a section card is never headerless. Drops shapeless entries.+const sanitizeSection = (s) => {+ if (!s || typeof s !== 'object') return null;+ const label = trimField(s.label, LABEL_MAX_LENGTH);+ const lyrics = trimField(s.lyrics, FIELD_MAX_LENGTH);+ if (!label && !lyrics) return null;+ return {+ id: trimField(s.id, ID_MAX_LENGTH) || `sec-${randomUUID().slice(0, 8)}`,+ label: label || 'Section',+ lyrics,+ };+};++// One voice layer the user is arranging ({ id, label, part, notes }). `id`+// references a songCraft VOICE_LAYERS entry when known but is free-text-safe.+const sanitizeLayer = (l) => {+ if (!l || typeof l !== 'object') return null;+ const label = trimField(l.label, LABEL_MAX_LENGTH);+ const part = trimField(l.part, PART_MAX_LENGTH);+ const notes = trimField(l.notes, FIELD_MAX_LENGTH);+ if (!label && !part && !notes) return null;+ return {+ id: trimField(l.id, ID_MAX_LENGTH) || `layer-${randomUUID().slice(0, 8)}`,+ label: label || 'Layer',+ part,+ notes,+ };+};++// A finite number or null — used by the pitch-analysis fields so a missing+// sample component (e.g. a silent frame with no detectable pitch) round-trips+// as null rather than NaN/0.+const finiteOrNull = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);++// One downsampled tuner sample ({ tMs, hz, cents, clarity }) from a take's+// pitch trace (#1027). `tMs` is the elapsed time in the take; hz/cents/clarity+// are the detected pitch, cents-from-target, and confidence. Drops shapeless+// entries; a sample with no time and no pitch carries no information.+const sanitizePitchSample = (s) => {+ if (!s || typeof s !== 'object') return null;+ const tMs = finiteOrNull(s.tMs);+ const hz = finiteOrNull(s.hz);+ if (tMs === null && hz === null) return null;+ return {+ tMs: tMs === null ? 0 : Math.max(0, Math.round(tMs)),+ hz,+ cents: finiteOrNull(s.cents),+ clarity: finiteOrNull(s.clarity),+ };+};++// The per-take accuracy summary (#1027), mirroring color-match's+// summarizeAccuracy output ({ percentInTune, graded, counts, perNote }). All+// fields are optional/absent-tolerant — a take recorded before color-match (or+// without scoring) has no accuracy at all, which is distinct from a scored take+// that graded zero notes (graded: 0). Returns null when there's nothing to+// persist so the field stays absent rather than an empty husk.+const sanitizeAccuracy = (a) => {+ if (!a || typeof a !== 'object') return null;+ const counts = a.counts && typeof a.counts === 'object' ? a.counts : {};+ const perNote = (Array.isArray(a.perNote) ? a.perNote : [])+ .map((g) => trimField(g, LABEL_MAX_LENGTH))+ .filter((g) => RECORDING_GRADES.includes(g))+ .slice(0, PER_NOTE_GRADES_MAX);+ const clampPercent = finiteOrNull(a.percentInTune);+ const clampGraded = finiteOrNull(a.graded);+ return {+ percentInTune: clampPercent === null ? 0 : Math.max(0, Math.min(100, Math.round(clampPercent))),+ graded: clampGraded === null ? perNote.length : Math.max(0, Math.round(clampGraded)),+ counts: {+ 'in-tune': Math.max(0, Math.round(finiteOrNull(counts['in-tune']) ?? 0)),+ close: Math.max(0, Math.round(finiteOrNull(counts.close) ?? 0)),+ off: Math.max(0, Math.round(finiteOrNull(counts.off) ?? 0)),+ missed: Math.max(0, Math.round(finiteOrNull(counts.missed) ?? 0)),+ },+ perNote,+ };+};++// One training attempt ({ percentInTune, graded, at }) — a graded take of one+// scope (a section or the whole song). Numbers are clamped; an attempt with no+// graded notes carries no signal and is dropped (mirrors songProgress.js, which+// never records a zero-note take). Returns null for a shapeless/empty attempt.+const sanitizeAttempt = (a) => {+ if (!a || typeof a !== 'object') return null;+ const graded = finiteOrNull(a.graded);+ if (graded === null || graded <= 0) return null;+ const pct = finiteOrNull(a.percentInTune);+ return {+ percentInTune: pct === null ? 0 : Math.max(0, Math.min(100, Math.round(pct))),+ graded: Math.max(0, Math.round(graded)),+ at: typeof a.at === 'string' ? a.at : new Date().toISOString(),+ };+};++// Training progress (#1028): `{ history: { <scope>: [attempt…] } }`. Each scope+// (a section id or the whole-song sentinel) keys a bounded, newest-last attempt+// list. Absent on legacy/untrained songs — returns null when there's nothing to+// persist so the field stays off the record (no wave of empty objects). The+// number of scopes and the per-scope history are both bounded so a hand-edited+// file can't grow the record without limit. Derived stats (best/avg/learned)+// are recomputed client-side from this history on read, never stored.+const sanitizeProgress = (p) => {+ if (!p || typeof p !== 'object') return null;+ const rawHistory = p.history && typeof p.history === 'object' ? p.history : {};+ const history = {};+ let scopeCount = 0;+ for (const [scope, attempts] of Object.entries(rawHistory)) {+ if (scopeCount >= PROGRESS_SCOPES_MAX) break;+ const key = trimField(scope, ID_MAX_LENGTH);+ // Skip empty keys and the prototype-pollution-prone keys — a section id is+ // always `sec-N` (or the `__whole__` sentinel), never one of these, so a+ // hand-edited `__proto__`/`constructor` scope is a malformed file, not data.+ if (!key || key === '__proto__' || key === 'constructor' || key === 'prototype') continue;+ const cleaned = sanitizeList(attempts, sanitizeAttempt, PROGRESS_HISTORY_MAX);+ if (!cleaned.length) continue;+ history[key] = cleaned;+ scopeCount += 1;+ }+ return Object.keys(history).length ? { history } : null;+};++// One saved vocal take ({ id, layerId, filename, label, durationMs, peak,+// mutedByDefault }). `filename` is the /api/uploads file name the audio is+// served from; a recording without one is meaningless, so it's dropped.+// `layerId` ties a take to a voice layer for the layered-playback mixer (free+// text — empty means "unassigned"). Numbers are coerced/clamped; bad values+// fall to sensible defaults rather than throwing.+//+// Optional pitch analysis (#1027): `pitchTrack` (a bounded, downsampled tuner+// trace) and `accuracy` (a color-match summary) are persisted so the tuner+// history and grading aren't recomputed on every open. Both are absent on+// legacy takes and on takes recorded without scoring — the fields only appear+// when there's analysis to keep, so a pre-feature record reads back unchanged.+const sanitizeRecording = (r) => {+ if (!r || typeof r !== 'object') return null;+ const filename = trimField(r.filename, URL_MAX_LENGTH);+ if (!filename) return null;+ const durationMs = typeof r.durationMs === 'number' && Number.isFinite(r.durationMs)+ ? Math.max(0, Math.round(r.durationMs)) : 0;+ const peak = typeof r.peak === 'number' && Number.isFinite(r.peak)+ ? Math.max(0, Math.min(1, r.peak)) : 0;+ const rec = {+ id: trimField(r.id, ID_MAX_LENGTH) || `rec-${randomUUID().slice(0, 8)}`,+ layerId: trimField(r.layerId, ID_MAX_LENGTH),+ label: trimField(r.label, LABEL_MAX_LENGTH),+ filename,+ durationMs,+ peak,+ muted: r.muted === true,+ createdAt: typeof r.createdAt === 'string' ? r.createdAt : new Date().toISOString(),+ };+ // Absent ⇒ omit (legacy/unscored take); present ⇒ sanitize + bound via the+ // shared sanitizeList. Keeping the keys off the object when there's no+ // analysis avoids a wave of empty arrays in data/rounds.json on every take.+ const pitchTrack = sanitizeList(r.pitchTrack, sanitizePitchSample, PITCH_TRACK_MAX);+ if (pitchTrack.length) rec.pitchTrack = pitchTrack;+ const accuracy = sanitizeAccuracy(r.accuracy);+ if (accuracy) rec.accuracy = accuracy;+ return rec;+};++// One labeled time range on a reference's attached audio (#2106):+// `{ layerId, startMs, endMs }` — "this span is the bass part alone". `layerId`+// ties the span to a voice layer (free text, same convention as recordings);+// times are clamped non-negative integers and a zero/negative-length span is+// dropped (it selects no audio). Used by the client's analysis view to extract+// a per-layer pitch track from the span.+//+// Optional stacked-mix backing window (#2121): `bgStartMs`/`bgEndMs` mark a+// slice just BEFORE the voice enters (the earlier layers alone) so the client+// can spectral-subtract the backing and extract a voice that never appears+// solo. Purely additive — the pair only persists when it forms a valid range+// that ENDS AT OR BEFORE the segment start (`bgEndMs <= startMs`); a window+// overlapping the segment would already contain the new voice, so subtracting+// it would cancel the very part being extracted. A legacy solo segment (no bg+// fields) round-trips unchanged.+const sanitizeRefSegment = (s) => {+ if (!s || typeof s !== 'object') return null;+ const startRaw = finiteOrNull(s.startMs);+ const endRaw = finiteOrNull(s.endMs);+ if (startRaw === null || endRaw === null) return null;+ const startMs = Math.max(0, Math.round(startRaw));+ const endMs = Math.max(0, Math.round(endRaw));+ if (endMs <= startMs) return null;+ const seg = {+ layerId: trimField(s.layerId, ID_MAX_LENGTH),+ startMs,+ endMs,+ };+ const bgStartRaw = finiteOrNull(s.bgStartMs);+ const bgEndRaw = finiteOrNull(s.bgEndMs);+ if (bgStartRaw !== null && bgEndRaw !== null) {+ const bgStartMs = Math.max(0, Math.round(bgStartRaw));+ const bgEndMs = Math.max(0, Math.round(bgEndRaw));+ if (bgEndMs > bgStartMs && bgEndMs <= startMs) {+ seg.bgStartMs = bgStartMs;+ seg.bgEndMs = bgEndMs;+ }+ }+ return seg;+};++// One reference link/video ({ id, url, label, note }) — external study+// material for the song (a TikTok performance, a tutorial, a chord chart).+// `url` is required (a reference without a target is meaningless); label/note+// are free text. The client decides how to render each url (TikTok videos+// embed; everything else is a link).+//+// Optional reference-audio analysis (#2106): `audioFilename` (an /api/uploads+// file, same convention as recordings[].filename) and `segments` (bounded+// labeled time ranges) only appear when set — absent keys stay absent so a+// legacy/pre-feature reference round-trips byte-identical (purely additive,+// no migration).+const sanitizeReference = (r) => {+ if (!r || typeof r !== 'object') return null;+ const url = trimField(r.url, URL_MAX_LENGTH);+ // Require an http(s) scheme — defense-in-depth so a hand-edited file or a+ // non-PortOS writer can't persist a javascript:/data: URL that a renderer+ // might trust (mirrors the client's isHttpUrl guard).+ if (!/^https?:\/\//i.test(url)) return null;+ const ref = {+ id: trimField(r.id, ID_MAX_LENGTH) || `ref-${randomUUID().slice(0, 8)}`,+ url,+ label: trimField(r.label, LABEL_MAX_LENGTH),+ note: trimField(r.note, FIELD_MAX_LENGTH),+ };+ const audioFilename = trimField(r.audioFilename, URL_MAX_LENGTH);+ if (audioFilename) {+ ref.audioFilename = audioFilename;+ // Segments are time ranges INTO the attached audio — meaningless without+ // it. Persisting them only alongside an audioFilename makes the invariant+ // structural: removing the audio clears them, so stale ranges can't+ // resurrect against a later, different recording.+ const segments = sanitizeList(r.segments, sanitizeRefSegment, REF_SEGMENTS_MAX);+ if (segments.length) ref.segments = segments;+ // A MuScriptor transcription OF the attached audio (an /api/uploads .mid+ // pointer) — same structural invariant as segments: derived from this+ // audio, so removing the audio drops it and a stale transcription can't+ // resurrect against a later, different recording.+ const midiFilename = trimField(r.midiFilename, URL_MAX_LENGTH);+ if (midiFilename) ref.midiFilename = midiFilename;+ }+ return ref;+};++// One sheet-music part — a harmony variation of the song's base score+// ({ id, label, role, score }). `score` is the PortOS lead-sheet DSL (same+// format as the base `score`); a part without notation is meaningless, so it's+// dropped. `role` references a songCraft HARMONY_PARTS id when known (bass,+// mid-harmony-1, high-harmony-1 …) but is free-text-safe so a newer/older client+// vocabulary can't 400. `label` defaults from the role/`Part` so a part card is+// never headerless.+const sanitizeScorePart = (p) => {+ if (!p || typeof p !== 'object') return null;+ const score = trimField(p.score, SCORE_MAX_LENGTH);+ if (!score) return null;+ const label = trimField(p.label, LABEL_MAX_LENGTH);+ const role = trimField(p.role, ID_MAX_LENGTH);+ return {+ id: trimField(p.id, ID_MAX_LENGTH) || `part-${randomUUID().slice(0, 8)}`,+ label: label || 'Part',+ role,+ score,+ };+};++const sanitizeList = (arr, fn, max) =>+ (Array.isArray(arr) ? arr : [])+ .map(fn)+ .filter(Boolean)+ .slice(0, max);++// Partner-song ids — the "symbiotic" link that lets rounds declare which other+// songs they're sung together with (a quodlibet stack). Keeps only non-empty+// strings, dedupes, and drops a self-reference (a song can't partner itself —+// that would make the round-stack render the same song twice). `selfId` is the+// owning song's id so the self-drop survives a hand-edited file.+const sanitizePartnerIds = (arr, selfId) => {+ const seen = new Set();+ return (Array.isArray(arr) ? arr : [])+ .map((v) => trimField(v, ID_MAX_LENGTH))+ .filter((id) => id && id !== selfId && !seen.has(id) && seen.add(id))+ .slice(0, PARTNERS_MAX);+};++// No built-in ids — the default when a caller sanitizes outside the service's+// seed context (every song reads back builtIn: false).+const NO_BUILTIN_IDS = new Set();++// Project a stored or inbound record onto the canonical song shape. Used on+// read (defends hand-edited JSON) and on write (normalizes the input).+// `builtinIds` is the caller's bundled-default id set (services/rounds.js+// passes BUILTIN_ROUND_IDS) — derived from the shipped seeds, NOT from `raw`,+// so the flag can't be lost on edit or spoofed on a hand-edited custom song.+export const sanitizeRound = (raw, builtinIds = NO_BUILTIN_IDS) => {+ if (!raw || typeof raw !== 'object') return null;+ const id = trimField(raw.id, ID_MAX_LENGTH);+ if (!id) return null;+ const song = {+ id,+ title: trimField(raw.title, TITLE_MAX_LENGTH) || 'Untitled round',+ artist: trimField(raw.artist, ARTIST_MAX_LENGTH),+ key: trimField(raw.key, KEY_MAX_LENGTH),+ tempo: sanitizeTempo(raw.tempo),+ rhythmShapeId: trimField(raw.rhythmShapeId, ID_MAX_LENGTH),+ notation: trimField(raw.notation, FIELD_MAX_LENGTH),+ // Sheet-music notation in the PortOS lead-sheet DSL (client/src/lib/+ // scoreNotation.js). A bounded free-text string — the client parses + renders+ // it; the server only length-caps it, so a newer/older DSL revision can't 400.+ score: trimField(raw.score, SCORE_MAX_LENGTH),+ // Harmony variations of the base `score` (bass, mid/high harmonies …), each+ // its own lead-sheet DSL. Absent ⇒ [] — purely additive, so an older peer or+ // a pre-feature record reads back as a song with no parts (no migration of+ // the on-disk shape needed; the field simply appears when the user adds one).+ scoreParts: sanitizeList(raw.scoreParts, sanitizeScorePart, SCORE_PARTS_MAX),+ notes: trimField(raw.notes, FIELD_MAX_LENGTH),+ learned: raw.learned === true,+ sections: sanitizeList(raw.sections, sanitizeSection, SECTIONS_MAX),+ layers: sanitizeList(raw.layers, sanitizeLayer, LAYERS_MAX),+ recordings: sanitizeList(raw.recordings, sanitizeRecording, RECORDINGS_MAX),+ references: sanitizeList(raw.references, sanitizeReference, REFERENCES_MAX),+ // Ids of other songs this one is sung together with (round-stack partners).+ partnerRoundIds: sanitizePartnerIds(raw.partnerRoundIds, id),+ builtIn: builtinIds.has(id),+ createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : new Date().toISOString(),+ updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : new Date().toISOString(),+ };+ // Training progress (#1028). Absent ⇒ omit (legacy/untrained song); present ⇒+ // attach the bounded per-scope attempt history. Keeping the key off the record+ // when there's no progress avoids an empty husk on every untrained song.+ const progress = sanitizeProgress(raw.progress);+ if (progress) song.progress = progress;+ return song;+};diff --git a/server/routes/brainSongbook.js b/server/routes/brainSongbook.jsindex b20dc05b25..c1ff5ebb0b 100644--- a/server/routes/brainSongbook.js+++ b/server/routes/brainSongbook.js@@ -110,7 +110,7 @@ router.post('/', asyncHandler(async (req, res) => {res.status(201).json(song);}));-router.put('/:id', asyncHandler(async (req, res) => {+router.patch('/:id', asyncHandler(async (req, res) => {// songUpdateSchema is defaults-free down to the nested `content` object, so// an omitted field (or omitted content.format/text) is genuinely absent// instead of resetting to its default (see brainValidation.js / zodCompat.js).diff --git a/server/routes/brainSongbook.test.js b/server/routes/brainSongbook.test.jsindex b0b00b3f4b..2ecdde99a2 100644--- a/server/routes/brainSongbook.test.js+++ b/server/routes/brainSongbook.test.js@@ -177,12 +177,12 @@ describe('Brain SongBook routes', () => {});});- describe('PUT /api/brain/songbook/:id', () => {+ describe('PATCH /api/brain/songbook/:id', () => {it('updates only the sent fields (no default injection) — the stage-flip path', async () => {const stored = baseSong({ capo: 5, key: 'Em', content: { format: 'chordpro', text: '{t: Example Song}' } });const seen = mockUpdateWith(stored);const res = await request(app)- .put(`/api/brain/songbook/${SONG_ID}`)+ .patch(`/api/brain/songbook/${SONG_ID}`).send({ stage: 'learning' });expect(res.status).toBe(200);expect(res.body.stage).toBe('learning');@@ -196,7 +196,7 @@ describe('Brain SongBook routes', () => {const stored = baseSong({ content: { format: 'chordpro', text: '{t: Old}' } });const seen = mockUpdateWith(stored);const res = await request(app)- .put(`/api/brain/songbook/${SONG_ID}`)+ .patch(`/api/brain/songbook/${SONG_ID}`).send({ content: { text: 'new text' } });expect(res.status).toBe(200);expect(seen.updates.content).toEqual({ format: 'chordpro', text: 'new text' });@@ -207,7 +207,7 @@ describe('Brain SongBook routes', () => {const stored = baseSong({ content: { format: 'chordpro', text: '{t: Keep me}' } });const seen = mockUpdateWith(stored);const res = await request(app)- .put(`/api/brain/songbook/${SONG_ID}`)+ .patch(`/api/brain/songbook/${SONG_ID}`).send({ content: { format: 'plain' } });expect(res.status).toBe(200);expect(seen.updates.content).toEqual({ format: 'plain', text: '{t: Keep me}' });@@ -215,7 +215,7 @@ describe('Brain SongBook routes', () => {it('400s on an invalid stage', async () => {const res = await request(app)- .put(`/api/brain/songbook/${SONG_ID}`)+ .patch(`/api/brain/songbook/${SONG_ID}`).send({ stage: 'perfected' });expect(res.status).toBe(400);expect(brainStorage.updateWith).not.toHaveBeenCalled();@@ -224,7 +224,7 @@ describe('Brain SongBook routes', () => {it('strips client-supplied attachments', async () => {const seen = mockUpdateWith(baseSong());await request(app)- .put(`/api/brain/songbook/${SONG_ID}`)+ .patch(`/api/brain/songbook/${SONG_ID}`).send({ title: 'New Title', attachments: [{ filename: 'forged.pdf', mime: 'application/pdf', size: 1, sha256: 'x'.repeat(64) }] });expect(seen.updates).toEqual({ title: 'New Title' });});@@ -232,7 +232,7 @@ describe('Brain SongBook routes', () => {it('404s when the song is missing', async () => {brainStorage.updateWith.mockResolvedValue(null);const res = await request(app)- .put(`/api/brain/songbook/${SONG_ID}`)+ .patch(`/api/brain/songbook/${SONG_ID}`).send({ title: 'X' });expect(res.status).toBe(404);});diff --git a/server/routes/games.js b/server/routes/games.jsindex d50c6aafb4..f0a3c7f730 100644--- a/server/routes/games.js+++ b/server/routes/games.js@@ -13,6 +13,8 @@ import {gameMusicBindingSchema,gameSpriteBindingSchema,gameUpdateSchema,+ isPaginationRequested,+ paginateArray,validateRequest,} from '../lib/validation.js';import {@@ -36,8 +38,15 @@ import {const router = Router();-router.get('/', asyncHandler(async (_req, res) => {- res.json(await listGames());+// Backward-compatible by default: returns the full games array. When a client+// passes `limit`/`offset`, the response becomes the bounded+// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.+router.get('/', asyncHandler(async (req, res) => {+ const games = await listGames();+ if (!isPaginationRequested(req.query)) {+ return res.json(games);+ }+ res.json(paginateArray(games, req.query, { defaultLimit: 50, maxLimit: 500 }));}));router.post('/', asyncHandler(async (req, res) => {diff --git a/server/routes/games.test.js b/server/routes/games.test.jsindex 68a9ffbe4a..f132c956cd 100644--- a/server/routes/games.test.js+++ b/server/routes/games.test.js@@ -36,6 +36,26 @@ const makeApp = () => {describe('Game routes', () => {beforeEach(() => vi.clearAllMocks());+ it('GET / returns the plain array by default', async () => {+ games.listGames.mockResolvedValueOnce([{ id: 'game-1', name: 'Example Game' }]);+ const response = await request(makeApp()).get('/api/games');+ expect(response.status).toBe(200);+ expect(response.body).toEqual([{ id: 'game-1', name: 'Example Game' }]);+ });++ it('GET / returns a bounded envelope when pagination is requested', async () => {+ games.listGames.mockResolvedValueOnce(+ Array.from({ length: 5 }, (_, i) => ({ id: `game-${i}`, name: `G${i}` }))+ );+ const response = await request(makeApp()).get('/api/games?limit=2&offset=1');+ expect(response.status).toBe(200);+ expect(response.body.items).toHaveLength(2);+ expect(response.body.items[0].id).toBe('game-1');+ expect(response.body.total).toBe(5);+ expect(response.body.limit).toBe(2);+ expect(response.body.offset).toBe(1);+ });+it('creates a managed-app-bound Game', async () => {games.createGame.mockResolvedValueOnce({ id: 'game-1', appId: 'app-1', name: 'Example Game' });const response = await request(makeApp())@@ -53,6 +73,61 @@ describe('Game routes', () => {expect(games.bindSprite).not.toHaveBeenCalled();});+ it('updates a Game name via PATCH', async () => {+ games.updateGame.mockResolvedValueOnce({ id: 'game-1', appId: 'app-1', name: 'Renamed Game' });+ const response = await request(makeApp())+ .patch('/api/games/game-1')+ .send({ name: 'Renamed Game' });+ expect(response.status).toBe(200);+ expect(response.body.name).toBe('Renamed Game');+ expect(games.updateGame).toHaveBeenCalledWith('game-1', { name: 'Renamed Game' });+ });++ it('rejects a PATCH with no fields', async () => {+ const response = await request(makeApp()).patch('/api/games/game-1').send({});+ expect(response.status).toBe(400);+ expect(games.updateGame).not.toHaveBeenCalled();+ });++ it('deletes a Game', async () => {+ games.deleteGame.mockResolvedValueOnce({ ok: true });+ const response = await request(makeApp()).delete('/api/games/game-1');+ expect(response.status).toBe(200);+ expect(response.body).toEqual({ ok: true });+ expect(games.deleteGame).toHaveBeenCalledWith('game-1');+ });++ it('unbinds a sprite from a Game', async () => {+ games.unbindSprite.mockResolvedValueOnce({ id: 'game-1', spriteBindings: [] });+ const response = await request(makeApp()).delete('/api/games/game-1/sprites/sprite-1');+ expect(response.status).toBe(200);+ expect(games.unbindSprite).toHaveBeenCalledWith('game-1', 'sprite-1');+ });++ it('binds music to a Game', async () => {+ games.bindMusic.mockResolvedValueOnce({ id: 'game-1', musicBindings: [{ id: 'music-1', trackId: 'track-1' }] });+ const response = await request(makeApp())+ .post('/api/games/game-1/music')+ .send({ trackId: 'track-1' });+ expect(response.status).toBe(201);+ expect(games.bindMusic).toHaveBeenCalledWith('game-1', { trackId: 'track-1' });+ });++ it('rejects a music binding missing trackId', async () => {+ const response = await request(makeApp())+ .post('/api/games/game-1/music')+ .send({ trackId: '' });+ expect(response.status).toBe(400);+ expect(games.bindMusic).not.toHaveBeenCalled();+ });++ it('unbinds music from a Game', async () => {+ games.unbindMusic.mockResolvedValueOnce({ id: 'game-1', musicBindings: [] });+ const response = await request(makeApp()).delete('/api/games/game-1/music/music-1');+ expect(response.status).toBe(200);+ expect(games.unbindMusic).toHaveBeenCalledWith('game-1', 'music-1');+ });+it('binds and publishes role-specific gallery artwork', async () => {const updated = { id: 'game-1', artworkBindings: [{ id: 'artwork-1' }] };games.bindArtwork.mockResolvedValueOnce(updated);diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 51cf6447b9..4c2aec47ae 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -22,6 +22,8 @@ import {musicVideoManualAnalysisSchema,musicVideoTranscribeMidiRequestSchema,recordRenderPinFields,+ isPaginationRequested,+ paginateArray,} from '../lib/validation.js';import { PATHS } from '../lib/fileUtils.js';import { safeUnder } from '../lib/ffmpeg.js';@@ -60,8 +62,15 @@ const router = Router();const projectCreateSchema = musicVideoProjectCreateSchema.extend(recordRenderPinFields);const projectUpdateSchema = musicVideoProjectUpdateSchema.extend(recordRenderPinFields);-router.get('/', asyncHandler(async (_req, res) => {- res.json(await listProjects());+// Backward-compatible by default: returns the full projects array. When a client+// passes `limit`/`offset`, the response becomes the bounded+// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.+router.get('/', asyncHandler(async (req, res) => {+ const projects = await listProjects();+ if (!isPaginationRequested(req.query)) {+ return res.json(projects);+ }+ res.json(paginateArray(projects, req.query, { defaultLimit: 50, maxLimit: 500 }));}));router.get('/:id', asyncHandler(async (req, res) => {diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.jsindex 525206b37e..76276493da 100644--- a/server/routes/musicVideo.test.js+++ b/server/routes/musicVideo.test.js@@ -80,6 +80,19 @@ describe('musicVideo routes', () => {expect(r.body).toEqual([{ id: 'mv-1', name: 'A' }]);});+ it('GET / returns a bounded envelope when pagination is requested', async () => {+ svc.listProjects.mockResolvedValueOnce(+ Array.from({ length: 5 }, (_, i) => ({ id: `mv-${i}`, name: `P${i}` }))+ );+ const r = await request(app).get('/api/music-video?limit=2&offset=1');+ expect(r.status).toBe(200);+ expect(r.body.items).toHaveLength(2);+ expect(r.body.items[0].id).toBe('mv-1');+ expect(r.body.total).toBe(5);+ expect(r.body.limit).toBe(2);+ expect(r.body.offset).toBe(1);+ });+it('GET /:id 404s when missing', async () => {svc.getProject.mockResolvedValue(null);const r = await request(app).get('/api/music-video/mv-x');diff --git a/server/routes/rounds.js b/server/routes/rounds.jsindex d3f2f759a5..a4e0467ece 100644--- a/server/routes/rounds.js+++ b/server/routes/rounds.js@@ -4,7 +4,7 @@* GET /api/rounds → { rounds }* GET /api/rounds/:id → { round }* POST /api/rounds → { round } (body: roundInputSchema)- * PUT /api/rounds/:id → { round } (body: roundInputSchema.partial())+ * PATCH /api/rounds/:id → { round } (body: roundInputSchema.partial())* DELETE /api/rounds/:id → { id }** The a cappella round workbench: write/arrange rounds and track which voice@@ -76,7 +76,7 @@ const accuracySchema = z.object({});// A saved vocal take. `filename` is the /api/uploads file the audio is served-// from (the client uploads the WAV first, then PUTs the round with the returned+// from (the client uploads the WAV first, then PATCHes the round with the returned// filename). Numbers are accepted for the mixer; the service clamps them.// `pitchTrack`/`accuracy` are optional per-take pitch analysis (#1027) — absent// on legacy/unscored takes, persisted so the tuner history isn't recomputed.@@ -152,8 +152,8 @@ const referenceSchema = z.object({midiFilename: str(svc.URL_MAX_LENGTH).optional(),});-// No `.default('')` on these fields: `.partial()` (used for PUT) materializes a-// default for an *omitted* key, which would turn a single-field PUT into a+// No `.default('')` on these fields: `.partial()` (used for PATCH) materializes a+// default for an *omitted* key, which would turn a single-field PATCH into a// wipe of every other field via updateRound's `'key' in patch` merge. Leaving// them plain-optional keeps omitted keys absent (preserve) vs present-empty// (clear); the service's `trimField` coerces a present `undefined`/'' anyway.@@ -240,7 +240,7 @@ router.get('/:id', asyncHandler(async (req, res) => {// Two-segment `reference-audio/...` paths are registered before `/:id` so the// literal segment can't be read as a round id. The kickoff returns 202 + a// jobId; progress streams over SSE; the client persists the returned filename-// on the reference via the normal PUT on Save.+// on the reference via the normal PATCH on Save.const referenceAudioImportSchema = z.object({ url: str(2048).min(1) });router.post('/reference-audio/import', asyncHandler(async (req, res) => {@@ -263,7 +263,7 @@ router.post('/reference-audio/import/:jobId/cancel', (req, res) => {// into a .mid via the local MuScriptor sidecar. Same job/SSE shape as the import// above: kickoff returns 202 + a jobId (503 with the install hint when the venv// isn't provisioned); progress streams over SSE; the client persists the-// returned midiFilename on the reference via the normal PUT on Save.+// returned midiFilename on the reference via the normal PATCH on Save.const transcribeMidiSchema = z.object({filename: str(svc.URL_MAX_LENGTH).min(1),model: z.enum(MUSCRIPTOR_MODELS).optional(),@@ -295,7 +295,7 @@ router.post('/', asyncHandler(async (req, res) => {res.json({ round });}));-router.put('/:id', asyncHandler(async (req, res) => {+router.patch('/:id', asyncHandler(async (req, res) => {const patch = validateRequest(roundInputSchema.partial(), req.body || {});const round = await svc.updateRound(req.params.id, patch).catch(rethrowRoundError);res.json({ round });diff --git a/server/routes/rounds.test.js b/server/routes/rounds.test.jsindex 366706ee42..cad5ecdbdd 100644--- a/server/routes/rounds.test.js+++ b/server/routes/rounds.test.js@@ -81,14 +81,14 @@ describe('rounds route', () => {expect(res.body.code).toBe('NOT_FOUND');});- it('PUT /:id forwards ONLY the keys the client sent — omitted fields are not clobbered', async () => {+ it('PATCH /:id forwards ONLY the keys the client sent — omitted fields are not clobbered', async () => {// Regression guard: a `.default('')` on the schema fields would make- // .partial() materialize defaults for omitted keys, so a title-only PUT+ // .partial() materialize defaults for omitted keys, so a title-only PATCH// would wipe artist/key/notation/notes via updateRound's `key in patch`// merge. The route must forward a patch containing ONLY `title`.mocks.updateRound.mockResolvedValue({ id: 'song-1', title: 'Renamed' });const res = await request(makeApp())- .put('/api/rounds/song-1')+ .patch('/api/rounds/song-1').send({ title: 'Renamed' });expect(res.status).toBe(200);expect(mocks.updateRound).toHaveBeenCalledTimes(1);@@ -99,17 +99,17 @@ describe('rounds route', () => {expect('notation' in patch).toBe(false);});- it('PUT /:id preserves an explicit empty-string clear (present, not absent)', async () => {+ it('PATCH /:id preserves an explicit empty-string clear (present, not absent)', async () => {mocks.updateRound.mockResolvedValue({ id: 'song-1', key: '' });- await request(makeApp()).put('/api/rounds/song-1').send({ key: '' });+ await request(makeApp()).patch('/api/rounds/song-1').send({ key: '' });const [, patch] = mocks.updateRound.mock.calls[0];expect('key' in patch).toBe(true);expect(patch.key).toBe('');});- it('PUT /:id maps a service NOT_FOUND to a 404', async () => {+ it('PATCH /:id maps a service NOT_FOUND to a 404', async () => {mocks.updateRound.mockRejectedValue(Object.assign(new Error('nope'), { code: 'NOT_FOUND' }));- const res = await request(makeApp()).put('/api/rounds/song-x').send({ title: 'x' });+ const res = await request(makeApp()).patch('/api/rounds/song-x').send({ title: 'x' });expect(res.status).toBe(404);expect(res.body.code).toBe('NOT_FOUND');});@@ -134,9 +134,9 @@ describe('rounds route', () => {expect(res.body.id).toBe('song-1');});- it('PUT /:id accepts a recordings array', async () => {+ it('PATCH /:id accepts a recordings array', async () => {mocks.updateRound.mockResolvedValue({ id: 'song-1' });- const res = await request(makeApp()).put('/api/rounds/song-1').send({+ const res = await request(makeApp()).patch('/api/rounds/song-1').send({recordings: [{ layerId: 'lead', filename: 'abc-vocal.wav', durationMs: 1200, peak: 0.4 }],});expect(res.status).toBe(200);@@ -144,17 +144,17 @@ describe('rounds route', () => {expect(patch.recordings[0].filename).toBe('abc-vocal.wav');});- it('PUT /:id rejects a recording with a peak outside 0–1', async () => {- const res = await request(makeApp()).put('/api/rounds/song-1').send({+ it('PATCH /:id rejects a recording with a peak outside 0–1', async () => {+ const res = await request(makeApp()).patch('/api/rounds/song-1').send({recordings: [{ filename: 'x.wav', peak: 5 }],});expect(res.status).toBe(400);expect(mocks.updateRound).not.toHaveBeenCalled();});- it('PUT /:id accepts a recording with pitchTrack + accuracy analysis (#1027)', async () => {+ it('PATCH /:id accepts a recording with pitchTrack + accuracy analysis (#1027)', async () => {mocks.updateRound.mockResolvedValue({ id: 'song-1' });- const res = await request(makeApp()).put('/api/rounds/song-1').send({+ const res = await request(makeApp()).patch('/api/rounds/song-1').send({recordings: [{filename: 'take.wav',pitchTrack: [{ tMs: 0, hz: 220, cents: -3, clarity: 0.9 }, { tMs: 50, hz: null }],@@ -167,9 +167,9 @@ describe('rounds route', () => {expect(patch.recordings[0].accuracy.percentInTune).toBe(80);});- it('PUT /:id accepts a legacy recording with no pitch analysis (absent-tolerant)', async () => {+ it('PATCH /:id accepts a legacy recording with no pitch analysis (absent-tolerant)', async () => {mocks.updateRound.mockResolvedValue({ id: 'song-1' });- const res = await request(makeApp()).put('/api/rounds/song-1').send({+ const res = await request(makeApp()).patch('/api/rounds/song-1').send({recordings: [{ filename: 'legacy.wav', durationMs: 500 }],});expect(res.status).toBe(200);@@ -177,18 +177,18 @@ describe('rounds route', () => {expect(patch.recordings[0]).not.toHaveProperty('pitchTrack');});- it('PUT /:id rejects a pitchTrack exceeding the bound', async () => {+ it('PATCH /:id rejects a pitchTrack exceeding the bound', async () => {const tooMany = Array.from({ length: 4001 }, (_, i) => ({ tMs: i }));- const res = await request(makeApp()).put('/api/rounds/song-1').send({+ const res = await request(makeApp()).patch('/api/rounds/song-1').send({recordings: [{ filename: 'x.wav', pitchTrack: tooMany }],});expect(res.status).toBe(400);expect(mocks.updateRound).not.toHaveBeenCalled();});- it('PUT /:id accepts a references array', async () => {+ it('PATCH /:id accepts a references array', async () => {mocks.updateRound.mockResolvedValue({ id: 'song-1' });- const res = await request(makeApp()).put('/api/rounds/song-1').send({+ const res = await request(makeApp()).patch('/api/rounds/song-1').send({references: [{ url: 'https://www.tiktok.com/@u/video/123', label: 'TikTok' }],});expect(res.status).toBe(200);@@ -196,11 +196,11 @@ describe('rounds route', () => {expect(patch.references[0].url).toBe('https://www.tiktok.com/@u/video/123');});- it('PUT /:id passes a segment stacked-mix backing window through validation (#2121)', async () => {+ it('PATCH /:id passes a segment stacked-mix backing window through validation (#2121)', async () => {// The Zod schema strips unknown keys, so bgStartMs/bgEndMs must be typed on// refSegmentSchema or they'd never reach the service sanitizer.mocks.updateRound.mockResolvedValue({ id: 'song-1' });- const res = await request(makeApp()).put('/api/rounds/song-1').send({+ const res = await request(makeApp()).patch('/api/rounds/song-1').send({references: [{url: 'https://www.tiktok.com/@u/video/123',audioFilename: 'ref.wav',@@ -212,28 +212,28 @@ describe('rounds route', () => {expect(patch.references[0].segments[0]).toMatchObject({ bgStartMs: 4000, bgEndMs: 8000 });});- it('PUT /:id rejects a reference without a url', async () => {- const res = await request(makeApp()).put('/api/rounds/song-1').send({+ it('PATCH /:id rejects a reference without a url', async () => {+ const res = await request(makeApp()).patch('/api/rounds/song-1').send({references: [{ label: 'no url' }],});expect(res.status).toBe(400);expect(mocks.updateRound).not.toHaveBeenCalled();});- it('PUT /:id accepts an empty-url reference (a blank row is dropped server-side, not rejected)', async () => {+ it('PATCH /:id accepts an empty-url reference (a blank row is dropped server-side, not rejected)', async () => {// The editor seeds new reference rows as { url: '' }; saving must not 400 —// the service drops the blank row. Guards against a future `.min(1)` that// would reject in-progress rows on save.mocks.updateRound.mockResolvedValue({ id: 'song-1' });- const res = await request(makeApp()).put('/api/rounds/song-1').send({+ const res = await request(makeApp()).patch('/api/rounds/song-1').send({references: [{ url: '' }],});expect(res.status).toBe(200);});- it('PUT /:id accepts a partnerRoundIds array', async () => {+ it('PATCH /:id accepts a partnerRoundIds array', async () => {mocks.updateRound.mockResolvedValue({ id: 'song-1' });- const res = await request(makeApp()).put('/api/rounds/song-1').send({+ const res = await request(makeApp()).patch('/api/rounds/song-1').send({partnerRoundIds: ['seed-ah-poor-bird', 'seed-rose-rose-rose-red'],});expect(res.status).toBe(200);@@ -241,9 +241,9 @@ describe('rounds route', () => {expect(patch.partnerRoundIds).toEqual(['seed-ah-poor-bird', 'seed-rose-rose-rose-red']);});- it('PUT /:id rejects more than PARTNERS_MAX partner ids', async () => {+ it('PATCH /:id rejects more than PARTNERS_MAX partner ids', async () => {const tooMany = Array.from({ length: 20 }, (_, i) => `seed-${i}`);- const res = await request(makeApp()).put('/api/rounds/song-1').send({ partnerRoundIds: tooMany });+ const res = await request(makeApp()).patch('/api/rounds/song-1').send({ partnerRoundIds: tooMany });expect(res.status).toBe(400);expect(mocks.updateRound).not.toHaveBeenCalled();});@@ -310,10 +310,10 @@ describe('rounds route', () => {expect(aiMocks.evaluateRound).not.toHaveBeenCalled();});- it('PUT /:id accepts a scoreParts array', async () => {+ it('PATCH /:id accepts a scoreParts array', async () => {mocks.updateRound.mockResolvedValue({ id: 'song-1' });const res = await request(makeApp())- .put('/api/rounds/song-1')+ .patch('/api/rounds/song-1').send({ scoreParts: [{ label: 'Bass', role: 'bass', score: '| G2w(x) |' }] });expect(res.status).toBe(200);const [, patch] = mocks.updateRound.mock.calls[0];@@ -321,9 +321,9 @@ describe('rounds route', () => {expect(patch.scoreParts[0].score).toBe('| G2w(x) |');});- it('PUT /:id rejects a scorePart without a score', async () => {+ it('PATCH /:id rejects a scorePart without a score', async () => {const res = await request(makeApp())- .put('/api/rounds/song-1')+ .patch('/api/rounds/song-1').send({ scoreParts: [{ label: 'Bass', role: 'bass' }] });expect(res.status).toBe(400);expect(mocks.updateRound).not.toHaveBeenCalled();diff --git a/server/routes/sprites.js b/server/routes/sprites.jsindex f54e854904..fa6a6568d6 100644--- a/server/routes/sprites.js+++ b/server/routes/sprites.js@@ -40,6 +40,8 @@ import {spriteAtlasCompileSchema,spriteAtlasPublishSchema,spriteAssetDeleteSchema,+ isPaginationRequested,+ paginateArray,} from '../lib/validation.js';import { z } from 'zod';import { optionalUploadFields } from '../lib/multipart.js';@@ -145,8 +147,15 @@ const referenceUpload = optionalUploadFields(['referenceImage'], {fileFilter: (_req, file, cb) => cb(null, ACCEPTED_REFERENCE_MIME.has((file.mimetype || '').toLowerCase())),});-router.get('/', asyncHandler(async (_req, res) => {- res.json(await listRecords());+// Backward-compatible by default: returns the full records array. When a client+// passes `limit`/`offset`, the response becomes the bounded+// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.+router.get('/', asyncHandler(async (req, res) => {+ const records = await listRecords();+ if (!isPaginationRequested(req.query)) {+ return res.json(records);+ }+ res.json(paginateArray(records, req.query, { defaultLimit: 50, maxLimit: 500 }));}));// Characters with a locked main reference — the pool that can seed a new maindiff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.jsindex f4c4fa2af6..b08bbddf21 100644--- a/server/routes/sprites.test.js+++ b/server/routes/sprites.test.js@@ -145,6 +145,19 @@ describe('sprites routes', () => {expect(r.body).toEqual([{ id: 'pioneer', kind: 'character', name: 'Pioneer' }]);});+ it('GET / returns a bounded envelope when pagination is requested', async () => {+ records.listRecords.mockResolvedValueOnce(+ Array.from({ length: 5 }, (_, i) => ({ id: `sprite-${i}`, kind: 'character', name: `S${i}` }))+ );+ const r = await request(app).get('/api/sprites?limit=2&offset=1');+ expect(r.status).toBe(200);+ expect(r.body.items).toHaveLength(2);+ expect(r.body.items[0].id).toBe('sprite-1');+ expect(r.body.total).toBe(5);+ expect(r.body.limit).toBe(2);+ expect(r.body.offset).toBe(1);+ });+it('POST / validates and delegates to createCharacter', async () => {const r = await request(app).post('/api/sprites').send({ name: 'Trail Hand #2' });expect(r.status).toBe(201);diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex 25e5b65028..465bde4c20 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -1,21 +1,11 @@/**- * Universe Builder Routes+ * Universe Builder Routes — /api/universe-builder*- * GET /api/universe-builder → Universe[]- * POST /api/universe-builder → Universe- * GET /api/universe-builder/:id → Universe- * PATCH /api/universe-builder/:id → Universe- * DELETE /api/universe-builder/:id → { id }- * POST /api/universe-builder/expand → { logline, premise, styleNotes, influences, categories, compositeSheets, characters, places, objects, llm }- * POST /api/universe-builder/describe-from-images → { description, llm }- * POST /api/universe-builder/analyze-style-reference → { reference, proposed, diff, rationale, llm }- * POST /api/universe-builder/:id/characters/:entryId/expand-from-images → { fields, updatedFields, llm }- * POST /api/universe-builder/:id/canon/:kind/:entryId/correct-from-image → { descField, currentDescription, proposedDescription, llm } | { locked, entryName }- * POST /api/universe-builder/:id/canon/:kind/:entryId/apply-image-correction → { universe, entry }- * POST /api/universe-builder/:id/render → { runId, collectionId, jobIds, promptCount }- * GET /api/universe-builder/:id/runs → Run[]- * POST /api/universe-builder/:id/style-references → Universe- * DELETE /api/universe-builder/:id/style-references/:referenceId → Universe+ * Universe CRUD plus the AI-assisted workflows that operate on a universe:+ * expand/refine, image-based description + canon correction, reference-sheet+ * and canon-entry rendering, run history, style references, and canon+ * entry management. Each endpoint carries its own doc comment below — this+ * header intentionally doesn't enumerate them (it drifted stale when it did).*/import { Router } from 'express';diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.jsindex 7ac83c34a8..d3204ac13e 100644--- a/server/routes/writersRoom.js+++ b/server/routes/writersRoom.js@@ -28,6 +28,8 @@ import {writersRoomPlaceUpdateSchema,writersRoomObjectCreateSchema,writersRoomObjectUpdateSchema,+ isPaginationRequested,+ paginateArray,} from '../lib/validation.js';import {listFolders, createFolder, deleteFolder,@@ -77,8 +79,15 @@ router.delete('/folders/:id', asyncHandler(async (req, res) => {// ---------- works -----------router.get('/works', asyncHandler(async (_req, res) => {- res.json(await listWorks());+// Backward-compatible by default: returns the full works array. When a client+// passes `limit`/`offset`, the response becomes the bounded+// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.+router.get('/works', asyncHandler(async (req, res) => {+ const works = await listWorks();+ if (!isPaginationRequested(req.query)) {+ return res.json(works);+ }+ res.json(paginateArray(works, req.query, { defaultLimit: 50, maxLimit: 500 }));}));router.post('/works', asyncHandler(async (req, res) => {diff --git a/server/routes/writersRoom.test.js b/server/routes/writersRoom.test.jsindex 705f63a598..61508a1676 100644--- a/server/routes/writersRoom.test.js+++ b/server/routes/writersRoom.test.js@@ -37,6 +37,13 @@ vi.mock('../services/writersRoom/places.js', () => ({deletePlace: vi.fn(async () => ({ ok: true })),}));+vi.mock('../services/writersRoom/objects.js', () => ({+ listObjects: vi.fn(async () => [{ id: 'wr-object-1', name: 'The Locket' }]),+ createObject: vi.fn(async (workId, data) => ({ id: 'wr-object-new', ...data })),+ updateObject: vi.fn(async (workId, objectId, data) => ({ id: objectId, ...data })),+ deleteObject: vi.fn(async () => ({ ok: true })),+}));+vi.mock('../services/writersRoom/evaluator.js', () => ({runAnalysis: vi.fn(),listAnalyses: vi.fn(async () => []),@@ -91,6 +98,7 @@ import * as svc from '../services/writersRoom/local.js';import * as catalogExtraction from '../services/catalogExtraction.js';import * as charSvc from '../services/writersRoom/characters.js';import * as placesSvc from '../services/writersRoom/places.js';+import * as objectsSvc from '../services/writersRoom/objects.js';import * as liveSvc from '../services/writersRoom/liveDirector.js';import writersRoomRoutes from './writersRoom.js';@@ -133,6 +141,25 @@ describe('writersRoom routes', () => {});describe('works', () => {+ it('GET /works returns the plain array by default', async () => {+ const r = await request(app).get('/api/writers-room/works');+ expect(r.status).toBe(200);+ expect(r.body).toEqual([{ id: 'wr-work-1', title: 'A' }]);+ });++ it('GET /works returns a bounded envelope when pagination is requested', async () => {+ svc.listWorks.mockResolvedValueOnce(+ Array.from({ length: 5 }, (_, i) => ({ id: `wr-work-${i}`, title: `W${i}` }))+ );+ const r = await request(app).get('/api/writers-room/works?limit=2&offset=1');+ expect(r.status).toBe(200);+ expect(r.body.items).toHaveLength(2);+ expect(r.body.items[0].id).toBe('wr-work-1');+ expect(r.body.total).toBe(5);+ expect(r.body.limit).toBe(2);+ expect(r.body.offset).toBe(1);+ });+it('POST /works rejects unknown kind', async () => {const r = await request(app).post('/api/writers-room/works').send({ title: 'X', kind: 'manifesto' });expect(r.status).toBe(400);@@ -340,6 +367,62 @@ describe('writersRoom routes', () => {});});+ describe('objects', () => {+ it('GET /works/:id/objects returns the bible', async () => {+ const r = await request(app).get('/api/writers-room/works/wr-work-1/objects');+ expect(r.status).toBe(200);+ expect(r.body[0].id).toBe('wr-object-1');+ expect(objectsSvc.listObjects).toHaveBeenCalledWith('wr-work-1');+ });++ it('POST /works/:id/objects rejects empty name (schema validation)', async () => {+ const r = await request(app).post('/api/writers-room/works/wr-work-1/objects').send({ name: '' });+ expect(r.status).toBe(400);+ expect(objectsSvc.createObject).not.toHaveBeenCalled();+ });++ it('POST /works/:id/objects rejects extra/unknown fields (strict schema)', async () => {+ const r = await request(app)+ .post('/api/writers-room/works/wr-work-1/objects')+ .send({ name: 'The Locket', wat: 'not allowed' });+ expect(r.status).toBe(400);+ });++ it('POST /works/:id/objects accepts a valid payload', async () => {+ const r = await request(app)+ .post('/api/writers-room/works/wr-work-1/objects')+ .send({ name: 'The Locket', significance: 'A family heirloom' });+ expect(r.status).toBe(201);+ expect(objectsSvc.createObject).toHaveBeenCalledWith('wr-work-1', {+ name: 'The Locket',+ significance: 'A family heirloom',+ });+ });++ it('PATCH /works/:id/objects/:objectId forwards a partial update', async () => {+ const r = await request(app)+ .patch('/api/writers-room/works/wr-work-1/objects/wr-object-1')+ .send({ description: 'Tarnished silver, engraved initials' });+ expect(r.status).toBe(200);+ expect(objectsSvc.updateObject).toHaveBeenCalledWith('wr-work-1', 'wr-object-1', {+ description: 'Tarnished silver, engraved initials',+ });+ });++ it('PATCH /works/:id/objects/:objectId rejects empty name', async () => {+ const r = await request(app)+ .patch('/api/writers-room/works/wr-work-1/objects/wr-object-1')+ .send({ name: ' ' });+ expect(r.status).toBe(400);+ });++ it('DELETE /works/:id/objects/:objectId forwards to the service', async () => {+ const r = await request(app).delete('/api/writers-room/works/wr-work-1/objects/wr-object-1');+ expect(r.status).toBe(200);+ expect(objectsSvc.deleteObject).toHaveBeenCalledWith('wr-work-1', 'wr-object-1');+ });+ });+describe('promote-to-pipeline', () => {it('POST /works/:id/promote-to-pipeline returns 201 with series + issue on fresh promote', async () => {const promoter = await import('../services/writersRoom/promoteToPipeline.js');diff --git a/server/services/rounds.js b/server/services/rounds.jsindex 1d5d0d8339..e838480cb2 100644--- a/server/services/rounds.js+++ b/server/services/rounds.js@@ -10,17 +10,29 @@* "Security Model"), so a per-file write queue serializes the read-modify-write* cycle rather than guarding against competing humans.*- * Shape bounds are exported so routes/rounds.js builds its Zod schema from the- * same source — sanitize-on-read and validate-at-the-boundary agree by- * construction. The rhythm-shape and layer id vocabularies mirror- * client/src/lib/songCraft.js; unknown ids are accepted (free-text fallback)- * so a client on a newer/older songCraft revision can't 400.+ * Shape bounds + sanitize helpers live in lib/roundsValidation.js and are+ * re-exported here so routes/rounds.js builds its Zod schema from the same+ * source — sanitize-on-read and validate-at-the-boundary agree by+ * construction. This file keeps the seed data (built-in rounds + canon-voice+ * derivation) and the file-backed CRUD.*/import { join } from 'path';import { randomUUID } from 'crypto';import { PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { sanitizeRound as sanitizeRoundRecord } from '../lib/roundsValidation.js';++// Shape bounds re-exported so routes/rounds.js and the seed migrations keep+// their existing import surface (svc.TITLE_MAX_LENGTH, …).+export {+ TITLE_MAX_LENGTH, ARTIST_MAX_LENGTH, KEY_MAX_LENGTH, FIELD_MAX_LENGTH,+ SCORE_MAX_LENGTH, SCORE_PARTS_MAX, LABEL_MAX_LENGTH, PART_MAX_LENGTH,+ ID_MAX_LENGTH, TEMPO_MIN, TEMPO_MAX, SECTIONS_MAX, LAYERS_MAX,+ RECORDINGS_MAX, REFERENCES_MAX, PARTNERS_MAX, URL_MAX_LENGTH,+ REF_SEGMENTS_MAX, PITCH_TRACK_MAX, PER_NOTE_GRADES_MAX,+ PROGRESS_HISTORY_MAX, PROGRESS_SCOPES_MAX, RECORDING_GRADES,+} from '../lib/roundsValidation.js';const STATE_PATH = join(PATHS.data, 'rounds.json');@@ -32,391 +44,11 @@ export const ERR_NOT_FOUND = 'NOT_FOUND';export const ERR_NOT_BUILTIN = 'NOT_BUILTIN';const makeErr = (message, code) => Object.assign(new Error(message), { code });-// --- Shape bounds (shared with routes/rounds.js#roundInputSchema) --------------export const TITLE_MAX_LENGTH = 200;-export const ARTIST_MAX_LENGTH = 200;-export const KEY_MAX_LENGTH = 24;-export const FIELD_MAX_LENGTH = 4000; // lyrics body / general notes-export const SCORE_MAX_LENGTH = 8000; // sheet-music notation (lead-sheet DSL)-export const SCORE_PARTS_MAX = 12; // harmony variations of the sheet music-export const LABEL_MAX_LENGTH = 120; // section + layer labels-export const PART_MAX_LENGTH = 60; // layer voice (e.g. "Bass")-export const ID_MAX_LENGTH = 60; // rhythm-shape / layer ids-export const TEMPO_MIN = 20;-export const TEMPO_MAX = 320;-export const SECTIONS_MAX = 60;-export const LAYERS_MAX = 24;-export const RECORDINGS_MAX = 64; // saved vocal takes for layered playback-export const REFERENCES_MAX = 12; // reference links/videos (e.g. TikTok)-export const PARTNERS_MAX = 12; // partner-song ids (rounds sung together)-export const URL_MAX_LENGTH = 512; // uploaded-file path/url-// Reference-audio analysis (#2106): labeled time ranges on a reference's-// attached audio ("0:00–0:14 melody alone"). Bounded so a hand-edited file-// can't balloon a reference; a layered TikTok build rarely has more than a-// handful of voice entrances.-export const REF_SEGMENTS_MAX = 24; // labeled time ranges per reference-// Per-take pitch analysis (#1027). The pitch track is a DOWNSAMPLED tuner trace-// kept for replay/training so it isn't recomputed on every open; bound it so a-// long take can't bloat data/rounds.json. `accuracy.perNote` mirrors the-// color-match grade-per-note array (#1025), bounded the same way a score can't-// be arbitrarily long.-export const PITCH_TRACK_MAX = 4000; // downsampled tuner samples per take-export const PER_NOTE_GRADES_MAX = 2000; // per-note color-match grades per take-// Training progress (#1028). `progress.history` maps a training scope (a-// section id or the whole-song sentinel) to a bounded array of graded attempts.-// Mirrors client/src/lib/songProgress.js HISTORY_MAX (kept window per scope) and-// caps the number of distinct scopes so a hand-edited file can't balloon the-// record. An attempt is `{ percentInTune, graded, at }`.-export const PROGRESS_HISTORY_MAX = 50; // attempts kept per scope-export const PROGRESS_SCOPES_MAX = 80; // distinct training scopes tracked-// Valid color-match grades — mirrors client/src/lib/colorMatch.js GRADE. An-// unrecognized grade is dropped (a newer/older client vocabulary can't 400 or-// poison the persisted array).-export const RECORDING_GRADES = ['in-tune', 'close', 'off', 'missed', 'pending'];--// Trim a string field, returning '' for non-strings. Mirrors the-// absent-vs-empty rule in CLAUDE.md: callers decide whether '' clears.-const trimField = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');--// Clamp an integer tempo into the supported band; null when unparseable so a-// song without a tempo stays distinct from one pinned to a bound.-const sanitizeTempo = (v) => {- if (typeof v !== 'number' || !Number.isFinite(v)) return null;- return Math.max(TEMPO_MIN, Math.min(TEMPO_MAX, Math.round(v)));-};--// One lyric/structure section ({ id, label, lyrics }). Label defaults from the-// id when blank so a section card is never headerless. Drops shapeless entries.-const sanitizeSection = (s) => {- if (!s || typeof s !== 'object') return null;- const label = trimField(s.label, LABEL_MAX_LENGTH);- const lyrics = trimField(s.lyrics, FIELD_MAX_LENGTH);- if (!label && !lyrics) return null;- return {- id: trimField(s.id, ID_MAX_LENGTH) || `sec-${randomUUID().slice(0, 8)}`,- label: label || 'Section',- lyrics,- };-};--// One voice layer the user is arranging ({ id, label, part, notes }). `id`-// references a songCraft VOICE_LAYERS entry when known but is free-text-safe.-const sanitizeLayer = (l) => {- if (!l || typeof l !== 'object') return null;- const label = trimField(l.label, LABEL_MAX_LENGTH);- const part = trimField(l.part, PART_MAX_LENGTH);- const notes = trimField(l.notes, FIELD_MAX_LENGTH);- if (!label && !part && !notes) return null;- return {- id: trimField(l.id, ID_MAX_LENGTH) || `layer-${randomUUID().slice(0, 8)}`,- label: label || 'Layer',- part,- notes,- };-};--// A finite number or null — used by the pitch-analysis fields so a missing-// sample component (e.g. a silent frame with no detectable pitch) round-trips-// as null rather than NaN/0.-const finiteOrNull = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);--// One downsampled tuner sample ({ tMs, hz, cents, clarity }) from a take's-// pitch trace (#1027). `tMs` is the elapsed time in the take; hz/cents/clarity-// are the detected pitch, cents-from-target, and confidence. Drops shapeless-// entries; a sample with no time and no pitch carries no information.-const sanitizePitchSample = (s) => {- if (!s || typeof s !== 'object') return null;- const tMs = finiteOrNull(s.tMs);- const hz = finiteOrNull(s.hz);- if (tMs === null && hz === null) return null;- return {- tMs: tMs === null ? 0 : Math.max(0, Math.round(tMs)),- hz,- cents: finiteOrNull(s.cents),- clarity: finiteOrNull(s.clarity),- };-};--// The per-take accuracy summary (#1027), mirroring color-match's-// summarizeAccuracy output ({ percentInTune, graded, counts, perNote }). All-// fields are optional/absent-tolerant — a take recorded before color-match (or-// without scoring) has no accuracy at all, which is distinct from a scored take-// that graded zero notes (graded: 0). Returns null when there's nothing to-// persist so the field stays absent rather than an empty husk.-const sanitizeAccuracy = (a) => {- if (!a || typeof a !== 'object') return null;- const counts = a.counts && typeof a.counts === 'object' ? a.counts : {};- const perNote = (Array.isArray(a.perNote) ? a.perNote : [])- .map((g) => trimField(g, LABEL_MAX_LENGTH))- .filter((g) => RECORDING_GRADES.includes(g))- .slice(0, PER_NOTE_GRADES_MAX);- const clampPercent = finiteOrNull(a.percentInTune);- const clampGraded = finiteOrNull(a.graded);- return {- percentInTune: clampPercent === null ? 0 : Math.max(0, Math.min(100, Math.round(clampPercent))),- graded: clampGraded === null ? perNote.length : Math.max(0, Math.round(clampGraded)),- counts: {- 'in-tune': Math.max(0, Math.round(finiteOrNull(counts['in-tune']) ?? 0)),- close: Math.max(0, Math.round(finiteOrNull(counts.close) ?? 0)),- off: Math.max(0, Math.round(finiteOrNull(counts.off) ?? 0)),- missed: Math.max(0, Math.round(finiteOrNull(counts.missed) ?? 0)),- },- perNote,- };-};--// One training attempt ({ percentInTune, graded, at }) — a graded take of one-// scope (a section or the whole song). Numbers are clamped; an attempt with no-// graded notes carries no signal and is dropped (mirrors songProgress.js, which-// never records a zero-note take). Returns null for a shapeless/empty attempt.-const sanitizeAttempt = (a) => {- if (!a || typeof a !== 'object') return null;- const graded = finiteOrNull(a.graded);- if (graded === null || graded <= 0) return null;- const pct = finiteOrNull(a.percentInTune);- return {- percentInTune: pct === null ? 0 : Math.max(0, Math.min(100, Math.round(pct))),- graded: Math.max(0, Math.round(graded)),- at: typeof a.at === 'string' ? a.at : new Date().toISOString(),- };-};--// Training progress (#1028): `{ history: { <scope>: [attempt…] } }`. Each scope-// (a section id or the whole-song sentinel) keys a bounded, newest-last attempt-// list. Absent on legacy/untrained songs — returns null when there's nothing to-// persist so the field stays off the record (no wave of empty objects). The-// number of scopes and the per-scope history are both bounded so a hand-edited-// file can't grow the record without limit. Derived stats (best/avg/learned)-// are recomputed client-side from this history on read, never stored.-const sanitizeProgress = (p) => {- if (!p || typeof p !== 'object') return null;- const rawHistory = p.history && typeof p.history === 'object' ? p.history : {};- const history = {};- let scopeCount = 0;- for (const [scope, attempts] of Object.entries(rawHistory)) {- if (scopeCount >= PROGRESS_SCOPES_MAX) break;- const key = trimField(scope, ID_MAX_LENGTH);- // Skip empty keys and the prototype-pollution-prone keys — a section id is- // always `sec-N` (or the `__whole__` sentinel), never one of these, so a- // hand-edited `__proto__`/`constructor` scope is a malformed file, not data.- if (!key || key === '__proto__' || key === 'constructor' || key === 'prototype') continue;- const cleaned = sanitizeList(attempts, sanitizeAttempt, PROGRESS_HISTORY_MAX);- if (!cleaned.length) continue;- history[key] = cleaned;- scopeCount += 1;- }- return Object.keys(history).length ? { history } : null;-};--// One saved vocal take ({ id, layerId, filename, label, durationMs, peak,-// mutedByDefault }). `filename` is the /api/uploads file name the audio is-// served from; a recording without one is meaningless, so it's dropped.-// `layerId` ties a take to a voice layer for the layered-playback mixer (free-// text — empty means "unassigned"). Numbers are coerced/clamped; bad values-// fall to sensible defaults rather than throwing.-//-// Optional pitch analysis (#1027): `pitchTrack` (a bounded, downsampled tuner-// trace) and `accuracy` (a color-match summary) are persisted so the tuner-// history and grading aren't recomputed on every open. Both are absent on-// legacy takes and on takes recorded without scoring — the fields only appear-// when there's analysis to keep, so a pre-feature record reads back unchanged.-const sanitizeRecording = (r) => {- if (!r || typeof r !== 'object') return null;- const filename = trimField(r.filename, URL_MAX_LENGTH);- if (!filename) return null;- const durationMs = typeof r.durationMs === 'number' && Number.isFinite(r.durationMs)- ? Math.max(0, Math.round(r.durationMs)) : 0;- const peak = typeof r.peak === 'number' && Number.isFinite(r.peak)- ? Math.max(0, Math.min(1, r.peak)) : 0;- const rec = {- id: trimField(r.id, ID_MAX_LENGTH) || `rec-${randomUUID().slice(0, 8)}`,- layerId: trimField(r.layerId, ID_MAX_LENGTH),- label: trimField(r.label, LABEL_MAX_LENGTH),- filename,- durationMs,- peak,- muted: r.muted === true,- createdAt: typeof r.createdAt === 'string' ? r.createdAt : new Date().toISOString(),- };- // Absent ⇒ omit (legacy/unscored take); present ⇒ sanitize + bound via the- // shared sanitizeList. Keeping the keys off the object when there's no- // analysis avoids a wave of empty arrays in data/rounds.json on every take.- const pitchTrack = sanitizeList(r.pitchTrack, sanitizePitchSample, PITCH_TRACK_MAX);- if (pitchTrack.length) rec.pitchTrack = pitchTrack;- const accuracy = sanitizeAccuracy(r.accuracy);- if (accuracy) rec.accuracy = accuracy;- return rec;-};--// One labeled time range on a reference's attached audio (#2106):-// `{ layerId, startMs, endMs }` — "this span is the bass part alone". `layerId`-// ties the span to a voice layer (free text, same convention as recordings);-// times are clamped non-negative integers and a zero/negative-length span is-// dropped (it selects no audio). Used by the client's analysis view to extract-// a per-layer pitch track from the span.-//-// Optional stacked-mix backing window (#2121): `bgStartMs`/`bgEndMs` mark a-// slice just BEFORE the voice enters (the earlier layers alone) so the client-// can spectral-subtract the backing and extract a voice that never appears-// solo. Purely additive — the pair only persists when it forms a valid range-// that ENDS AT OR BEFORE the segment start (`bgEndMs <= startMs`); a window-// overlapping the segment would already contain the new voice, so subtracting-// it would cancel the very part being extracted. A legacy solo segment (no bg-// fields) round-trips unchanged.-const sanitizeRefSegment = (s) => {- if (!s || typeof s !== 'object') return null;- const startRaw = finiteOrNull(s.startMs);- const endRaw = finiteOrNull(s.endMs);- if (startRaw === null || endRaw === null) return null;- const startMs = Math.max(0, Math.round(startRaw));- const endMs = Math.max(0, Math.round(endRaw));- if (endMs <= startMs) return null;- const seg = {- layerId: trimField(s.layerId, ID_MAX_LENGTH),- startMs,- endMs,- };- const bgStartRaw = finiteOrNull(s.bgStartMs);- const bgEndRaw = finiteOrNull(s.bgEndMs);- if (bgStartRaw !== null && bgEndRaw !== null) {- const bgStartMs = Math.max(0, Math.round(bgStartRaw));- const bgEndMs = Math.max(0, Math.round(bgEndRaw));- if (bgEndMs > bgStartMs && bgEndMs <= startMs) {- seg.bgStartMs = bgStartMs;- seg.bgEndMs = bgEndMs;- }- }- return seg;-};--// One reference link/video ({ id, url, label, note }) — external study-// material for the song (a TikTok performance, a tutorial, a chord chart).-// `url` is required (a reference without a target is meaningless); label/note-// are free text. The client decides how to render each url (TikTok videos-// embed; everything else is a link).-//-// Optional reference-audio analysis (#2106): `audioFilename` (an /api/uploads-// file, same convention as recordings[].filename) and `segments` (bounded-// labeled time ranges) only appear when set — absent keys stay absent so a-// legacy/pre-feature reference round-trips byte-identical (purely additive,-// no migration).-const sanitizeReference = (r) => {- if (!r || typeof r !== 'object') return null;- const url = trimField(r.url, URL_MAX_LENGTH);- // Require an http(s) scheme — defense-in-depth so a hand-edited file or a- // non-PortOS writer can't persist a javascript:/data: URL that a renderer- // might trust (mirrors the client's isHttpUrl guard).- if (!/^https?:\/\//i.test(url)) return null;- const ref = {- id: trimField(r.id, ID_MAX_LENGTH) || `ref-${randomUUID().slice(0, 8)}`,- url,- label: trimField(r.label, LABEL_MAX_LENGTH),- note: trimField(r.note, FIELD_MAX_LENGTH),- };- const audioFilename = trimField(r.audioFilename, URL_MAX_LENGTH);- if (audioFilename) {- ref.audioFilename = audioFilename;- // Segments are time ranges INTO the attached audio — meaningless without- // it. Persisting them only alongside an audioFilename makes the invariant- // structural: removing the audio clears them, so stale ranges can't- // resurrect against a later, different recording.- const segments = sanitizeList(r.segments, sanitizeRefSegment, REF_SEGMENTS_MAX);- if (segments.length) ref.segments = segments;- // A MuScriptor transcription OF the attached audio (an /api/uploads .mid- // pointer) — same structural invariant as segments: derived from this- // audio, so removing the audio drops it and a stale transcription can't- // resurrect against a later, different recording.- const midiFilename = trimField(r.midiFilename, URL_MAX_LENGTH);- if (midiFilename) ref.midiFilename = midiFilename;- }- return ref;-};--// One sheet-music part — a harmony variation of the song's base score-// ({ id, label, role, score }). `score` is the PortOS lead-sheet DSL (same-// format as the base `score`); a part without notation is meaningless, so it's-// dropped. `role` references a songCraft HARMONY_PARTS id when known (bass,-// mid-harmony-1, high-harmony-1 …) but is free-text-safe so a newer/older client-// vocabulary can't 400. `label` defaults from the role/`Part` so a part card is-// never headerless.-const sanitizeScorePart = (p) => {- if (!p || typeof p !== 'object') return null;- const score = trimField(p.score, SCORE_MAX_LENGTH);- if (!score) return null;- const label = trimField(p.label, LABEL_MAX_LENGTH);- const role = trimField(p.role, ID_MAX_LENGTH);- return {- id: trimField(p.id, ID_MAX_LENGTH) || `part-${randomUUID().slice(0, 8)}`,- label: label || 'Part',- role,- score,- };-};--const sanitizeList = (arr, fn, max) =>- (Array.isArray(arr) ? arr : [])- .map(fn)- .filter(Boolean)- .slice(0, max);--// Partner-song ids — the "symbiotic" link that lets rounds declare which other-// songs they're sung together with (a quodlibet stack). Keeps only non-empty-// strings, dedupes, and drops a self-reference (a song can't partner itself —-// that would make the round-stack render the same song twice). `selfId` is the-// owning song's id so the self-drop survives a hand-edited file.-const sanitizePartnerIds = (arr, selfId) => {- const seen = new Set();- return (Array.isArray(arr) ? arr : [])- .map((v) => trimField(v, ID_MAX_LENGTH))- .filter((id) => id && id !== selfId && !seen.has(id) && seen.add(id))- .slice(0, PARTNERS_MAX);-};--// Project a stored or inbound record onto the canonical song shape. Used on-// read (defends hand-edited JSON) and on write (normalizes the input).-export const sanitizeRound = (raw) => {- if (!raw || typeof raw !== 'object') return null;- const id = trimField(raw.id, ID_MAX_LENGTH);- if (!id) return null;- const song = {- id,- title: trimField(raw.title, TITLE_MAX_LENGTH) || 'Untitled round',- artist: trimField(raw.artist, ARTIST_MAX_LENGTH),- key: trimField(raw.key, KEY_MAX_LENGTH),- tempo: sanitizeTempo(raw.tempo),- rhythmShapeId: trimField(raw.rhythmShapeId, ID_MAX_LENGTH),- notation: trimField(raw.notation, FIELD_MAX_LENGTH),- // Sheet-music notation in the PortOS lead-sheet DSL (client/src/lib/- // scoreNotation.js). A bounded free-text string — the client parses + renders- // it; the server only length-caps it, so a newer/older DSL revision can't 400.- score: trimField(raw.score, SCORE_MAX_LENGTH),- // Harmony variations of the base `score` (bass, mid/high harmonies …), each- // its own lead-sheet DSL. Absent ⇒ [] — purely additive, so an older peer or- // a pre-feature record reads back as a song with no parts (no migration of- // the on-disk shape needed; the field simply appears when the user adds one).- scoreParts: sanitizeList(raw.scoreParts, sanitizeScorePart, SCORE_PARTS_MAX),- notes: trimField(raw.notes, FIELD_MAX_LENGTH),- learned: raw.learned === true,- sections: sanitizeList(raw.sections, sanitizeSection, SECTIONS_MAX),- layers: sanitizeList(raw.layers, sanitizeLayer, LAYERS_MAX),- recordings: sanitizeList(raw.recordings, sanitizeRecording, RECORDINGS_MAX),- references: sanitizeList(raw.references, sanitizeReference, REFERENCES_MAX),- // Ids of other songs this one is sung together with (round-stack partners).- partnerRoundIds: sanitizePartnerIds(raw.partnerRoundIds, id),- // Derived from the shipped-seed id set, NOT from `raw` — so the flag can't- // be lost on edit or spoofed on a hand-edited custom song. A built-in- // default can be restored to its shipped content via refreshRoundFromTemplate.- builtIn: BUILTIN_ROUND_IDS.has(id),- createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : new Date().toISOString(),- updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : new Date().toISOString(),- };- // Training progress (#1028). Absent ⇒ omit (legacy/untrained song); present ⇒- // attach the bounded per-scope attempt history. Keeping the key off the record- // when there's no progress avoids an empty husk on every untrained song.- const progress = sanitizeProgress(raw.progress);- if (progress) song.progress = progress;- return song;-};+// Project a stored or inbound record onto the canonical song shape, stamping+// `builtIn` from the shipped-seed id set. Used on read (defends hand-edited+// JSON) and on write (normalizes the input). The sanitizer itself lives in+// lib/roundsValidation.js.+export const sanitizeRound = (raw) => sanitizeRoundRecord(raw, BUILTIN_ROUND_IDS);// Worked-example harmony stack for the built-in "500 Miles" — the chord-tone// voicing the AI-derive feature is meant to produce (the song the user pointed@@ -875,7 +507,7 @@ export const BUILTIN_ROUND_IDS = new Set(SEED_ROUNDS.map((s) => s.id));const seedTemplate = (id) => SEED_ROUNDS.find((s) => s.id === id) || null;// Serialize the read-modify-write cycle so two mutations issued back-to-back-// (e.g. a rename PUT followed by a layer edit) each merge against the freshest+// (e.g. a rename PATCH followed by a layer edit) each merge against the freshest// persisted state instead of racing on a stale snapshot. Single-user, so this// is re-entrancy hygiene, not a multi-actor lock (see CLAUDE.md Security Model).const enqueue = createFileWriteQueue();diff --git a/server/services/universeBuilderRefine.js b/server/services/universeBuilderRefine.jsindex d69fa94de6..4ab8d4ab0c 100644--- a/server/services/universeBuilderRefine.js+++ b/server/services/universeBuilderRefine.js@@ -12,6 +12,7 @@*/import { ServerError } from "../lib/errorHandler.js";+import { findBalancedBlocks, tryParseWithRepair } from "../lib/jsonExtract.js";import { assertProvider, resolveProviderAndModel, resolveEffectiveModel, runPromptThroughProvider, assertVisionRunUsedImages } from "../lib/promptRunner.js";import { resolveAPIProvider } from "../lib/aiProvider.js";import {@@ -54,11 +55,12 @@ const cleanChanges = (changes) =>.slice(0, MAX_CHANGES): [];-// Same brace-walker as mediaPromptRefiner: Codex CLI echoes the prompt to+// Same extractor shape as mediaPromptRefiner: Codex CLI echoes the prompt to// stdout before the model response, and the prompt itself contains a JSON// schema example whose braces balance but whose contents are placeholder-// text. Walk every brace-balanced block in order and return the first that-// looks like a refinement payload (object with a `starterPrompt` string).+// text. Walk every brace-balanced block in order (lib/jsonExtract.js) and+// return the first that looks like a refinement payload (object with a+// `starterPrompt` string).const isPlaceholder = (s) => typeof s === "string" && /^\s*<.+>\s*$/.test(s);function extractRefinementJson(raw) {@@ -68,54 +70,32 @@ function extractRefinementJson(raw) {const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/);if (fence) s = fence[1].trim();- let i = 0;- let lastErr;+ const candidates = findBalancedBlocks(s);+ if (!candidates.length) candidates.push(s);++ // Walk every balanced block ourselves rather than calling the shared+ // extractJson — we need a tri-state outcome (real refinement, placeholder+ // echo, or parse error) to surface the "schema placeholder" error message+ // that helps users pick a stronger model. extractJson's shape predicate+ // collapses placeholder-vs-real into a single fallback path.let placeholderSeen = false;- while (i < s.length) {- const start = s.indexOf("{", i);- if (start === -1) break;- let depth = 0;- let inString = false;- let escaped = false;- let end = -1;- for (let j = start; j < s.length; j += 1) {- const ch = s[j];- if (inString) {- if (escaped) escaped = false;- else if (ch === "\\") escaped = true;- else if (ch === '"') inString = false;- continue;- }- if (ch === '"') {- inString = true;- continue;- }- if (ch === "{") depth += 1;- else if (ch === "}") {- depth -= 1;- if (depth === 0) {- end = j;- break;- }- }+ let lastErr;+ for (const block of candidates) {+ const result = tryParseWithRepair(block);+ if (result.error) {+ lastErr = result.error;+ continue;}- if (end === -1) break;- const block = s.slice(start, end + 1);- try {- const value = JSON.parse(block);- if (- value &&- typeof value === "object" &&- typeof value.starterPrompt === "string"- ) {- if (isPlaceholder(value.starterPrompt)) {- placeholderSeen = true;- } else return value;- }- } catch (e) {- lastErr = e;+ const { value } = result;+ if (+ value &&+ typeof value === "object" &&+ typeof value.starterPrompt === "string"+ ) {+ if (isPlaceholder(value.starterPrompt)) {+ placeholderSeen = true;+ } else return value;}- i = end + 1;}if (placeholderSeen) {throw new Error(