Skip to content

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

feat([issue-1770]): federate musicVideoProject records across sync peers

[._.]/ Adam Eivyadc9be45fec7
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 0f5b148877..d820691ac8 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -7,7 +7,7 @@ import {
Database, Brain, CheckCircle2, AlertCircle, Clock,
RefreshCcw, Timer,
Target, Sword, Fingerprint, HeartPulse, ChevronDown, ChevronRight,
- Lock, Globe, Info, Sparkles, Film, Images, Library, BookOpen, FilePen, Music, Music2, Disc3, Clapperboard, Palette, BookText, FolderTree
+ Lock, Globe, Info, Sparkles, Film, Images, Library, BookOpen, FilePen, Music, Music2, Disc3, Clapperboard, Palette, BookText, FolderTree, Video
} from 'lucide-react';
import toast from '../components/ui/Toast';
import Pill from '../components/ui/Pill';
@@ -526,13 +526,14 @@ const SYNC_CATEGORY_META = [
{ key: 'writersRoomWorks', label: 'Writers Room', icon: BookText, description: 'Writers Room works: manuscripts + draft versions + prose bodies (PostgreSQL)' },
{ key: 'writersRoomFolders', label: 'Writers Room Folders', icon: FolderTree, description: 'Writers Room library folders: names + nesting (PostgreSQL)' },
{ key: 'writersRoomExercises', label: 'Writers Room Sprints', icon: Timer, description: 'Writers Room writing-sprint sessions + appended prose (PostgreSQL)' },
+ { key: 'musicVideoProjects', label: 'Music Video', icon: Video, description: 'Music Video projects: director board + beat-aligned scenes (PostgreSQL)' },
{ key: 'catalog', label: 'Catalog', icon: Library, description: 'Creative ingredients catalog: orphan ingredients + ref links (PostgreSQL)' }
];
// Snapshot categories — exclude the per-record / delta-based categories that
// have no 60s snapshot checksum: brain + memory (delta), catalog + authors/music
// (PostgreSQL, per-record peer-push only — no snapshot loop).
-const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors', 'artists', 'albums', 'tracks', 'creativeDirectorProjects', 'moodBoards', 'writersRoomWorks', 'writersRoomFolders', 'writersRoomExercises']);
+const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors', 'artists', 'albums', 'tracks', 'creativeDirectorProjects', 'moodBoards', 'writersRoomWorks', 'writersRoomFolders', 'writersRoomExercises', 'musicVideoProjects']);
const SNAPSHOT_CATEGORIES = SYNC_CATEGORY_META.filter(m => !NON_SNAPSHOT_KEYS.has(m.key));
// Indicator backed by REAL coverage diffing (record IDs vs confirmed pushes),
diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.js
index 7b2ccea07d..a6645f4994 100644
--- a/server/lib/conflictJournal.js
+++ b/server/lib/conflictJournal.js
@@ -365,6 +365,18 @@ export const RESTORABLE_FIELDS = Object.freeze({
// Server-owned / structural fields are excluded (`id`/`createdAt`/`startedAt`/
// the LWW-tombstone trio). `writersRoomExercise` matches the record kind.
writersRoomExercise: ['workId', 'prompt', 'durationSeconds', 'startingWords', 'endingWords', 'wordsAdded', 'appendedText', 'status', 'finishedAt'],
+ // Music Video projects (#1770): the user-authored config + creative content the
+ // merge can restore. `scenes[]` (the beat-aligned director board with prompts)
+ // carries the bulk of the work, alongside name/status/mode/trackId/
+ // uploadedAudioFilename/concept. Server-owned / machine-managed fields are
+ // excluded — `id`/`createdAt`/the LWW-tombstone trio are structural,
+ // `renderHistoryId` is a derived output pointer, and `audioAnalysis` is the
+ // machine-derived beat cache (regenerated from the audio, not hand-authored).
+ // The whole record is hashed for DETECTION by contentHashForRecord (no scalar
+ // narrowing); this set is what the Conflicts UI offers for restore.
+ // `musicVideoProject` matches the record kind and updateProject (via
+ // applyProjectPatch's wholesale spread) accepts every field here.
+ musicVideoProject: ['name', 'status', 'mode', 'trackId', 'uploadedAudioFilename', 'concept', 'scenes'],
});
const present = (v) => v !== undefined;
diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.js
index 54568bb94f..4d8c8dc791 100644
--- a/server/lib/peerSyncValidation.js
+++ b/server/lib/peerSyncValidation.js
@@ -15,7 +15,7 @@ import { catalogSyncIngredientSchema, catalogSyncRefSchema } from './catalogVali
// subscriptions target another PortOS instance over Tailnet.
export const peerSubscribeSchema = z.object({
peerId: z.string().trim().min(1).max(120),
- recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise']),
+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject']),
recordId: z.string().trim().min(1).max(120),
}).strict();
@@ -238,6 +238,16 @@ const writersRoomExercisePushSchema = z.object({
kind: z.literal('writersRoomExercise'),
...peerSyncPushBase,
}).strict();
+// Music Video projects (#1770) push the bare record (metadata + beat-aligned
+// scenes[]) — no bundled children/linked collection, and referenced media
+// (uploaded audio, scene images/rendered videos) is NOT bundled in this phase,
+// so the base shape alone suffices and the sender always ships `assetManifest:
+// []` (`.strict()` rejects smuggled bundle keys, same posture as
+// creativeDirectorProject/writersRoomFolder).
+const musicVideoProjectPushSchema = z.object({
+ kind: z.literal('musicVideoProject'),
+ ...peerSyncPushBase,
+}).strict();
export const peerSyncPushSchema = z.discriminatedUnion('kind', [
universePushSchema,
seriesPushSchema,
@@ -251,13 +261,14 @@ export const peerSyncPushSchema = z.discriminatedUnion('kind', [
writersRoomWorkPushSchema,
writersRoomFolderPushSchema,
writersRoomExercisePushSchema,
+ musicVideoProjectPushSchema,
]);
// Manual sync action schemas — used by POST /sync-record, /sync-now, /pull-metadata.
export const peerSyncRecordSchema = z.object({
peerId: z.string().trim().min(1).max(120),
- recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise']),
+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject']),
recordId: z.string().trim().min(1).max(200),
}).strict();
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 128e9197d0..d71e66a456 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -347,6 +347,19 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// their existing `startedAt`/`finishedAt` (see sanitizeExerciseForSync). The
// FIRST incompatible exercise-shape change MUST bump this to 2.
writersRoomExercises: 1,
+ // v1 = Music Video projects (PostgreSQL `music_video_projects`) federated via
+ // the per-record peer-sync push pipeline (record kind `musicVideoProject`, sync
+ // category `musicVideoProjects`, #1770 — follow-up to #1760 Phase 1). Same
+ // posture as `creativeDirectorProjects`/`writersRoomFolders`: a brand-NEW synced
+ // record type with its own per-category gate — a v1 sender pushing to a ≤v0
+ // (pre-feature) receiver is sender-ahead on `musicVideoProjects` and gets a 412
+ // (only that category pauses); a v1 receiver still accepts a ≤v0 sender
+ // (pre-feature peers never push a `musicVideoProject`). The project body
+ // (metadata + beat-aligned scenes) is LWW-overwritten whole; referenced media
+ // (uploaded audio, scene images/rendered videos) is NOT bundled in this phase —
+ // it federates via its own channels / a follow-up. The FIRST incompatible
+ // project-shape change MUST bump this to 2.
+ musicVideoProjects: 1,
// v1 = standalone media-library federation (#1566). NOT a record kind — it's
// the wire contract for the library-level asset manifest a full-sync peer
// advertises at GET /api/peer-sync/library-manifest. The receiver-pull sweep
@@ -436,6 +449,7 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({
writersRoomWork: Object.freeze(['writersRoomWorks']),
writersRoomFolder: Object.freeze(['writersRoomFolders']),
writersRoomExercise: Object.freeze(['writersRoomExercises']),
+ musicVideoProject: Object.freeze(['musicVideoProjects']),
});
/**
diff --git a/server/lib/syncWire.js b/server/lib/syncWire.js
index 12e1d592f2..d3cf5afa77 100644
--- a/server/lib/syncWire.js
+++ b/server/lib/syncWire.js
@@ -165,7 +165,8 @@ export function sanitizeRecordForWire(kind, record) {
case 'creativeDirectorProject':
case 'moodBoard':
case 'writersRoomFolder':
- case 'writersRoomExercise': {
+ case 'writersRoomExercise':
+ case 'musicVideoProject': {
// Persona/music/creative-director/mood-board records: like mediaCollection,
// no `ephemeral` flag — always wire-syncable when present. Strip-then-tail-
// re-add the soft-delete pair for byte-stable checksums. The whole record
@@ -176,7 +177,8 @@ export function sanitizeRecordForWire(kind, record) {
// record LWW contract; a moodBoard (name/description/items) is the same.
// Writers Room folders + exercises (#1645) are also body-less whole-record
// LWW kinds with no ephemeral counters — they wire identically (no liveMode
- // strip like writersRoomWork below).
+ // strip like writersRoomWork below). A musicVideoProject (#1770:
+ // metadata + beat-aligned scenes[]) is the same whole-record LWW contract.
const { deleted: _d, deletedAt: _da, ...rest } = record;
return { ...rest, ...sanitizeSoftDeleteFields(record) };
}
diff --git a/server/routes/instances.js b/server/routes/instances.js
index 3102412cfc..4bf43a53cf 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -70,6 +70,7 @@ const syncCategoriesSchema = z.object({
writersRoomWorks: z.boolean().optional(),
writersRoomFolders: z.boolean().optional(),
writersRoomExercises: z.boolean().optional(),
+ musicVideoProjects: z.boolean().optional(),
catalog: z.boolean().optional()
}).optional();
diff --git a/server/services/conflictJournalResolver.js b/server/services/conflictJournalResolver.js
index 665cc417fb..96ab11cc96 100644
--- a/server/services/conflictJournalResolver.js
+++ b/server/services/conflictJournalResolver.js
@@ -36,6 +36,7 @@ import { updateSeries, ERR_NOT_FOUND as SERIES_NOT_FOUND } from './pipeline/seri
import { updateCollection, getCollection, ERR_NOT_FOUND as COLLECTION_NOT_FOUND } from './mediaCollections.js';
import { updateIssue, ERR_NOT_FOUND as ISSUE_NOT_FOUND } from './pipeline/issues.js';
import { updateProject } from './creativeDirector/local.js';
+import { updateProject as updateMusicVideoProject } from './musicVideo/projects.js';
import { restoreBoard } from './moodBoard/index.js';
import { updateWork, restoreFolder, restoreExercise } from './writersRoom/local.js';
@@ -134,6 +135,13 @@ async function applyToRecord(kind, recordId, patch, { replace = false } = {}) {
// merge-fields both apply faithfully through the same call. It validates +
// rejects a tombstoned row (404 → translateGone → ERR_TARGET_GONE).
await restoreBoard(recordId, patch).catch(translateGone);
+ } else if (kind === 'musicVideoProject') {
+ // updateProject does a wholesale spread (applyProjectPatch → touch), so the
+ // restorable scalars + scenes[] in the snapshot patch overwrite the live
+ // values faithfully — restore-all and merge-fields both apply through the
+ // same path. It validates `status` and rejects a missing/tombstoned row with
+ // the generic ServerError 'NOT_FOUND' (→ translateGone → ERR_TARGET_GONE).
+ await updateMusicVideoProject(recordId, patch).catch(translateGone);
} else if (kind === 'writersRoomWork') {
// updateWork applies the snapshot's title/kind/status/folderId/imageStyle/
// liveMode (the RESTORABLE_FIELDS set) through its allow-list + the liveMode
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index ca5d71563a..74cca33170 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -1113,6 +1113,10 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {
// RECORD_KIND_SCHEMA_CATEGORIES.writersRoomFolder / .writersRoomExercise.
'writersRoomFolders',
'writersRoomExercises',
+ // Music Video projects (#1770) → per-record peer-push only (no 60s
+ // file-snapshot category). Gated at applyIncomingPush via
+ // compareSchemaVersions / RECORD_KIND_SCHEMA_CATEGORIES.musicVideoProject.
+ 'musicVideoProjects',
// Standalone media library (#1566) → its own receiver-pull endpoint
// (GET /api/peer-sync/library-manifest), NOT the file-snapshot transfer.
// Versioned for the manifest envelope and gated by syncMediaLibraryFromPeer's
diff --git a/server/services/instances.js b/server/services/instances.js
index 3bfd64dee4..3155ce2d8b 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -262,6 +262,7 @@ const DEFAULT_SYNC_CATEGORIES = {
writersRoomWorks: false,
writersRoomFolders: false,
writersRoomExercises: false,
+ musicVideoProjects: false,
catalog: false
};
@@ -298,6 +299,7 @@ const PER_RECORD_CATEGORY_KINDS = Object.freeze([
['writersRoomWorks', 'writersRoomWork'],
['writersRoomFolders', 'writersRoomFolder'],
['writersRoomExercises', 'writersRoomExercise'],
+ ['musicVideoProjects', 'musicVideoProject'],
]);
export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, auth }) {
diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.js
index c660015b12..5a29a909f0 100644
--- a/server/services/musicVideo/projects.js
+++ b/server/services/musicVideo/projects.js
@@ -11,14 +11,18 @@
* NODE_ENV=test — both UNSUPPORTED for production. Tests boot without a DB,
* so they exercise the file backend.
*
- * Federation note: peer-sync of `musicVideoProject` records (record-event emit,
- * LWW merge, tombstone GC — the wiring the CD store carries) is a deliberate
- * follow-up, tracked as its own issue. The store is db-primary and fully usable
- * locally now; adding federation later is additive (the soft-delete fields are
- * already on the record). Until then this dispatcher does no record-event emit.
+ * Federation (#1770): peer-sync of `musicVideoProject` records mirrors the CD
+ * store — the structural mutators emit record events (announce on create,
+ * updated on edits, deleted on tombstone) routed through the recordEvents
+ * subscription adapter (a no-op until peerSync registers it at boot, so this
+ * store never imports peerSync and no load-order cycle forms). The backends
+ * carry the LWW merge (`mergeProjectsFromSync`) + tombstone GC
+ * (`pruneTombstonedProjects`); both are re-exported here for peerSync + the GC
+ * sweep. The soft-delete fields were already on the record, so this was additive.
*/
import { checkHealth, ensureSchema } from '../../lib/db.js';
+import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';
let backend = null;
let backendName = null;
@@ -51,6 +55,18 @@ export function getProjectsBackendName() {
return backendName;
}
+// Announce a newly-created project to the per-record peer-sync pipeline: emit the
+// 'updated' event so any existing subscription pushes it, AND auto-subscribe
+// every musicVideoProjects-enabled peer so brand-new projects (and their later
+// tombstones) propagate. Routed through the recordEvents subscription adapter (a
+// no-op until peerSync registers it at boot) so this store doesn't import
+// peerSync — peerSync statically imports mergeProjectsFromSync from here, so
+// importing it back would close a load-order cycle. Mirrors CD announceNewProject.
+function announceNewProject(id) {
+ emitRecordUpdated('musicVideoProject', id);
+ autoSubscribeRecordToAllPeers('musicVideoProject', id).catch(() => {});
+}
+
export async function listProjects(options = {}) {
return (await selectBackend()).listProjects(options);
}
@@ -59,34 +75,66 @@ export async function getProject(id, options = {}) {
return (await selectBackend()).getProject(id, options);
}
+/** Live project ids (or all when includeDeleted) — used by tombstone GC sweeps. */
+export async function listProjectIds(options = {}) {
+ return (await selectBackend()).listProjectIds(options);
+}
+
export async function createProject(input) {
- return (await selectBackend()).createProject(input);
+ const project = await (await selectBackend()).createProject(input);
+ announceNewProject(project.id);
+ return project;
}
export async function updateProject(id, patch) {
- return (await selectBackend()).updateProject(id, patch);
+ const next = await (await selectBackend()).updateProject(id, patch);
+ emitRecordUpdated('musicVideoProject', id);
+ return next;
}
export async function deleteProject(id) {
- return (await selectBackend()).deleteProject(id);
+ const result = await (await selectBackend()).deleteProject(id);
+ // Soft-delete tombstone — push the deletion to subscribed peers immediately.
+ emitRecordDeleted('musicVideoProject', id);
+ return result;
}
export async function setProjectAnalysis(id, analysis) {
- return (await selectBackend()).setProjectAnalysis(id, analysis);
+ const next = await (await selectBackend()).setProjectAnalysis(id, analysis);
+ emitRecordUpdated('musicVideoProject', id);
+ return next;
}
export async function addProjectScene(id, sceneInput) {
- return (await selectBackend()).addProjectScene(id, sceneInput);
+ const scene = await (await selectBackend()).addProjectScene(id, sceneInput);
+ emitRecordUpdated('musicVideoProject', id);
+ return scene;
}
export async function updateScene(id, sceneId, patch) {
- return (await selectBackend()).updateScene(id, sceneId, patch);
+ const result = await (await selectBackend()).updateScene(id, sceneId, patch);
+ emitRecordUpdated('musicVideoProject', id);
+ return result;
}
export async function deleteScene(id, sceneId) {
- return (await selectBackend()).deleteScene(id, sceneId);
+ const next = await (await selectBackend()).deleteScene(id, sceneId);
+ emitRecordUpdated('musicVideoProject', id);
+ return next;
}
export async function reorderProjectScenes(id, orderedIds) {
- return (await selectBackend()).reorderProjectScenes(id, orderedIds);
+ const next = await (await selectBackend()).reorderProjectScenes(id, orderedIds);
+ emitRecordUpdated('musicVideoProject', id);
+ return next;
+}
+
+/** Merge an incoming batch of project records from a peer (LWW, tombstone-aware). */
+export async function mergeProjectsFromSync(remoteProjects, options = {}) {
+ return (await selectBackend()).mergeProjectsFromSync(remoteProjects, options);
+}
+
+/** Hard-remove project tombstones older than the cutoff (called by tombstone GC). */
+export async function pruneTombstonedProjects(olderThanMs) {
+ return (await selectBackend()).pruneTombstonedProjects(olderThanMs);
}
diff --git a/server/services/musicVideo/projects.test.js b/server/services/musicVideo/projects.test.js
new file mode 100644
index 0000000000..d5dc7b77ba
--- /dev/null
+++ b/server/services/musicVideo/projects.test.js
@@ -0,0 +1,78 @@
+/**
+ * Music Video dispatcher — peer-sync record-event wiring (#1770). Asserts the
+ * dispatcher fires the recordEvents emits (announce on create, updated on every
+ * structural mutator, deleted on tombstone) so a project federates after a local
+ * edit. The backend is exercised for real via the file backend (NODE_ENV=test);
+ * only recordEvents is mocked so we can spy on the emits.
+ */
+
+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(), 'mv-projects-dispatch-test-'));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+});
+
+const emitRecordUpdated = vi.fn();
+const emitRecordDeleted = vi.fn();
+const autoSubscribeRecordToAllPeers = vi.fn(async () => {});
+vi.mock('../sharing/recordEvents.js', () => ({
+ emitRecordUpdated: (...a) => emitRecordUpdated(...a),
+ emitRecordDeleted: (...a) => emitRecordDeleted(...a),
+ autoSubscribeRecordToAllPeers: (...a) => autoSubscribeRecordToAllPeers(...a),
+}));
+
+const projects = await import('./projects.js');
+
+function reset() {
+ rmSync(join(TEST_DATA_ROOT, 'music-video-projects.json'), { force: true });
+ emitRecordUpdated.mockClear();
+ emitRecordDeleted.mockClear();
+ autoSubscribeRecordToAllPeers.mockClear();
+}
+beforeEach(reset);
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+describe('musicVideo dispatcher — record-event emit (#1770)', () => {
+ it('announces a new project (emit updated + auto-subscribe peers)', async () => {
+ const p = await projects.createProject({ name: 'A' });
+ expect(emitRecordUpdated).toHaveBeenCalledWith('musicVideoProject', p.id);
+ expect(autoSubscribeRecordToAllPeers).toHaveBeenCalledWith('musicVideoProject', p.id);
+ });
+
+ it('emits updated on metadata edits, analysis, and every scene mutator', async () => {
+ const p = await projects.createProject({ name: 'A' });
+ emitRecordUpdated.mockClear();
+
+ await projects.updateProject(p.id, { name: 'B' });
+ await projects.setProjectAnalysis(p.id, { bpm: 120, beats: [0], downbeats: [0], sections: [], durationSec: 5 });
+ const s1 = await projects.addProjectScene(p.id, { prompt: 'one' });
+ const s2 = await projects.addProjectScene(p.id, { prompt: 'two' });
+ await projects.updateScene(p.id, s1.sceneId, { prompt: 'one-edited' });
+ await projects.reorderProjectScenes(p.id, [s2.sceneId, s1.sceneId]);
+ await projects.deleteScene(p.id, s2.sceneId);
+
+ // update + analysis + 2 add + update + reorder + deleteScene = 7 structural emits
+ expect(emitRecordUpdated).toHaveBeenCalledTimes(7);
+ expect(emitRecordUpdated.mock.calls.every(([kind, id]) => kind === 'musicVideoProject' && id === p.id)).toBe(true);
+ expect(emitRecordDeleted).not.toHaveBeenCalled();
+ });
+
+ it('emits deleted on soft-delete (tombstone federates)', async () => {
+ const p = await projects.createProject({ name: 'A' });
+ emitRecordDeleted.mockClear();
+ await projects.deleteProject(p.id);
+ expect(emitRecordDeleted).toHaveBeenCalledWith('musicVideoProject', p.id);
+ });
+
+ it('re-exports the federation merge/prune helpers for peerSync + GC', async () => {
+ expect(typeof projects.mergeProjectsFromSync).toBe('function');
+ expect(typeof projects.pruneTombstonedProjects).toBe('function');
+ expect(typeof projects.listProjectIds).toBe('function');
+ });
+});
diff --git a/server/services/musicVideo/projectsDB.js b/server/services/musicVideo/projectsDB.js
index e657716c28..85ba8a525d 100644
--- a/server/services/musicVideo/projectsDB.js
+++ b/server/services/musicVideo/projectsDB.js
@@ -22,7 +22,11 @@ import {
applySceneUpdate,
removeScene,
reorderScenes,
+ mergeProjectRecord,
} from './projectsLogic.js';
+import {
+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+} from '../../lib/conflictJournal.js';
// `data` JSONB is the whole record; status/created_at/updated_at are a queryable
// mirror kept in lockstep but never read back — reads return `data` verbatim so
@@ -70,6 +74,14 @@ export async function getProject(id, { includeDeleted = false } = {}) {
return includeDeleted || !project.deleted ? project : null;
}
+/** Live project ids (or all when includeDeleted) — used by tombstone GC sweeps. */
+export async function listProjectIds({ includeDeleted = false } = {}) {
+ const result = includeDeleted
+ ? await query(`SELECT id FROM music_video_projects`)
+ : await query(`SELECT id FROM music_video_projects WHERE deleted = FALSE`);
+ return result.rows.map((r) => r.id);
+}
+
export async function createProject(input) {
const id = `mv-${randomUUID()}`;
const now = new Date().toISOString();
@@ -112,6 +124,63 @@ export async function deleteProject(id) {
});
}
+/**
+ * Merge an incoming batch of project records from a peer (per-record push). Each
+ * record's read-modify-write runs inside `withTransaction` + `SELECT … FOR
+ * UPDATE` so a concurrent local edit can't lose to (or clobber) the merge. LWW
+ * on `updatedAt` (tombstone-aware) via the shared `mergeProjectRecord` decision —
+ * identical to the file backend so the two can't drift. Seeds/advances the
+ * conflict-journal base hash and journals the about-to-be-overwritten local
+ * version when remote wins (best-effort). Mirrors creativeDirector/projectsDB.js.
+ * Returns `{ applied, count }`.
+ */
+export async function mergeProjectsFromSync(remoteProjects, { source = { via: 'sync', peerId: null } } = {}) {
+ if (!Array.isArray(remoteProjects)) return { applied: false, count: 0 };
+ let changed = 0;
+ for (const remote of remoteProjects) {
+ const applied = await withTransaction(async (client) => {
+ const sel = await client.query(`SELECT data FROM music_video_projects WHERE id = $1 FOR UPDATE`, [remote?.id]);
+ const local = rowToProject(sel.rows[0]);
+ const { next, inserted, remoteWins, changed: didChange } = mergeProjectRecord(local, remote);
+ if (!next) return false; // malformed remote → dropped
+ if (inserted) {
+ await persist(client.query.bind(client), next);
+ await setSyncBaseHash('musicVideoProject', next.id, contentHashForRecord('musicVideoProject', next));
+ return true;
+ }
+ // local wins, OR remote won but is byte-identical to local (already agree).
+ if (!remoteWins || !didChange) return false;
+ await maybeJournalBeforeOverwrite({ kind: 'musicVideoProject', id: next.id, local, remote: next, source });
+ await persist(client.query.bind(client), next);
+ await setSyncBaseHash('musicVideoProject', next.id, contentHashForRecord('musicVideoProject', 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 projects whose deletedAt is older than the cutoff.
+ * Called by tombstoneGc once every subscribed peer has acked the deletion.
+ * Evicts each pruned project's conflict-journal base hash. Mirrors
+ * creativeDirector/projectsDB.js `pruneTombstonedProjects`.
+ */
+export async function pruneTombstonedProjects(olderThanMs) {
+ if (!Number.isFinite(olderThanMs)) return { pruned: 0 };
+ const cutoffIso = new Date(olderThanMs).toISOString();
+ const { rows } = await query(
+ `DELETE FROM music_video_projects
+ WHERE deleted = TRUE AND deleted_at IS NOT NULL AND deleted_at < $1
+ RETURNING id`,
+ [cutoffIso],
+ );
+ for (const r of rows) await deleteSyncBaseHash('musicVideoProject', r.id);
+ return { pruned: rows.length };
+}
+
export async function setProjectAnalysis(id, analysis) {
const { project } = await withLockedProject(id, (p) => ({ project: setAudioAnalysis(p, analysis) }));
return project;
diff --git a/server/services/musicVideo/projectsFile.js b/server/services/musicVideo/projectsFile.js
index 635b668a79..f36110f424 100644
--- a/server/services/musicVideo/projectsFile.js
+++ b/server/services/musicVideo/projectsFile.js
@@ -19,7 +19,11 @@ import {
applySceneUpdate,
removeScene,
reorderScenes,
+ mergeProjectRecord,
} from './projectsLogic.js';
+import {
+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+} from '../../lib/conflictJournal.js';
const PROJECTS_FILE = join(PATHS.data, 'music-video-projects.json');
@@ -45,6 +49,12 @@ export async function getProject(id, { includeDeleted = false } = {}) {
return includeDeleted || !found.deleted ? found : null;
}
+/** Live project ids (or all when includeDeleted) — used by tombstone GC sweeps. */
+export async function listProjectIds({ includeDeleted = false } = {}) {
+ const all = await loadAll();
+ return (includeDeleted ? all : all.filter((p) => !p.deleted)).map((p) => p.id);
+}
+
export async function createProject(input) {
const id = `mv-${randomUUID()}`;
const now = new Date().toISOString();
@@ -79,6 +89,59 @@ export async function deleteProject(id) {
return { ok: true };
}
+/**
+ * File-backend mirror of projectsDB.js `mergeProjectsFromSync` — LWW-per-id
+ * (tombstone-aware) via the shared `mergeProjectRecord` decision so the two
+ * backends can't drift. Single load → per-record merge → single save.
+ */
+export async function mergeProjectsFromSync(remoteProjects, { source = { via: 'sync', peerId: null } } = {}) {
+ if (!Array.isArray(remoteProjects)) return { applied: false, count: 0 };
+ const all = await loadAll();
+ const byId = new Map(all.map((p) => [p.id, p]));
+ let changed = 0;
+ for (const remote of remoteProjects) {
+ const local = byId.get(remote?.id) || null;
+ const { next, inserted, remoteWins, changed: didChange } = mergeProjectRecord(local, remote);
+ if (!next) continue;
+ if (inserted) {
+ byId.set(next.id, next);
+ await setSyncBaseHash('musicVideoProject', next.id, contentHashForRecord('musicVideoProject', next));
+ changed += 1;
+ continue;
+ }
+ if (!remoteWins || !didChange) continue;
+ await maybeJournalBeforeOverwrite({ kind: 'musicVideoProject', id: next.id, local, remote: next, source });
+ byId.set(next.id, next);
+ await setSyncBaseHash('musicVideoProject', next.id, contentHashForRecord('musicVideoProject', 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 projects whose deletedAt is older than the cutoff.
+ * Mirrors projectsDB.js `pruneTombstonedProjects`; evicts each pruned project's
+ * base hash.
+ */
+export async function pruneTombstonedProjects(olderThanMs) {
+ if (!Number.isFinite(olderThanMs)) return { pruned: 0 };
+ const all = await loadAll();
+ const survivors = [];
+ const pruned = [];
+ for (const p of all) {
+ const ms = p.deleted ? Date.parse(p.deletedAt || '') : NaN;
+ if (p.deleted && Number.isFinite(ms) && ms < olderThanMs) pruned.push(p.id);
+ else survivors.push(p);
+ }
+ if (pruned.length === 0) return { pruned: 0 };
+ await saveAll(survivors);
+ for (const id of pruned) await deleteSyncBaseHash('musicVideoProject', id);
+ return { pruned: pruned.length };
+}
+
export async function setProjectAnalysis(id, analysis) {
const { all, idx } = await loadAllAndIndex(id);
all[idx] = setAudioAnalysis(all[idx], analysis);
diff --git a/server/services/musicVideo/projectsFile.test.js b/server/services/musicVideo/projectsFile.test.js
index cbb82e0c66..1f09df97bf 100644
--- a/server/services/musicVideo/projectsFile.test.js
+++ b/server/services/musicVideo/projectsFile.test.js
@@ -83,3 +83,56 @@ describe('projectsFile backend', () => {
await expect(file.addProjectScene(p.id, { prompt: 'x' })).rejects.toThrow(/not found/i);
});
});
+
+describe('projectsFile federation (#1770)', () => {
+ it('listProjectIds returns live ids, or all when includeDeleted', async () => {
+ const a = await file.createProject({ name: 'A' });
+ const b = await file.createProject({ name: 'B' });
+ await file.deleteProject(b.id);
+ expect(await file.listProjectIds()).toEqual([a.id]);
+ expect((await file.listProjectIds({ includeDeleted: true })).sort()).toEqual([a.id, b.id].sort());
+ });
+
+ it('mergeProjectsFromSync inserts a brand-new peer record', async () => {
+ const remote = { id: 'mv-peer-1', name: 'Peer', status: 'draft', updatedAt: '2026-02-01T00:00:00Z', createdAt: '2026-02-01T00:00:00Z', scenes: [] };
+ const res = await file.mergeProjectsFromSync([remote]);
+ expect(res).toEqual({ applied: true, count: 1 });
+ expect((await file.getProject('mv-peer-1')).name).toBe('Peer');
+ });
+
+ it('mergeProjectsFromSync applies a newer remote and ignores an older one', async () => {
+ const p = await file.createProject({ name: 'Local' });
+ const newer = { ...p, name: 'RemoteNewer', updatedAt: '2099-01-01T00:00:00Z' };
+ expect(await file.mergeProjectsFromSync([newer])).toEqual({ applied: true, count: 1 });
+ expect((await file.getProject(p.id)).name).toBe('RemoteNewer');
+
+ const older = { ...p, name: 'RemoteOlder', updatedAt: '2000-01-01T00:00:00Z' };
+ expect(await file.mergeProjectsFromSync([older])).toEqual({ applied: false, count: 0 });
+ expect((await file.getProject(p.id)).name).toBe('RemoteNewer');
+ });
+
+ it('mergeProjectsFromSync applies a remote tombstone (delete federates)', async () => {
+ const p = await file.createProject({ name: 'Doomed' });
+ const tombstone = { ...p, deleted: true, deletedAt: '2099-01-01T00:00:00Z', updatedAt: '2099-01-01T00:00:00Z' };
+ expect(await file.mergeProjectsFromSync([tombstone])).toEqual({ applied: true, count: 1 });
+ expect(await file.getProject(p.id)).toBeNull();
+ expect(await file.getProject(p.id, { includeDeleted: true })).toMatchObject({ deleted: true });
+ });
+
+ it('pruneTombstonedProjects hard-removes only old-enough tombstones', async () => {
+ const keep = await file.createProject({ name: 'Live' });
+ // Insert an already-old tombstone via the sync insert path (insert applies
+ // regardless of LWW), so its deletedAt sits far enough in the past to prune.
+ await file.mergeProjectsFromSync([{
+ id: 'mv-old-tomb', name: 'Old', status: 'draft', scenes: [],
+ createdAt: '2000-01-01T00:00:00Z', updatedAt: '2000-01-02T00:00:00Z',
+ deleted: true, deletedAt: '2000-01-01T00:00:00Z',
+ }]);
+
+ // A future cutoff prunes the old tombstone; a pre-tombstone cutoff would not.
+ expect((await file.pruneTombstonedProjects(Date.parse('1990-01-01T00:00:00Z'))).pruned).toBe(0);
+ const res = await file.pruneTombstonedProjects(Date.parse('2010-01-01T00:00:00Z'));
+ expect(res.pruned).toBe(1);
+ expect(await file.listProjectIds({ includeDeleted: true })).toEqual([keep.id]);
+ });
+});
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index ac1ccc77fc..b0641708d1 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -8,10 +8,10 @@
* throws a ServerError on a validation failure), leaving read/write to the
* caller.
*
- * Scope note: peer-sync federation (sanitize/merge/tombstone-GC helpers the CD
- * store carries) is deferred to a follow-up — see services/musicVideo/projects.js.
- * The soft-delete fields are kept on the record now so adding federation later
- * is purely additive.
+ * Peer-sync federation (#1770): the sanitize + LWW-merge decision helpers the CD
+ * store carries now live here too (`sanitizeProjectForSync`, `mergeProjectRecord`),
+ * shared by both backends so the merge can't drift. The soft-delete fields were
+ * already on the record, so federation was purely additive (no record migration).
*/
import { randomUUID } from 'crypto';
@@ -22,10 +22,14 @@ import {
musicVideoSceneCreateSchema,
musicVideoSceneUpdateSchema,
} from '../../lib/validation.js';
+import { compareNewerWins } from '../../lib/lwwTimestamp.js';
+import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
// Re-exported for the PG backend's typed mirror columns (mirrors the CD store).
export { mirrorTimestamp } from '../../lib/pgTimestamp.js';
+const isStr = (v) => typeof v === 'string';
+
const STATUS_COLUMN_MAX = 32;
/** Safe value for the `status` mirror column — bounded, never null. */
@@ -172,3 +176,45 @@ export function reorderScenes(project, orderedIds) {
const nextScenes = orderedIds.map((id, i) => ({ ...byId.get(id), order: i }));
return touch(project, { scenes: nextScenes });
}
+
+// ---- peer-sync federation (#1770) -----------------------------------------
+// Mirrors the Creative Director store (creativeDirector/projectsLogic.js): a
+// project is a whole-record LWW kind (no item-union, no ephemeral flag), so the
+// wire form is the record with normalized soft-delete fields and the merge is a
+// straight `updatedAt` newest-wins decision. Both backends call through here so
+// the file and PG paths can't diverge.
+
+/**
+ * Wire-safe / merge-safe projection of a peer-supplied project record. Rejects a
+ * non-object or one missing an id (the receiver could never apply it), and
+ * normalizes the timestamps + soft-delete pair so a legacy/hand-edited payload
+ * converges byte-for-byte with a freshly-written one. Returns null when unusable.
+ */
+export function sanitizeProjectForSync(raw) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ if (!isStr(raw.id) || !raw.id) return null;
+ const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();
+ const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;
+ const { deleted, deletedAt } = sanitizeSoftDeleteFields(raw);
+ return { ...raw, createdAt, updatedAt, deleted, deletedAt };
+}
+
+/**
+ * LWW merge decision for one incoming peer record against the local copy.
+ * Returns `{ next, inserted, remoteWins, changed }`:
+ * - malformed remote → `{ next: null, ... }` (caller drops it)
+ * - no local copy → insert the remote
+ * - otherwise newest-`updatedAt`-wins; `changed` is false when the winner is
+ * byte-identical to local (a same-`updatedAt` re-push no-ops, no churn).
+ * Tombstone-aware purely via `updatedAt`: deleteProject stamps a fresh
+ * `updatedAt`, so a tombstone beats an older live copy and can't be resurrected.
+ */
+export function mergeProjectRecord(local, remoteRaw) {
+ const remote = sanitizeProjectForSync(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 };
+}
diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.js
index 1de4715ab6..caba6631bc 100644
--- a/server/services/musicVideo/projectsLogic.test.js
+++ b/server/services/musicVideo/projectsLogic.test.js
@@ -8,6 +8,8 @@ import {
removeScene,
reorderScenes,
mirrorStatus,
+ sanitizeProjectForSync,
+ mergeProjectRecord,
} from './projectsLogic.js';
const baseProject = () => buildProjectRecord({ name: 'Test MV' }, { id: 'mv-1', now: '2026-01-01T00:00:00.000Z' });
@@ -141,3 +143,79 @@ describe('mirrorStatus', () => {
expect(mirrorStatus('x'.repeat(40))).toHaveLength(32);
});
});
+
+describe('sanitizeProjectForSync (#1770 federation)', () => {
+ it('rejects non-objects, arrays, and id-less records', () => {
+ expect(sanitizeProjectForSync(null)).toBeNull();
+ expect(sanitizeProjectForSync('x')).toBeNull();
+ expect(sanitizeProjectForSync([])).toBeNull();
+ expect(sanitizeProjectForSync({})).toBeNull();
+ expect(sanitizeProjectForSync({ id: '' })).toBeNull();
+ });
+
+ it('normalizes timestamps and the soft-delete pair', () => {
+ const out = sanitizeProjectForSync({ id: 'mv-1', name: 'A' });
+ expect(out.id).toBe('mv-1');
+ expect(typeof out.createdAt).toBe('string');
+ expect(out.updatedAt).toBe(out.createdAt); // defaults updatedAt to createdAt
+ expect(out.deleted).toBe(false);
+ expect(out.deletedAt).toBeNull();
+ });
+
+ it('drops a stray deletedAt when deleted is false', () => {
+ const out = sanitizeProjectForSync({ id: 'mv-1', updatedAt: 'u', deleted: false, deletedAt: '2026-01-01T00:00:00Z' });
+ expect(out.deletedAt).toBeNull();
+ });
+
+ it('keeps a tombstone with deleted=true + deletedAt', () => {
+ const out = sanitizeProjectForSync({ id: 'mv-1', updatedAt: 'u', deleted: true, deletedAt: '2026-01-01T00:00:00Z' });
+ expect(out.deleted).toBe(true);
+ expect(out.deletedAt).toBe('2026-01-01T00:00:00Z');
+ });
+});
+
+describe('mergeProjectRecord (#1770 LWW)', () => {
+ it('drops a malformed remote', () => {
+ expect(mergeProjectRecord(null, {}).next).toBeNull();
+ });
+
+ it('inserts when there is no local copy', () => {
+ const r = mergeProjectRecord(null, { id: 'mv-1', updatedAt: '2026-01-02T00:00:00Z', name: 'X' });
+ expect(r.inserted).toBe(true);
+ expect(r.remoteWins).toBe(true);
+ expect(r.next.name).toBe('X');
+ });
+
+ it('remote with a newer updatedAt wins', () => {
+ const local = { id: 'mv-1', updatedAt: '2026-01-01T00:00:00Z', name: 'old' };
+ const remote = { id: 'mv-1', updatedAt: '2026-01-05T00:00:00Z', name: 'new' };
+ const r = mergeProjectRecord(local, remote);
+ expect(r.remoteWins).toBe(true);
+ expect(r.changed).toBe(true);
+ expect(r.next.name).toBe('new');
+ });
+
+ it('local with a newer updatedAt wins (no change applied)', () => {
+ const local = { id: 'mv-1', updatedAt: '2026-01-05T00:00:00Z', name: 'local' };
+ const remote = { id: 'mv-1', updatedAt: '2026-01-01T00:00:00Z', name: 'remote' };
+ const r = mergeProjectRecord(local, remote);
+ expect(r.remoteWins).toBe(false);
+ expect(r.changed).toBe(false);
+ expect(r.next.name).toBe('local');
+ });
+
+ it('a remote tombstone beats an older live local copy (no resurrection)', () => {
+ const local = { id: 'mv-1', updatedAt: '2026-01-01T00:00:00Z', deleted: false, deletedAt: null };
+ const remote = { id: 'mv-1', updatedAt: '2026-01-05T00:00:00Z', deleted: true, deletedAt: '2026-01-05T00:00:00Z' };
+ const r = mergeProjectRecord(local, remote);
+ expect(r.remoteWins).toBe(true);
+ expect(r.next.deleted).toBe(true);
+ });
+
+ it('a same-updatedAt re-push is a no-op (changed=false, no churn)', () => {
+ const local = { id: 'mv-1', updatedAt: '2026-01-05T00:00:00Z', name: 'same', deleted: false, deletedAt: null };
+ const remote = { id: 'mv-1', updatedAt: '2026-01-05T00:00:00Z', name: 'same' };
+ const r = mergeProjectRecord(local, remote);
+ expect(r.changed).toBe(false);
+ });
+});
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 75c520b6f4..5970a2256b 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -105,6 +105,11 @@ import {
mergeProjectsFromSync,
startingImageFilename,
} from '../creativeDirector/local.js';
+import {
+ getProject as getMusicVideoProject,
+ listProjects as listMusicVideoProjects,
+ mergeProjectsFromSync as mergeMusicVideoProjectsFromSync,
+} from '../musicVideo/projects.js';
import {
getBoard,
listBoards,
@@ -133,7 +138,7 @@ import {
removeCursor as removeTombstoneCursor,
} from './peerTombstoneCursors.js';
-export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise']);
+export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject']);
/**
* Cross-cutting event bus for the peer-sync receiver. The asset-pull worker
@@ -415,6 +420,7 @@ const KIND_TO_CATEGORY = Object.freeze({
writersRoomWork: 'writersRoomWorks',
writersRoomFolder: 'writersRoomFolders',
writersRoomExercise: 'writersRoomExercises',
+ musicVideoProject: 'musicVideoProjects',
});
function peerAllowsOutbound(peer) {
@@ -531,6 +537,8 @@ async function listRecordsForKind(recordKind) {
// Live exercises as { id, updatedAt } (#1645). updatedAt is derived from
// finishedAt ?? startedAt in the facade so coverage keys on the wire value.
records = await listExercisesForSync().catch(() => []);
+ } else if (recordKind === 'musicVideoProject') {
+ records = await listMusicVideoProjects({ includeDeleted: false }).catch(() => []);
}
return records.filter(r => r?.ephemeral !== true && isNonEmptyStr(r?.id));
}
@@ -834,6 +842,10 @@ async function buildIntegrityAssetManifest(kind, record) {
if (kind === 'album') return buildAlbumAssetManifest(record);
if (kind === 'track') return buildTrackAssetManifest(record);
if (kind === 'creativeDirectorProject') return buildProjectAssetManifest(record);
+ // Music Video projects (#1770): the record federates but its referenced media
+ // (uploaded audio, scene reference images / rendered videos) is NOT bundled in
+ // this phase — empty manifest, mirroring the body-less Writers Room kinds.
+ if (kind === 'musicVideoProject') return [];
if (kind === 'moodBoard') return buildBoardAssetManifest(record);
if (kind === 'series') {
const childIssues = await listIssues({ seriesId: record?.id, includeDeleted: true }).catch(() => []);
@@ -1074,6 +1086,10 @@ async function isSubscriptionRecordTombstone(sub) {
const record = await getExerciseForSync(sub.recordId).catch(() => null);
return record?.deleted === true;
}
+ if (sub.recordKind === 'musicVideoProject') {
+ const record = await getMusicVideoProject(sub.recordId, { includeDeleted: true }).catch(() => null);
+ return record?.deleted === true;
+ }
return false;
}
@@ -1672,6 +1688,17 @@ async function buildPushPayload(sub, sourceInstanceId) {
if (!sanitized) return null;
return { kind: 'writersRoomExercise', record: sanitized, assetManifest: [], sourceInstanceId, portosMeta };
}
+ if (sub.recordKind === 'musicVideoProject') {
+ // #1770 — the record (metadata + beat-aligned scenes) is the LWW envelope.
+ // Referenced media (uploaded audio, scene images/rendered videos) is NOT
+ // bundled in this phase, so the asset manifest is empty (writersRoomFolder
+ // pattern). Media-asset bundling is a follow-up.
+ const record = await getMusicVideoProject(sub.recordId, { includeDeleted: true }).catch(() => null);
+ if (!record) return null;
+ const sanitized = sanitizeRecordForWire('musicVideoProject', record);
+ if (!sanitized) return null;
+ return { kind: 'musicVideoProject', record: sanitized, assetManifest: [], sourceInstanceId, portosMeta };
+ }
return null;
}
@@ -2151,6 +2178,8 @@ export async function applyIncomingPush(payload) {
await mergeFoldersFromSync([record], { source });
} else if (kind === 'writersRoomExercise') {
await mergeExercisesFromSync([record], { source });
+ } else if (kind === 'musicVideoProject') {
+ await mergeMusicVideoProjectsFromSync([record], { source });
}
// Apply the bundled collection (if any) — same LWW + union-of-items
@@ -2448,6 +2477,13 @@ async function classifyLocalRecord(recordKind, recordId) {
const e = await getExerciseForSync(recordId).catch(() => null);
return e ? 'syncable' : 'missing';
}
+ if (recordKind === 'musicVideoProject') {
+ // Music Video projects have no `ephemeral` concept (like the persona/music/CD/
+ // board kinds) — a found project (live or tombstoned) is always 'syncable'.
+ // No ping-pong risk: lastPushedHash + LWW same-`updatedAt` no-op merge prevent it.
+ const p = await getMusicVideoProject(recordId, { includeDeleted: true }).catch(() => null);
+ return p ? 'syncable' : 'missing';
+ }
return 'missing';
}
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index b6bc0e4851..67b494ed74 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -330,7 +330,7 @@ describe('peerSync', () => {
// caught — this list is canonical and its order can affect iteration
// elsewhere (e.g. syncNow's per-kind backfill). Issues piggyback on series
// subscriptions; direct issue subs are intentionally rejected (Stage 2).
- expect(PEER_SUBSCRIBABLE_KINDS).toEqual(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise']);
+ expect(PEER_SUBSCRIBABLE_KINDS).toEqual(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject']);
});
});
diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.js
index 4f1cb22b97..7a3e8ecc79 100644
--- a/server/services/sharing/tombstoneGc.js
+++ b/server/services/sharing/tombstoneGc.js
@@ -35,6 +35,10 @@ import { pruneTombstonedArtists, listArtistIds } from '../artists/index.js';
import { pruneTombstonedAlbums, listAlbumIds } from '../albums/index.js';
import { pruneTombstonedTracks, listTrackIds } from '../tracks/index.js';
import { pruneTombstonedProjects, listProjectIds } from '../creativeDirector/local.js';
+import {
+ pruneTombstonedProjects as pruneTombstonedMusicVideoProjects,
+ listProjectIds as listMusicVideoProjectIds,
+} from '../musicVideo/projects.js';
import { pruneTombstonedBoards, listBoardIds } from '../moodBoard/index.js';
import {
pruneTombstonedWorks, listWorkIdsForSync,
@@ -62,6 +66,7 @@ const LIVE_ID_LISTERS = Object.freeze({
album: () => listAlbumIds(),
track: () => listTrackIds(),
creativeDirectorProject: () => listProjectIds(),
+ musicVideoProject: () => listMusicVideoProjectIds(),
moodBoard: () => listBoardIds(),
writersRoomWork: () => listWorkIdsForSync(),
writersRoomFolder: () => listFolderIdsForSync(),
@@ -84,6 +89,7 @@ const ALL_ID_LISTERS = Object.freeze({
album: () => listAlbumIds({ includeDeleted: true }),
track: () => listTrackIds({ includeDeleted: true }),
creativeDirectorProject: () => listProjectIds({ includeDeleted: true }),
+ musicVideoProject: () => listMusicVideoProjectIds({ includeDeleted: true }),
moodBoard: () => listBoardIds({ includeDeleted: true }),
writersRoomWork: () => listWorkIdsForSync({ includeDeleted: true }),
writersRoomFolder: () => listFolderIdsForSync({ includeDeleted: true }),
@@ -257,6 +263,7 @@ function refusedFromCutoffs(cutoffs) {
albumCutoff,
trackCutoff,
projectCutoff,
+ musicVideoProjectCutoff,
boardCutoff,
workCutoff,
folderCutoff,
@@ -277,6 +284,7 @@ function refusedFromCutoffs(cutoffs) {
if (albumCutoff === null) refused.push('album');
if (trackCutoff === null) refused.push('track');
if (projectCutoff === null) refused.push('creativeDirectorProject');
+ if (musicVideoProjectCutoff === null) refused.push('musicVideoProject');
if (boardCutoff === null) refused.push('moodBoard');
if (workCutoff === null) refused.push('writersRoomWork');
if (folderCutoff === null) refused.push('writersRoomFolder');
@@ -306,6 +314,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
albumCutoff,
trackCutoff,
projectCutoff,
+ musicVideoProjectCutoff,
boardCutoff,
workCutoff,
folderCutoff,
@@ -319,13 +328,14 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
cutoffForKind('album', { peers, subs, now, graceMs }),
cutoffForKind('track', { peers, subs, now, graceMs }),
cutoffForKind('creativeDirectorProject', { peers, subs, now, graceMs }),
+ cutoffForKind('musicVideoProject', { peers, subs, now, graceMs }),
cutoffForKind('moodBoard', { peers, subs, now, graceMs }),
cutoffForKind('writersRoomWork', { peers, subs, now, graceMs }),
cutoffForKind('writersRoomFolder', { peers, subs, now, graceMs }),
cutoffForKind('writersRoomExercise', { peers, subs, now, graceMs }),
]);
const issueCutoff = seriesCutoff;
- const [u, s, i, c, a, ar, al, t, cd, mb, wr, wrf, wre] = await Promise.all([
+ const [u, s, i, c, a, ar, al, t, cd, mv, mb, wr, wrf, wre] = await Promise.all([
universeCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedUniverses(universeCutoff),
seriesCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedSeries(seriesCutoff),
issueCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedIssues(issueCutoff),
@@ -335,6 +345,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
albumCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedAlbums(albumCutoff),
trackCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedTracks(trackCutoff),
projectCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedProjects(projectCutoff),
+ musicVideoProjectCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedMusicVideoProjects(musicVideoProjectCutoff),
boardCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedBoards(boardCutoff),
workCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedWorks(workCutoff),
folderCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedFolders(folderCutoff),
@@ -364,13 +375,14 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
albums: al.pruned,
tracks: t.pruned,
creativeDirectorProjects: cd.pruned,
+ musicVideoProjects: mv.pruned,
moodBoards: mb.pruned,
writersRoomWorks: wr.pruned,
writersRoomFolders: wrf.pruned,
writersRoomExercises: wre.pruned,
orphanBaseHashes: orphan.pruned,
orphanSubscriptions: orphanSubs.pruned,
- refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff }),
+ refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff }),
};
}
@@ -379,7 +391,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
// coverage matters), so this hardcodes graceMs:0 internally.
export async function getSweepStatus({ now = Date.now() } = {}) {
const { peers, subs } = await loadState();
- const [universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff] = await Promise.all([
+ const [universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff] = await Promise.all([
cutoffForKind('universe', { peers, subs, now, graceMs: 0 }),
cutoffForKind('series', { peers, subs, now, graceMs: 0 }),
cutoffForKind('mediaCollection', { peers, subs, now, graceMs: 0 }),
@@ -388,12 +400,13 @@ export async function getSweepStatus({ now = Date.now() } = {}) {
cutoffForKind('album', { peers, subs, now, graceMs: 0 }),
cutoffForKind('track', { peers, subs, now, graceMs: 0 }),
cutoffForKind('creativeDirectorProject', { peers, subs, now, graceMs: 0 }),
+ cutoffForKind('musicVideoProject', { peers, subs, now, graceMs: 0 }),
cutoffForKind('moodBoard', { peers, subs, now, graceMs: 0 }),
cutoffForKind('writersRoomWork', { peers, subs, now, graceMs: 0 }),
cutoffForKind('writersRoomFolder', { peers, subs, now, graceMs: 0 }),
cutoffForKind('writersRoomExercise', { peers, subs, now, graceMs: 0 }),
]);
- return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff }) };
+ return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff }) };
}
export const TOMBSTONE_GRACE_MS = GRACE_MS;
diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.js
index 004fb19db8..501047da6d 100644
--- a/server/services/sharing/tombstoneGc.test.js
+++ b/server/services/sharing/tombstoneGc.test.js
@@ -40,6 +40,10 @@ vi.mock('../creativeDirector/local.js', () => ({
pruneTombstonedProjects: vi.fn().mockResolvedValue({ pruned: 0 }),
listProjectIds: vi.fn().mockResolvedValue([]),
}));
+vi.mock('../musicVideo/projects.js', () => ({
+ pruneTombstonedProjects: vi.fn().mockResolvedValue({ pruned: 0 }),
+ listProjectIds: vi.fn().mockResolvedValue([]),
+}));
vi.mock('../moodBoard/index.js', () => ({
pruneTombstonedBoards: vi.fn().mockResolvedValue({ pruned: 0 }),
listBoardIds: vi.fn().mockResolvedValue([]),
@@ -80,6 +84,7 @@ import { pruneTombstonedArtists, listArtistIds } from '../artists/index.js';
import { pruneTombstonedAlbums, listAlbumIds } from '../albums/index.js';
import { pruneTombstonedTracks, listTrackIds } from '../tracks/index.js';
import { pruneTombstonedProjects } from '../creativeDirector/local.js';
+import { pruneTombstonedProjects as pruneTombstonedMusicVideoProjects } from '../musicVideo/projects.js';
import { pruneTombstonedBoards } from '../moodBoard/index.js';
import { pruneTombstonedWorks, pruneTombstonedFolders, pruneTombstonedExercises } from '../writersRoom/sync.js';
import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';
@@ -438,6 +443,7 @@ describe('sweepTombstones — return shape', () => {
pruneTombstonedAlbums.mockResolvedValueOnce({ pruned: 6 });
pruneTombstonedTracks.mockResolvedValueOnce({ pruned: 7 });
pruneTombstonedProjects.mockResolvedValueOnce({ pruned: 8 });
+ pruneTombstonedMusicVideoProjects.mockResolvedValueOnce({ pruned: 13 });
pruneTombstonedBoards.mockResolvedValueOnce({ pruned: 9 });
pruneTombstonedWorks.mockResolvedValueOnce({ pruned: 10 });
pruneTombstonedFolders.mockResolvedValueOnce({ pruned: 11 });
@@ -453,6 +459,7 @@ describe('sweepTombstones — return shape', () => {
albums: 6,
tracks: 7,
creativeDirectorProjects: 8,
+ musicVideoProjects: 13,
moodBoards: 9,
writersRoomWorks: 10,
writersRoomFolders: 11,