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 Writers Room works across peers (#1565)

[._.]/ Adam Eivyebd954e47ed6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d919560a0d..548b5c226f 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-1565] Writers Room works now federate across peers.** Writers Room manuscripts (works + their draft-version history) were `db-primary` (`writers_room_works` + decomposed `writers_room_draft_versions`, since #1017) but had never been wired into the cross-peer sync graph, so a node pair couldn't mirror your writing. Works now ride the same per-record peer-sync push pipeline as Creative Director projects and Mood Boards: there's a new **Writers Room** sync category on the Instances page (covered automatically by Full mirror peers), creating a work auto-subscribes it to every Writers-Room-enabled peer, edits propagate last-write-wins (newer `updatedAt` wins, with a Conflicts-tab entry archived — restorable down to title/kind/status/folder/image-style/live-mode — when both sides diverged from a common base), and a **delete becomes a soft-delete tombstone** (works used to hard-delete) the merge keeps an out-of-date peer from resurrecting. The file-primary `.md` draft prose bodies stay file-primary and replicate as pulled assets via a dedicated SHA256 body manifest (the receiver diffs each draft against its local disk and pulls only the missing/changed bodies from the sender's `/data/writers-room` mount), so prose is never round-tripped through the database record. Cross-version pushes are version-gated (`writersRoomWorks` schema v1) so a newer peer can't corrupt an older one. Folders and exercises don't federate yet (they need soft-delete columns first) — tracked as follow-ups under #1565. (`server/services/writersRoom/`, `server/services/sharing/peerSync.js`, `server/services/sharing/tombstoneGc.js`, `server/services/conflictJournalResolver.js`, `server/services/instances.js`, `server/lib/schemaVersions.js`, `server/lib/syncWire.js`, `server/lib/conflictJournal.js`, `server/index.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`)
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 232312769d..14326eb419 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -7,7 +7,7 @@ import {
Database, Brain, CheckCircle2, AlertCircle, Clock,
RefreshCcw, Timer,
Target, Sword, Fingerprint, HeartPulse, ChevronDown, ChevronRight,
- Lock, Globe, Info, Sparkles, Film, Images, Library, BookOpen, FilePen, Music, Music2, Disc3, Clapperboard, Palette
+ Lock, Globe, Info, Sparkles, Film, Images, Library, BookOpen, FilePen, Music, Music2, Disc3, Clapperboard, Palette, BookText
} from 'lucide-react';
import toast from '../components/ui/Toast';
import Pill from '../components/ui/Pill';
@@ -523,13 +523,14 @@ const SYNC_CATEGORY_META = [
{ 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: 'writersRoomWorks', label: 'Writers Room', icon: BookText, description: 'Writers Room works: manuscripts + draft versions + prose bodies (PostgreSQL)' },
{ key: 'catalog', label: 'Catalog', icon: Library, description: 'Creative ingredients catalog: orphan ingredients + ref links (PostgreSQL)' }
];
// Snapshot categories — exclude the per-record / delta-based categories that
// have no 60s snapshot checksum: brain + memory (delta), catalog + authors/music
// (PostgreSQL, per-record peer-push only — no snapshot loop).
-const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors', 'artists', 'albums', 'tracks', 'creativeDirectorProjects', 'moodBoards']);
+const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors', 'artists', 'albums', 'tracks', 'creativeDirectorProjects', 'moodBoards', 'writersRoomWorks']);
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/index.js b/server/index.js
index 05f59fe8eb..cdc642027a 100644
--- a/server/index.js
+++ b/server/index.js
@@ -183,6 +183,7 @@ import { seriesStore } from './services/pipeline/series.js';
import { issueStore } from './services/pipeline/issues.js';
import { storyBuilderStore } from './services/storyBuilder.js';
import { writersRoomStore } from './services/writersRoom/store.js';
+import { wrWorksDir } from './services/writersRoom/_shared.js';
import { mediaCollectionStore } from './services/mediaCollections.js';
import { createPortOSProviderRoutes } from './routes/providers.js';
import { createPortOSRunsRoutes } from './routes/runs.js';
@@ -707,6 +708,11 @@ app.use('/data/music', express.static(PATHS.music));
// Brain Memory conversation viewer renders these inline (`![](/data/brain-
// imports/...)`) and as asset links. Read-only; range support for large PDFs.
app.use('/data/brain-imports', express.static(PATHS.brainImportAssets, ASSET_STATIC_OPTS));
+// Writers Room file-primary draft prose bodies (works/<workId>/drafts/<draftId>.md).
+// Federation (#1565) pulls them peer→peer from this mount: a receiver that merged
+// a work record GETs each missing body's bytes by its nested path. Read-only;
+// range support for large drafts. (Tailnet-only per the project's threat model.)
+app.use('/data/writers-room/works', express.static(wrWorksDir(), ASSET_STATIC_OPTS));
// Serve built client UI (production mode — no Vite dev server needed)
const CLIENT_DIST = join(__dirname, '..', 'client', 'dist');
diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.js
index 8680102282..649f4509f7 100644
--- a/server/lib/conflictJournal.js
+++ b/server/lib/conflictJournal.js
@@ -343,6 +343,16 @@ export const RESTORABLE_FIELDS = Object.freeze({
// routes restore through restoreBoard → applyBoardRestore (which accepts items,
// unlike the route's applyBoardPatch).
moodBoard: ['name', 'description', 'items'],
+ // Writers Room works (#1565): the user-authored manifest fields the merge can
+ // restore through `updateWork` (which accepts exactly this set + the liveMode
+ // partial-merge). Server-owned / structural fields are excluded — `id`/
+ // `createdAt`/the LWW-tombstone trio, the draft-version structure
+ // (`drafts`/`activeDraftVersionId`, file-primary + lineage-managed), and the
+ // bridge links (`pipelineSeriesId`/`cdProjectId`/`mediaCollectionId`, set by
+ // their own helpers). The whole manifest is hashed for DETECTION by
+ // contentHashForRecord (no scalar narrowing); this set is what the Conflicts UI
+ // offers for restore. `writersRoomWork` matches the record kind.
+ writersRoomWork: ['title', 'kind', 'status', 'folderId', 'imageStyle', 'liveMode'],
});
const present = (v) => v !== undefined;
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 196f9ce874..963ec68a05 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -287,6 +287,20 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// 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,
+ // v1 = Writers Room works (PostgreSQL `writers_room_works` + decomposed
+ // `writers_room_draft_versions`) federated via the per-record peer-sync push
+ // pipeline (record kind `writersRoomWork`, sync category `writersRoomWorks`,
+ // #1565). Same posture as `creativeDirectorProjects`/`moodBoards`: 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 `writersRoomWorks` and gets a
+ // 412 (only that category pauses); a v1 receiver still accepts a ≤v0 sender
+ // (pre-feature peers never push a `writersRoomWork`). The FIRST incompatible
+ // work-shape change MUST bump this to 2 then. The work manifest (metadata +
+ // decomposed draft-version metadata in drafts[]) is LWW-overwritten whole; the
+ // file-primary `.md` draft prose bodies ride a separate body manifest (SHA256
+ // diff + receiver-pull), never round-tripped through the record. Folders +
+ // exercises are NOT federated yet (they lack soft-delete columns).
+ writersRoomWorks: 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
@@ -332,6 +346,7 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({
storyBuilder: Object.freeze(['storyBuilder']),
creativeDirectorProject: Object.freeze(['creativeDirectorProjects']),
moodBoard: Object.freeze(['moodBoards']),
+ writersRoomWork: Object.freeze(['writersRoomWorks']),
});
/**
diff --git a/server/lib/syncWire.js b/server/lib/syncWire.js
index 29ae3ca8b8..5c26a0a0da 100644
--- a/server/lib/syncWire.js
+++ b/server/lib/syncWire.js
@@ -163,16 +163,19 @@ export function sanitizeRecordForWire(kind, record) {
case 'album':
case 'track':
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; a
- // moodBoard (name/description/items) is the same whole-record contract.
+ case 'moodBoard':
+ case 'writersRoomWork': {
+ // Persona/music/creative-director/mood-board/writers-room 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; a moodBoard
+ // (name/description/items) and a writersRoomWork (the manifest +
+ // decomposed draft-version METADATA in drafts[]; the .md prose bodies ride
+ // a separate body manifest) are 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.js
index 135da4d6d3..1e7c8473c8 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -67,6 +67,7 @@ const syncCategoriesSchema = z.object({
tracks: z.boolean().optional(),
creativeDirectorProjects: z.boolean().optional(),
moodBoards: z.boolean().optional(),
+ writersRoomWorks: z.boolean().optional(),
catalog: z.boolean().optional()
}).optional();
diff --git a/server/services/conflictJournalResolver.js b/server/services/conflictJournalResolver.js
index 628c3a8881..f54e6a311d 100644
--- a/server/services/conflictJournalResolver.js
+++ b/server/services/conflictJournalResolver.js
@@ -37,6 +37,7 @@ import { updateCollection, getCollection, ERR_NOT_FOUND as COLLECTION_NOT_FOUND
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';
+import { updateWork } from './writersRoom/local.js';
export const ERR_NOT_FOUND = 'CONFLICT_JOURNAL_NOT_FOUND';
export const ERR_VALIDATION = 'CONFLICT_JOURNAL_VALIDATION';
@@ -133,6 +134,15 @@ async function applyToRecord(kind, recordId, patch, { replace = false } = {}) {
// merge-fields both apply faithfully through the same call. It validates +
// rejects a tombstoned row (404 → translateGone → ERR_TARGET_GONE).
await restoreBoard(recordId, patch).catch(translateGone);
+ } else if (kind === 'writersRoomWork') {
+ // updateWork applies the snapshot's title/kind/status/folderId/imageStyle/
+ // liveMode (the RESTORABLE_FIELDS set) through its allow-list + the liveMode
+ // partial merge, so restore-all and merge-fields both apply faithfully. It
+ // throws the generic ServerError 'NOT_FOUND' for a missing/tombstoned work
+ // (caught by translateGone → ERR_TARGET_GONE). The draft-version structure
+ // and prose bodies are not restorable here (they're file-primary + lineage-
+ // managed) — RESTORABLE_FIELDS.writersRoomWork omits them.
+ await updateWork(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.js
index dcf7758787..c675e96cdb 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -1102,6 +1102,11 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {
// category). Gated at applyIncomingPush via compareSchemaVersions /
// RECORD_KIND_SCHEMA_CATEGORIES.moodBoard.
'moodBoards',
+ // Writers Room works (#1565) → per-record peer-push only (no 60s
+ // file-snapshot category; the .md prose bodies ride a dedicated body
+ // manifest). Gated at applyIncomingPush via compareSchemaVersions /
+ // RECORD_KIND_SCHEMA_CATEGORIES.writersRoomWork.
+ 'writersRoomWorks',
]);
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 5b79e5a51d..cc9165d295 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -240,6 +240,7 @@ const DEFAULT_SYNC_CATEGORIES = {
tracks: false,
creativeDirectorProjects: false,
moodBoards: false,
+ writersRoomWorks: false,
catalog: false
};
@@ -273,6 +274,7 @@ const PER_RECORD_CATEGORY_KINDS = Object.freeze([
['tracks', 'track'],
['creativeDirectorProjects', 'creativeDirectorProject'],
['moodBoards', 'moodBoard'],
+ ['writersRoomWorks', 'writersRoomWork'],
]);
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 f5618d5d70..88419f97d5 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -109,6 +109,14 @@ import {
mergeBoardsFromSync,
imageUrlToAppAsset,
} from '../moodBoard/index.js';
+import {
+ getWorkForSync,
+ mergeWorksFromSync,
+ buildWorkBodyManifest,
+ diffWorkBodyManifest,
+} from '../writersRoom/sync.js';
+import { WRITERS_ROOM_DRAFT_ASSET_KIND } from '../writersRoom/syncLogic.js';
+import { WORK_ID_RE, DRAFT_ID_RE, wrWorkDir, wrDraftPath } from '../writersRoom/_shared.js';
import { parseKey } from '../../lib/mediaItemKey.js';
import {
initCursor,
@@ -116,7 +124,7 @@ import {
removeCursor as removeTombstoneCursor,
} from './peerTombstoneCursors.js';
-export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard']);
+export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork']);
/**
* Cross-cutting event bus for the peer-sync receiver. The asset-pull worker
@@ -395,6 +403,7 @@ const KIND_TO_CATEGORY = Object.freeze({
track: 'tracks',
creativeDirectorProject: 'creativeDirectorProjects',
moodBoard: 'moodBoards',
+ writersRoomWork: 'writersRoomWorks',
});
function peerAllowsOutbound(peer) {
@@ -1090,6 +1099,7 @@ export async function pushRecordToPeer(sub, options = {}) {
manuscriptReview: payload.manuscriptReview ?? null,
reverseOutline: payload.reverseOutline ?? null,
assetManifest: payload.assetManifest ?? [],
+ draftBodyManifest: payload.draftBodyManifest ?? [],
});
if (sub.lastPushedHash && sub.lastPushedHash === hash) {
return { pushed: false, reason: 'unchanged', hash };
@@ -1593,6 +1603,17 @@ async function buildPushPayload(sub, sourceInstanceId) {
const assetManifest = record.deleted === true ? [] : await buildBoardAssetManifest(record);
return { kind: 'moodBoard', record: sanitized, assetManifest, sourceInstanceId, portosMeta };
}
+ if (sub.recordKind === 'writersRoomWork') {
+ const record = await getWorkForSync(sub.recordId).catch(() => null);
+ if (!record) return null;
+ const sanitized = sanitizeRecordForWire('writersRoomWork', record);
+ if (!sanitized) return null;
+ // The work manifest carries draft-version METADATA; the file-primary `.md`
+ // prose bodies ride a separate `draftBodyManifest` (SHA256 per draft) the
+ // receiver diffs + pulls. A tombstone ships neither asset manifest.
+ const draftBodyManifest = record.deleted === true ? [] : await buildWorkBodyManifest(record);
+ return { kind: 'writersRoomWork', record: sanitized, assetManifest: [], draftBodyManifest, sourceInstanceId, portosMeta };
+ }
return null;
}
@@ -1872,7 +1893,7 @@ export async function applyIncomingPush(payload) {
if (!isPlainObject(payload)) {
throw makeErr('payload must be an object', ERR_VALIDATION);
}
- const { kind, record, issues, linkedCollection, catalogBundle, manuscriptReview, reverseOutline, assetManifest, sourceInstanceId, portosMeta } = payload;
+ const { kind, record, issues, linkedCollection, catalogBundle, manuscriptReview, reverseOutline, assetManifest, draftBodyManifest, sourceInstanceId, portosMeta } = payload;
if (!PEER_SUBSCRIBABLE_KINDS.includes(kind)) {
throw makeErr(`unknown kind: ${kind}`, ERR_VALIDATION);
}
@@ -2059,6 +2080,8 @@ export async function applyIncomingPush(payload) {
await mergeProjectsFromSync([record], { source });
} else if (kind === 'moodBoard') {
await mergeBoardsFromSync([record], { source });
+ } else if (kind === 'writersRoomWork') {
+ await mergeWorksFromSync([record], { source });
}
// Apply the bundled collection (if any) — same LWW + union-of-items
@@ -2152,6 +2175,21 @@ export async function applyIncomingPush(payload) {
});
}
+ // Writers Room: the file-primary draft `.md` bodies ride their own manifest
+ // (the generic asset pipeline keys on a flat basename + single dir per kind;
+ // bodies live at works/<workId>/drafts/<draftId>.md). Diff against local disk
+ // and background-pull the missing ones from the sender's /data/writers-room
+ // static mount. Same guards as the asset path: skip for local-ephemeral (works
+ // have no ephemeral flag, but keep the symmetry) and tombstone pushes.
+ if (kind === 'writersRoomWork' && !localEphemeral && record.deleted !== true) {
+ const missingBodies = await diffWorkBodyManifest(draftBodyManifest);
+ if (missingBodies.length > 0) {
+ pullMissingWorkBodies(sourceInstanceId, missingBodies).catch((err) => {
+ console.log(`⚠️ peerSync: draft-body pull from ${sourceInstanceId} failed: ${err.message}`);
+ });
+ }
+ }
+
return {
missingAssets,
reverseSubscriptionCreated,
@@ -2308,6 +2346,14 @@ async function classifyLocalRecord(recordKind, recordId) {
const b = await getBoard(recordId, { includeDeleted: true }).catch(() => null);
return b ? 'syncable' : 'missing';
}
+ if (recordKind === 'writersRoomWork') {
+ // Works have no `ephemeral` concept (like the persona/music/CD/board kinds) —
+ // a found work (live or tombstoned) is always 'syncable', so an inbound work
+ // push bootstraps bidirectional sync. No ping-pong risk: lastPushedHash + LWW
+ // same-`updatedAt` no-op merge prevent it.
+ const w = await getWorkForSync(recordId).catch(() => null);
+ return w ? 'syncable' : 'missing';
+ }
return 'missing';
}
@@ -2385,6 +2431,103 @@ async function pullMissingAssetsFromPeer(senderInstanceId, missingAssets) {
}
}
+/**
+ * Fetch a peer's static-mount asset URL into a size-capped Buffer, or null on
+ * any failure. Centralizes the content-length guards shared by the generic
+ * asset pull (`doPullOneAsset`) and the Writers Room draft-body pull
+ * (`pullOneWorkBody`): REQUIRE a trustworthy content-length header up front
+ * (Express serve-static always sets it) so a hostile peer can't OOM us by
+ * shipping a huge body under a small filename before the `.arrayBuffer()` cap
+ * runs. `label` is the filename used in log lines.
+ */
+async function fetchCappedAssetBuffer(peer, url, label, maxBytes) {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), ASSET_PULL_TIMEOUT_MS);
+ // maxBytes propagates into the HTTPS shim's streaming cap (see
+ // server/lib/httpClient.js); the plain-HTTP path falls back to the
+ // post-resolve content-length checks below (serve-static always sets it).
+ const res = await peerFetch(url, { signal: controller.signal, maxBytes }, peer)
+ .finally(() => clearTimeout(timeoutId))
+ .catch((err) => {
+ if (err?.message?.includes('exceed')) {
+ console.log(`⚠️ peerSync: ${label} exceeded asset size cap — ${err.message}`);
+ }
+ return null;
+ });
+ if (!res || !res.ok) return null;
+ // Use has() to distinguish "header missing" from "header is '0'" — without it
+ // `Number(null)` is 0 and slips past the finite-non-negative guard.
+ if (!res.headers.has('content-length')) {
+ console.log(`⚠️ peerSync: asset ${label} has no content-length — refusing pull`);
+ return null;
+ }
+ const contentLength = Number(res.headers.get('content-length'));
+ if (!Number.isFinite(contentLength) || contentLength <= 0) {
+ console.log(`⚠️ peerSync: asset ${label} has invalid content-length (${res.headers.get('content-length')}) — refusing pull`);
+ return null;
+ }
+ if (contentLength > maxBytes) {
+ console.log(`⚠️ peerSync: asset ${label} too large (${contentLength}) — refusing pull`);
+ return null;
+ }
+ const buffer = Buffer.from(await res.arrayBuffer());
+ // Defense in depth: the server claimed length X but actually sent more.
+ if (buffer.length > maxBytes || buffer.length !== contentLength) {
+ console.log(`⚠️ peerSync: asset ${label} length mismatch (header=${contentLength}, body=${buffer.length}) — refusing pull`);
+ return null;
+ }
+ return buffer;
+}
+
+// --- Receiver-side Writers Room draft-body pull -------------------------
+// Bodies live at works/<workId>/drafts/<draftId>.md (nested), not a flat
+// basename under one dir, so they ride a dedicated manifest + pull instead of
+// the generic flat-asset pipeline. The sender serves them from its
+// /data/writers-room/works static mount (server/index.js).
+const WORK_BODY_PULL_MAX_BYTES = 16 * 1024 * 1024; // bodies are ≤5MB (validated); 16MB is generous
+
+async function pullMissingWorkBodies(senderInstanceId, missingBodies) {
+ if (!isStr(senderInstanceId) || !Array.isArray(missingBodies) || missingBodies.length === 0) return;
+ const peer = await findPeerById(senderInstanceId);
+ if (!peer) {
+ console.log(`⚠️ peerSync: can't pull draft bodies — peer ${senderInstanceId} not in registry`);
+ return;
+ }
+ const base = peerBaseUrl(peer);
+ for (const entry of missingBodies) {
+ await pullOneWorkBody(peer, base, entry).catch((err) => {
+ console.log(`⚠️ peerSync: draft-body pull ${entry?.draftId} from ${peer.name || senderInstanceId} failed: ${err.message}`);
+ });
+ }
+}
+
+async function pullOneWorkBody(peer, base, entry) {
+ const { workId, draftId } = entry || {};
+ // Re-validate the path segments here even though diffWorkBodyManifest already
+ // did — belt-and-suspenders against a future refactor that bypasses the diff.
+ if (typeof workId !== 'string' || !WORK_ID_RE.test(workId)) return;
+ if (typeof draftId !== 'string' || !DRAFT_ID_RE.test(draftId)) return;
+ const safeLabel = `${workId}/${draftId}.md`;
+ const key = inflightKey(peer.instanceId, WRITERS_ROOM_DRAFT_ASSET_KIND, safeLabel);
+ if (inflightPulls.has(key)) return;
+ inflightPulls.add(key);
+ try {
+ const url = `${base}/data/writers-room/works/${encodeURIComponent(workId)}/drafts/${encodeURIComponent(draftId)}.md`;
+ const buffer = await fetchCappedAssetBuffer(peer, url, safeLabel, WORK_BODY_PULL_MAX_BYTES);
+ if (!buffer) return;
+ await ensureDir(join(wrWorkDir(workId), 'drafts'));
+ await atomicWrite(wrDraftPath(workId, draftId), buffer);
+ peerSyncEvents.emit('asset-arrived', {
+ filename: `${draftId}.md`,
+ kind: WRITERS_ROOM_DRAFT_ASSET_KIND,
+ peerId: peer.instanceId,
+ });
+ console.log(`📥 peerSync: pulled draft body ${safeLabel} from ${peer.name || peer.instanceId} (${buffer.length} bytes)`);
+ } finally {
+ inflightPulls.delete(key);
+ }
+}
+
async function pullOneAsset(peer, base, entry) {
const urlPrefix = ASSET_KIND_TO_URL_PREFIX[entry.kind];
const localDir = directoryForAssetKind(entry.kind);
@@ -2427,60 +2570,8 @@ async function doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName)
}
const url = `${base}${urlPrefix}/${encodeURIComponent(safeName)}`;
- const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(), ASSET_PULL_TIMEOUT_MS);
- // maxBytes propagates into the HTTPS shim's streaming cap (see
- // server/lib/httpClient.js) — without it, an oversized HTTPS asset
- // buffers the whole body before the post-resolve content-length
- // check fires. The plain-HTTP fetch path falls back to the
- // post-resolve checks below (Node's fetch doesn't accept maxBytes,
- // but Content-Length is universally set by serve-static).
- const res = await peerFetch(url, { signal: controller.signal, maxBytes: ASSET_PULL_MAX_BYTES }, peer)
- .finally(() => clearTimeout(timeoutId))
- .catch((err) => {
- // The HTTPS shim rejects with a thrown Error when maxBytes is
- // exceeded — distinguish from network/abort errors so we don't
- // spam the log on a normal abort.
- if (err?.message?.includes('exceed')) {
- console.log(`⚠️ peerSync: ${safeName} exceeded asset size cap — ${err.message}`);
- }
- return null;
- });
- if (!res || !res.ok) return;
- // Size-cap enforcement: REQUIRE a trustworthy content-length header up
- // front and refuse the pull if missing or over-cap. Without the header
- // we'd have to buffer the whole response before checking buffer.length,
- // which defeats the cap (a hostile peer could ship a 10GB file under a
- // small filename and OOM the receiver before the check runs). Express's
- // `serve-static` always sets content-length for static files (verified
- // by the `acceptRanges: true` mount config in server/index.js), so this
- // is enforceable in the real deployment path.
- // Use has() to distinguish "header missing" from "header is '0'" — without
- // the explicit check, `Number(null)` is 0 and slips past the finite-non-negative
- // guard, letting a peer that omits the header buffer an unbounded body before
- // the size cap runs (the cap on .arrayBuffer() length only kicks in AFTER the
- // body lands in memory).
- if (!res.headers.has('content-length')) {
- console.log(`⚠️ peerSync: asset ${safeName} has no content-length — refusing pull`);
- return;
- }
- const contentLength = Number(res.headers.get('content-length'));
- if (!Number.isFinite(contentLength) || contentLength <= 0) {
- console.log(`⚠️ peerSync: asset ${safeName} has invalid content-length (${res.headers.get('content-length')}) — refusing pull`);
- return;
- }
- if (contentLength > ASSET_PULL_MAX_BYTES) {
- console.log(`⚠️ peerSync: asset ${safeName} too large (${contentLength}) — refusing pull`);
- return;
- }
- const buffer = Buffer.from(await res.arrayBuffer());
- // Defense in depth: the server claimed length X but actually sent more
- // (shouldn't happen with serve-static, but content-length is just a
- // header). Refuse to write the partial / over-cap result.
- if (buffer.length > ASSET_PULL_MAX_BYTES || buffer.length !== contentLength) {
- console.log(`⚠️ peerSync: asset ${safeName} length mismatch (header=${contentLength}, body=${buffer.length}) — refusing pull`);
- return;
- }
+ const buffer = await fetchCappedAssetBuffer(peer, url, safeName, ASSET_PULL_MAX_BYTES);
+ if (!buffer) return;
await ensureDir(localDir);
const fullPath = join(localDir, safeName);
// atomicWrite (temp + rename) so a crash mid-write doesn't leave a
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 650f3579e4..0fecd1960d 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, moodBoard]', () => {
+ it('is exactly [universe, series, mediaCollection, author, artist, album, track, creativeDirectorProject, moodBoard, writersRoomWork]', () => {
// 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', 'moodBoard']);
+ expect(PEER_SUBSCRIBABLE_KINDS).toEqual(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork']);
});
});
diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.js
index 96d7727e86..9eb1380ae0 100644
--- a/server/services/sharing/tombstoneGc.js
+++ b/server/services/sharing/tombstoneGc.js
@@ -36,6 +36,7 @@ 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 { pruneTombstonedWorks, listWorkIdsForSync } from '../writersRoom/sync.js';
import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';
import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';
import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';
@@ -58,6 +59,7 @@ const LIVE_ID_LISTERS = Object.freeze({
track: () => listTrackIds(),
creativeDirectorProject: () => listProjectIds(),
moodBoard: () => listBoardIds(),
+ writersRoomWork: () => listWorkIdsForSync(),
});
// Each peer-subscribable kind's UNCAPPED id source INCLUDING tombstones —
@@ -77,6 +79,7 @@ const ALL_ID_LISTERS = Object.freeze({
track: () => listTrackIds({ includeDeleted: true }),
creativeDirectorProject: () => listProjectIds({ includeDeleted: true }),
moodBoard: () => listBoardIds({ includeDeleted: true }),
+ writersRoomWork: () => listWorkIdsForSync({ includeDeleted: true }),
});
// Build a kind-aware id-membership resolver for ONE sweep: lazily list each
@@ -247,6 +250,7 @@ function refusedFromCutoffs(cutoffs) {
trackCutoff,
projectCutoff,
boardCutoff,
+ workCutoff,
} = cutoffs;
if (universeCutoff === null) refused.push('universe');
// Issue tombstones ride series pushes — refused exactly when series is.
@@ -264,6 +268,7 @@ function refusedFromCutoffs(cutoffs) {
if (trackCutoff === null) refused.push('track');
if (projectCutoff === null) refused.push('creativeDirectorProject');
if (boardCutoff === null) refused.push('moodBoard');
+ if (workCutoff === null) refused.push('writersRoomWork');
return refused;
}
@@ -290,6 +295,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
trackCutoff,
projectCutoff,
boardCutoff,
+ workCutoff,
] = await Promise.all([
cutoffForKind('universe', { peers, subs, now, graceMs }),
cutoffForKind('series', { peers, subs, now, graceMs }),
@@ -300,9 +306,10 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
cutoffForKind('track', { peers, subs, now, graceMs }),
cutoffForKind('creativeDirectorProject', { peers, subs, now, graceMs }),
cutoffForKind('moodBoard', { peers, subs, now, graceMs }),
+ cutoffForKind('writersRoomWork', { peers, subs, now, graceMs }),
]);
const issueCutoff = seriesCutoff;
- const [u, s, i, c, a, ar, al, t, cd, mb] = await Promise.all([
+ const [u, s, i, c, a, ar, al, t, cd, mb, wr] = 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),
@@ -313,6 +320,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
trackCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedTracks(trackCutoff),
projectCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedProjects(projectCutoff),
boardCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedBoards(boardCutoff),
+ workCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedWorks(workCutoff),
]);
// 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
@@ -339,9 +347,10 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
tracks: t.pruned,
creativeDirectorProjects: cd.pruned,
moodBoards: mb.pruned,
+ writersRoomWorks: wr.pruned,
orphanBaseHashes: orphan.pruned,
orphanSubscriptions: orphanSubs.pruned,
- refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, boardCutoff }),
+ refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, boardCutoff, workCutoff }),
};
}
@@ -350,7 +359,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
// coverage matters), so this hardcodes graceMs:0 internally.
export async function getSweepStatus({ now = Date.now() } = {}) {
const { peers, subs } = await loadState();
- const [universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, boardCutoff] = await Promise.all([
+ const [universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, boardCutoff, workCutoff] = await Promise.all([
cutoffForKind('universe', { peers, subs, now, graceMs: 0 }),
cutoffForKind('series', { peers, subs, now, graceMs: 0 }),
cutoffForKind('mediaCollection', { peers, subs, now, graceMs: 0 }),
@@ -360,8 +369,9 @@ export async function getSweepStatus({ now = Date.now() } = {}) {
cutoffForKind('track', { peers, subs, now, graceMs: 0 }),
cutoffForKind('creativeDirectorProject', { peers, subs, now, graceMs: 0 }),
cutoffForKind('moodBoard', { peers, subs, now, graceMs: 0 }),
+ cutoffForKind('writersRoomWork', { peers, subs, now, graceMs: 0 }),
]);
- return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, boardCutoff }) };
+ return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, boardCutoff, workCutoff }) };
}
export const TOMBSTONE_GRACE_MS = GRACE_MS;
diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.js
index 4e30fc8972..e848ffd5b2 100644
--- a/server/services/sharing/tombstoneGc.test.js
+++ b/server/services/sharing/tombstoneGc.test.js
@@ -44,6 +44,10 @@ vi.mock('../moodBoard/index.js', () => ({
pruneTombstonedBoards: vi.fn().mockResolvedValue({ pruned: 0 }),
listBoardIds: vi.fn().mockResolvedValue([]),
}));
+vi.mock('../writersRoom/sync.js', () => ({
+ pruneTombstonedWorks: vi.fn().mockResolvedValue({ pruned: 0 }),
+ listWorkIdsForSync: vi.fn().mockResolvedValue([]),
+}));
vi.mock('../../lib/conflictJournal.js', () => ({
pruneOrphanedBaseHashes: vi.fn().mockResolvedValue({ pruned: 0 }),
}));
@@ -73,6 +77,7 @@ 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 { pruneTombstonedWorks } from '../writersRoom/sync.js';
import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';
import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';
import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';
@@ -430,6 +435,7 @@ describe('sweepTombstones — return shape', () => {
pruneTombstonedTracks.mockResolvedValueOnce({ pruned: 7 });
pruneTombstonedProjects.mockResolvedValueOnce({ pruned: 8 });
pruneTombstonedBoards.mockResolvedValueOnce({ pruned: 9 });
+ pruneTombstonedWorks.mockResolvedValueOnce({ pruned: 10 });
const result = await sweepTombstones({ now: NOW });
expect(result).toEqual({
universes: 2,
@@ -442,6 +448,7 @@ describe('sweepTombstones — return shape', () => {
tracks: 7,
creativeDirectorProjects: 8,
moodBoards: 9,
+ writersRoomWorks: 10,
orphanBaseHashes: 0,
orphanSubscriptions: 0,
refused: [],
diff --git a/server/services/writersRoom/db.js b/server/services/writersRoom/db.js
index 84178b5ec8..04790fd931 100644
--- a/server/services/writersRoom/db.js
+++ b/server/services/writersRoom/db.js
@@ -18,12 +18,26 @@
* splits it on write, so its public API is unchanged.
*
* The `data` JSONB on every table holds the FULL lossless record; the typed
- * columns are a queryable mirror (never read back into the record). Writers Room
- * is NOT federated, so there is no ephemeral/sync column and no mutation epoch.
+ * columns are a queryable mirror (never read back into the record).
+ *
+ * Works FEDERATE across peers as of #1565 (record kind `writersRoomWork`, sync
+ * category `writersRoomWorks`): `deleteWork` soft-deletes (tombstone) instead of
+ * hard-deleting so the deletion propagates without an out-of-date peer
+ * resurrecting it, and `mergeWorksFromSync` LWW-merges an incoming work the same
+ * way creativeDirector/projectsDB.js does — per-record `withTransaction` +
+ * `SELECT … FOR UPDATE`, conflict-journal base hash seeding, and journaling the
+ * about-to-be-overwritten local version when remote wins. The `deleted`/`deletedAt`
+ * columns (added in #1017) carry the tombstone; the same pair is mirrored into the
+ * work row's `data` JSONB so the sync sanitizer round-trips it. Folders and
+ * exercises do NOT federate yet (they lack soft-delete columns).
*/
import { query, withTransaction } from '../../lib/db.js';
import { mirrorTimestamp } from '../../lib/pgTimestamp.js';
+import {
+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,
+} from '../../lib/conflictJournal.js';
+import { WRITERS_ROOM_WORK_KIND, mergeWorkRecord } from './syncLogic.js';
// ---------- folders ----------
@@ -112,10 +126,16 @@ function rowsToManifest(workRow, draftRows) {
return manifest;
}
-/** One work's manifest (rebuilt from its row + draft rows), or null. */
-export async function readWork(id) {
+/**
+ * One work's manifest (rebuilt from its row + draft rows), or null. Live works
+ * only by default; `includeDeleted` surfaces a tombstoned work too (federation
+ * reads it to compare `updatedAt` and to push the tombstone to peers).
+ */
+export async function readWork(id, { includeDeleted = false } = {}) {
const work = await query(
- `SELECT data FROM writers_room_works WHERE id = $1 AND deleted = FALSE`,
+ includeDeleted
+ ? `SELECT data FROM writers_room_works WHERE id = $1`
+ : `SELECT data FROM writers_room_works WHERE id = $1 AND deleted = FALSE`,
[id],
);
if (!work.rows[0]) return null;
@@ -126,10 +146,12 @@ export async function readWork(id) {
return rowsToManifest(work.rows[0], drafts.rows);
}
-/** Every live work id (non-deleted). */
-export async function listWorkIds() {
+/** Every work id — live only by default, or all (incl. tombstones) when asked. */
+export async function listWorkIds({ includeDeleted = false } = {}) {
const { rows } = await query(
- `SELECT id FROM writers_room_works WHERE deleted = FALSE`,
+ includeDeleted
+ ? `SELECT id FROM writers_room_works`
+ : `SELECT id FROM writers_room_works WHERE deleted = FALSE`,
);
return rows.map((r) => r.id);
}
@@ -178,94 +200,194 @@ function draftBinds(workId, draft) {
* draft rows or a draft set out of sync with the manifest.
*/
export async function writeWork(manifest) {
+ await withTransaction((client) => persistWorkTx(client, manifest));
+ return manifest;
+}
+
+/**
+ * Upsert a work manifest + its draft rows on an open transaction client. Shared
+ * by `writeWork` (its own transaction) and `mergeWorksFromSync` (the per-record
+ * merge transaction). The work row's `data` holds the manifest WITHOUT the
+ * drafts[] array — the draft rows are authoritative — but WITH the normalized
+ * soft-delete pair so the sync sanitizer round-trips a tombstone. Honors
+ * `manifest.deleted`/`manifest.deletedAt` (default live) so a tombstone merge
+ * persists the deletion instead of resurrecting the row.
+ */
+async function persistWorkTx(client, manifest) {
const now = new Date().toISOString();
const createdAt = mirrorTimestamp(manifest?.createdAt, now);
- const drafts = Array.isArray(manifest?.drafts) ? manifest.drafts : [];
- // The work row's `data` holds the manifest WITHOUT the drafts[] array — the
- // draft rows are authoritative, so embedding them too would duplicate (and
- // risk drifting from) the decomposed source of truth.
- const { drafts: _omit, ...workData } = manifest;
- await withTransaction(async (client) => {
+ // `drafts` absent (not an array) means "don't touch the draft rows" — the
+ // soft-delete tombstone path persists only the work row and must KEEP the
+ // existing draft rows (+ .md bodies) until hard-prune. An empty array still
+ // means "authoritative empty set → delete all draft rows" (the original
+ // behavior writeWork relied on for a version delete).
+ const hasDrafts = Array.isArray(manifest?.drafts);
+ const drafts = hasDrafts ? manifest.drafts : [];
+ const deleted = manifest?.deleted === true;
+ const deletedAt = deleted ? mirrorTimestamp(manifest?.deletedAt, now) : null;
+ const { drafts: _omit, ...rest } = manifest;
+ // Mirror the tombstone trio INTO the JSONB so readWork(includeDeleted) surfaces
+ // it to the sync sanitizer (the columns alone are never read back into data).
+ const workData = { ...rest, deleted, deletedAt };
+ await client.query(
+ `INSERT INTO writers_room_works
+ (id, folder_id, title, kind, status, active_draft_version_id,
+ pipeline_series_id, pipeline_issue_id, cd_project_id, media_collection_id,
+ data, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::jsonb,$12,$13,$14,$15)
+ ON CONFLICT (id) DO UPDATE SET
+ folder_id = EXCLUDED.folder_id,
+ title = EXCLUDED.title,
+ kind = EXCLUDED.kind,
+ status = EXCLUDED.status,
+ active_draft_version_id = EXCLUDED.active_draft_version_id,
+ pipeline_series_id = EXCLUDED.pipeline_series_id,
+ pipeline_issue_id = EXCLUDED.pipeline_issue_id,
+ cd_project_id = EXCLUDED.cd_project_id,
+ media_collection_id = EXCLUDED.media_collection_id,
+ data = EXCLUDED.data,
+ updated_at = EXCLUDED.updated_at,
+ deleted = EXCLUDED.deleted,
+ deleted_at = EXCLUDED.deleted_at`,
+ [
+ manifest.id,
+ typeof manifest?.folderId === 'string' && manifest.folderId ? manifest.folderId : null,
+ String(manifest?.title ?? ''),
+ typeof manifest?.kind === 'string' ? manifest.kind.slice(0, 32) : null,
+ typeof manifest?.status === 'string' ? manifest.status.slice(0, 32) : null,
+ typeof manifest?.activeDraftVersionId === 'string' ? manifest.activeDraftVersionId : null,
+ typeof manifest?.pipelineSeriesId === 'string' ? manifest.pipelineSeriesId : null,
+ typeof manifest?.pipelineIssueId === 'string' ? manifest.pipelineIssueId : null,
+ typeof manifest?.cdProjectId === 'string' ? manifest.cdProjectId : null,
+ typeof manifest?.mediaCollectionId === 'string' ? manifest.mediaCollectionId : null,
+ JSON.stringify(workData),
+ createdAt,
+ mirrorTimestamp(manifest?.updatedAt, createdAt),
+ deleted,
+ deletedAt,
+ ],
+ );
+ if (!hasDrafts) return; // tombstone-only persist — leave draft rows untouched
+ for (const draft of drafts) {
+ if (!draft || typeof draft.id !== 'string') continue;
await client.query(
- `INSERT INTO writers_room_works
- (id, folder_id, title, kind, status, active_draft_version_id,
- pipeline_series_id, pipeline_issue_id, cd_project_id, media_collection_id,
- data, created_at, updated_at, deleted, deleted_at)
- VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::jsonb,$12,$13,FALSE,NULL)
+ `INSERT INTO writers_room_draft_versions
+ (id, work_id, label, content_file, content_hash, word_count,
+ segment_index, created_from_version_id, data, created_at)
+ VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8,$9::jsonb,$10)
ON CONFLICT (id) DO UPDATE SET
- folder_id = EXCLUDED.folder_id,
- title = EXCLUDED.title,
- kind = EXCLUDED.kind,
- status = EXCLUDED.status,
- active_draft_version_id = EXCLUDED.active_draft_version_id,
- pipeline_series_id = EXCLUDED.pipeline_series_id,
- pipeline_issue_id = EXCLUDED.pipeline_issue_id,
- cd_project_id = EXCLUDED.cd_project_id,
- media_collection_id = EXCLUDED.media_collection_id,
- data = EXCLUDED.data,
- updated_at = EXCLUDED.updated_at,
- deleted = FALSE,
- deleted_at = NULL`,
- [
- manifest.id,
- typeof manifest?.folderId === 'string' && manifest.folderId ? manifest.folderId : null,
- String(manifest?.title ?? ''),
- typeof manifest?.kind === 'string' ? manifest.kind.slice(0, 32) : null,
- typeof manifest?.status === 'string' ? manifest.status.slice(0, 32) : null,
- typeof manifest?.activeDraftVersionId === 'string' ? manifest.activeDraftVersionId : null,
- typeof manifest?.pipelineSeriesId === 'string' ? manifest.pipelineSeriesId : null,
- typeof manifest?.pipelineIssueId === 'string' ? manifest.pipelineIssueId : null,
- typeof manifest?.cdProjectId === 'string' ? manifest.cdProjectId : null,
- typeof manifest?.mediaCollectionId === 'string' ? manifest.mediaCollectionId : null,
- JSON.stringify(workData),
- createdAt,
- mirrorTimestamp(manifest?.updatedAt, createdAt),
- ],
+ work_id = EXCLUDED.work_id,
+ label = EXCLUDED.label,
+ content_file = EXCLUDED.content_file,
+ content_hash = EXCLUDED.content_hash,
+ word_count = EXCLUDED.word_count,
+ segment_index = EXCLUDED.segment_index,
+ created_from_version_id = EXCLUDED.created_from_version_id,
+ data = EXCLUDED.data`,
+ draftBinds(manifest.id, draft),
);
- for (const draft of drafts) {
- if (!draft || typeof draft.id !== 'string') continue;
- await client.query(
- `INSERT INTO writers_room_draft_versions
- (id, work_id, label, content_file, content_hash, word_count,
- segment_index, created_from_version_id, data, created_at)
- VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8,$9::jsonb,$10)
- ON CONFLICT (id) DO UPDATE SET
- work_id = EXCLUDED.work_id,
- label = EXCLUDED.label,
- content_file = EXCLUDED.content_file,
- content_hash = EXCLUDED.content_hash,
- word_count = EXCLUDED.word_count,
- segment_index = EXCLUDED.segment_index,
- created_from_version_id = EXCLUDED.created_from_version_id,
- data = EXCLUDED.data`,
- draftBinds(manifest.id, draft),
- );
- }
- // Prune draft rows that are no longer part of the manifest (version delete).
- const keepIds = drafts.map((d) => d?.id).filter((id) => typeof id === 'string');
- if (keepIds.length > 0) {
- await client.query(
- `DELETE FROM writers_room_draft_versions WHERE work_id = $1 AND id <> ALL($2::text[])`,
- [manifest.id, keepIds],
- );
- } else {
- await client.query(`DELETE FROM writers_room_draft_versions WHERE work_id = $1`, [manifest.id]);
- }
- });
- return manifest;
+ }
+ // Prune draft rows that are no longer part of the manifest (version delete).
+ const keepIds = drafts.map((d) => d?.id).filter((id) => typeof id === 'string');
+ if (keepIds.length > 0) {
+ await client.query(
+ `DELETE FROM writers_room_draft_versions WHERE work_id = $1 AND id <> ALL($2::text[])`,
+ [manifest.id, keepIds],
+ );
+ } else {
+ await client.query(`DELETE FROM writers_room_draft_versions WHERE work_id = $1`, [manifest.id]);
+ }
}
/**
- * Hard-delete a work and its draft rows (the file backend rm -rf's the dir; the
- * DB backend mirrors that destructive delete rather than tombstoning, since
- * Writers Room is not federated so there are no peers to propagate a tombstone
- * to). local.js still rm's the on-disk .md bodies. Idempotent.
+ * Soft-delete a work (tombstone) so the deletion federates and an out-of-date
+ * peer can't resurrect it via the LWW merge (#1565). The work row + its draft
+ * rows + the on-disk .md bodies all stay until tombstone GC hard-prunes them
+ * (`pruneTombstonedWorks`); `deleted`/`deletedAt`/`updatedAt` stamp now so the
+ * tombstone wins on merge. Idempotent: a missing/already-deleted work is a no-op
+ * (the caller already 404s a missing work before reaching here).
*/
export async function deleteWork(id) {
await withTransaction(async (client) => {
- await client.query(`DELETE FROM writers_room_draft_versions WHERE work_id = $1`, [id]);
- await client.query(`DELETE FROM writers_room_works WHERE id = $1`, [id]);
+ const sel = await client.query(`SELECT data FROM writers_room_works WHERE id = $1 FOR UPDATE`, [id]);
+ const current = sel.rows[0]?.data;
+ if (!current || current.deleted === true) return;
+ const now = new Date().toISOString();
+ await persistWorkTx(client, { ...current, drafts: undefined, deleted: true, deletedAt: now, updatedAt: now });
+ });
+}
+
+/**
+ * Merge an incoming batch of work 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 `mergeWorkRecord` decision —
+ * identical to the file backend so the two can't drift. Mirrors
+ * `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 mergeWorksFromSync(remoteWorks, { source = { via: 'sync', peerId: null } } = {}) {
+ if (!Array.isArray(remoteWorks)) return { applied: false, count: 0 };
+ let changed = 0;
+ for (const remote of remoteWorks) {
+ const applied = await withTransaction(async (client) => {
+ // Lock the work row, then rebuild the local manifest (row data + its draft
+ // rows) so the LWW comparison + journaled snapshot see the full record.
+ const sel = await client.query(`SELECT data FROM writers_room_works WHERE id = $1 FOR UPDATE`, [remote?.id]);
+ let local = null;
+ if (sel.rows[0]) {
+ const draftRows = await client.query(
+ `SELECT data FROM writers_room_draft_versions WHERE work_id = $1 ORDER BY created_at, id`,
+ [remote.id],
+ );
+ local = rowsToManifest(sel.rows[0], draftRows.rows);
+ }
+ const { next, inserted, remoteWins, changed: didChange } = mergeWorkRecord(local, remote);
+ if (!next) return false; // malformed remote → dropped
+ if (inserted) {
+ await persistWorkTx(client, next);
+ await setSyncBaseHash(WRITERS_ROOM_WORK_KIND, next.id, contentHashForRecord(WRITERS_ROOM_WORK_KIND, next));
+ return true;
+ }
+ if (!remoteWins || !didChange) return false; // local wins, or no-op
+ await maybeJournalBeforeOverwrite({ kind: WRITERS_ROOM_WORK_KIND, id: next.id, local, remote: next, source });
+ await persistWorkTx(client, next);
+ await setSyncBaseHash(WRITERS_ROOM_WORK_KIND, next.id, contentHashForRecord(WRITERS_ROOM_WORK_KIND, 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 works (+ their draft rows) whose deletedAt is older than
+ * the cutoff. Called by tombstone GC once every subscribed peer has acked the
+ * deletion. Returns the pruned ids so the facade (sync.js) can rm the on-disk .md
+ * dirs + evict each work's conflict-journal base hash. Mirrors
+ * `pruneTombstonedProjects` (the base-hash eviction lives in the facade here
+ * because the .md cleanup is a facade concern too).
+ */
+export async function pruneTombstonedWorks(olderThanMs) {
+ if (!Number.isFinite(olderThanMs)) return { pruned: 0, ids: [] };
+ const cutoffIso = new Date(olderThanMs).toISOString();
+ const ids = await withTransaction(async (client) => {
+ const { rows } = await client.query(
+ `DELETE FROM writers_room_works
+ WHERE deleted = TRUE AND deleted_at IS NOT NULL AND deleted_at < $1
+ RETURNING id`,
+ [cutoffIso],
+ );
+ const pruned = rows.map((r) => r.id);
+ if (pruned.length > 0) {
+ await client.query(`DELETE FROM writers_room_draft_versions WHERE work_id = ANY($1::text[])`, [pruned]);
+ }
+ return pruned;
});
+ return { pruned: ids.length, ids };
}
/**
diff --git a/server/services/writersRoom/db.test.js b/server/services/writersRoom/db.test.js
index efefe5eab0..10cd8d5d9e 100644
--- a/server/services/writersRoom/db.test.js
+++ b/server/services/writersRoom/db.test.js
@@ -141,16 +141,46 @@ describe.skipIf(!dbReady)('Writers Room DB adapter round-trip', () => {
expect(dcol.content_hash).toBe('h'.repeat(64));
});
- it('listWorks excludes soft-deleted works and rebuilds drafts in one pass', async () => {
+ it('deleteWork soft-deletes (tombstone) — hidden from live reads, row + drafts retained for federation', async () => {
await db.writeWork(manifest('wr-work-1'));
await db.writeWork(manifest('wr-work-2', { drafts: [draft('wr-draft-c')], activeDraftVersionId: 'wr-draft-c' }));
- await db.deleteWork('wr-work-2'); // hard delete (WR not federated)
+ await db.deleteWork('wr-work-2'); // soft-delete tombstone (#1565 federation)
const works = await db.listWorks();
expect(works.map((w) => w.id)).toEqual(['wr-work-1']);
expect(works[0].drafts.map((d) => d.id)).toEqual(['wr-draft-a']);
+ // Live reads filter the tombstone out…
expect(await db.readWork('wr-work-2')).toBeNull();
- // Draft rows for the deleted work are gone too.
- expect((await query(`SELECT 1 FROM writers_room_draft_versions WHERE work_id = 'wr-work-2'`)).rows).toHaveLength(0);
+ expect(await db.listWorkIds()).toEqual(['wr-work-1']);
+ // …but the row, its draft rows, and the tombstone trio survive until prune.
+ expect((await query(`SELECT deleted FROM writers_room_works WHERE id = 'wr-work-2'`)).rows[0].deleted).toBe(true);
+ expect((await query(`SELECT 1 FROM writers_room_draft_versions WHERE work_id = 'wr-work-2'`)).rows).toHaveLength(1);
+ // readWork({ includeDeleted }) surfaces the tombstone for the federation push.
+ const tomb = await db.readWork('wr-work-2', { includeDeleted: true });
+ expect(tomb.deleted).toBe(true);
+ expect(await db.listWorkIds({ includeDeleted: true })).toEqual(expect.arrayContaining(['wr-work-1', 'wr-work-2']));
+ });
+
+ it('mergeWorksFromSync inserts a remote work and LWW-resolves a later edit', async () => {
+ const insert = await db.mergeWorksFromSync([manifest('wr-work-1', { title: 'Remote', updatedAt: '2026-02-01T00:00:00.000Z' })]);
+ expect(insert).toEqual({ applied: true, count: 1 });
+ expect((await db.readWork('wr-work-1')).title).toBe('Remote');
+ // Older remote loses (no-op); newer remote wins.
+ expect(await db.mergeWorksFromSync([manifest('wr-work-1', { title: 'Stale', updatedAt: '2026-01-01T00:00:00.000Z' })])).toEqual({ applied: false, count: 0 });
+ expect((await db.readWork('wr-work-1')).title).toBe('Remote');
+ expect(await db.mergeWorksFromSync([manifest('wr-work-1', { title: 'Newer', updatedAt: '2026-03-01T00:00:00.000Z' })])).toEqual({ applied: true, count: 1 });
+ expect((await db.readWork('wr-work-1')).title).toBe('Newer');
+ });
+
+ it('pruneTombstonedWorks hard-removes old tombstones (rows + drafts) and returns their ids', async () => {
+ await db.writeWork(manifest('wr-work-1'));
+ await db.mergeWorksFromSync([manifest('wr-work-1', { deleted: true, deletedAt: '2026-01-05T00:00:00.000Z', updatedAt: '2026-01-05T00:00:00.000Z' })]);
+ // Cutoff before the tombstone → nothing pruned.
+ expect(await db.pruneTombstonedWorks(Date.parse('2026-01-04T00:00:00.000Z'))).toEqual({ pruned: 0, ids: [] });
+ expect((await query(`SELECT 1 FROM writers_room_works WHERE id = 'wr-work-1'`)).rows).toHaveLength(1);
+ // Cutoff after the tombstone → row + draft rows gone, id returned.
+ expect(await db.pruneTombstonedWorks(Date.parse('2026-02-01T00:00:00.000Z'))).toEqual({ pruned: 1, ids: ['wr-work-1'] });
+ expect((await query(`SELECT 1 FROM writers_room_works WHERE id = 'wr-work-1'`)).rows).toHaveLength(0);
+ expect((await query(`SELECT 1 FROM writers_room_draft_versions WHERE work_id = 'wr-work-1'`)).rows).toHaveLength(0);
});
it('exercise upsert round-trips and mirror columns reflect work_id/status', async () => {
diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.js
index 5162d7999d..a69fd9c1bd 100644
--- a/server/services/writersRoom/local.js
+++ b/server/services/writersRoom/local.js
@@ -15,11 +15,13 @@
*/
import { randomUUID, createHash } from 'crypto';
-import { readFile, rm } from 'fs/promises';
+import { readFile } from 'fs/promises';
import { atomicWrite, ensureDir } from '../../lib/fileUtils.js';
import { WORK_KINDS, WORK_STATUSES } from '../../lib/writersRoomPresets.js';
+import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';
import { nowIso, badRequest, notFound, wrWorkDir, wrDraftPath } from './_shared.js';
import { writersRoomStore } from './store.js';
+import { WRITERS_ROOM_WORK_KIND } from './syncLogic.js';
const store = () => writersRoomStore();
@@ -136,9 +138,20 @@ async function loadManifest(workId) {
return store().readWork(workId);
}
-async function saveManifest(workId, manifest) {
+// Announce a persisted work change to the per-record peer-sync pipeline (#1565)
+// so any existing subscription pushes the new state (+ its draft-body manifest).
+// 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 mergeWorksFromSync from writersRoom/sync.js, so importing
+// it back would close a load-order cycle. Mirrors creativeDirector/local.js.
+//
+// `announce: false` opts the hot-path live-mode usage-counter writes out of a
+// push (they fire once per suggest call) — the bumped counter rides the next
+// structural push, exactly as Creative Director's recordRun does NOT emit.
+async function saveManifest(workId, manifest, { announce = true } = {}) {
await ensureDir(`${wrWorkDir(workId)}/drafts`);
await store().writeWork(manifest);
+ if (announce) emitRecordUpdated(WRITERS_ROOM_WORK_KIND, workId);
}
// Lazy-import to break a circular dep (mediaCollections doesn't import us, but
@@ -245,6 +258,9 @@ export async function createWork({ folderId = null, title, kind = 'short-story'
updatedAt: now,
};
await saveManifest(id, manifest);
+ // Auto-subscribe every writersRoomWorks-enabled peer so brand-new works (and
+ // their later tombstones) propagate without waiting for a reconnect (#1565).
+ autoSubscribeRecordToAllPeers(WRITERS_ROOM_WORK_KIND, id).catch(() => {});
return manifest;
}
@@ -384,7 +400,7 @@ export async function recordLiveModeUsage(id) {
const today = utcDayKey();
const count = live.usage.date === today ? live.usage.count + 1 : 1;
const nextLive = { ...live, usage: { date: today, count } };
- await saveManifest(id, { ...manifest, liveMode: nextLive, updatedAt: nowIso() });
+ await saveManifest(id, { ...manifest, liveMode: nextLive, updatedAt: nowIso() }, { announce: false });
return nextLive;
}
@@ -402,7 +418,7 @@ export async function recordLiveModeRenderUsage(id) {
const today = utcDayKey();
const count = live.renderUsage.date === today ? live.renderUsage.count + 1 : 1;
const nextLive = { ...live, renderUsage: { date: today, count } };
- await saveManifest(id, { ...manifest, liveMode: nextLive, updatedAt: nowIso() });
+ await saveManifest(id, { ...manifest, liveMode: nextLive, updatedAt: nowIso() }, { announce: false });
return nextLive;
}
@@ -418,11 +434,14 @@ export async function deleteWork(id) {
}
throw err;
});
- // Drop the metadata rows (no-op on the file backend, where the manifest lives
- // in the work dir the rm below removes) AND rm the on-disk dir holding the
- // file-primary draft .md bodies.
+ // Soft-delete tombstone (#1565) so the deletion federates and an out-of-date
+ // peer can't resurrect the work via the LWW merge. The work row/manifest + its
+ // draft rows + the on-disk .md bodies all stay until tombstone GC hard-prunes
+ // them (sync.js pruneTombstonedWorks). The record drops out of every user-facing
+ // read immediately (readWork/listWorks filter `deleted`).
await store().deleteWork(id);
- await rm(wrWorkDir(id), { recursive: true, force: true });
+ // Push the tombstone to subscribed peers immediately.
+ emitRecordDeleted(WRITERS_ROOM_WORK_KIND, id);
return { ok: true };
}
diff --git a/server/services/writersRoom/store.js b/server/services/writersRoom/store.js
index cabe0f7dde..4c397a6cea 100644
--- a/server/services/writersRoom/store.js
+++ b/server/services/writersRoom/store.js
@@ -16,9 +16,13 @@
* UNSUPPORTED for production). The file backend reproduces the legacy
* on-disk JSON format so tests boot without a DB exactly as before.
*
- * Writers Room is NOT federated (no dataSync category, no schema-version gate),
- * so — unlike the universe/pipeline/story-builder stores — there is NO mutation
- * epoch here: a storage swap has no peer-visible effect to invalidate.
+ * Works FEDERATE across peers as of #1565 via the per-record peer-sync push
+ * pipeline (not the 60s snapshot loop), so this dispatcher also routes the
+ * federation primitives (readWork includeDeleted, listWorkIds includeDeleted,
+ * mergeWorksFromSync, pruneTombstonedWorks) to whichever backend is active —
+ * both implement the same LWW/tombstone semantics from syncLogic.js. There is
+ * still NO mutation epoch here: works ride per-record pushes, not the snapshot
+ * checksum a storage swap would invalidate.
*
* The first PG-backed call runs a one-time, marker-gated import of the legacy
* data/writers-room file store into the tables (migrateWritersRoomToDB).
@@ -28,6 +32,10 @@ import { readFile, readdir } from 'fs/promises';
import { atomicWrite, ensureDir, readJSONFile, safeJSONParse } from '../../lib/fileUtils.js';
import { checkHealth, ensureSchema } from '../../lib/db.js';
import { ServerError } from '../../lib/errorHandler.js';
+import {
+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,
+} from '../../lib/conflictJournal.js';
+import { WRITERS_ROOM_WORK_KIND, mergeWorkRecord } from './syncLogic.js';
import {
WORK_ID_RE, wrRoot, wrFoldersFile, wrExercisesFile, wrWorksDir, wrManifestPath,
} from './_shared.js';
@@ -107,9 +115,23 @@ function makeFileBackend() {
if (idx >= 0) all[idx] = exercise; else all.push(exercise);
await saveExercises(all);
},
- // works (manifest carries its own drafts[] in the file format)
- readWork: loadManifest,
- listWorkIds,
+ // works (manifest carries its own drafts[] in the file format). A
+ // soft-deleted work (tombstone) stays on disk; readWork/listWorks/listWorkIds
+ // filter it out unless includeDeleted, mirroring the PG backend's
+ // `WHERE deleted = FALSE`.
+ readWork: async (id, { includeDeleted = false } = {}) => {
+ const manifest = await loadManifest(id);
+ if (!manifest) return null;
+ if (!includeDeleted && manifest.deleted === true) return null;
+ return manifest;
+ },
+ listWorkIds: async ({ includeDeleted = false } = {}) => {
+ const ids = await listWorkIds();
+ if (includeDeleted) return ids;
+ // Load manifests concurrently (mirrors listWorks below) to filter tombstones.
+ const manifests = await Promise.all(ids.map((id) => loadManifest(id).catch(() => null)));
+ return ids.filter((_, i) => manifests[i] && manifests[i].deleted !== true);
+ },
listWorks: async () => {
const ids = await listWorkIds();
// Tolerate a corrupted manifest per work (drop it from the listing) so one
@@ -123,15 +145,54 @@ function makeFileBackend() {
}
throw err;
})));
- return manifests.filter((m) => m != null);
+ return manifests.filter((m) => m != null && m.deleted !== true);
},
writeWork: async (manifest) => { await saveManifest(manifest.id, manifest); return manifest; },
- deleteWork: async () => {}, // local.js rm -rf's the dir directly on the file backend
+ deleteWork: async (id) => {
+ // Soft-delete tombstone (#1565) so the deletion federates — mirror the PG
+ // backend. Leave the .md bodies on disk until hard-prune. Idempotent.
+ const manifest = await loadManifest(id).catch(() => null);
+ if (!manifest || manifest.deleted === true) return;
+ const now = new Date().toISOString();
+ await saveManifest(id, { ...manifest, deleted: true, deletedAt: now, updatedAt: now });
+ },
+ mergeWorksFromSync: async (remoteWorks, { source = { via: 'sync', peerId: null } } = {}) => {
+ if (!Array.isArray(remoteWorks)) return { applied: false, count: 0 };
+ let changed = 0;
+ for (const remote of remoteWorks) {
+ const local = await loadManifest(remote?.id).catch(() => null);
+ const { next, inserted, remoteWins, changed: didChange } = mergeWorkRecord(local, remote);
+ if (!next) continue;
+ if (!inserted && (!remoteWins || !didChange)) continue;
+ if (!inserted) {
+ await maybeJournalBeforeOverwrite({ kind: WRITERS_ROOM_WORK_KIND, id: next.id, local, remote: next, source });
+ }
+ await saveManifest(next.id, next);
+ await setSyncBaseHash(WRITERS_ROOM_WORK_KIND, next.id, contentHashForRecord(WRITERS_ROOM_WORK_KIND, next));
+ changed += 1;
+ }
+ await flushBaseHashes();
+ return changed === 0 ? { applied: false, count: 0 } : { applied: true, count: changed };
+ },
+ pruneTombstonedWorks: async (olderThanMs) => {
+ if (!Number.isFinite(olderThanMs)) return { pruned: 0, ids: [] };
+ const ids = await listWorkIds();
+ const manifests = await Promise.all(ids.map((id) => loadManifest(id).catch(() => null)));
+ const out = ids.filter((_, i) => {
+ const m = manifests[i];
+ const deletedMs = m?.deleted === true ? Date.parse(m.deletedAt || '') : NaN;
+ return Number.isFinite(deletedMs) && deletedMs < olderThanMs;
+ });
+ // The facade (sync.js) rm's each id's dir (manifest + bodies) and evicts the
+ // base hash — uniform with the PG backend, whose rows are dropped here.
+ return { pruned: out.length, ids: out };
+ },
listDraftVersionsForCoherence: async () => {
const ids = await listWorkIds();
const out = [];
for (const id of ids) {
const m = await loadManifest(id).catch(() => null);
+ if (!m || m.deleted === true) continue;
for (const d of m?.drafts || []) {
out.push({ id: d.id, workId: id, contentFile: d.contentFile, contentHash: d.contentHash });
}
@@ -188,11 +249,13 @@ export function writersRoomStore() {
deleteFolder: async (id) => (await getBackend()).deleteFolder(id),
listExercises: async () => (await getBackend()).listExercises(),
writeExercise: async (exercise) => (await getBackend()).writeExercise(exercise),
- readWork: async (id) => (await getBackend()).readWork(id),
- listWorkIds: async () => (await getBackend()).listWorkIds(),
+ readWork: async (id, opts) => (await getBackend()).readWork(id, opts),
+ listWorkIds: async (opts) => (await getBackend()).listWorkIds(opts),
listWorks: async () => (await getBackend()).listWorks(),
writeWork: async (manifest) => (await getBackend()).writeWork(manifest),
deleteWork: async (id) => (await getBackend()).deleteWork(id),
+ mergeWorksFromSync: async (remoteWorks, opts) => (await getBackend()).mergeWorksFromSync(remoteWorks, opts),
+ pruneTombstonedWorks: async (olderThanMs) => (await getBackend()).pruneTombstonedWorks(olderThanMs),
listDraftVersionsForCoherence: async () => (await getBackend()).listDraftVersionsForCoherence(),
};
}
diff --git a/server/services/writersRoom/sync.js b/server/services/writersRoom/sync.js
new file mode 100644
index 0000000000..4b42472c18
--- /dev/null
+++ b/server/services/writersRoom/sync.js
@@ -0,0 +1,102 @@
+/**
+ * Writers Room — cross-peer federation facade (#1565).
+ *
+ * The single import surface for the peer-sync graph (peerSync.js) and tombstone
+ * GC (tombstoneGc.js). Routes the LWW/tombstone merge + prune through the active
+ * storage backend (store.js → db.js or the file backend) and owns the two
+ * facade-level concerns the backends can't: the file-primary draft `.md` BODY
+ * asset manifest (sender) + diff (receiver), and the on-disk cleanup + base-hash
+ * eviction when a tombstone is hard-pruned.
+ *
+ * Mirrors creativeDirector/local.js's federation re-exports + moodBoard/index.js,
+ * but keeps the announce hooks in local.js (the mutators live there). This module
+ * does NOT import peerSync — peerSync statically imports `mergeWorksFromSync`
+ * from here, so importing it back would close a load-order cycle.
+ */
+
+import { rm } from 'fs/promises';
+import { existsSync } from 'fs';
+import { sha256File } from '../../lib/fileUtils.js';
+import { deleteSyncBaseHash } from '../../lib/conflictJournal.js';
+import { writersRoomStore } from './store.js';
+import {
+ WRITERS_ROOM_WORK_KIND, WRITERS_ROOM_DRAFT_ASSET_KIND, draftAssetEntries,
+} from './syncLogic.js';
+import { WORK_ID_RE, DRAFT_ID_RE, wrWorkDir, wrDraftPath } from './_shared.js';
+
+const store = () => writersRoomStore();
+
+/** One work's manifest including a tombstone (for the LWW compare + the push). */
+export async function getWorkForSync(id) {
+ return store().readWork(id, { includeDeleted: true });
+}
+
+/** Work ids — live only by default, or all (incl. tombstones) when asked. */
+export async function listWorkIdsForSync(options = {}) {
+ return store().listWorkIds(options);
+}
+
+/** Merge an incoming batch of work records from a peer (LWW, tombstone-aware). */
+export async function mergeWorksFromSync(remoteWorks, options = {}) {
+ return store().mergeWorksFromSync(remoteWorks, options);
+}
+
+/**
+ * Hard-remove tombstoned works older than the cutoff (called by tombstone GC).
+ * The backend drops the rows (PG) / identifies the dirs (file); this facade then
+ * rm's each work's on-disk dir (manifest + file-primary `.md` bodies) and evicts
+ * its conflict-journal base hash — uniform across both backends. Returns `{ pruned }`.
+ */
+export async function pruneTombstonedWorks(olderThanMs) {
+ const { pruned, ids } = await store().pruneTombstonedWorks(olderThanMs);
+ for (const id of ids) {
+ if (typeof id !== 'string' || !WORK_ID_RE.test(id)) continue;
+ await rm(wrWorkDir(id), { recursive: true, force: true }).catch(() => {});
+ await deleteSyncBaseHash(WRITERS_ROOM_WORK_KIND, id);
+ }
+ return { pruned };
+}
+
+/**
+ * Sender-side: hash each of a work's file-primary draft bodies so the receiver
+ * can pull the bytes from `/data/writers-room/works/<workId>/drafts/<draftId>.md`.
+ * A body with no readable file is skipped silently (can't ship bytes we don't
+ * have, mirroring hashImageForManifest). Tombstone callers pass `[]` upstream.
+ */
+export async function buildWorkBodyManifest(work) {
+ const entries = draftAssetEntries(work);
+ const out = [];
+ for (const { workId, draftId } of entries) {
+ const sha256 = await sha256File(wrDraftPath(workId, draftId)).catch(() => null);
+ if (sha256) out.push({ kind: WRITERS_ROOM_DRAFT_ASSET_KIND, workId, draftId, sha256 });
+ }
+ return out;
+}
+
+/**
+ * Receiver-side: given an incoming draft-body manifest, return the subset whose
+ * local `.md` is absent OR whose hash differs (peer has a newer body). Validates
+ * every workId/draftId as a path segment before any FS op — a peer-supplied id
+ * is untrusted (same traversal posture as sanitizeAssetFilename in the generic
+ * asset pipeline). Echoes only the sanitized fields so junk can't round-trip.
+ */
+export async function diffWorkBodyManifest(manifest) {
+ if (!Array.isArray(manifest)) return [];
+ const missing = [];
+ for (const entry of manifest) {
+ if (!entry || typeof entry !== 'object') continue;
+ const { workId, draftId, sha256 } = entry;
+ if (typeof workId !== 'string' || !WORK_ID_RE.test(workId)) continue;
+ if (typeof draftId !== 'string' || !DRAFT_ID_RE.test(draftId)) continue;
+ if (typeof sha256 !== 'string' || !sha256) continue;
+ const sanitized = { kind: WRITERS_ROOM_DRAFT_ASSET_KIND, workId, draftId, sha256 };
+ const fullPath = wrDraftPath(workId, draftId);
+ if (!existsSync(fullPath)) {
+ missing.push(sanitized);
+ continue;
+ }
+ const localHash = await sha256File(fullPath).catch(() => null);
+ if (localHash !== sha256) missing.push(sanitized);
+ }
+ return missing;
+}
diff --git a/server/services/writersRoom/sync.test.js b/server/services/writersRoom/sync.test.js
new file mode 100644
index 0000000000..3040778028
--- /dev/null
+++ b/server/services/writersRoom/sync.test.js
@@ -0,0 +1,120 @@
+/**
+ * Writers Room federation facade (#1565) — file-backend round-trip.
+ *
+ * Mirrors creativeDirector/projectsFile.test.js: runs against a tmpdir in the
+ * normal (non-DB) suite so it covers the work-specific sync side effects without
+ * Postgres — LWW merge (insert / older-loses / newer-wins), soft-delete
+ * tombstone (dropped from live reads, surfaced to federation), tombstone hard-
+ * prune (the .md dir + base hash gone), and the file-primary draft-body manifest
+ * build + receiver diff. The PostgreSQL backend shares the same `mergeWorkRecord`
+ * decision (db.js), so its gated round-trip doesn't need to re-pin these.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'wr-sync-test-'));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+});
+
+const sync = await import('./sync.js');
+const { writersRoomStore, _resetWritersRoomStore } = await import('./store.js');
+const cj = await import('../../lib/conflictJournal.js');
+const { wrWorkDir, wrDraftPath } = await import('./_shared.js');
+
+const WR = join(TEST_DATA_ROOT, 'writers-room');
+const WORK = 'wr-work-11111111-1111-1111-1111-111111111111';
+const DRAFT = 'wr-draft-22222222-2222-2222-2222-222222222222';
+
+const work = (extra = {}) => ({
+ id: WORK,
+ title: 'A Tale',
+ kind: 'short-story',
+ status: 'drafting',
+ activeDraftVersionId: DRAFT,
+ drafts: [{ id: DRAFT, label: 'Draft 1', contentFile: `drafts/${DRAFT}.md`, contentHash: 'h', wordCount: 3, segmentIndex: [], createdAt: '2026-01-01T00:00:00.000Z' }],
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-02T00:00:00.000Z',
+ ...extra,
+});
+
+function writeBody(text) {
+ mkdirSync(join(wrWorkDir(WORK), 'drafts'), { recursive: true });
+ writeFileSync(wrDraftPath(WORK, DRAFT), text);
+}
+
+describe('Writers Room federation facade — file backend', () => {
+ beforeEach(() => {
+ rmSync(WR, { recursive: true, force: true });
+ _resetWritersRoomStore();
+ cj.__resetBaseHashCacheForTests();
+ });
+ afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+ it('inserts a remote work and seeds its base hash', async () => {
+ const res = await sync.mergeWorksFromSync([work()]);
+ expect(res).toEqual({ applied: true, count: 1 });
+ const got = await sync.getWorkForSync(WORK);
+ expect(got.title).toBe('A Tale');
+ expect(got.drafts).toHaveLength(1);
+ });
+
+ it('LWW: older remote loses, newer wins', async () => {
+ await sync.mergeWorksFromSync([work({ updatedAt: '2026-01-02T00:00:00.000Z', title: 'Local' })]);
+ const older = await sync.mergeWorksFromSync([work({ updatedAt: '2026-01-01T00:00:00.000Z', title: 'Older' })]);
+ expect(older).toEqual({ applied: false, count: 0 });
+ expect((await sync.getWorkForSync(WORK)).title).toBe('Local');
+ const newer = await sync.mergeWorksFromSync([work({ updatedAt: '2026-01-03T00:00:00.000Z', title: 'Newer' })]);
+ expect(newer).toEqual({ applied: true, count: 1 });
+ expect((await sync.getWorkForSync(WORK)).title).toBe('Newer');
+ });
+
+ it('a newer tombstone overwrites a live local and hides it from live reads', async () => {
+ await sync.mergeWorksFromSync([work({ updatedAt: '2026-01-02T00:00:00.000Z' })]);
+ await sync.mergeWorksFromSync([work({ updatedAt: '2026-01-05T00:00:00.000Z', deleted: true, deletedAt: '2026-01-05T00:00:00.000Z' })]);
+ expect(await writersRoomStore().readWork(WORK)).toBeNull(); // live read filters it
+ const tomb = await sync.getWorkForSync(WORK);
+ expect(tomb.deleted).toBe(true);
+ expect((await writersRoomStore().listWorkIds())).not.toContain(WORK); // live-only listing
+ expect((await sync.listWorkIdsForSync({ includeDeleted: true }))).toContain(WORK);
+ });
+
+ it('pruneTombstonedWorks rm\'s the dir for an old tombstone and leaves a fresh one', async () => {
+ await sync.mergeWorksFromSync([work({ updatedAt: '2026-01-05T00:00:00.000Z', deleted: true, deletedAt: '2026-01-05T00:00:00.000Z' })]);
+ expect(existsSync(wrWorkDir(WORK))).toBe(true);
+ // Cutoff before the tombstone → not pruned.
+ expect(await sync.pruneTombstonedWorks(Date.parse('2026-01-04T00:00:00.000Z'))).toEqual({ pruned: 0 });
+ expect(existsSync(wrWorkDir(WORK))).toBe(true);
+ // Cutoff after the tombstone → pruned + dir gone.
+ expect(await sync.pruneTombstonedWorks(Date.parse('2026-02-01T00:00:00.000Z'))).toEqual({ pruned: 1 });
+ expect(existsSync(wrWorkDir(WORK))).toBe(false);
+ expect(await sync.getWorkForSync(WORK)).toBeNull();
+ });
+
+ it('builds a draft-body manifest from the on-disk .md and diffs it against local', async () => {
+ writeBody('Once upon a time.');
+ const manifest = await sync.buildWorkBodyManifest(work());
+ expect(manifest).toHaveLength(1);
+ expect(manifest[0]).toMatchObject({ kind: 'writers-room-draft', workId: WORK, draftId: DRAFT });
+ expect(typeof manifest[0].sha256).toBe('string');
+
+ // Identical hash → nothing missing.
+ expect(await sync.diffWorkBodyManifest(manifest)).toEqual([]);
+ // Different hash → the body is reported missing (peer has a newer body).
+ const stale = [{ ...manifest[0], sha256: 'f'.repeat(64) }];
+ expect(await sync.diffWorkBodyManifest(stale)).toEqual(stale.map((e) => ({ kind: e.kind, workId: e.workId, draftId: e.draftId, sha256: e.sha256 })));
+ });
+
+ it('diffWorkBodyManifest reports an absent local body as missing and rejects bad ids', async () => {
+ const entry = { kind: 'writers-room-draft', workId: WORK, draftId: DRAFT, sha256: 'a'.repeat(64) };
+ expect(await sync.diffWorkBodyManifest([entry])).toEqual([entry]); // no .md on disk
+ // Path-traversal / malformed ids never reach an FS op.
+ expect(await sync.diffWorkBodyManifest([{ ...entry, workId: '../etc' }])).toEqual([]);
+ expect(await sync.diffWorkBodyManifest([{ ...entry, draftId: 'x/../y' }])).toEqual([]);
+ });
+});
diff --git a/server/services/writersRoom/syncLogic.js b/server/services/writersRoom/syncLogic.js
new file mode 100644
index 0000000000..55aabbe40f
--- /dev/null
+++ b/server/services/writersRoom/syncLogic.js
@@ -0,0 +1,87 @@
+/**
+ * Writers Room — pure record transforms for cross-peer federation (#1565).
+ *
+ * Works (PostgreSQL `writers_room_works` + decomposed `writers_room_draft_versions`)
+ * federate across peers via the per-record peer-sync push pipeline — record kind
+ * `writersRoomWork`, sync category `writersRoomWorks`. A federated work record IS
+ * the manifest local.js round-trips: work metadata + the active-draft pointer +
+ * the version history (`drafts[]` of draft-version METADATA). The draft PROSE
+ * BODIES stay file-primary (`works/<workId>/drafts/<draftId>.md`) and replicate
+ * separately as assets via the body manifest in sync.js — never round-tripped
+ * through this record.
+ *
+ * This module is storage-agnostic so the PostgreSQL backend (db.js) and the
+ * test/dev file backend (store.js) can never drift in how an incoming work is
+ * sanitized or LWW-merged. Mirrors creativeDirector/projectsLogic.js.
+ */
+
+import { compareNewerWins } from '../../lib/lwwTimestamp.js';
+import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
+import { WORK_ID_RE, DRAFT_ID_RE } from './_shared.js';
+
+const isStr = (v) => typeof v === 'string';
+
+// The peer-sync record kind + the asset kind its draft bodies ride. Exported so
+// peerSync.js / sync.js reference one source of truth instead of bare strings.
+export const WRITERS_ROOM_WORK_KIND = 'writersRoomWork';
+export const WRITERS_ROOM_DRAFT_ASSET_KIND = 'writers-room-draft';
+
+/**
+ * Normalize a raw work manifest into the canonical stored shape for a sync
+ * round-trip. Returns null for a non-object or a record without a usable id
+ * (the "drop on the floor" contract every sanitizer shares, so a malformed peer
+ * payload can't land). The work body (title/kind/status/drafts/links/liveMode)
+ * 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. Mirrors `sanitizeProjectForSync`.
+ */
+export function sanitizeWorkForSync(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 work 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 manifest is LWW-overwritten (no
+ * field-union), so it is hashed in full by `contentHashForRecord`.
+ */
+export function mergeWorkRecord(local, remoteRaw) {
+ const remote = sanitizeWorkForSync(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 };
+}
+
+/**
+ * The draft-version → file-body asset references a work carries: one entry per
+ * draft version whose id + work id are valid path segments. Pure (no disk I/O) —
+ * sync.js hashes the on-disk `.md` per entry to build the wire manifest, and the
+ * receiver resolves each `{ workId, draftId }` to `works/<workId>/drafts/<draftId>.md`.
+ * Skips drafts with a malformed id so a hand-edited/corrupt manifest can't smuggle
+ * a path-traversal filename into the asset pull.
+ */
+export function draftAssetEntries(work) {
+ const drafts = Array.isArray(work?.drafts) ? work.drafts : [];
+ const workId = work?.id;
+ if (!isStr(workId) || !WORK_ID_RE.test(workId)) return [];
+ const out = [];
+ for (const d of drafts) {
+ const draftId = d?.id;
+ if (!isStr(draftId) || !DRAFT_ID_RE.test(draftId)) continue;
+ out.push({ workId, draftId });
+ }
+ return out;
+}
diff --git a/server/services/writersRoom/syncLogic.test.js b/server/services/writersRoom/syncLogic.test.js
new file mode 100644
index 0000000000..00f918cd07
--- /dev/null
+++ b/server/services/writersRoom/syncLogic.test.js
@@ -0,0 +1,121 @@
+/**
+ * Writers Room sync logic (#1565) — pure transforms, no DB / no disk.
+ *
+ * Mirrors creativeDirector/projectsLogic's sanitize + LWW-merge coverage: the
+ * "drop on the floor" contract for malformed payloads, the soft-delete trio
+ * normalization, last-writer-wins on `updatedAt` (tombstone-aware), and the
+ * draft-version → file-body asset entry extraction (with path-segment validation).
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ sanitizeWorkForSync, mergeWorkRecord, draftAssetEntries,
+ WRITERS_ROOM_WORK_KIND, WRITERS_ROOM_DRAFT_ASSET_KIND,
+} from './syncLogic.js';
+
+const WORK = 'wr-work-11111111-1111-1111-1111-111111111111';
+const DRAFT = 'wr-draft-22222222-2222-2222-2222-222222222222';
+
+const work = (extra = {}) => ({
+ id: WORK,
+ title: 'A Tale',
+ kind: 'short-story',
+ status: 'drafting',
+ activeDraftVersionId: DRAFT,
+ drafts: [{ id: DRAFT, label: 'Draft 1', contentFile: `drafts/${DRAFT}.md`, contentHash: 'h', wordCount: 3, segmentIndex: [], createdAt: '2026-01-01T00:00:00.000Z' }],
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-02T00:00:00.000Z',
+ ...extra,
+});
+
+describe('sanitizeWorkForSync', () => {
+ it('drops non-objects and records without a usable id', () => {
+ expect(sanitizeWorkForSync(null)).toBeNull();
+ expect(sanitizeWorkForSync([])).toBeNull();
+ expect(sanitizeWorkForSync({ title: 'no id' })).toBeNull();
+ expect(sanitizeWorkForSync({ id: '' })).toBeNull();
+ });
+
+ it('normalizes the soft-delete trio and preserves the body verbatim', () => {
+ const s = sanitizeWorkForSync(work());
+ expect(s.deleted).toBe(false);
+ expect(s.deletedAt).toBeNull();
+ expect(s.title).toBe('A Tale');
+ expect(s.drafts).toHaveLength(1);
+ });
+
+ it('clears a stray deletedAt when deleted is false, keeps it when true', () => {
+ expect(sanitizeWorkForSync(work({ deleted: false, deletedAt: '2026-02-01T00:00:00.000Z' })).deletedAt).toBeNull();
+ const tomb = sanitizeWorkForSync(work({ deleted: true, deletedAt: '2026-02-01T00:00:00.000Z' }));
+ expect(tomb.deleted).toBe(true);
+ expect(tomb.deletedAt).toBe('2026-02-01T00:00:00.000Z');
+ });
+
+ it('defaults missing updatedAt to createdAt', () => {
+ const s = sanitizeWorkForSync({ id: WORK, createdAt: '2026-03-01T00:00:00.000Z' });
+ expect(s.updatedAt).toBe('2026-03-01T00:00:00.000Z');
+ });
+});
+
+describe('mergeWorkRecord', () => {
+ it('inserts a remote with no local counterpart', () => {
+ const { next, inserted, remoteWins, changed } = mergeWorkRecord(null, work());
+ expect(inserted).toBe(true);
+ expect(remoteWins).toBe(true);
+ expect(changed).toBe(true);
+ expect(next.id).toBe(WORK);
+ });
+
+ it('drops a malformed remote (next: null)', () => {
+ expect(mergeWorkRecord(work(), { title: 'no id' }).next).toBeNull();
+ });
+
+ it('newer remote updatedAt wins; older loses', () => {
+ const local = sanitizeWorkForSync(work({ updatedAt: '2026-01-02T00:00:00.000Z', title: 'Local' }));
+ const newer = mergeWorkRecord(local, work({ updatedAt: '2026-01-03T00:00:00.000Z', title: 'Remote' }));
+ expect(newer.remoteWins).toBe(true);
+ expect(newer.next.title).toBe('Remote');
+ const older = mergeWorkRecord(local, work({ updatedAt: '2026-01-01T00:00:00.000Z', title: 'Remote' }));
+ expect(older.remoteWins).toBe(false);
+ expect(older.next.title).toBe('Local');
+ });
+
+ it('a newer tombstone overwrites a live local', () => {
+ const local = sanitizeWorkForSync(work({ updatedAt: '2026-01-02T00:00:00.000Z' }));
+ const { next, remoteWins } = mergeWorkRecord(local, work({ updatedAt: '2026-01-05T00:00:00.000Z', deleted: true, deletedAt: '2026-01-05T00:00:00.000Z' }));
+ expect(remoteWins).toBe(true);
+ expect(next.deleted).toBe(true);
+ });
+
+ it('a byte-identical remote win is not "changed"', () => {
+ const local = sanitizeWorkForSync(work());
+ const { remoteWins, changed } = mergeWorkRecord(local, work());
+ // equal updatedAt → tie → local wins (remoteWins false), and no change
+ expect(remoteWins).toBe(false);
+ expect(changed).toBe(false);
+ });
+});
+
+describe('draftAssetEntries', () => {
+ it('returns one entry per valid draft with the work id', () => {
+ const entries = draftAssetEntries(work());
+ expect(entries).toEqual([{ workId: WORK, draftId: DRAFT }]);
+ });
+
+ it('skips drafts with a malformed id (path-traversal guard)', () => {
+ const entries = draftAssetEntries(work({ drafts: [{ id: '../etc/passwd' }, { id: DRAFT }] }));
+ expect(entries).toEqual([{ workId: WORK, draftId: DRAFT }]);
+ });
+
+ it('returns [] for a work with a malformed id or no drafts', () => {
+ expect(draftAssetEntries({ id: 'bogus', drafts: [{ id: DRAFT }] })).toEqual([]);
+ expect(draftAssetEntries(work({ drafts: undefined }))).toEqual([]);
+ });
+});
+
+describe('exported kind constants', () => {
+ it('match the federation record + asset kinds', () => {
+ expect(WRITERS_ROOM_WORK_KIND).toBe('writersRoomWork');
+ expect(WRITERS_ROOM_DRAFT_ASSET_KIND).toBe('writers-room-draft');
+ });
+});