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: federate Creative Director projects across peers (#1564)

[._.]/ Adam Eivyaa33aed4a5cc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9688d521ca..3b365a4370 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -59,6 +59,8 @@
- **[issue-1636] Reciprocal sync (including full mirror) is now truly two-directional when one machine added the other.** When machine A added peer B and asked B to mirror back — but the user on B never explicitly added A — B adopted the sync categories yet still never pushed its *own* existing universes, series, authors, and music back to A, so the "mirror" was silently one-directional until someone on B also connected to A. B now treats A's explicit reciprocal-sync request as permission to push back and starts mirroring its existing records to A right away. Machines that mutually added each other were already fine; this only fixes the asymmetric "A added B" setup.
+- **[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`)
+
- **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.jsx
index dde8ce55a0..18d08fa747 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
+ Lock, Globe, Info, Sparkles, Film, Images, Library, BookOpen, FilePen, Music, Music2, Disc3, Clapperboard
} from 'lucide-react';
import toast from '../components/ui/Toast';
import Pill from '../components/ui/Pill';
@@ -521,13 +521,14 @@ const SYNC_CATEGORY_META = [
{ key: 'artists', label: 'Artists', icon: Music, description: 'Music artist personas + portraits (PostgreSQL)' },
{ 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: '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']);
+const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors', 'artists', 'albums', 'tracks', 'creativeDirectorProjects']);
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 8cf5e02b4f..ecefe3ba40 100644
--- a/server/lib/conflictJournal.js
+++ b/server/lib/conflictJournal.js
@@ -324,6 +324,16 @@ export const RESTORABLE_FIELDS = Object.freeze({
// `seriesId` is the immutable parent link, `origin` is share provenance —
// and `mergeIssuePatch` accepts every field listed here.
issue: ['title', 'status', 'seasonId', 'arcPosition', 'arcRole', 'lengthProfile', 'pageTarget', 'minutesTarget', 'stages'],
+ // Creative Director projects (#1564): the user-authored config + creative
+ // content the merge can restore. `treatment` (logline/synopsis/scenes) carries
+ // the bulk of the work. Server-owned / machine-managed fields are excluded —
+ // `id`/`createdAt`/the LWW-tombstone trip are structural, `collectionId`/
+ // `timelineProjectId`/`finalVideoId` are derived output pointers, and `runs[]`
+ // is render history (regenerated, 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. `creativeDirectorProject`
+ // matches the record kind and mergeProjectRecord accepts every field here.
+ creativeDirectorProject: ['name', 'status', 'styleSpec', 'userStory', 'treatment', 'aspectRatio', 'quality', 'modelId', 'targetDurationSeconds', 'disableAudio', 'autoAcceptScenes', 'startingImageFile'],
});
const present = (v) => v !== undefined;
diff --git a/server/lib/db.js b/server/lib/db.js
index c69a7782c8..eb33939e61 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -809,19 +809,29 @@ async function ensureSchemaImpl() {
// Creative Director projects (Phase 3, issue #997). One row per project;
// the full record lives in `data` JSONB, with status/created_at/updated_at
// mirrored into columns (kept in lockstep on every write) for future
- // queries. `listProjects` sorts by created_at; nothing filters status yet
- // (the recovery scan filters in JS), so no status/updated_at index — an
- // unused index is just write amplification. CD is local-only (not
- // federated) so no sync_sequence/tombstone. `status` is app-layer gated
- // (PROJECT_STATUSES), no DB CHECK. Mirrors the creative_director_projects
- // block in init-db.sql.
+ // queries. `listProjects` sorts by created_at. `status` is app-layer gated
+ // (PROJECT_STATUSES), no DB CHECK. As of #1564 projects FEDERATE across peers
+ // via the per-record peer-sync push pipeline (record kind
+ // `creativeDirectorProject`, sync category `creativeDirectorProjects`), so
+ // the soft-delete tombstone trio (deleted/deleted_at + LWW updated_at) mirrors
+ // the authors table — a delete is a tombstone the merge keeps an out-of-date
+ // peer from resurrecting. Mirrors the creative_director_projects block in
+ // init-db.sql; the ADD COLUMN upgrades below backfill existing installs.
`CREATE TABLE IF NOT EXISTS creative_director_projects (
id TEXT PRIMARY KEY,
status VARCHAR(32) NOT NULL DEFAULT 'draft',
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). The partial index serves
+ // the live-list filter (deleted = FALSE).
+ `ALTER TABLE creative_director_projects ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
+ `ALTER TABLE creative_director_projects ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
+ `CREATE INDEX IF NOT EXISTS idx_creative_director_projects_live ON creative_director_projects (deleted) WHERE deleted = FALSE`,
// Mood boards (issue #911). A dedicated inspiration/mood-board canvas,
// distinct from raw Media History, for collecting visual + textual
diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.js
index db7868e026..d9a382c9d2 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']),
+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject']),
recordId: z.string().trim().min(1).max(120),
}).strict();
@@ -181,6 +181,15 @@ const trackPushSchema = z.object({
kind: z.literal('track'),
...peerSyncPushBase,
}).strict();
+// Creative Director projects (#1564) push the bare record + the project's
+// `startingImageFile` in the asset manifest — no bundled children/linked
+// collection/catalog rows (scene renders ride the project's linked media
+// collection, federated separately), so the base shape alone (`.strict()`
+// rejects smuggled bundle keys, same posture as author/mediaCollection).
+const creativeDirectorProjectPushSchema = z.object({
+ kind: z.literal('creativeDirectorProject'),
+ ...peerSyncPushBase,
+}).strict();
export const peerSyncPushSchema = z.discriminatedUnion('kind', [
universePushSchema,
seriesPushSchema,
@@ -189,13 +198,14 @@ export const peerSyncPushSchema = z.discriminatedUnion('kind', [
artistPushSchema,
albumPushSchema,
trackPushSchema,
+ creativeDirectorProjectPushSchema,
]);
// 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']),
+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject']),
recordId: z.string().trim().min(1).max(200),
}).strict();
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index c1d6df08fe..b514199ee6 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -263,6 +263,20 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// to 2 then (where a v1 peer would round-trip the new shape through an
// unaware sanitizer).
storyBuilder: 1,
+ // v1 = Creative Director projects (PostgreSQL `creative_director_projects`)
+ // federated via the per-record peer-sync push pipeline (record kind
+ // `creativeDirectorProject`, sync category `creativeDirectorProjects`, #1564).
+ // A brand-NEW synced record type like `authors`/`storyBuilder`, so it gets its
+ // own per-category gate: a v1 sender pushing to a ≤v0 (pre-feature) receiver is
+ // sender-ahead on `creativeDirectorProjects` and gets a 412 — only that
+ // category pauses; every other keeps flowing (per-category gate via
+ // scopeVersionDiff). A v1 receiver still accepts a ≤v0 sender (sender-behind):
+ // pre-feature peers never push a `creativeDirectorProject` at all, so there's
+ // nothing to gate. The FIRST incompatible project-shape change MUST bump this
+ // to 2 then (where a v1 peer would round-trip the new shape through an unaware
+ // sanitizer). The project body is LWW-overwritten whole; scene video renders
+ // ride the project's linked media collection (federated separately).
+ creativeDirectorProjects: 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
@@ -306,6 +320,7 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({
'cat-ingredient': Object.freeze(['catalog']),
'cat-scrap': Object.freeze(['catalog']),
storyBuilder: Object.freeze(['storyBuilder']),
+ creativeDirectorProject: Object.freeze(['creativeDirectorProjects']),
});
/**
diff --git a/server/lib/syncWire.js b/server/lib/syncWire.js
index 8b737a69b2..2ba9531b1d 100644
--- a/server/lib/syncWire.js
+++ b/server/lib/syncWire.js
@@ -161,14 +161,16 @@ export function sanitizeRecordForWire(kind, record) {
case 'author':
case 'artist':
case 'album':
- case 'track': {
- // Persona/music 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 full record is small (a handful of text
- // fields + the LWW/tombstone trio), so unlike mediaCollection there's no
- // item-union — the whole record is LWW-overwritten on merge and the wire
- // form converges byte-for-byte, so it feeds the conflict-journal content
- // hash directly (no scalar narrowing in contentHashForRecord).
+ case 'track':
+ case 'creativeDirectorProject': {
+ // Persona/music/creative-director 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.
const { deleted: _d, deletedAt: _da, ...rest } = record;
return { ...rest, ...sanitizeSoftDeleteFields(record) };
}
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 719603d6a6..1345162b66 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -635,9 +635,12 @@ CREATE TRIGGER trg_catalog_tag_updated_at
-- creative-director-projects.json caused. Normalizing scenes/runs is deferred
-- to a later phase if a cross-project scene/run query ever materializes.
--
--- CD is local-only (NOT federated — see plan §"Peer sync"), so there is no
--- sync_sequence / soft-delete-tombstone column: a delete is a hard DELETE.
--- `status` has no DB CHECK; valid values are gated at the app layer via
+-- As of #1564 CD projects FEDERATE across peers via the per-record peer-sync
+-- push pipeline (record kind `creativeDirectorProject`, sync category
+-- `creativeDirectorProjects`), so the soft-delete tombstone trio
+-- (deleted/deleted_at + LWW updated_at) mirrors the authors table — a delete is a
+-- tombstone the merge keeps an out-of-date peer from resurrecting (NOT a hard
+-- DELETE). `status` has no DB CHECK; valid values are gated at the app layer via
-- PROJECT_STATUSES (creativeDirectorPresets.js), matching the catalog
-- ingredients convention so a new status needs no constraint migration.
CREATE TABLE IF NOT EXISTS creative_director_projects (
@@ -645,8 +648,12 @@ CREATE TABLE IF NOT EXISTS creative_director_projects (
status VARCHAR(32) NOT NULL DEFAULT 'draft',
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
);
+-- Partial index for the live-list filter (deleted = FALSE).
+CREATE INDEX IF NOT EXISTS idx_creative_director_projects_live ON creative_director_projects (deleted) WHERE deleted = FALSE;
-- Mood boards (issue #911). A dedicated inspiration/mood-board canvas, distinct
-- from raw Media History, for collecting visual + textual references that feed
diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.js
index ba0f2a81bc..3370bdd661 100644
--- a/server/services/creativeDirector/local.js
+++ b/server/services/creativeDirector/local.js
@@ -23,8 +23,9 @@
*/
import { checkHealth, ensureSchema } from '../../lib/db.js';
+import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';
-export { trimRuns } from './projectsLogic.js';
+export { trimRuns, startingImageFilename } from './projectsLogic.js';
let backend = null;
let backendName = null;
@@ -65,32 +66,76 @@ export function getProjectsBackendName() {
return backendName;
}
-export async function listProjects() {
- return (await selectBackend()).listProjects();
+// Announce a newly-created project to the per-record peer-sync pipeline (#1564):
+// emit the 'updated' event so any existing subscription pushes it, AND
+// auto-subscribe every creativeDirectorProjects-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 authors/index.js announceNewAuthor.
+function announceNewProject(id) {
+ emitRecordUpdated('creativeDirectorProject', id);
+ autoSubscribeRecordToAllPeers('creativeDirectorProject', id).catch(() => {});
}
-export async function getProject(id) {
- return (await selectBackend()).getProject(id);
+export async function listProjects(options = {}) {
+ return (await selectBackend()).listProjects(options);
+}
+
+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);
+ // A standalone project reaches peers only via its per-record subscription —
+ // without this emit a structural edit never propagates after the initial
+ // subscribe. The hot-path render mutators (recordRun/updateRun) deliberately
+ // do NOT emit (they fire many times per scene render); run-history converges
+ // on the next structural push, which carries the whole record (runs included).
+ emitRecordUpdated('creativeDirectorProject', next.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('creativeDirectorProject', id);
+ return result;
}
export async function setTreatment(id, treatmentInput) {
- return (await selectBackend()).setTreatment(id, treatmentInput);
+ const next = await (await selectBackend()).setTreatment(id, treatmentInput);
+ emitRecordUpdated('creativeDirectorProject', id);
+ return next;
}
export async function updateScene(id, sceneId, patch) {
- return (await selectBackend()).updateScene(id, sceneId, patch);
+ const result = await (await selectBackend()).updateScene(id, sceneId, patch);
+ emitRecordUpdated('creativeDirectorProject', id);
+ return result;
+}
+
+/** 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);
}
export async function recordRun(id, runEntry) {
diff --git a/server/services/creativeDirector/projectsDB.js b/server/services/creativeDirector/projectsDB.js
index c78a29da74..97dfdf1595 100644
--- a/server/services/creativeDirector/projectsDB.js
+++ b/server/services/creativeDirector/projectsDB.js
@@ -31,7 +31,11 @@ import {
applySceneUpdate,
appendRun,
applyRunUpdate,
+ mergeProjectRecord,
} from './projectsLogic.js';
+import {
+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+} from '../../lib/conflictJournal.js';
// The `data` JSONB is the whole record. status/created_at/updated_at are
// mirrored into columns (kept in lockstep with the JSONB on every write) for
@@ -55,35 +59,49 @@ async function persist(exec, project) {
const now = new Date().toISOString();
const createdAt = mirrorTimestamp(project.createdAt, now);
await exec(
- `INSERT INTO creative_director_projects (id, status, data, created_at, updated_at)
- VALUES ($1, $2, $3::jsonb, $4, $5)
+ `INSERT INTO creative_director_projects (id, status, data, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7)
ON CONFLICT (id) DO UPDATE SET
status = EXCLUDED.status,
data = EXCLUDED.data,
- updated_at = EXCLUDED.updated_at`,
+ updated_at = EXCLUDED.updated_at,
+ deleted = EXCLUDED.deleted,
+ deleted_at = EXCLUDED.deleted_at`,
[
project.id,
mirrorStatus(project.status),
JSON.stringify(project),
createdAt,
mirrorTimestamp(project.updatedAt, createdAt),
+ project.deleted === true,
+ mirrorTimestamp(project.deletedAt, null),
],
);
return project;
}
-export async function listProjects() {
+export async function listProjects({ includeDeleted = false } = {}) {
// created_at ASC preserves the file backend's append order (the UI sorts
// client-side; recovery + tests don't depend on order, but stable beats random).
- const result = await query(
- `SELECT data FROM creative_director_projects ORDER BY created_at ASC`,
- );
+ const result = includeDeleted
+ ? await query(`SELECT data FROM creative_director_projects ORDER BY created_at ASC`)
+ : await query(`SELECT data FROM creative_director_projects WHERE deleted = FALSE ORDER BY created_at ASC`);
return result.rows.map(rowToProject);
}
-export async function getProject(id) {
+export async function getProject(id, { includeDeleted = false } = {}) {
const result = await query(`SELECT data FROM creative_director_projects WHERE id = $1`, [id]);
- return rowToProject(result.rows[0]);
+ const project = rowToProject(result.rows[0]);
+ if (!project) return null;
+ 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 creative_director_projects`)
+ : await query(`SELECT id FROM creative_director_projects WHERE deleted = FALSE`);
+ return result.rows.map((r) => r.id);
}
export async function createProject(input) {
@@ -124,9 +142,78 @@ export async function updateProject(id, patch) {
}
export async function deleteProject(id) {
- const result = await query(`DELETE FROM creative_director_projects WHERE id = $1`, [id]);
- if (result.rowCount === 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- return { ok: true };
+ // Soft-delete tombstone (#1564) so the deletion federates and an out-of-date
+ // peer can't resurrect the project 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 creative_director_projects WHERE id = $1 FOR UPDATE`,
+ [id],
+ );
+ const current = rowToProject(sel.rows[0]);
+ if (!current || current.deleted) throw new ServerError('Project 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 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. Mirrors
+ * `mergeAuthorsFromSync`: 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 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 creative_director_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('creativeDirectorProject', next.id, contentHashForRecord('creativeDirectorProject', next));
+ return true;
+ }
+ // local wins, OR remote won but is byte-identical to local (already agree).
+ if (!remoteWins || !didChange) return false;
+ await maybeJournalBeforeOverwrite({ kind: 'creativeDirectorProject', id: next.id, local, remote: next, source });
+ await persist(client.query.bind(client), next);
+ await setSyncBaseHash('creativeDirectorProject', next.id, contentHashForRecord('creativeDirectorProject', 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
+ * pruneTombstonedAuthors).
+ */
+export async function pruneTombstonedProjects(olderThanMs) {
+ if (!Number.isFinite(olderThanMs)) return { pruned: 0 };
+ const cutoffIso = new Date(olderThanMs).toISOString();
+ const { rows } = await query(
+ `DELETE FROM creative_director_projects
+ WHERE deleted = TRUE AND deleted_at IS NOT NULL AND deleted_at < $1
+ RETURNING id`,
+ [cutoffIso],
+ );
+ for (const r of rows) await deleteSyncBaseHash('creativeDirectorProject', r.id);
+ return { pruned: rows.length };
}
export async function setTreatment(id, treatmentInput) {
diff --git a/server/services/creativeDirector/projectsFile.js b/server/services/creativeDirector/projectsFile.js
index e393c6ace5..27efcd35d6 100644
--- a/server/services/creativeDirector/projectsFile.js
+++ b/server/services/creativeDirector/projectsFile.js
@@ -24,7 +24,11 @@ import {
applySceneUpdate,
appendRun,
applyRunUpdate,
+ mergeProjectRecord,
} from './projectsLogic.js';
+import {
+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+} from '../../lib/conflictJournal.js';
const PROJECTS_FILE = join(PATHS.data, 'creative-director-projects.json');
@@ -44,13 +48,22 @@ async function saveAll(projects) {
await atomicWrite(PROJECTS_FILE, projects);
}
-export async function listProjects() {
- return loadAll();
+export async function listProjects({ includeDeleted = false } = {}) {
+ const all = await loadAll();
+ return includeDeleted ? all : all.filter((p) => !p.deleted);
+}
+
+export async function getProject(id, { includeDeleted = false } = {}) {
+ const all = await loadAll();
+ const found = all.find((p) => p.id === id);
+ if (!found) return null;
+ return includeDeleted || !found.deleted ? found : null;
}
-export async function getProject(id) {
+/** Live project ids (or all when includeDeleted) — used by tombstone GC sweeps. */
+export async function listProjectIds({ includeDeleted = false } = {}) {
const all = await loadAll();
- return all.find((p) => p.id === id) || null;
+ return (includeDeleted ? all : all.filter((p) => !p.deleted)).map((p) => p.id);
}
export async function createProject(input) {
@@ -77,13 +90,70 @@ export async function updateProject(id, patch) {
}
export async function deleteProject(id) {
+ // Soft-delete tombstone (#1564) — mirrors projectsDB.deleteProject so the two
+ // backends can't drift. The record stays so the deletion can federate.
const all = await loadAll();
- const next = all.filter((p) => p.id !== id);
- if (next.length === all.length) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- await saveAll(next);
+ const idx = all.findIndex((p) => p.id === id);
+ if (idx < 0 || all[idx].deleted) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const now = new Date().toISOString();
+ all[idx] = { ...all[idx], deleted: true, deletedAt: now, updatedAt: now };
+ await saveAll(all);
return { 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('creativeDirectorProject', next.id, contentHashForRecord('creativeDirectorProject', next));
+ changed += 1;
+ continue;
+ }
+ if (!remoteWins || !didChange) continue;
+ await maybeJournalBeforeOverwrite({ kind: 'creativeDirectorProject', id: next.id, local, remote: next, source });
+ byId.set(next.id, next);
+ await setSyncBaseHash('creativeDirectorProject', next.id, contentHashForRecord('creativeDirectorProject', 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('creativeDirectorProject', id);
+ return { pruned: pruned.length };
+}
+
export async function setTreatment(id, treatmentInput) {
const all = await loadAll();
const idx = all.findIndex((p) => p.id === id);
diff --git a/server/services/creativeDirector/projectsFile.test.js b/server/services/creativeDirector/projectsFile.test.js
new file mode 100644
index 0000000000..776a16bf1d
--- /dev/null
+++ b/server/services/creativeDirector/projectsFile.test.js
@@ -0,0 +1,118 @@
+/**
+ * Creative Director file-backend federation merge (#1564) — soft-delete,
+ * LWW merge, tombstone prune, and the conflict-journal + base-hash wiring.
+ *
+ * Mirrors authors/file.test.js: runs against a tmpdir in the normal (non-DB)
+ * suite, so it covers the project-specific sync side effects (`setSyncBaseHash`
+ * seeding on insert, `maybeJournalBeforeOverwrite` archiving the losing local
+ * version on a true 3-way divergence, soft-delete tombstone, prune eviction)
+ * without touching real `data/` or needing Postgres. The Postgres backend shares
+ * the same `mergeProjectRecord` decision, so its round-trip in projectsDB.test.js
+ * doesn't need to re-pin these.
+ */
+
+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(), 'cd-projects-file-test-'));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+});
+// createProject would otherwise spin up the full media stack; we only test the
+// federation paths here, none of which create a collection.
+vi.mock('../mediaCollections.js', () => ({
+ createCollection: vi.fn(async () => ({ id: 'col-test' })),
+}));
+
+const file = await import('./projectsFile.js');
+const cj = await import('../../lib/conflictJournal.js');
+
+function reset() {
+ rmSync(join(TEST_DATA_ROOT, 'creative-director-projects.json'), { force: true });
+ rmSync(join(TEST_DATA_ROOT, 'sharing'), { recursive: true, force: true });
+ rmSync(join(TEST_DATA_ROOT, 'conflict-journal'), { recursive: true, force: true });
+ cj.__resetBaseHashCacheForTests();
+}
+beforeEach(reset);
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+const project = (id, extra = {}) => ({
+ id,
+ name: `P-${id}`,
+ status: 'draft',
+ createdAt: '2026-06-23T00:00:00.000Z',
+ updatedAt: '2026-06-23T00:00:00.000Z',
+ styleSpec: '',
+ treatment: null,
+ runs: [],
+ deleted: false,
+ deletedAt: null,
+ ...extra,
+});
+const journalEntries = () => cj.conflictJournalStore().loadAll();
+
+describe('projectsFile federation merge', () => {
+ it('inserts a remote project and seeds its base hash', async () => {
+ const res = await file.mergeProjectsFromSync([project('cd-1')]);
+ expect(res).toEqual({ applied: true, count: 1 });
+ expect(await file.getProject('cd-1')).toMatchObject({ id: 'cd-1' });
+ expect(await cj.getSyncBaseHash('creativeDirectorProject', 'cd-1')).toBeTruthy();
+ });
+
+ it('journals the losing local version on a true 3-way divergence (both diverged from base)', async () => {
+ // Persist a local record, then pin the synced base hash to a THIRD, different
+ // version — so both the stored local and the incoming remote differ from base
+ // (the 3-way-divergence precondition the journal detects). Mirrors the authors
+ // file-backend journaling test.
+ const local = project('cd-1', { styleSpec: 'local-edit', updatedAt: '2026-06-23T00:30:00.000Z' });
+ await file.mergeProjectsFromSync([local]); // inserts local + seeds base = local's hash
+ const base = project('cd-1', { styleSpec: 'common-ancestor', updatedAt: '2026-06-23T00:00:00.000Z' });
+ await cj.setSyncBaseHash('creativeDirectorProject', 'cd-1', cj.contentHashForRecord('creativeDirectorProject', base));
+
+ const remoteWinner = project('cd-1', { styleSpec: 'remote-edit', updatedAt: '2026-06-23T01:00:00.000Z' });
+ const res = await file.mergeProjectsFromSync([remoteWinner], { source: { via: 'peer-push', peerId: 'peer-A' } });
+ expect(res.applied).toBe(true);
+ expect((await file.getProject('cd-1')).styleSpec).toBe('remote-edit');
+
+ const entry = (await journalEntries()).find((e) => e.recordKind === 'creativeDirectorProject' && e.recordId === 'cd-1');
+ expect(entry).toBeTruthy();
+ expect(entry.source.peerId).toBe('peer-A');
+ expect(entry.localSnapshot.styleSpec).toBe('local-edit');
+ expect(entry.remoteSnapshot.styleSpec).toBe('remote-edit');
+ });
+
+ it('older remote loses — local preserved, no write', async () => {
+ await file.mergeProjectsFromSync([project('cd-1', { updatedAt: '2026-06-23T02:00:00.000Z', styleSpec: 'keep' })]);
+ const res = await file.mergeProjectsFromSync([project('cd-1', { updatedAt: '2026-06-23T01:00:00.000Z', styleSpec: 'stale' })]);
+ expect(res).toEqual({ applied: false, count: 0 });
+ expect((await file.getProject('cd-1')).styleSpec).toBe('keep');
+ });
+
+ it('soft-delete tombstones the project (excluded from live reads, present with includeDeleted)', async () => {
+ await file.mergeProjectsFromSync([project('cd-1')]);
+ await file.deleteProject('cd-1');
+ expect(await file.getProject('cd-1')).toBeNull();
+ expect(await file.getProject('cd-1', { includeDeleted: true })).toMatchObject({ id: 'cd-1', deleted: true });
+ expect(await file.listProjectIds()).toEqual([]);
+ expect(await file.listProjectIds({ includeDeleted: true })).toEqual(['cd-1']);
+ });
+
+ it('a newer remote tombstone overwrites a live local project', async () => {
+ await file.mergeProjectsFromSync([project('cd-1', { updatedAt: '2026-06-23T00:00:00.000Z' })]);
+ await file.mergeProjectsFromSync([project('cd-1', { updatedAt: '2026-06-23T05:00:00.000Z', deleted: true, deletedAt: '2026-06-23T05:00:00.000Z' })]);
+ expect(await file.getProject('cd-1')).toBeNull();
+ expect(await file.getProject('cd-1', { includeDeleted: true })).toMatchObject({ deleted: true });
+ });
+
+ it('pruneTombstonedProjects hard-removes old tombstones and evicts the base hash', async () => {
+ await file.mergeProjectsFromSync([project('cd-1', { updatedAt: '2026-06-23T00:00:00.000Z', deleted: true, deletedAt: '2026-06-23T00:00:00.000Z' })]);
+ const res = await file.pruneTombstonedProjects(Date.parse('2030-01-01T00:00:00.000Z'));
+ expect(res.pruned).toBe(1);
+ expect(await file.getProject('cd-1', { includeDeleted: true })).toBeNull();
+ expect(await cj.getSyncBaseHash('creativeDirectorProject', 'cd-1')).toBeNull();
+ });
+});
diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.js
index e26ffe9b15..eb5730471b 100644
--- a/server/services/creativeDirector/projectsLogic.js
+++ b/server/services/creativeDirector/projectsLogic.js
@@ -14,6 +14,10 @@ import { randomUUID } from 'crypto';
import { ServerError } from '../../lib/errorHandler.js';
import { creativeDirectorTreatmentSchema } from '../../lib/validation.js';
import { PROJECT_STATUSES } from '../../lib/creativeDirectorPresets.js';
+import { compareNewerWins } from '../../lib/lwwTimestamp.js';
+import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
+
+const isStr = (v) => typeof v === 'string';
// TIMESTAMPTZ bind-safety helper, shared with the media asset index (#1000) and
// any other store that mirrors a hand-editable timestamp into a typed column.
@@ -106,9 +110,79 @@ export function buildProjectRecord(input, { id, now, collectionId }) {
finalVideoId: null,
treatment: null,
runs: [],
+ // Soft-delete / LWW tombstone trio (#1564) — projects federate across peers
+ // via the per-record push pipeline (record kind `creativeDirectorProject`,
+ // sync category `creativeDirectorProjects`), so a delete is a tombstone the
+ // merge can keep an out-of-date peer from resurrecting.
+ deleted: false,
+ deletedAt: null,
};
}
+/**
+ * Resolve a project's `startingImageFile` to the bare gallery-image filename
+ * under `data/images/` so the peer-sync asset pipeline can hash + transfer it.
+ * Mirrors `headshotImageFilename` in services/authors/logic.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. Scene
+ * video renders are NOT covered here: they live in the project's linked media
+ * collection, which federates as its own record (so its bytes ride that
+ * collection's manifest). This covers only the project's direct image input.
+ */
+export function startingImageFilename(startingImageFile) {
+ if (!isStr(startingImageFile)) return null;
+ const url = startingImageFile.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;
+}
+
+/**
+ * Normalize a raw project 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 the other sanitizers' "drop on the floor" contract so a malformed
+ * peer payload can't land). The project body (treatment/scenes/runs/scalars) is
+ * passed 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 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 project record against the local copy —
+ * mirrors `mergeAuthorRecord` (services/authors/logic.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 like mediaCollection items), so it is hashed in full by
+ * `contentHashForRecord` — no scalar-narrowing branch.
+ */
+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 };
+}
+
/** Merge a project metadata patch, validating status. Returns the next record. */
export function applyProjectPatch(project, patch) {
if (patch.status && !PROJECT_STATUSES.includes(patch.status)) {
diff --git a/server/services/creativeDirector/projectsLogic.test.js b/server/services/creativeDirector/projectsLogic.test.js
index 361a73cfeb..b6bb471aac 100644
--- a/server/services/creativeDirector/projectsLogic.test.js
+++ b/server/services/creativeDirector/projectsLogic.test.js
@@ -16,6 +16,9 @@ import {
applySceneUpdate,
appendRun,
applyRunUpdate,
+ sanitizeProjectForSync,
+ mergeProjectRecord,
+ startingImageFilename,
} from './projectsLogic.js';
const VALID_TREATMENT = {
@@ -167,3 +170,80 @@ describe('trimRuns', () => {
expect(trimRuns(null)).toEqual([]);
});
});
+
+// --- Federation (#1564) — soft-delete + LWW merge decision ------------------
+
+describe('buildProjectRecord soft-delete trio', () => {
+ it('stamps deleted=false / deletedAt=null on a fresh project', () => {
+ const p = buildProjectRecord(
+ { name: 'X', aspectRatio: '1:1', quality: 'draft', modelId: 'm', targetDurationSeconds: 9 },
+ { id: 'cd-1', now: '2026-06-23T00:00:00.000Z', collectionId: 'col-1' },
+ );
+ expect(p.deleted).toBe(false);
+ expect(p.deletedAt).toBeNull();
+ });
+});
+
+describe('startingImageFilename', () => {
+ it('reduces a /data/images/ path or bare filename to the basename', () => {
+ expect(startingImageFilename('/data/images/start.png')).toBe('start.png');
+ expect(startingImageFilename('start.png')).toBe('start.png');
+ expect(startingImageFilename('/data/images/start.png?v=2')).toBe('start.png');
+ });
+ it('returns null for empty, external, or non-images absolute paths', () => {
+ expect(startingImageFilename('')).toBeNull();
+ expect(startingImageFilename(null)).toBeNull();
+ expect(startingImageFilename('https://example.com/x.png')).toBeNull();
+ expect(startingImageFilename('data:image/png;base64,AAAA')).toBeNull();
+ expect(startingImageFilename('/data/videos/x.mp4')).toBeNull();
+ });
+});
+
+describe('sanitizeProjectForSync', () => {
+ it('drops a non-object or id-less record (drop-on-floor contract)', () => {
+ expect(sanitizeProjectForSync(null)).toBeNull();
+ expect(sanitizeProjectForSync([])).toBeNull();
+ expect(sanitizeProjectForSync({ name: 'no id' })).toBeNull();
+ });
+ it('normalizes the soft-delete trio and preserves the body verbatim', () => {
+ const out = sanitizeProjectForSync({ id: 'cd-1', name: 'X', styleSpec: 'noir', updatedAt: '2026-06-23T00:00:00.000Z', deleted: true, deletedAt: '2026-06-23T01:00:00.000Z' });
+ expect(out).toMatchObject({ id: 'cd-1', name: 'X', styleSpec: 'noir', deleted: true, deletedAt: '2026-06-23T01:00:00.000Z' });
+ });
+ it('forces deletedAt=null when not deleted', () => {
+ const out = sanitizeProjectForSync({ id: 'cd-1', name: 'X', deleted: false, deletedAt: 'stray' });
+ expect(out.deleted).toBe(false);
+ expect(out.deletedAt).toBeNull();
+ });
+});
+
+describe('mergeProjectRecord (LWW, tombstone-aware)', () => {
+ const at = (iso, extra = {}) => ({ id: 'cd-1', name: 'P', updatedAt: iso, ...extra });
+ it('inserts when there is no local counterpart', () => {
+ const { next, inserted, remoteWins } = mergeProjectRecord(null, at('2026-06-23T00:00:00.000Z'));
+ expect(inserted).toBe(true);
+ expect(remoteWins).toBe(true);
+ expect(next.id).toBe('cd-1');
+ });
+ it('remote with a newer updatedAt wins', () => {
+ const local = at('2026-06-23T00:00:00.000Z', { styleSpec: 'old' });
+ const { next, remoteWins, changed } = mergeProjectRecord(local, at('2026-06-23T01:00:00.000Z', { styleSpec: 'new' }));
+ expect(remoteWins).toBe(true);
+ expect(changed).toBe(true);
+ expect(next.styleSpec).toBe('new');
+ });
+ it('local wins when its updatedAt is newer (no change)', () => {
+ const local = at('2026-06-23T02:00:00.000Z', { styleSpec: 'keep' });
+ const { next, remoteWins } = mergeProjectRecord(local, at('2026-06-23T01:00:00.000Z', { styleSpec: 'lose' }));
+ expect(remoteWins).toBe(false);
+ expect(next.styleSpec).toBe('keep');
+ });
+ it('a newer remote tombstone overwrites a live local record', () => {
+ const local = at('2026-06-23T00:00:00.000Z');
+ const { next, remoteWins } = mergeProjectRecord(local, at('2026-06-23T03:00:00.000Z', { deleted: true, deletedAt: '2026-06-23T03:00:00.000Z' }));
+ expect(remoteWins).toBe(true);
+ expect(next.deleted).toBe(true);
+ });
+ it('drops a malformed remote (next null)', () => {
+ expect(mergeProjectRecord(at('2026-06-23T00:00:00.000Z'), { name: 'no id' }).next).toBeNull();
+ });
+});
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index 14a5a0688c..b55b91b9e4 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -1094,6 +1094,10 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {
'artists',
'albums',
'tracks',
+ // Creative Director projects (#1564) → per-record peer-push only (no 60s
+ // file-snapshot category). Gated at applyIncomingPush via
+ // compareSchemaVersions / RECORD_KIND_SCHEMA_CATEGORIES.creativeDirectorProject.
+ 'creativeDirectorProjects',
]);
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.js
index 4a1b318305..372da775da 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -238,6 +238,7 @@ const DEFAULT_SYNC_CATEGORIES = {
artists: false,
albums: false,
tracks: false,
+ creativeDirectorProjects: false,
catalog: false
};
@@ -269,6 +270,7 @@ const PER_RECORD_CATEGORY_KINDS = Object.freeze([
['artists', 'artist'],
['albums', 'album'],
['tracks', 'track'],
+ ['creativeDirectorProjects', 'creativeDirectorProject'],
]);
export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, auth }) {
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 738a7a0d6f..a8d520e17f 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -97,13 +97,19 @@ import {
mergeTracksFromSync,
trackAudioFilename,
} from '../tracks/index.js';
+import {
+ getProject,
+ listProjects,
+ mergeProjectsFromSync,
+ startingImageFilename,
+} from '../creativeDirector/local.js';
import {
initCursor,
ackDeletesUpTo,
removeCursor as removeTombstoneCursor,
} from './peerTombstoneCursors.js';
-export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track']);
+export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject']);
/**
* Cross-cutting event bus for the peer-sync receiver. The asset-pull worker
@@ -380,6 +386,7 @@ const KIND_TO_CATEGORY = Object.freeze({
artist: 'artists',
album: 'albums',
track: 'tracks',
+ creativeDirectorProject: 'creativeDirectorProjects',
});
function peerAllowsOutbound(peer) {
@@ -478,6 +485,8 @@ async function listRecordsForKind(recordKind) {
records = await listAlbums({ includeDeleted: false }).catch(() => []);
} else if (recordKind === 'track') {
records = await listTracks({ includeDeleted: false }).catch(() => []);
+ } else if (recordKind === 'creativeDirectorProject') {
+ records = await listProjects({ includeDeleted: false }).catch(() => []);
}
return records.filter(r => r?.ephemeral !== true && isNonEmptyStr(r?.id));
}
@@ -780,6 +789,7 @@ async function buildIntegrityAssetManifest(kind, record) {
if (kind === 'artist') return buildArtistAssetManifest(record);
if (kind === 'album') return buildAlbumAssetManifest(record);
if (kind === 'track') return buildTrackAssetManifest(record);
+ if (kind === 'creativeDirectorProject') return buildProjectAssetManifest(record);
if (kind === 'series') {
const childIssues = await listIssues({ seriesId: record?.id, includeDeleted: true }).catch(() => []);
const manifestIssues = childIssues.filter(
@@ -998,6 +1008,10 @@ async function isSubscriptionRecordTombstone(sub) {
const record = await getTrack(sub.recordId, { includeDeleted: true }).catch(() => null);
return record?.deleted === true;
}
+ if (sub.recordKind === 'creativeDirectorProject') {
+ const record = await getProject(sub.recordId, { includeDeleted: true }).catch(() => null);
+ return record?.deleted === true;
+ }
return false;
}
@@ -1548,6 +1562,14 @@ async function buildPushPayload(sub, sourceInstanceId) {
const assetManifest = record.deleted === true ? [] : await buildTrackAssetManifest(record);
return { kind: 'track', record: sanitized, assetManifest, sourceInstanceId, portosMeta };
}
+ if (sub.recordKind === 'creativeDirectorProject') {
+ const record = await getProject(sub.recordId, { includeDeleted: true }).catch(() => null);
+ if (!record) return null;
+ const sanitized = sanitizeRecordForWire('creativeDirectorProject', record);
+ if (!sanitized) return null;
+ const assetManifest = record.deleted === true ? [] : await buildProjectAssetManifest(record);
+ return { kind: 'creativeDirectorProject', record: sanitized, assetManifest, sourceInstanceId, portosMeta };
+ }
return null;
}
@@ -1597,6 +1619,23 @@ async function buildTrackAssetManifest(track) {
return entries.filter(Boolean);
}
+/**
+ * Hash a Creative Director project's direct image input (`startingImageFile`) so
+ * the receiver can pull the bytes from `/data/images/`. `startingImageFilename`
+ * returns null for an external URL / non-local path, so those never ship (the
+ * receiver resolves the same URL itself). Scene VIDEO renders are NOT hashed
+ * here: they live in the project's linked media collection, which federates as
+ * its own record and ships its bytes via that collection's manifest — duplicating
+ * them here would double the transfer. This mirrors buildAuthorAssetManifest:
+ * one direct asset, missing-local-file skipped silently.
+ */
+async function buildProjectAssetManifest(project) {
+ const filename = startingImageFilename(project?.startingImageFile);
+ if (!filename) return [];
+ const entry = await hashImageForManifest(filename);
+ return entry ? [entry] : [];
+}
+
/**
* Build the catalog bundle (`{ ingredients, refs }`) that piggy-backs on a
* universe record push. Catalog data lives in Postgres only — on a non-Postgres
@@ -1944,6 +1983,8 @@ export async function applyIncomingPush(payload) {
await mergeAlbumsFromSync([record], { source });
} else if (kind === 'track') {
await mergeTracksFromSync([record], { source });
+ } else if (kind === 'creativeDirectorProject') {
+ await mergeProjectsFromSync([record], { source });
}
// Apply the bundled collection (if any) — same LWW + union-of-items
@@ -2179,6 +2220,13 @@ async function classifyLocalRecord(recordKind, recordId) {
const t = await getTrack(recordId, { includeDeleted: true }).catch(() => null);
return t ? 'syncable' : 'missing';
}
+ if (recordKind === 'creativeDirectorProject') {
+ // CD projects have no `ephemeral` concept (like the persona/music kinds) — a
+ // found record (live or tombstoned) is always 'syncable'. No ping-pong risk:
+ // lastPushedHash + LWW same-`updatedAt` no-op merge prevent it.
+ const p = await getProject(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 5bca7d368b..0654a952cb 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]', () => {
+ it('is exactly [universe, series, mediaCollection, author, artist, album, track, creativeDirectorProject]', () => {
// 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']);
+ expect(PEER_SUBSCRIBABLE_KINDS).toEqual(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject']);
});
});
diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.js
index 6630b3be28..bbe80b18a3 100644
--- a/server/services/sharing/tombstoneGc.js
+++ b/server/services/sharing/tombstoneGc.js
@@ -34,6 +34,7 @@ import { pruneTombstonedAuthors, listAuthorIds } from '../authors/index.js';
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 { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';
import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';
import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';
@@ -54,6 +55,7 @@ const LIVE_ID_LISTERS = Object.freeze({
artist: () => listArtistIds(),
album: () => listAlbumIds(),
track: () => listTrackIds(),
+ creativeDirectorProject: () => listProjectIds(),
});
// Each peer-subscribable kind's UNCAPPED id source INCLUDING tombstones —
@@ -71,6 +73,7 @@ const ALL_ID_LISTERS = Object.freeze({
artist: () => listArtistIds({ includeDeleted: true }),
album: () => listAlbumIds({ includeDeleted: true }),
track: () => listTrackIds({ includeDeleted: true }),
+ creativeDirectorProject: () => listProjectIds({ includeDeleted: true }),
});
// Build a kind-aware id-membership resolver for ONE sweep: lazily list each
@@ -239,6 +242,7 @@ function refusedFromCutoffs(cutoffs) {
artistCutoff,
albumCutoff,
trackCutoff,
+ projectCutoff,
} = cutoffs;
if (universeCutoff === null) refused.push('universe');
// Issue tombstones ride series pushes — refused exactly when series is.
@@ -254,6 +258,7 @@ function refusedFromCutoffs(cutoffs) {
if (artistCutoff === null) refused.push('artist');
if (albumCutoff === null) refused.push('album');
if (trackCutoff === null) refused.push('track');
+ if (projectCutoff === null) refused.push('creativeDirectorProject');
return refused;
}
@@ -278,6 +283,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
artistCutoff,
albumCutoff,
trackCutoff,
+ projectCutoff,
] = await Promise.all([
cutoffForKind('universe', { peers, subs, now, graceMs }),
cutoffForKind('series', { peers, subs, now, graceMs }),
@@ -286,9 +292,10 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
cutoffForKind('artist', { peers, subs, now, graceMs }),
cutoffForKind('album', { peers, subs, now, graceMs }),
cutoffForKind('track', { peers, subs, now, graceMs }),
+ cutoffForKind('creativeDirectorProject', { peers, subs, now, graceMs }),
]);
const issueCutoff = seriesCutoff;
- const [u, s, i, c, a, ar, al, t] = await Promise.all([
+ const [u, s, i, c, a, ar, al, t, cd] = 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),
@@ -297,6 +304,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
artistCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedArtists(artistCutoff),
albumCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedAlbums(albumCutoff),
trackCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedTracks(trackCutoff),
+ projectCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedProjects(projectCutoff),
]);
// 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
@@ -321,9 +329,10 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
artists: ar.pruned,
albums: al.pruned,
tracks: t.pruned,
+ creativeDirectorProjects: cd.pruned,
orphanBaseHashes: orphan.pruned,
orphanSubscriptions: orphanSubs.pruned,
- refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff }),
+ refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff }),
};
}
@@ -332,7 +341,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] = await Promise.all([
+ const [universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff] = await Promise.all([
cutoffForKind('universe', { peers, subs, now, graceMs: 0 }),
cutoffForKind('series', { peers, subs, now, graceMs: 0 }),
cutoffForKind('mediaCollection', { peers, subs, now, graceMs: 0 }),
@@ -340,8 +349,9 @@ export async function getSweepStatus({ now = Date.now() } = {}) {
cutoffForKind('artist', { peers, subs, now, graceMs: 0 }),
cutoffForKind('album', { peers, subs, now, graceMs: 0 }),
cutoffForKind('track', { peers, subs, now, graceMs: 0 }),
+ cutoffForKind('creativeDirectorProject', { peers, subs, now, graceMs: 0 }),
]);
- return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff }) };
+ return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff }) };
}
export const TOMBSTONE_GRACE_MS = GRACE_MS;
diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.js
index 8f06e701c1..c2feb76091 100644
--- a/server/services/sharing/tombstoneGc.test.js
+++ b/server/services/sharing/tombstoneGc.test.js
@@ -36,6 +36,10 @@ vi.mock('../tracks/index.js', () => ({
pruneTombstonedTracks: vi.fn().mockResolvedValue({ pruned: 0 }),
listTrackIds: vi.fn().mockResolvedValue([]),
}));
+vi.mock('../creativeDirector/local.js', () => ({
+ pruneTombstonedProjects: vi.fn().mockResolvedValue({ pruned: 0 }),
+ listProjectIds: vi.fn().mockResolvedValue([]),
+}));
vi.mock('../../lib/conflictJournal.js', () => ({
pruneOrphanedBaseHashes: vi.fn().mockResolvedValue({ pruned: 0 }),
}));
@@ -63,6 +67,7 @@ import { pruneTombstonedAuthors, listAuthorIds } from '../authors/index.js';
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 { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';
import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';
import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';
@@ -418,6 +423,7 @@ describe('sweepTombstones — return shape', () => {
pruneTombstonedArtists.mockResolvedValueOnce({ pruned: 4 });
pruneTombstonedAlbums.mockResolvedValueOnce({ pruned: 6 });
pruneTombstonedTracks.mockResolvedValueOnce({ pruned: 7 });
+ pruneTombstonedProjects.mockResolvedValueOnce({ pruned: 8 });
const result = await sweepTombstones({ now: NOW });
expect(result).toEqual({
universes: 2,
@@ -428,6 +434,7 @@ describe('sweepTombstones — return shape', () => {
artists: 4,
albums: 6,
tracks: 7,
+ creativeDirectorProjects: 8,
orphanBaseHashes: 0,
orphanSubscriptions: 0,
refused: [],