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
feat: federate Mood Boards across peers (#1564)
[._.]/ Adam Eivy5903b45b0879
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d75618e44c..d919560a0d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -61,6 +61,8 @@- **[issue-1564] Creative Director projects now federate across peers.** Creative Director projects (treatment, scenes, runs) were `db-primary` but local-only — a node pair couldn't mirror that creative work. Projects now ride the same per-record peer-sync push pipeline as Authors and Music: there's a new **Creative Director** sync category on the Instances page (and it's covered automatically by Full mirror peers), creating a project auto-subscribes it to every project-enabled peer, edits propagate as last-write-wins (newer `updatedAt` wins, with a Conflicts-tab entry archived when both sides diverged from a common base), and a delete becomes a tombstone the merge keeps an out-of-date peer from resurrecting. The project's starting image replicates as a pulled asset; scene video renders ride the project's linked media collection (federated separately). Cross-version pushes are version-gated (`creativeDirectorProjects` schema v1) so a newer peer can't corrupt an older one. (Mood Boards federation, also part of #1564, remains to ship in a follow-up.) (`server/services/creativeDirector/`, `server/services/sharing/peerSync.js`, `server/services/sharing/tombstoneGc.js`, `server/lib/schemaVersions.js`, `server/lib/syncWire.js`, `server/lib/conflictJournal.js`, `client/src/pages/Instances.jsx`)+- **[issue-1564] Mood Boards now federate across peers (completing #1564).** Mood boards (the pinned image + text reference canvas) were `db-primary` but local-only, so a node pair couldn't mirror them. Boards now ride the same per-record peer-sync push pipeline as Creative Director projects: there's a new **Mood Boards** sync category on the Instances page (and it's covered automatically by Full mirror peers), creating a board auto-subscribes it to every board-enabled peer, edits propagate as last-write-wins (newer `updatedAt` wins, with a Conflicts-tab entry archived — restorable down to the board's `items[]` — when both sides diverged from a common base), and a delete becomes a tombstone the merge keeps an out-of-date peer from resurrecting. Image bytes a board's items reference (gallery media-keys or `/data/images/...` URLs) replicate as pulled assets; external image URLs resolve on the receiver. Cross-version pushes are version-gated (`moodBoards` schema v1) so a newer peer can't corrupt an older one. (`server/services/moodBoard/`, `server/services/sharing/peerSync.js`, `server/services/sharing/tombstoneGc.js`, `server/services/conflictJournalResolver.js`, `server/lib/schemaVersions.js`, `server/lib/syncWire.js`, `server/lib/conflictJournal.js`, `server/lib/peerSyncValidation.js`, `client/src/pages/Instances.jsx`)+- **Comic-page proof/final render buttons no longer get stuck "loading"/disabled on already-rendered pages.** Navigating into an issue's Comic tab — for example right after kicking off an unrelated render like a volume cover — could leave a page's **Proof**/**Final** buttons spinning and disabled even though that page's render finished long ago. The in-flight check re-armed an "unknown" status on every navigation and only cleared it once a job-status fetch (or a 5-second grace timer) resolved, ignoring that the slot already carried a rendered image. It now treats a slot that already has a rendered filename as settled immediately (the server clears the filename when a re-render is queued, so a present filename is an authoritative "done" signal), so the buttons are clickable right away and you can queue the next render without waiting. (`client/src/hooks/useSlotInFlight.js`)- **The Volume covers section on a series page is now expanded by default** instead of starting collapsed, so the front/back cover editors and render buttons are visible without an extra click. (`client/src/components/pipeline/ArcCanvas.jsx`)- **Claude Code TUI agents now reliably wait for the input prompt before sending their task (and no longer wedge the shell on startup hiccups).** TUI-provider CoS agents (e.g. `claude-code-tui`) run their CLI as a *child* of a persistent PTY shell, and the old prompt-delivery gate fired on a crude "saw output, then went idle" heuristic. During Claude Code's startup that lull happens *before* the input box exists — and on a folder it hasn't seen, claude shows a **"trust this folder?" gate** that `--dangerously-skip-permissions` does not bypass (common because agents start in fresh worktrees). The gate would paste the task into the banner / trust menu, or — if claude had already exited — into the returned shell prompt, leaving a frozen, un-typeable session showing a literal `^[[200~ …` and a silently-failed run. The spawner now (1) **waits until the shell can actually run commands** before injecting the CLI command — a fixed 200 ms delay raced a heavy interactive shell (powerlevel10k / async plugins / nvm-PATH setup), so the command ran before the env was ready and the launched TUI fell straight back to the prompt. Heuristic timing watches (a prompt-marker, or settle-on-output-quiet) are *both* fooled by powerlevel10k's *instant prompt* (it renders a fake-ready prompt — and enables bracketed-paste mode — before `.zshrc` finishes) and by slow mid-load quiet gaps (nvm/plugins) that trip a settle timer just as easily, sending the command into a half-loaded shell where the instant-prompt→real-prompt redraw swallows it (the command sits echoed-but-unexecuted at a bare prompt — the intermittent wedge). It now **proves the shell is executing commands with a round-trip probe**: it prints a unique nonce and waits to *see that nonce in the output* before injecting the command. The nonce is split in the probe source (`'PORTOSRDY' '<nonce>'`) so the command echo never contains the assembled string — only the executed output matches — and instant-prompt keystroke buffering replays the probe into the real shell, so the gate is theme- and shell-agnostic with a bounded fallback if the probe never round-trips, (2) gates the paste on claude **re-enabling bracketed-paste mode** (`ESC[?2004h`, after the shell turned it off to run the command) as the input-ready signal — this is what makes the paste's leading `ESC` read as a paste rather than as Escape (which cancels claude's input — the intermittent "something other than Enter canceled it" failure); the visible footer text (`bypass permissions on (shift+tab to cycle)`) is deliberately NOT used because claude renders it with inter-glyph cursor moves that strip its spaces after ANSI-stripping, making it unmatchable, (3) **auto-confirms the folder-trust prompt** (Enter on the default "Yes, I trust") so claims run in fresh worktrees, (4) probes that the CLI is still a live child of the shell before pasting, and (5) **never blind-pastes** — if the input prompt never appears within 45 s (or the CLI exited), it finalizes the run as a failure carrying the CLI's captured output (`tui-not-ready` / `tui-exited-early`) instead of dumping into the shell. Non-claude TUI providers keep their existing handshake. (`server/services/agentTuiSpawning.js`, `server/lib/tuiHandshake.js`, `server/services/shell.js`)diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex 18d08fa747..232312769d 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+ Lock, Globe, Info, Sparkles, Film, Images, Library, BookOpen, FilePen, Music, Music2, Disc3, Clapperboard, Palette} from 'lucide-react';import toast from '../components/ui/Toast';import Pill from '../components/ui/Pill';@@ -522,13 +522,14 @@ const SYNC_CATEGORY_META = [{ key: 'albums', label: 'Albums', icon: Disc3, description: 'Music albums + cover art and ordered track lists (PostgreSQL)' },{ key: 'tracks', label: 'Tracks', icon: Music2, description: 'Music tracks + attached audio files (PostgreSQL)' },{ key: 'creativeDirectorProjects', label: 'Creative Director', icon: Clapperboard, description: 'Creative Director projects: treatment, scenes, runs (PostgreSQL)' },+ { key: 'moodBoards', label: 'Mood Boards', icon: Palette, description: 'Mood boards: pinned image + text references (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']);+const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors', 'artists', 'albums', 'tracks', 'creativeDirectorProjects', 'moodBoards']);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.jsindex ecefe3ba40..8680102282 100644--- a/server/lib/conflictJournal.js+++ b/server/lib/conflictJournal.js@@ -334,6 +334,15 @@ export const RESTORABLE_FIELDS = Object.freeze({// is what the Conflicts UI offers for restore. `creativeDirectorProject`// matches the record kind and mergeProjectRecord accepts every field here.creativeDirectorProject: ['name', 'status', 'styleSpec', 'userStory', 'treatment', 'aspectRatio', 'quality', 'modelId', 'targetDurationSeconds', 'disableAudio', 'autoAcceptScenes', 'startingImageFile'],+ // Mood boards (#1564): the user-authored fields the merge can restore. `items[]`+ // (the pinned image/text references) carries the bulk of the work, alongside+ // name/description. Server-owned / structural fields are excluded — `id`/+ // `createdAt`/the LWW-tombstone trio. The whole record is hashed for DETECTION+ // by contentHashForRecord (no scalar narrowing); this set is what the Conflicts+ // UI offers for restore. `moodBoard` matches the record kind, and the resolver+ // routes restore through restoreBoard → applyBoardRestore (which accepts items,+ // unlike the route's applyBoardPatch).+ moodBoard: ['name', 'description', 'items'],});const present = (v) => v !== undefined;diff --git a/server/lib/db.js b/server/lib/db.jsindex eb33939e61..9535cd0a8b 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -840,19 +840,30 @@ async function ensureSchemaImpl() {// external URL, or a text note + optional caption/source backref) live// inline in the board's JSONB rather than a child table — a board is read/// written whole, has a small bounded item list, and there are no cross-board- // item queries. `name` mirrors a column for the live-list sort. Mood boards- // are db-primary and LOCAL-ONLY (no sync_sequence/tombstone) — like- // creative_director_projects, they don't federate to peers in v1. Mirrors- // the mood_boards block in init-db.sql.+ // item queries. `name` mirrors a column for the live-list sort. As of #1564+ // mood boards FEDERATE across peers via the per-record peer-sync push pipeline+ // (record kind `moodBoard`, sync category `moodBoards`), so the soft-delete+ // tombstone trio (deleted/deleted_at + LWW updated_at) mirrors+ // creative_director_projects — a delete is a tombstone the merge keeps an+ // out-of-date peer from resurrecting. Mirrors the mood_boards block in+ // init-db.sql; the ADD COLUMN upgrades below backfill existing installs.`CREATE TABLE IF NOT EXISTS mood_boards (id TEXT PRIMARY KEY,name TEXT NOT NULL,data JSONB NOT NULL DEFAULT '{}'::jsonb,created_at TIMESTAMPTZ DEFAULT NOW(),- updated_at TIMESTAMPTZ DEFAULT NOW()+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ deleted BOOLEAN DEFAULT FALSE,+ deleted_at TIMESTAMPTZ)`,+ // Backfill the tombstone columns on installs created before #1564 (the+ // CREATE above is a no-op once the table exists).+ `ALTER TABLE mood_boards ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,+ `ALTER TABLE mood_boards ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,// updated_at DESC is the board-list "recently touched" sort.`CREATE INDEX IF NOT EXISTS idx_mood_boards_updated ON mood_boards (updated_at DESC)`,+ // Partial index for the live-list filter (deleted = FALSE).+ `CREATE INDEX IF NOT EXISTS idx_mood_boards_live ON mood_boards (deleted) WHERE deleted = FALSE`,// Media asset index (Phase 3.2, issue #1000). One row per generated image// or video; the bytes stay on disk (data/images, data/videos) and thediff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.jsindex d9a382c9d2..e7ff831a24 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']),+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard']),recordId: z.string().trim().min(1).max(120),}).strict();@@ -190,6 +190,14 @@ const creativeDirectorProjectPushSchema = z.object({kind: z.literal('creativeDirectorProject'),...peerSyncPushBase,}).strict();+// Mood boards (#1564) push the bare record + any local image bytes its items[]+// reference in the asset manifest — no bundled children/linked collection rows,+// so the base shape alone suffices (`.strict()` rejects smuggled bundle keys,+// same posture as author/creativeDirectorProject).+const moodBoardPushSchema = z.object({+ kind: z.literal('moodBoard'),+ ...peerSyncPushBase,+}).strict();export const peerSyncPushSchema = z.discriminatedUnion('kind', [universePushSchema,seriesPushSchema,@@ -199,13 +207,14 @@ export const peerSyncPushSchema = z.discriminatedUnion('kind', [albumPushSchema,trackPushSchema,creativeDirectorProjectPushSchema,+ moodBoardPushSchema,]);// 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']),+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard']),recordId: z.string().trim().min(1).max(200),}).strict();diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex b514199ee6..196f9ce874 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -277,6 +277,16 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// sanitizer). The project body is LWW-overwritten whole; scene video renders// ride the project's linked media collection (federated separately).creativeDirectorProjects: 1,+ // v1 = Mood boards (PostgreSQL `mood_boards`) federated via the per-record+ // peer-sync push pipeline (record kind `moodBoard`, sync category `moodBoards`,+ // #1564). Same posture as `creativeDirectorProjects` above: 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 `moodBoards` and gets a 412 (only+ // that category pauses); a v1 receiver still accepts a ≤v0 sender (pre-feature+ // peers never push a `moodBoard`). The FIRST incompatible board-shape change+ // MUST bump this to 2 then. The board body (name/description/items) is+ // LWW-overwritten whole; referenced image bytes ride the asset manifest.+ moodBoards: 1,// NOTE: `videoHistory` is intentionally NOT listed here. The version gate// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the// comparator walks the union of keys), so declaring a brand-new key would@@ -321,6 +331,7 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({'cat-scrap': Object.freeze(['catalog']),storyBuilder: Object.freeze(['storyBuilder']),creativeDirectorProject: Object.freeze(['creativeDirectorProjects']),+ moodBoard: Object.freeze(['moodBoards']),});/**diff --git a/server/lib/syncWire.js b/server/lib/syncWire.jsindex 2ba9531b1d..29ae3ca8b8 100644--- a/server/lib/syncWire.js+++ b/server/lib/syncWire.js@@ -162,15 +162,17 @@ export function sanitizeRecordForWire(kind, record) {case 'artist':case 'album':case 'track':- case 'creativeDirectorProject': {- // Persona/music/creative-director records: like mediaCollection, no- // `ephemeral` flag — always wire-syncable when present. Strip-then-tail-+ case 'creativeDirectorProject':+ case 'moodBoard': {+ // 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// is LWW-overwritten on merge (no item-union), so the wire form converges// byte-for-byte and feeds the conflict-journal content hash directly (no// scalar narrowing in contentHashForRecord). A creativeDirectorProject is// larger than a persona (treatment/scenes/runs) but follows the same whole-- // record LWW contract — every field is app-authored data that mirrors.+ // record LWW contract — every field is app-authored data that mirrors; a+ // moodBoard (name/description/items) is the same whole-record contract.const { deleted: _d, deletedAt: _da, ...rest } = record;return { ...rest, ...sanitizeSoftDeleteFields(record) };}diff --git a/server/routes/instances.js b/server/routes/instances.jsindex b85605f417..135da4d6d3 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -66,6 +66,7 @@ const syncCategoriesSchema = z.object({albums: z.boolean().optional(),tracks: z.boolean().optional(),creativeDirectorProjects: z.boolean().optional(),+ moodBoards: z.boolean().optional(),catalog: z.boolean().optional()}).optional();diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 1345162b66..103a420d77 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -662,18 +662,30 @@ CREATE INDEX IF NOT EXISTS idx_creative_director_projects_live ON creative_direc-- text note, optional caption, and an optional source backref — kept inline in-- the board's JSONB rather than a child table because a board is read/written-- whole (a small bounded item list, no cross-board item queries). `name` mirrors--- a column for the live-list sort. Mood boards are db-primary and LOCAL-ONLY--- (no sync_sequence/tombstone) — like creative_director_projects, they don't--- federate to peers in v1. Mirrors the mood_boards block in db.js ensureSchema().+-- a column for the live-list sort. As of #1564 mood boards FEDERATE across peers+-- via the per-record peer-sync push pipeline (record kind `moodBoard`, sync+-- category `moodBoards`), so the soft-delete tombstone trio (deleted/deleted_at ++-- LWW updated_at) mirrors creative_director_projects — a delete is a tombstone the+-- merge keeps an out-of-date peer from resurrecting (NOT a hard DELETE). Mirrors+-- the mood_boards block in db.js ensureSchema().CREATE TABLE IF NOT EXISTS mood_boards (id TEXT PRIMARY KEY,name TEXT NOT NULL,data JSONB NOT NULL DEFAULT '{}'::jsonb,created_at TIMESTAMPTZ DEFAULT NOW(),- updated_at TIMESTAMPTZ DEFAULT NOW()+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ deleted BOOLEAN DEFAULT FALSE, -- soft-delete tombstone so deletes propagate to peers+ deleted_at TIMESTAMPTZ);+-- Backfill the tombstone columns on installs created before #1564 (the CREATE+-- above is a no-op once the table exists), so re-applying this schema to an+-- existing DB stays idempotent and the partial index below can reference `deleted`.+ALTER TABLE mood_boards ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE;+ALTER TABLE mood_boards ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;-- updated_at DESC is the board-list "recently touched" sort.CREATE INDEX IF NOT EXISTS idx_mood_boards_updated ON mood_boards (updated_at DESC);+-- Partial index for the live-list filter (deleted = FALSE).+CREATE INDEX IF NOT EXISTS idx_mood_boards_live ON mood_boards (deleted) WHERE deleted = FALSE;-- Media asset index (Phase 3.2, issue #1000). One row per generated image or-- video. The bytes stay on disk (data/images, data/videos) and the imagediff --git a/server/services/conflictJournalResolver.js b/server/services/conflictJournalResolver.jsindex c46d7fd358..628c3a8881 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/seriimport { 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 { restoreBoard } from './moodBoard/index.js';export const ERR_NOT_FOUND = 'CONFLICT_JOURNAL_NOT_FOUND';export const ERR_VALIDATION = 'CONFLICT_JOURNAL_VALIDATION';@@ -125,6 +126,13 @@ async function applyToRecord(kind, recordId, patch, { replace = false } = {}) {// same path. updateProject validates `status` and rejects a tombstoned row// (404 → translateGone → ERR_TARGET_GONE).await updateProject(recordId, patch).catch(translateGone);+ } else if (kind === 'moodBoard') {+ // restoreBoard applies the snapshot's name/description/items wholesale (via+ // applyBoardRestore — the route's applyBoardPatch only touches name/description,+ // so this dedicated path is what brings items[] back), so restore-all and+ // 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 {throw makeErr(`Unsupported conflict kind: ${kind}`, ERR_VALIDATION);}diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex b55b91b9e4..dcf7758787 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -1098,6 +1098,10 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {// file-snapshot category). Gated at applyIncomingPush via// compareSchemaVersions / RECORD_KIND_SCHEMA_CATEGORIES.creativeDirectorProject.'creativeDirectorProjects',+ // Mood boards (#1564) → per-record peer-push only (no 60s file-snapshot+ // category). Gated at applyIncomingPush via compareSchemaVersions /+ // RECORD_KIND_SCHEMA_CATEGORIES.moodBoard.+ 'moodBoards',]);const covered = new Set(Object.values(dataSync.getSnapshotCategorySchemaKeys()).flat());for (const key of Object.keys(PORTOS_SCHEMA_VERSIONS)) {diff --git a/server/services/instances.js b/server/services/instances.jsindex 372da775da..5b79e5a51d 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -239,6 +239,7 @@ const DEFAULT_SYNC_CATEGORIES = {albums: false,tracks: false,creativeDirectorProjects: false,+ moodBoards: false,catalog: false};@@ -271,6 +272,7 @@ const PER_RECORD_CATEGORY_KINDS = Object.freeze([['albums', 'album'],['tracks', 'track'],['creativeDirectorProjects', 'creativeDirectorProject'],+ ['moodBoards', 'moodBoard'],]);export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, auth }) {diff --git a/server/services/moodBoard/db.js b/server/services/moodBoard/db.jsindex 1b7e0a03f4..a3c95aa543 100644--- a/server/services/moodBoard/db.js+++ b/server/services/moodBoard/db.js@@ -3,8 +3,11 @@** One row per board in `mood_boards`: id / name / created_at / updated_at as* columns, the full record (name/description/items[]) in `data` JSONB. Mood- * boards are db-primary and local-only (no federation in v1), modeled on the- * creativeDirector projectsDB store.+ * boards are db-primary, modeled on the creativeDirector projectsDB store. As of+ * #1564 they FEDERATE across peers via the per-record peer-sync push pipeline+ * (record kind `moodBoard`, sync category `moodBoards`), so a delete is a+ * soft-delete tombstone (deleted/deleted_at + LWW updated_at) the merge keeps an+ * out-of-date peer from resurrecting — mirroring creative_director_projects.** Concurrency: the trust model is single-user, but a board has more than one* write path that can touch the SAME board (board PATCH + item add/update/remove@@ -24,10 +27,15 @@ import { mirrorTimestamp } from '../../lib/pgTimestamp.js';import {buildBoardRecord,applyBoardPatch,+ applyBoardRestore,addItem,updateItem,removeItem,+ mergeBoardRecord,} from './logic.js';+import {+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,+} from '../../lib/conflictJournal.js';// `data` JSONB is the whole record; name/created_at/updated_at mirror into// columns (kept in lockstep on every write) for the live-list sort. Reads@@ -41,34 +49,48 @@ async function persist(exec, board) {const now = new Date().toISOString();const createdAt = mirrorTimestamp(board.createdAt, now);await exec(- `INSERT INTO mood_boards (id, name, data, created_at, updated_at)- VALUES ($1, $2, $3::jsonb, $4, $5)+ `INSERT INTO mood_boards (id, name, data, created_at, updated_at, deleted, deleted_at)+ VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7)ON CONFLICT (id) DO UPDATE SETname = EXCLUDED.name,data = EXCLUDED.data,- updated_at = EXCLUDED.updated_at`,+ updated_at = EXCLUDED.updated_at,+ deleted = EXCLUDED.deleted,+ deleted_at = EXCLUDED.deleted_at`,[board.id,board.name,JSON.stringify(board),createdAt,mirrorTimestamp(board.updatedAt, createdAt),+ board.deleted === true,+ mirrorTimestamp(board.deletedAt, null),],);return board;}-export async function listBoards() {+export async function listBoards({ includeDeleted = false } = {}) {// updated_at DESC — most-recently-touched first (the board grid's default).- const result = await query(- `SELECT data FROM mood_boards ORDER BY updated_at DESC`,- );+ const result = includeDeleted+ ? await query(`SELECT data FROM mood_boards ORDER BY updated_at DESC`)+ : await query(`SELECT data FROM mood_boards WHERE deleted = FALSE ORDER BY updated_at DESC`);return result.rows.map(rowToBoard);}-export async function getBoard(id) {+export async function getBoard(id, { includeDeleted = false } = {}) {const result = await query(`SELECT data FROM mood_boards WHERE id = $1`, [id]);- return rowToBoard(result.rows[0]);+ const board = rowToBoard(result.rows[0]);+ if (!board) return null;+ return includeDeleted || !board.deleted ? board : null;+}++/** Live board ids (or all when includeDeleted) — used by tombstone GC sweeps. */+export async function listBoardIds({ includeDeleted = false } = {}) {+ const result = includeDeleted+ ? await query(`SELECT id FROM mood_boards`)+ : await query(`SELECT id FROM mood_boards WHERE deleted = FALSE`);+ return result.rows.map((r) => r.id);}export async function createBoard(input) {@@ -88,7 +110,13 @@ async function withLockedBoard(id, mutate) {[id],);const board = rowToBoard(sel.rows[0]);- if (!board) {+ // A tombstoned board (#1564 soft-delete) is treated as gone for every+ // user-facing mutator — without this, an item add/update/remove or a PATCH+ // after deletion would resurrect the row, bump updatedAt, and re-push a+ // modified tombstone to peers while getBoard 404s the same id.+ // mergeBoardsFromSync (peer tombstone apply) bypasses this path via its own+ // persist, so receiving a tombstone still works.+ if (!board || board.deleted) {throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });}const { board: next, result, skipPersist } = mutate(board);@@ -102,12 +130,88 @@ export async function updateBoard(id, patch) {return board;}+/**+ * Faithful conflict-restore (RESTORABLE_FIELDS.moodBoard = name/description/items)+ * wired into conflictJournalResolver. Goes through the row lock + tombstone guard+ * like every other mutator, but uses applyBoardRestore so a "restore my whole+ * version" also brings back items[] (applyBoardPatch only touches name/description).+ */+export async function restoreBoard(id, patch) {+ const { board } = await withLockedBoard(id, (b) => ({ board: applyBoardRestore(b, patch) }));+ return board;+}+export async function deleteBoard(id) {- const result = await query(`DELETE FROM mood_boards WHERE id = $1`, [id]);- if (result.rowCount === 0) {- throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });+ // Soft-delete tombstone (#1564) so the deletion federates and an out-of-date+ // peer can't resurrect the board via the LWW merge. The row stays; `deleted`+ // flips and `updatedAt`/`deletedAt` stamp now so the tombstone wins on merge.+ return withTransaction(async (client) => {+ const sel = await client.query(+ `SELECT data FROM mood_boards WHERE id = $1 FOR UPDATE`,+ [id],+ );+ const current = rowToBoard(sel.rows[0]);+ if (!current || current.deleted) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });+ const now = new Date().toISOString();+ const next = { ...current, deleted: true, deletedAt: now, updatedAt: now };+ await persist(client.query.bind(client), next);+ return { ok: true };+ });+}++/**+ * Merge an incoming batch of board 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 `mergeBoardRecord` decision —+ * identical contract to mergeProjectsFromSync: seeds/advances the conflict-journal+ * base hash and journals the about-to-be-overwritten local version when remote+ * wins (best-effort, never throws into the merge). Returns `{ applied, count }`.+ */+export async function mergeBoardsFromSync(remoteBoards, { source = { via: 'sync', peerId: null } } = {}) {+ if (!Array.isArray(remoteBoards)) return { applied: false, count: 0 };+ let changed = 0;+ for (const remote of remoteBoards) {+ const applied = await withTransaction(async (client) => {+ const sel = await client.query(`SELECT data FROM mood_boards WHERE id = $1 FOR UPDATE`, [remote?.id]);+ const local = rowToBoard(sel.rows[0]);+ const { next, inserted, remoteWins, changed: didChange } = mergeBoardRecord(local, remote);+ if (!next) return false; // malformed remote → dropped+ if (inserted) {+ await persist(client.query.bind(client), next);+ await setSyncBaseHash('moodBoard', next.id, contentHashForRecord('moodBoard', next));+ return true;+ }+ // local wins, OR remote won but is byte-identical to local (already agree).+ if (!remoteWins || !didChange) return false;+ await maybeJournalBeforeOverwrite({ kind: 'moodBoard', id: next.id, local, remote: next, source });+ await persist(client.query.bind(client), next);+ await setSyncBaseHash('moodBoard', next.id, contentHashForRecord('moodBoard', next));+ return true;+ });+ if (applied) changed += 1;}- return { ok: true };+ await flushBaseHashes();+ if (changed === 0) return { applied: false, count: 0 };+ return { applied: true, count: changed };+}++/**+ * Hard-remove tombstoned boards whose deletedAt is older than the cutoff. Called+ * by tombstoneGc once every subscribed peer has acked the deletion. Evicts each+ * pruned board's conflict-journal base hash (mirrors pruneTombstonedProjects).+ */+export async function pruneTombstonedBoards(olderThanMs) {+ if (!Number.isFinite(olderThanMs)) return { pruned: 0 };+ const cutoffIso = new Date(olderThanMs).toISOString();+ const { rows } = await query(+ `DELETE FROM mood_boards+ WHERE deleted = TRUE AND deleted_at IS NOT NULL AND deleted_at < $1+ RETURNING id`,+ [cutoffIso],+ );+ for (const r of rows) await deleteSyncBaseHash('moodBoard', r.id);+ return { pruned: rows.length };}export async function addBoardItem(id, itemInput) {diff --git a/server/services/moodBoard/db.test.js b/server/services/moodBoard/db.test.jsindex 1e92214c6f..77d90894cc 100644--- a/server/services/moodBoard/db.test.js+++ b/server/services/moodBoard/db.test.js@@ -4,13 +4,25 @@* Like projectsDB.test.js / mediaAssetIndex/db.test.js, this needs a live* PostgreSQL with the schema applied. If no DB is reachable (CI, fresh* checkout), it SKIPS cleanly rather than failing red. When a DB IS reachable it- * exercises create/list/get/update + the item add/update/remove ops, cleaning up- * its own rows after (only rows it created — no global table mutation).+ * exercises create/list/get/update + the item add/update/remove ops + the #1564+ * federation paths (soft-delete tombstone, LWW merge, prune, restore), cleaning+ * up its own rows after (only rows it created — no global table mutation).*/-import { describe, it, expect, afterAll, beforeAll } from 'vitest';+import { describe, it, expect, afterAll, beforeAll, vi } from 'vitest';import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';+// Stub the conflict-journal so mergeBoardsFromSync exercises its DB persist + LWW+// decision WITHOUT writing real base-hash / journal files under data/ during the+// test:db run (the pure LWW decision itself is pinned in logic.test.js).+vi.mock('../../lib/conflictJournal.js', () => ({+ maybeJournalBeforeOverwrite: vi.fn().mockResolvedValue(undefined),+ setSyncBaseHash: vi.fn().mockResolvedValue(undefined),+ contentHashForRecord: vi.fn(() => 'test-hash'),+ flushBaseHashes: vi.fn().mockResolvedValue(undefined),+ deleteSyncBaseHash: vi.fn().mockResolvedValue(undefined),+}));+let dbReady = false;let skipReason = '';{@@ -39,7 +51,7 @@ describe.skipIf(!dbReady)('mood board DB round-trip', () => {for (const id of created) {await query(`DELETE FROM mood_boards WHERE id = $1`, [id]).catch(() => {});}- await close();+ // The pool is closed once, by the federation describe's afterAll (runs last).});it('creates, lists, and gets a board (lossless data)', async () => {@@ -92,10 +104,87 @@ describe.skipIf(!dbReady)('mood board DB round-trip', () => {await expect(db.deleteBoard('mb-missing')).rejects.toThrow(/not found/i);});- it('deletes a board', async () => {+ it('soft-deletes a board (tombstone), hiding it from live reads but not includeDeleted', async () => {const board = await db.createBoard({ name: 'Delete me' });+ created.push(board.id); // soft-delete leaves the row — afterAll hard-deletes itconst result = await db.deleteBoard(board.id);expect(result.ok).toBe(true);+ // Live reads hide the tombstone…expect(await db.getBoard(board.id)).toBeNull();+ expect((await db.listBoards()).some((b) => b.id === board.id)).toBe(false);+ expect(await db.listBoardIds()).not.toContain(board.id);+ // …but includeDeleted surfaces it with the tombstone trio set.+ const tomb = await db.getBoard(board.id, { includeDeleted: true });+ expect(tomb).toMatchObject({ deleted: true });+ expect(typeof tomb.deletedAt).toBe('string');+ expect(await db.listBoardIds({ includeDeleted: true })).toContain(board.id);+ // Deleting again 404s (idempotent tombstone), and user mutators refuse it.+ await expect(db.deleteBoard(board.id)).rejects.toThrow(/not found/i);+ await expect(db.updateBoard(board.id, { name: 'zombie' })).rejects.toThrow(/not found/i);+ await expect(db.addBoardItem(board.id, { type: 'text', text: 'z' })).rejects.toThrow(/not found/i);+ });+});++describe.skipIf(!dbReady)('mood board federation (#1564)', () => {+ let db;+ const created = [];+ const remote = (id, over = {}) => ({+ id, name: `R-${id}`, description: '', items: [],+ createdAt: '2026-06-23T00:00:00.000Z', updatedAt: '2026-06-23T00:00:00.000Z',+ deleted: false, deletedAt: null, ...over,+ });+ beforeAll(async () => { db = await import('./db.js'); });+ afterAll(async () => {+ for (const id of created) await query(`DELETE FROM mood_boards WHERE id = $1`, [id]).catch(() => {});+ await close();+ });++ it('inserts a remote board on first merge', async () => {+ const id = `mb-fed-insert-${Date.now()}`;+ created.push(id);+ const res = await db.mergeBoardsFromSync([remote(id, { name: 'Inserted' })]);+ expect(res).toEqual({ applied: true, count: 1 });+ expect((await db.getBoard(id)).name).toBe('Inserted');+ });++ it('newer remote updatedAt wins; older loses', async () => {+ const id = `mb-fed-lww-${Date.now()}`;+ created.push(id);+ await db.mergeBoardsFromSync([remote(id, { name: 'v1', updatedAt: '2026-06-23T00:00:00.000Z' })]);+ // Older remote → no change.+ const older = await db.mergeBoardsFromSync([remote(id, { name: 'stale', updatedAt: '2026-06-22T00:00:00.000Z' })]);+ expect(older.applied).toBe(false);+ expect((await db.getBoard(id)).name).toBe('v1');+ // Newer remote → wins.+ await db.mergeBoardsFromSync([remote(id, { name: 'v2', updatedAt: '2026-06-24T00:00:00.000Z' })]);+ expect((await db.getBoard(id)).name).toBe('v2');+ });++ it('applies a remote tombstone (delete federates)', async () => {+ const id = `mb-fed-tomb-${Date.now()}`;+ created.push(id);+ await db.mergeBoardsFromSync([remote(id, { updatedAt: '2026-06-23T00:00:00.000Z' })]);+ await db.mergeBoardsFromSync([remote(id, { updatedAt: '2026-06-24T00:00:00.000Z', deleted: true, deletedAt: '2026-06-24T00:00:00.000Z' })]);+ expect(await db.getBoard(id)).toBeNull();+ expect(await db.getBoard(id, { includeDeleted: true })).toMatchObject({ deleted: true });+ });++ it('restoreBoard brings back name/description/items wholesale', async () => {+ const board = await db.createBoard({ name: 'Orig' });+ created.push(board.id);+ const items = [{ id: 'mbi-r1', type: 'text', text: 'restored', mediaKey: null, imageUrl: null, caption: null, source: null, createdAt: 't0' }];+ const restored = await db.restoreBoard(board.id, { name: 'Restored', description: 'd', items });+ expect(restored.name).toBe('Restored');+ expect(restored.items).toEqual(items);+ expect((await db.getBoard(board.id)).description).toBe('d');+ });++ it('pruneTombstonedBoards hard-removes tombstones older than the cutoff', async () => {+ const id = `mb-fed-prune-${Date.now()}`;+ created.push(id);+ await db.mergeBoardsFromSync([remote(id, { updatedAt: '2026-06-23T00:00:00.000Z', deleted: true, deletedAt: '2026-06-23T00:00:00.000Z' })]);+ const res = await db.pruneTombstonedBoards(Date.parse('2030-01-01T00:00:00.000Z'));+ expect(res.pruned).toBeGreaterThanOrEqual(1);+ expect(await db.getBoard(id, { includeDeleted: true })).toBeNull();});});diff --git a/server/services/moodBoard/index.js b/server/services/moodBoard/index.jsindex b326f23d97..e375a1bbae 100644--- a/server/services/moodBoard/index.js+++ b/server/services/moodBoard/index.js@@ -1,19 +1,94 @@/*** Mood Board service — public entry (issue #911).*- * Mood boards are db-primary, local-only records (no file backend, no- * federation in v1), so the public surface is just the Postgres store. The- * pure transforms live in logic.js (unit-tested without a DB); db.js does the- * row I/O + per-board row locking. Routes import from here.+ * Mood boards are db-primary records (no file backend). As of #1564 they FEDERATE+ * across peers via the per-record peer-sync push pipeline (record kind+ * `moodBoard`, sync category `moodBoards`). The pure transforms live in logic.js+ * (unit-tested without a DB); db.js does the row I/O + per-board row locking ++ * the LWW/tombstone merge. Routes import from here.+ *+ * This module wraps db.js's mutators with the peer-sync announce hooks — mirroring+ * authors/index.js — so creating/editing/deleting a board propagates to subscribed+ * peers. Announce is 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 mergeBoardsFromSync from here, so importing it back+ * would close a load-order cycle.*/+import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';+import * as store from './db.js';++// Read paths + federation entry points pass straight through to the store. The+// asset-manifest filename resolver lives in logic.js (pure) and is re-exported+// here so peerSync imports a single module (mirrors creativeDirector/local.js+// re-exporting startingImageFilename).export {listBoards,getBoard,- createBoard,- updateBoard,- deleteBoard,- addBoardItem,- updateBoardItem,- removeBoardItem,+ listBoardIds,+ mergeBoardsFromSync,+ pruneTombstonedBoards,} from './db.js';+export { imageUrlToImageFilename } from './logic.js';++// Announce a newly-created board to the per-record peer-sync pipeline: emit the+// 'updated' event so any existing subscription pushes it, AND auto-subscribe+// every moodBoards-enabled peer so brand-new boards (and their later tombstones)+// propagate. Call ONLY when a brand-new record was persisted. Mirrors+// authors/index.js announceNewAuthor.+function announceNewBoard(id) {+ emitRecordUpdated('moodBoard', id);+ autoSubscribeRecordToAllPeers('moodBoard', id).catch(() => {});+}++export async function createBoard(input) {+ const board = await store.createBoard(input);+ announceNewBoard(board.id);+ return board;+}++export async function updateBoard(id, patch) {+ const next = await store.updateBoard(id, patch);+ // A standalone board reaches peers only via its per-record subscription —+ // without this emit an edit never propagates after the initial subscribe.+ emitRecordUpdated('moodBoard', next.id);+ return next;+}++// Conflict-journal restore path (see db.restoreBoard). Re-propagate the restored+// version so it wins LWW on peers too.+export async function restoreBoard(id, patch) {+ const next = await store.restoreBoard(id, patch);+ emitRecordUpdated('moodBoard', next.id);+ return next;+}++export async function deleteBoard(id) {+ const result = await store.deleteBoard(id);+ // Soft-delete tombstone — push the deletion to subscribed peers immediately+ // (peerSync's delete listener reads the record with includeDeleted and pushes+ // the tombstone).+ emitRecordDeleted('moodBoard', id);+ return result;+}++// Inline item ops mutate the board record, so each propagates the whole board as+// a structural edit (human-pace affordances, not a hot loop — safe to emit every+// time; lastPushedHash + same-`updatedAt` LWW no-op dedup prevent ping-pong).+export async function addBoardItem(id, itemInput) {+ const item = await store.addBoardItem(id, itemInput);+ emitRecordUpdated('moodBoard', id);+ return item;+}++export async function updateBoardItem(id, itemId, patch) {+ const item = await store.updateBoardItem(id, itemId, patch);+ emitRecordUpdated('moodBoard', id);+ return item;+}++export async function removeBoardItem(id, itemId) {+ const board = await store.removeBoardItem(id, itemId);+ emitRecordUpdated('moodBoard', id);+ return board;+}diff --git a/server/services/moodBoard/logic.js b/server/services/moodBoard/logic.jsindex 06c5ce1324..dcff3b54dc 100644--- a/server/services/moodBoard/logic.js+++ b/server/services/moodBoard/logic.js@@ -13,6 +13,10 @@import { randomUUID } from 'crypto';import { ServerError } from '../../lib/errorHandler.js';+import { compareNewerWins } from '../../lib/lwwTimestamp.js';+import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';++const isStr = (v) => typeof v === 'string';// Bound the inline items[] so a single board row's JSONB can't grow without// limit (a board is loaded/serialized whole on every read/write). Far above any@@ -34,9 +38,78 @@ export function buildBoardRecord(input, { id, now = nowIso() } = {}) {items: [],createdAt: now,updatedAt: now,+ // Soft-delete / LWW tombstone trio (#1564) — boards federate across peers+ // via the per-record push pipeline (record kind `moodBoard`, sync category+ // `moodBoards`), so a delete is a tombstone the merge keeps an out-of-date+ // peer from resurrecting. Mirrors the creativeDirector project record.+ deleted: false,+ deletedAt: null,};}+/**+ * Normalize a raw board record into the canonical stored shape for a sync+ * round-trip. Returns null for a non-object or a record without a usable id+ * (mirrors `sanitizeProjectForSync`'s "drop on the floor" contract so a+ * malformed peer payload can't land). The board body (name/description/items)+ * passes through verbatim — it is all app-authored data — while the LWW key+ * (`updatedAt`) and the soft-delete trio are normalized so the wire/hash shape+ * is stable regardless of on-disk key position.+ */+export function sanitizeBoardForSync(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 board record against the local copy —+ * mirrors `mergeProjectRecord` (creativeDirector/projectsLogic.js):+ * - remote sanitized here (drop-on-floor on a malformed payload → `next: null`).+ * - No local counterpart → insert the remote verbatim (`inserted: true`).+ * - Both present → newer `updatedAt` wins (`compareNewerWins`: epoch-ms,+ * unparseable-loses, tie → local). Tombstones ride the same path.+ * Returns `{ next, inserted, remoteWins, changed }`; `changed` is false when the+ * winner is byte-identical to local. The whole record is LWW-overwritten (no+ * field-union), so it is hashed in full by `contentHashForRecord`.+ */+export function mergeBoardRecord(local, remoteRaw) {+ const remote = sanitizeBoardForSync(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 };+}++/**+ * Resolve a board item's app-path `imageUrl` to the bare gallery-image filename+ * under `data/images/` so the peer-sync asset pipeline can hash + transfer it.+ * Mirrors `startingImageFilename` in creativeDirector/projectsLogic.js: returns+ * null for an empty/non-string value, an external URL (`http(s)://…`, `data:`,+ * `blob:`), or any non-images absolute path — the receiver resolves those+ * itself. A media-key reference (`image:<ref>`) is handled separately by the+ * manifest builder (it carries the bare ref directly); this covers only the+ * `imageUrl` pointer.+ */+export function imageUrlToImageFilename(imageUrl) {+ if (!isStr(imageUrl)) return null;+ const url = imageUrl.trim();+ if (!url) return null;+ if (/^(https?:|data:|blob:)/i.test(url)) return null;+ let name = url;+ const imagesPrefix = '/data/images/';+ if (url.startsWith(imagesPrefix)) name = url.slice(imagesPrefix.length);+ else if (url.startsWith('/')) return null; // some other absolute path → not a gallery image+ name = name.split(/[?#]/)[0];+ const base = name.split('/').pop();+ return base || null;+}+// Apply a PATCH to board-level fields (name/description). Absent keys preserve// the original; a present empty string clears (description). `items` is managed// only through the dedicated item ops below, never a bulk board PATCH.@@ -126,3 +199,20 @@ export function removeItem(board, itemId) {const next = { ...board, items: nextItems, updatedAt: nowIso() };return { board: next, removed: true };}++// Faithful conflict-restore of the restorable board fields (RESTORABLE_FIELDS.+// moodBoard = name/description/items). Unlike applyBoardPatch — the route PATCH+// path, which only touches name/description because items are managed through+// the dedicated item ops — a "restore my whole version" must bring back the+// board's items[]. The conflict resolver narrows `patch` to the allowed fields+// (via `pick`), so this just spreads the present ones and bumps updatedAt so the+// restore wins LWW and re-propagates. Mirrors creativeDirector's+// applyProjectPatch wholesale-spread restore path.+export function applyBoardRestore(board, patch) {+ const next = { ...board };+ if (patch.name !== undefined) next.name = patch.name;+ if (patch.description !== undefined) next.description = patch.description;+ if (Array.isArray(patch.items)) next.items = patch.items;+ next.updatedAt = nowIso();+ return next;+}diff --git a/server/services/moodBoard/logic.test.js b/server/services/moodBoard/logic.test.jsindex 1c3da91487..f55dac06fc 100644--- a/server/services/moodBoard/logic.test.js+++ b/server/services/moodBoard/logic.test.js@@ -8,14 +8,18 @@ import { describe, it, expect } from 'vitest';import {buildBoardRecord,applyBoardPatch,+ applyBoardRestore,addItem,updateItem,removeItem,+ sanitizeBoardForSync,+ mergeBoardRecord,+ imageUrlToImageFilename,MAX_ITEMS_PER_BOARD,} from './logic.js';describe('buildBoardRecord', () => {- it('builds a board with empty items and mirrored timestamps', () => {+ it('builds a board with empty items, mirrored timestamps, and the soft-delete trio', () => {const board = buildBoardRecord({ name: 'Refs' }, { id: 'mb-1', now: 't0' });expect(board).toEqual({id: 'mb-1',@@ -24,6 +28,8 @@ describe('buildBoardRecord', () => {items: [],createdAt: 't0',updatedAt: 't0',+ deleted: false,+ deletedAt: null,});});it('keeps a provided description', () => {@@ -131,3 +137,90 @@ describe('removeItem', () => {expect(board).toBe(withItem);});});++describe('sanitizeBoardForSync', () => {+ it('drops a non-object or id-less record', () => {+ expect(sanitizeBoardForSync(null)).toBeNull();+ expect(sanitizeBoardForSync([])).toBeNull();+ expect(sanitizeBoardForSync({ name: 'no id' })).toBeNull();+ });+ it('normalizes the soft-delete trio and defaults updatedAt to createdAt', () => {+ const out = sanitizeBoardForSync({ id: 'mb-1', name: 'A', createdAt: 't0' });+ expect(out).toMatchObject({ id: 'mb-1', createdAt: 't0', updatedAt: 't0', deleted: false, deletedAt: null });+ });+ it('preserves a tombstone', () => {+ const out = sanitizeBoardForSync({ id: 'mb-1', name: 'A', createdAt: 't0', updatedAt: 't1', deleted: true, deletedAt: 't1' });+ expect(out).toMatchObject({ deleted: true, deletedAt: 't1' });+ });+});++describe('mergeBoardRecord (LWW)', () => {+ const board = (over = {}) => ({ id: 'mb-1', name: 'A', description: '', items: [], createdAt: 't0', updatedAt: '2026-06-23T00:00:00.000Z', deleted: false, deletedAt: null, ...over });++ it('inserts when there is no local copy', () => {+ const { next, inserted, remoteWins } = mergeBoardRecord(null, board());+ expect(inserted).toBe(true);+ expect(remoteWins).toBe(true);+ expect(next.id).toBe('mb-1');+ });+ it('drops a malformed remote', () => {+ expect(mergeBoardRecord(board(), { name: 'no id' }).next).toBeNull();+ });+ it('newer remote updatedAt wins', () => {+ const local = board({ updatedAt: '2026-06-23T00:00:00.000Z' });+ const remote = board({ name: 'B', updatedAt: '2026-06-24T00:00:00.000Z' });+ const { remoteWins, changed, next } = mergeBoardRecord(local, remote);+ expect(remoteWins).toBe(true);+ expect(changed).toBe(true);+ expect(next.name).toBe('B');+ });+ it('older remote loses (local kept)', () => {+ const local = board({ name: 'local', updatedAt: '2026-06-24T00:00:00.000Z' });+ const remote = board({ name: 'remote', updatedAt: '2026-06-23T00:00:00.000Z' });+ const { remoteWins, next } = mergeBoardRecord(local, remote);+ expect(remoteWins).toBe(false);+ expect(next.name).toBe('local');+ });+ it('a tombstone with a newer updatedAt wins over a live local', () => {+ const local = board({ updatedAt: '2026-06-23T00:00:00.000Z' });+ const remote = board({ updatedAt: '2026-06-24T00:00:00.000Z', deleted: true, deletedAt: '2026-06-24T00:00:00.000Z' });+ const { remoteWins, next } = mergeBoardRecord(local, remote);+ expect(remoteWins).toBe(true);+ expect(next.deleted).toBe(true);+ });+ it('reports changed:false when the winner is byte-identical to local', () => {+ const local = board();+ const { changed } = mergeBoardRecord(local, board());+ expect(changed).toBe(false);+ });+});++describe('imageUrlToImageFilename', () => {+ it('strips the app-path prefix to a bare gallery filename', () => {+ expect(imageUrlToImageFilename('/data/images/foo.png')).toBe('foo.png');+ expect(imageUrlToImageFilename('/data/images/sub/foo.png?v=2')).toBe('foo.png');+ });+ it('returns null for external / non-images / empty values', () => {+ expect(imageUrlToImageFilename('https://x/y.png')).toBeNull();+ expect(imageUrlToImageFilename('data:image/png;base64,AAA')).toBeNull();+ expect(imageUrlToImageFilename('/data/videos/clip.mp4')).toBeNull();+ expect(imageUrlToImageFilename('')).toBeNull();+ expect(imageUrlToImageFilename(null)).toBeNull();+ });+});++describe('applyBoardRestore', () => {+ it('wholesale-restores name/description/items (unlike applyBoardPatch) and bumps updatedAt', () => {+ const base = buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' });+ const items = [{ id: 'mbi-1', type: 'text', text: 'restored', mediaKey: null, imageUrl: null, caption: null, source: null, createdAt: 't0' }];+ const next = applyBoardRestore(base, { name: 'B', description: 'd', items });+ expect(next.name).toBe('B');+ expect(next.description).toBe('d');+ expect(next.items).toEqual(items);+ expect(next.updatedAt).not.toBe('t0');+ });+ it('ignores a non-array items field', () => {+ const base = { ...buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' }), items: [{ id: 'x' }] };+ expect(applyBoardRestore(base, { items: 'nope' }).items).toEqual([{ id: 'x' }]);+ });+});diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex a8d520e17f..e23a6309f7 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -103,13 +103,20 @@ import {mergeProjectsFromSync,startingImageFilename,} from '../creativeDirector/local.js';+import {+ getBoard,+ listBoards,+ mergeBoardsFromSync,+ imageUrlToImageFilename,+} from '../moodBoard/index.js';+import { parseKey } from '../../lib/mediaItemKey.js';import {initCursor,ackDeletesUpTo,removeCursor as removeTombstoneCursor,} from './peerTombstoneCursors.js';-export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject']);+export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard']);/*** Cross-cutting event bus for the peer-sync receiver. The asset-pull worker@@ -387,6 +394,7 @@ const KIND_TO_CATEGORY = Object.freeze({album: 'albums',track: 'tracks',creativeDirectorProject: 'creativeDirectorProjects',+ moodBoard: 'moodBoards',});function peerAllowsOutbound(peer) {@@ -487,6 +495,8 @@ async function listRecordsForKind(recordKind) {records = await listTracks({ includeDeleted: false }).catch(() => []);} else if (recordKind === 'creativeDirectorProject') {records = await listProjects({ includeDeleted: false }).catch(() => []);+ } else if (recordKind === 'moodBoard') {+ records = await listBoards({ includeDeleted: false }).catch(() => []);}return records.filter(r => r?.ephemeral !== true && isNonEmptyStr(r?.id));}@@ -790,6 +800,7 @@ async function buildIntegrityAssetManifest(kind, record) {if (kind === 'album') return buildAlbumAssetManifest(record);if (kind === 'track') return buildTrackAssetManifest(record);if (kind === 'creativeDirectorProject') return buildProjectAssetManifest(record);+ if (kind === 'moodBoard') return buildBoardAssetManifest(record);if (kind === 'series') {const childIssues = await listIssues({ seriesId: record?.id, includeDeleted: true }).catch(() => []);const manifestIssues = childIssues.filter(@@ -1012,6 +1023,10 @@ async function isSubscriptionRecordTombstone(sub) {const record = await getProject(sub.recordId, { includeDeleted: true }).catch(() => null);return record?.deleted === true;}+ if (sub.recordKind === 'moodBoard') {+ const record = await getBoard(sub.recordId, { includeDeleted: true }).catch(() => null);+ return record?.deleted === true;+ }return false;}@@ -1570,6 +1585,14 @@ async function buildPushPayload(sub, sourceInstanceId) {const assetManifest = record.deleted === true ? [] : await buildProjectAssetManifest(record);return { kind: 'creativeDirectorProject', record: sanitized, assetManifest, sourceInstanceId, portosMeta };}+ if (sub.recordKind === 'moodBoard') {+ const record = await getBoard(sub.recordId, { includeDeleted: true }).catch(() => null);+ if (!record) return null;+ const sanitized = sanitizeRecordForWire('moodBoard', record);+ if (!sanitized) return null;+ const assetManifest = record.deleted === true ? [] : await buildBoardAssetManifest(record);+ return { kind: 'moodBoard', record: sanitized, assetManifest, sourceInstanceId, portosMeta };+ }return null;}@@ -1636,6 +1659,46 @@ async function buildProjectAssetManifest(project) {return entry ? [entry] : [];}+/**+ * Hash the local image bytes a mood board's items reference so the receiver can+ * pull them from `/data/images/` (or `/data/videos/`). An image item points at+ * local bytes two ways: a media-key (`image:<ref>` / `video:<ref>`) into the+ * gallery, or an app-path `imageUrl` (`/data/images/...`). External URLs+ * (http(s)/data/blob) resolve on the receiver itself → skipped. Mirrors+ * `buildAssetManifestForCollection`: path-traversal-guarded, missing-local-file+ * skipped silently (including a null-hash entry would make every receiver+ * re-request bytes the sender can't fulfill), dedup-by-`<kind>:<filename>` so a+ * media-key and imageUrl pointing at the same file ship once. Text items carry+ * no bytes.+ */+async function buildBoardAssetManifest(board) {+ const dedup = new Map();+ for (const it of board?.items || []) {+ if (!it || it.type !== 'image') continue;+ const pending = [];+ if (typeof it.mediaKey === 'string') {+ const parsed = parseKey(it.mediaKey);+ if (parsed) {+ const safeName = sanitizeAssetFilename(parsed.ref);+ if (safeName) {+ pending.push(parsed.kind === 'video'+ ? hashSimpleAsset(collectionVideoRefToFilename(safeName), 'video', PATHS.videos)+ : hashImageForManifest(safeName));+ }+ }+ }+ if (typeof it.imageUrl === 'string') {+ const filename = imageUrlToImageFilename(it.imageUrl);+ const safeName = filename ? sanitizeAssetFilename(filename) : null;+ if (safeName) pending.push(hashImageForManifest(safeName));+ }+ for (const entry of await Promise.all(pending)) {+ if (entry) dedup.set(`${entry.kind}:${entry.filename}`, entry);+ }+ }+ return [...dedup.values()];+}+/*** Build the catalog bundle (`{ ingredients, refs }`) that piggy-backs on a* universe record push. Catalog data lives in Postgres only — on a non-Postgres@@ -1985,6 +2048,8 @@ export async function applyIncomingPush(payload) {await mergeTracksFromSync([record], { source });} else if (kind === 'creativeDirectorProject') {await mergeProjectsFromSync([record], { source });+ } else if (kind === 'moodBoard') {+ await mergeBoardsFromSync([record], { source });}// Apply the bundled collection (if any) — same LWW + union-of-items@@ -2227,6 +2292,13 @@ async function classifyLocalRecord(recordKind, recordId) {const p = await getProject(recordId, { includeDeleted: true }).catch(() => null);return p ? 'syncable' : 'missing';}+ if (recordKind === 'moodBoard') {+ // Mood boards have no `ephemeral` concept (like the persona/music/CD kinds) —+ // a found record (live or tombstoned) is always 'syncable'. No ping-pong risk:+ // lastPushedHash + LWW same-`updatedAt` no-op merge prevent it.+ const b = await getBoard(recordId, { includeDeleted: true }).catch(() => null);+ return b ? 'syncable' : 'missing';+ }return 'missing';}diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 0654a952cb..650f3579e4 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -313,12 +313,12 @@ afterEach(async () => {describe('peerSync', () => {describe('PEER_SUBSCRIBABLE_KINDS', () => {- it('is exactly [universe, series, mediaCollection, author, artist, album, track, creativeDirectorProject]', () => {+ it('is exactly [universe, series, mediaCollection, author, artist, album, track, creativeDirectorProject, moodBoard]', () => {// Exact equality (not toContain) so an accidental add/remove/reorder is// 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']);+ expect(PEER_SUBSCRIBABLE_KINDS).toEqual(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard']);});});diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.jsindex bbe80b18a3..96d7727e86 100644--- a/server/services/sharing/tombstoneGc.js+++ b/server/services/sharing/tombstoneGc.js@@ -35,6 +35,7 @@ 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 { pruneTombstonedBoards, listBoardIds } from '../moodBoard/index.js';import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';@@ -56,6 +57,7 @@ const LIVE_ID_LISTERS = Object.freeze({album: () => listAlbumIds(),track: () => listTrackIds(),creativeDirectorProject: () => listProjectIds(),+ moodBoard: () => listBoardIds(),});// Each peer-subscribable kind's UNCAPPED id source INCLUDING tombstones —@@ -74,6 +76,7 @@ const ALL_ID_LISTERS = Object.freeze({album: () => listAlbumIds({ includeDeleted: true }),track: () => listTrackIds({ includeDeleted: true }),creativeDirectorProject: () => listProjectIds({ includeDeleted: true }),+ moodBoard: () => listBoardIds({ includeDeleted: true }),});// Build a kind-aware id-membership resolver for ONE sweep: lazily list each@@ -243,6 +246,7 @@ function refusedFromCutoffs(cutoffs) {albumCutoff,trackCutoff,projectCutoff,+ boardCutoff,} = cutoffs;if (universeCutoff === null) refused.push('universe');// Issue tombstones ride series pushes — refused exactly when series is.@@ -259,6 +263,7 @@ function refusedFromCutoffs(cutoffs) {if (albumCutoff === null) refused.push('album');if (trackCutoff === null) refused.push('track');if (projectCutoff === null) refused.push('creativeDirectorProject');+ if (boardCutoff === null) refused.push('moodBoard');return refused;}@@ -284,6 +289,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =albumCutoff,trackCutoff,projectCutoff,+ boardCutoff,] = await Promise.all([cutoffForKind('universe', { peers, subs, now, graceMs }),cutoffForKind('series', { peers, subs, now, graceMs }),@@ -293,9 +299,10 @@ 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('moodBoard', { peers, subs, now, graceMs }),]);const issueCutoff = seriesCutoff;- const [u, s, i, c, a, ar, al, t, cd] = await Promise.all([+ const [u, s, i, c, a, ar, al, t, cd, mb] = 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),@@ -305,6 +312,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),+ boardCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedBoards(boardCutoff),]);// Backstop AFTER the tombstone prunes: the prune paths already evict a freshly// hard-deleted record's base hash, so this sweep mops up only keys that@@ -330,9 +338,10 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =albums: al.pruned,tracks: t.pruned,creativeDirectorProjects: cd.pruned,+ moodBoards: mb.pruned,orphanBaseHashes: orphan.pruned,orphanSubscriptions: orphanSubs.pruned,- refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff }),+ refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, boardCutoff }),};}@@ -341,7 +350,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] = await Promise.all([+ const [universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, boardCutoff] = await Promise.all([cutoffForKind('universe', { peers, subs, now, graceMs: 0 }),cutoffForKind('series', { peers, subs, now, graceMs: 0 }),cutoffForKind('mediaCollection', { peers, subs, now, graceMs: 0 }),@@ -350,8 +359,9 @@ 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('moodBoard', { peers, subs, now, graceMs: 0 }),]);- return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff }) };+ return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, boardCutoff }) };}export const TOMBSTONE_GRACE_MS = GRACE_MS;diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.jsindex c2feb76091..4e30fc8972 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('../moodBoard/index.js', () => ({+ pruneTombstonedBoards: vi.fn().mockResolvedValue({ pruned: 0 }),+ listBoardIds: vi.fn().mockResolvedValue([]),+}));vi.mock('../../lib/conflictJournal.js', () => ({pruneOrphanedBaseHashes: vi.fn().mockResolvedValue({ pruned: 0 }),}));@@ -68,6 +72,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 { pruneTombstonedBoards } from '../moodBoard/index.js';import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';@@ -424,6 +429,7 @@ describe('sweepTombstones — return shape', () => {pruneTombstonedAlbums.mockResolvedValueOnce({ pruned: 6 });pruneTombstonedTracks.mockResolvedValueOnce({ pruned: 7 });pruneTombstonedProjects.mockResolvedValueOnce({ pruned: 8 });+ pruneTombstonedBoards.mockResolvedValueOnce({ pruned: 9 });const result = await sweepTombstones({ now: NOW });expect(result).toEqual({universes: 2,@@ -435,6 +441,7 @@ describe('sweepTombstones — return shape', () => {albums: 6,tracks: 7,creativeDirectorProjects: 8,+ moodBoards: 9,orphanBaseHashes: 0,orphanSubscriptions: 0,refused: [],