Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Federate card decks to peers as record kind `deck`
Adam Eivyf9c27fa495fb
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex 09902b1942..b2928132b2 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, Sparkles, Film, Images, Library, BookOpen, FilePen, Music, Music2, Disc3, Clapperboard, Palette, BookText, FolderTree, Video, Waypoints, Gauge+ Lock, Globe, Sparkles, Film, Images, Library, BookOpen, FilePen, Music, Music2, Disc3, Clapperboard, Palette, BookText, FolderTree, Video, Waypoints, Gauge, Spade} from 'lucide-react';import { useSearchParams } from 'react-router';import Drawer from '../components/Drawer';@@ -576,13 +576,14 @@ const SYNC_CATEGORY_META = [{ key: 'musicVideoProjects', label: 'Music Video', icon: Video, description: 'Music Video projects: director board + beat-aligned scenes (PostgreSQL)' },{ key: 'creativeCommissions', label: 'Commissions', icon: Target, description: 'Creative Commission briefs (name + intent + genre + generation settings) — the schedule + run history stay machine-local (PostgreSQL)' },{ key: 'commissionFeedback', label: 'Commission Feedback', icon: Target, description: 'Creative Commission taste reactions that steer the next run — the schedule stays machine-local (PostgreSQL)' },+ { key: 'decks', label: 'Decks', icon: Spade, description: 'Card decks: style guide, samples, per-card prompts + rendered card art — the image/LLM pins stay machine-local (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, and creative// record kinds handled by the per-record peer-push pipeline.-const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors', 'artists', 'albums', 'tracks', 'creativeDirectorProjects', 'moodBoards', 'fableLoom', 'writersRoomWorks', 'writersRoomFolders', 'writersRoomExercises', 'musicVideoProjects', 'commissionFeedback', 'creativeCommissions']);+const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors', 'artists', 'albums', 'tracks', 'creativeDirectorProjects', 'moodBoards', 'fableLoom', 'writersRoomWorks', 'writersRoomFolders', 'writersRoomExercises', 'musicVideoProjects', 'commissionFeedback', 'creativeCommissions', 'decks']);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/docs/API.md b/docs/API.mdindex 713fa02493..e9fa8b70c7 100644--- a/docs/API.md+++ b/docs/API.md@@ -617,7 +617,7 @@ return an `{ items, total }` envelope.### Decks-Playing-card / tarot deck designer (Create → Decks). Decks are db-primary and machine-local; card images live in the shared gallery and are referenced by filename.+Playing-card / tarot deck designer (Create → Decks). Decks are db-primary and federate to peers as record kind `deck` under the **Decks** sync category (off by default, per peer) — the deck ships with its full card roster, while the image/LLM pins and each card's in-flight render job stay machine-local. Card images live in the shared gallery, are referenced by filename, and ride the push asset manifest.| Method | Endpoint | Description ||--------|----------|-------------|@@ -625,7 +625,7 @@ Playing-card / tarot deck designer (Create → Decks). Decks are db-primary and| POST | `/decks` | Create a deck (`name`, `kind` = `playing` \| `tarot`, optional `universeId`, `seedStyleFromUniverse`); mints the full card roster || GET | `/decks/:id` | Deck + cards + completion || PATCH | `/decks/:id` | Style guide (`styleNotes`, `influences`, `layoutPrompt`), universe link, render pin (`imageMode`/`imageModelId`), LLM pins |-| DELETE | `/decks/:id` | Delete the deck and its cards (gallery images are kept) |+| DELETE | `/decks/:id` | Tombstone the deck so the deletion reaches subscribed peers; it disappears from reads immediately and the rows are hard-removed by the tombstone GC sweep (gallery images are kept) || PATCH | `/decks/:id/cards/:cardId` | Edit a card (`prompt`, `negativePrompt`, `primaryImageRef`, `imageRefs`, `canonRef`) || POST | `/decks/:id/analyze-sample` | Stateless vision analysis of a gallery image → proposed style guide + diff || POST | `/decks/:id/samples` | Persist a reviewed sample; `adopt` applies the proposal in the same write |diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.jsindex c7e49ed736..e9018b420a 100644--- a/server/lib/conflictJournal.js+++ b/server/lib/conflictJournal.js@@ -542,6 +542,12 @@ export const RESTORABLE_FIELDS = Object.freeze({// machine-local schedule/runs/assignment/enabled are never in a snapshot// (stripped from the wire) so they're excluded.creativeCommission: ['name', 'targetAbility', 'brief', 'generation', 'feedbackWindow'],+ // A deck (#decks) restores its authored style guide + identity. `kind` is+ // structural (the roster is minted from it and a CHECK constrains the+ // column), `cards[]` is the roster itself (restored with the deck row by+ // `restoreDeck`, not offered as an individually-overlayable field), and the+ // install-capability pins never reach a snapshot (stripped from the wire).+ deck: ['name', 'description', 'styleNotes', 'influences', 'layoutPrompt', 'samples', 'cardSize', 'universeId'],// FableLoom restores the authored story graph, playback configuration, and// story-level render preferences.// Universe/series ids are structural links and stay on the live record.diff --git a/server/lib/db/schema/decks.js b/server/lib/db/schema/decks.jsindex 909c6306fc..ae82deb0e6 100644--- a/server/lib/db/schema/decks.js+++ b/server/lib/db/schema/decks.js@@ -3,7 +3,14 @@// is its own row so a completed render attaches to ONE card without a// read-modify-write of the whole deck. Rendered bytes live in the shared// gallery (`data/images/`) and are referenced by filename from the card row.-// Machine-local: decks never federate.+//+// Decks FEDERATE (record kind `deck`, sync category `decks`) — the deck and its+// full card roster ride one push as a whole-record LWW unit, so a deck designed+// on one machine reaches the peers subscribed to it. The install-capability+// pins (`imageMode` / `imageModelId` / `promptLlm`) and each card's in-flight+// `render` job state stay machine-local (stripped by syncWire's `deck` case).+// Because a delete must propagate, the deck row carries the soft-delete+// tombstone pair the LWW merge needs — a hard delete never reaches a peer.export const decksDdl = [`CREATE TABLE IF NOT EXISTS decks (id UUID PRIMARY KEY,@@ -12,8 +19,13 @@ export const decksDdl = [universe_id TEXT,definition JSONB NOT NULL DEFAULT '{}'::jsonb,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ deleted BOOLEAN NOT NULL DEFAULT FALSE,+ deleted_at TIMESTAMPTZ)`,+ // Idempotent upgrade for installs whose decks table predates federation.+ `ALTER TABLE decks ADD COLUMN IF NOT EXISTS deleted BOOLEAN NOT NULL DEFAULT FALSE`,+ `ALTER TABLE decks ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,`CREATE TABLE IF NOT EXISTS deck_cards (id UUID PRIMARY KEY,deck_id UUID NOT NULL REFERENCES decks (id) ON DELETE CASCADE,@@ -24,4 +36,5 @@ export const decksDdl = [UNIQUE (deck_id, key))`,`CREATE INDEX IF NOT EXISTS idx_deck_cards_deck ON deck_cards (deck_id, position)`,+ `CREATE INDEX IF NOT EXISTS idx_decks_deleted ON decks (deleted, updated_at DESC)`,];diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex 9fb64f8dfa..4d2f8a5f16 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -489,7 +489,19 @@ describe('deferred imports stay deferred (#6156)', () => {// the toolkit's own catalog module precisely to avoid dragging that subtree in,// and no production module gained an edge — so raise by exactly that delta and// keep the headroom.-const MAX_STATIC_INSTANTIATIONS = 103925;+// Federating card decks (record kind `deck`) measures +30: `services/decks.js`+// becomes a static edge of the four peer-sync modules a new federated kind must+// register in (recordKinds.js, peerSync.js, tombstoneGc.js,+// conflictJournalResolver.js), dragging the one subtree it owns that those+// modules did not already reach — `lib/deckTemplates.js` and the deck+// validation/prompt leaves beside it. Everything else it imports (db.js,+// conflictJournal.js, recordEvents.js, renderTargets.js) those four already+// had. There is no narrowing available: the descriptor table needs the getter+// and merger at module scope, by construction. The federation suite that+// covers it (services/decksSync.db.test.js) measures a further +40, all of it+// that one new test file's own closure — decks.js plus the syncWire/db-gate+// leaves it asserts against, no production edge. Raise by exactly those deltas.+const MAX_STATIC_INSTANTIATIONS = 103995;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.jsindex 3cc75a7330..77dd7b40a7 100644--- a/server/lib/peerSyncValidation.js+++ b/server/lib/peerSyncValidation.js@@ -16,7 +16,7 @@ import { TASK_STATUS_VALUES, TASK_PRIORITY_VALUES } from './taskParser.js';// subscriptions target another PortOS instance over Tailnet.export const peerSubscribeSchema = z.object({peerId: z.string().trim().min(1).max(120),- recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'fableLoom', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']),+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'fableLoom', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission', 'deck']),recordId: z.string().trim().min(1).max(120),}).strict();@@ -271,6 +271,14 @@ const musicVideoProjectPushSchema = z.object({}).strict();// Creative Commission feedback (#2686) — a body-less reaction record, no assets;// the sender always ships `assetManifest: []` (base still requires the field).+// Card decks (#decks) push the deck record with its full card roster bundled+// inside `record.cards[]` — cards are not independently subscribable, so there+// is no extra envelope key. Rendered card art + analyzed style samples ride the+// base `assetManifest` as gallery images.+const deckPushSchema = z.object({+ kind: z.literal('deck'),+ ...peerSyncPushBase,+}).strict();const commissionFeedbackPushSchema = z.object({kind: z.literal('commissionFeedback'),...peerSyncPushBase,@@ -297,13 +305,14 @@ export const peerSyncPushSchema = z.discriminatedUnion('kind', [musicVideoProjectPushSchema,commissionFeedbackPushSchema,creativeCommissionPushSchema,+ deckPushSchema,]);// Manual sync action schemas — used by POST /sync-record, /sync-now, /pull-metadata.export const peerSyncRecordSchema = z.object({peerId: z.string().trim().min(1).max(120),- recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'fableLoom', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']),+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'fableLoom', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission', 'deck']),recordId: z.string().trim().min(1).max(200),}).strict();diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 9650d6dcfc..a38ae6c73c 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -228,6 +228,17 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// gate against. The FIRST incompatible outline-doc shape change (reverseOutline.js// SCHEMA_VERSION 1→2) MUST introduce a gate then, same as the review above.mediaCollections: 1,+ // v1 = card decks (PostgreSQL `decks` + `deck_cards`) federated via the+ // per-record peer-sync push pipeline (record kind `deck`, sync category+ // `decks`). A brand-NEW synced record type, so it gets its own per-category+ // gate: a v1 sender pushing to a ≤v0 (pre-feature) receiver is sender-ahead+ // on `decks` and gets a 409 — only the decks category pauses, every other+ // category keeps flowing. A v1 receiver still accepts a ≤v0 sender+ // (sender-behind): pre-feature peers never push a `deck` record at all. The+ // FIRST incompatible deck/card-shape change MUST bump this to 2 (where a v1+ // peer would round-trip the new shape through an unaware sanitizer and LWW+ // the strip back onto the newer peer).+ decks: 1,// v1 = author personas (PostgreSQL `authors` table) federated via the// per-record peer-sync push pipeline (record kind `author`, sync category// `authors`). A brand-NEW synced record type like `storyBuilder` below, so it@@ -729,6 +740,7 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({musicVideoProject: Object.freeze(['musicVideoProjects']),commissionFeedback: Object.freeze(['commissionFeedback']),creativeCommission: Object.freeze(['creativeCommissions']),+ deck: Object.freeze(['decks']),});/**diff --git a/server/lib/syncWire.js b/server/lib/syncWire.jsindex d6b93658f4..97b059ea56 100644--- a/server/lib/syncWire.js+++ b/server/lib/syncWire.js@@ -350,6 +350,29 @@ export function sanitizeRecordForWire(kind, record) {const { deleted: _d, deletedAt: _da, ...rest } = record;return { ...rest, ...sanitizeSoftDeleteFields(record) };}+ case 'deck': {+ // A deck (#decks) federates as ONE whole-record LWW unit: the deck row+ // plus its full card roster. Three classes of field stay wire-local:+ // - `imageMode` / `imageModelId` / `promptLlm` are install-capability+ // pins (the peer may not have that provider configured) — same+ // contract as musicVideoProject's render pins.+ // - `completion` is derived from the cards, so shipping it would be a+ // second source of truth AND a hash that moves with no user edit.+ // - each card's `id` (a local row id) and `render` (an in-flight media+ // jobId, meaningless on another machine). `imageRefs` /+ // `primaryImageRef` DO travel: the push asset manifest carries their+ // gallery bytes, so the receiver can show the rendered cards.+ // Cards are addressed by their stable roster `key` and sorted by it so+ // the wire form (and the conflict-journal content hash) is byte-stable+ // regardless of local row ordering.+ const { deleted: _d, deletedAt: _da, imageMode: _im, imageModelId: _imi,+ promptLlm: _pl, completion: _c, cards, ...rest } = record;+ const wireCards = (Array.isArray(cards) ? cards : [])+ .filter((c) => isNonBlankStr(c?.key))+ .map(({ id: _cid, deckId: _did, render: _r, ...card }) => card)+ .sort((a, b) => a.key.localeCompare(b.key));+ return { ...rest, cards: wireCards, ...sanitizeSoftDeleteFields(record) };+ }case 'musicVideoProject': {// Music Video projects are whole-record LWW, but their image render pin// and video backend are install-capability choices: a peer may not havediff --git a/server/lib/syncWire.test.js b/server/lib/syncWire.test.jsindex 2b68dfece7..bc6727572b 100644--- a/server/lib/syncWire.test.js+++ b/server/lib/syncWire.test.js@@ -74,6 +74,73 @@ describe('syncWire', () => {expect(sanitizeRecordForWire('universe', 'string')).toBeNull();});+ describe('deck (#decks)', () => {+ const deck = () => ({+ id: 'deck-1',+ name: 'Example Deck',+ kind: 'tarot',+ universeId: 'u-1',+ styleNotes: 'woodcut',+ // Install-capability pins + derived completion — none of these travel.+ imageMode: 'grok',+ imageModelId: 'grok-image-1',+ promptLlm: { provider: 'claude', model: 'claude-opus-5' },+ completion: { rendered: 3, total: 78 },+ cards: [+ { id: 'row-b', deckId: 'deck-1', key: 'b', prompt: 'two', imageRefs: ['b.png'], primaryImageRef: 'b.png', render: { jobId: 'job-9', status: 'queued' } },+ { id: 'row-a', deckId: 'deck-1', key: 'a', prompt: 'one', imageRefs: [] },+ ],+ deleted: false,+ deletedAt: null,+ });++ it('strips the install-capability pins and derived completion', () => {+ const wire = sanitizeRecordForWire('deck', deck());+ expect(wire).not.toHaveProperty('imageMode');+ expect(wire).not.toHaveProperty('imageModelId');+ expect(wire).not.toHaveProperty('promptLlm');+ expect(wire).not.toHaveProperty('completion');+ expect(wire.name).toBe('Example Deck');+ expect(wire.universeId).toBe('u-1');+ });++ it('ships cards keyed by roster key, sorted, without local row ids or in-flight render state', () => {+ const wire = sanitizeRecordForWire('deck', deck());+ expect(wire.cards.map((c) => c.key)).toEqual(['a', 'b']);+ for (const card of wire.cards) {+ expect(card).not.toHaveProperty('id');+ expect(card).not.toHaveProperty('deckId');+ expect(card).not.toHaveProperty('render');+ }+ // Rendered gallery refs DO travel — the push asset manifest carries+ // their bytes, so the receiver can show the finished cards.+ expect(wire.cards[1].imageRefs).toEqual(['b.png']);+ expect(wire.cards[1].primaryImageRef).toBe('b.png');+ });++ it('is byte-stable against local card ordering and render churn (the content hash must not move on a no-op)', () => {+ const a = deck();+ const b = deck();+ b.cards.reverse();+ b.cards[0].render = { jobId: 'job-different', status: 'failed' };+ b.imageMode = 'local';+ expect(JSON.stringify(sanitizeRecordForWire('deck', a)))+ .toBe(JSON.stringify(sanitizeRecordForWire('deck', b)));+ });++ it('drops cards with no roster key (they cannot be addressed on the receiver)', () => {+ const record = deck();+ record.cards.push({ id: 'row-c', key: ' ', prompt: 'orphan' });+ expect(sanitizeRecordForWire('deck', record).cards).toHaveLength(2);+ });++ it('normalizes the soft-delete pair on a tombstone', () => {+ const wire = sanitizeRecordForWire('deck', { ...deck(), deleted: true, deletedAt: '2026-05-01T00:00:00Z' });+ expect(wire.deleted).toBe(true);+ expect(wire.deletedAt).toBe('2026-05-01T00:00:00Z');+ });+ });+it('returns null for unknown kinds', () => {expect(sanitizeRecordForWire('mystery', { id: 'x' })).toBeNull();});diff --git a/server/routes/decks.db.test.js b/server/routes/decks.db.test.jsindex 1e629f27f2..7502b1b9e3 100644--- a/server/routes/decks.db.test.js+++ b/server/routes/decks.db.test.js@@ -134,10 +134,17 @@ describe.skipIf(!ready)('decks over HTTP and PostgreSQL', () => {expect((await post(`/${deck.id}/samples`, { sample })).body.samples).toHaveLength(1);expect((await del(`/${deck.id}/samples/deck-sample-1`)).body.samples).toHaveLength(0);+ // A delete tombstones the deck so the deletion can reach subscribed peers+ // (#decks federation). It reads as gone, and a second delete 404s — but the+ // card rows survive until the tombstone GC hard-removes the deck, which is+ // what lets a conflict-journal restore bring the roster back. The cascade+ // itself is covered by `services/decksSync.db.test.js`.expect((await del(`/${deck.id}`)).status).toBe(200);expect((await get(`/${deck.id}`)).status).toBe(404);- const { rows } = await query('SELECT COUNT(*)::int AS n FROM deck_cards WHERE deck_id = $1', [deck.id]);- expect(rows[0].n).toBe(0);+ expect((await get('')).body.some((d) => d.id === deck.id)).toBe(false);+ const { rows } = await query('SELECT deleted, deleted_at FROM decks WHERE id = $1', [deck.id]);+ expect(rows[0]).toMatchObject({ deleted: true });+ expect(rows[0].deleted_at).toBeTruthy();expect((await del(`/${deck.id}`)).status).toBe(404);});});diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 8a4df21742..cda5a33de6 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -2080,7 +2080,9 @@ CREATE TABLE IF NOT EXISTS decks (universe_id TEXT,definition JSONB NOT NULL DEFAULT '{}'::jsonb,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ deleted BOOLEAN NOT NULL DEFAULT FALSE,+ deleted_at TIMESTAMPTZ);CREATE TABLE IF NOT EXISTS deck_cards (id UUID PRIMARY KEY,@@ -2092,3 +2094,4 @@ CREATE TABLE IF NOT EXISTS deck_cards (UNIQUE (deck_id, key));CREATE INDEX IF NOT EXISTS idx_deck_cards_deck ON deck_cards (deck_id, position);+CREATE INDEX IF NOT EXISTS idx_decks_deleted ON decks (deleted, updated_at DESC);diff --git a/server/services/conflictJournalResolver.js b/server/services/conflictJournalResolver.jsindex edcee0c587..09565d33b6 100644--- a/server/services/conflictJournalResolver.js+++ b/server/services/conflictJournalResolver.js@@ -41,6 +41,7 @@ import { restoreBoard } from './moodBoard/index.js';import { updateWork, restoreFolder, restoreExercise } from './writersRoom/local.js';import { restoreCommissionFeedback } from './creativeCommissions/feedbackStore.js';import { restoreCommission } from './creativeCommissions/store.js';+import { restoreDeck } from './decks.js';import { restoreLoom } from './fableLoom/index.js';export const ERR_NOT_FOUND = 'CONFLICT_JOURNAL_NOT_FOUND';@@ -182,6 +183,12 @@ async function applyToRecord(kind, recordId, patch, { replace = false } = {}) {// runs/assignment are kept as-is. Returns null for a missing record (#2686).const restored = await restoreCommission(recordId, patch).catch(translateGone);if (!restored) throw makeErr(`The ${kind} this conflict targets no longer exists — discard the entry.`, ERR_TARGET_GONE);+ } else if (kind === 'deck') {+ // restoreDeck merges the snapshot's style-guide/identity fields, un-tombstones,+ // and bumps updatedAt so the restore wins the next LWW and re-pushes. Returns+ // null for a deck already hard-pruned by the tombstone sweep (→ ERR_TARGET_GONE).+ const restored = await restoreDeck(recordId, patch).catch(translateGone);+ if (!restored) throw makeErr(`The ${kind} this conflict targets no longer exists — discard the entry.`, ERR_TARGET_GONE);} else if (kind === 'fableLoom') {// Restore the authored story graph and playback settings through the normal// loom mutation path so the edit is sanitized, timestamped, and re-pushed.diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex 4a6c4b5373..5c8453908d 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -1156,6 +1156,11 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {// file-snapshot category). Gated at applyIncomingPush via// compareSchemaVersions / RECORD_KIND_SCHEMA_CATEGORIES.creativeCommission.'creativeCommissions',+ // Card decks (#decks) → per-record peer-push only (no 60s file-snapshot+ // category; the deck ships its card roster inside its own record). Gated+ // at applyIncomingPush via compareSchemaVersions /+ // RECORD_KIND_SCHEMA_CATEGORIES.deck.+ 'decks',// FableLoom stories → per-record peer-push only (no 60s snapshot// category). Gated at applyIncomingPush via compareSchemaVersions /// RECORD_KIND_SCHEMA_CATEGORIES.fableLoom.diff --git a/server/services/decks.js b/server/services/decks.jsindex 40ca0cfe2d..8497efd7dd 100644--- a/server/services/decks.js+++ b/server/services/decks.js@@ -9,24 +9,39 @@* the shared gallery (`data/images/`) and are referenced by filename, the same* way universe canon entries carry `imageRefs`.*- * Machine-local: decks never federate (root AGENTS.md privacy rule) — a deck- * that references a universe carries only that universe's id.+ * Federated (record kind `deck`, sync category `decks`): a deck rides one push+ * carrying its own row plus the FULL card roster, merged whole-record LWW on+ * the deck's `updatedAt`. The install-capability pins (`imageMode` /+ * `imageModelId` / `promptLlm`) and each card's in-flight `render` job state+ * are machine-local and stripped from the wire (`syncWire.js`'s `deck` case) —+ * a peer may not have the pinned provider, and a jobId means nothing there.+ * Rendered gallery bytes flow through the push asset manifest, so a received+ * card's `imageRefs` resolve locally. A deck that references a universe carries+ * only that universe's id — no canon text crosses with it.*/import { randomUUID } from 'node:crypto';import { query, withTransaction, ensureSchema } from '../lib/db.js';import { ServerError } from '../lib/errorHandler.js';-import { trimTo } from '../lib/textUtils.js';+import { trimTo, isNonBlankStr } from '../lib/textUtils.js';import { sanitizeLlmRoutePin } from '../lib/llmRoutePin.js';import { universeVisualStyleTokens } from '../lib/universeVisualStyle.js';import { DECK_CARD_SIZE, DECK_CARD_SIZE_BY_KIND, DEFAULT_LAYOUT_PROMPT, deckCardRoster, deckCompletion } from '../lib/deckTemplates.js';import { DECK_CARD_IMAGE_REFS_MAX, DECK_SAMPLES_MAX } from '../lib/deckValidation.js';import { recordRenderPin } from '../lib/renderTargets.js';+import { createRecordWriteQueue } from '../lib/fileWriteQueue.js';+import {+ contentHashForRecord, setSyncBaseHash, deleteSyncBaseHash, flushBaseHashes,+ withBaseHashFlushBatch, maybeJournalBeforeOverwrite,+} from '../lib/conflictJournal.js';+import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from './sharing/recordEvents.js';const notFound = (what = 'Deck') => new ServerError(`${what} not found`, {status: 404, code: what === 'Deck' ? 'DECK_NOT_FOUND' : 'DECK_CARD_NOT_FOUND',});+const isoOrNull = (v) => (v instanceof Date ? v.toISOString() : (v || null));+const filenames = (values) => (Array.isArray(values) ? values : []).map((v) => trimTo(v)).filter(Boolean);// ── Projections ──────────────────────────────────────────────────────────────@@ -48,8 +63,13 @@ const projectDeck = (row) => {imageModelId: pin.modelId,cardSize: d.cardSize?.width && d.cardSize?.height ? d.cardSize : { ...(DECK_CARD_SIZE_BY_KIND[row.kind] || DECK_CARD_SIZE) },promptLlm: sanitizeLlmRoutePin(d.promptLlm),- createdAt: row.created_at,- updatedAt: row.updated_at,+ // ISO strings, not the driver's Date objects: these are the LWW clock the+ // sync merge compares and the wire form hashes, and a Date compares as+ // "not a string" (so every remote would win). JSON output is unchanged.+ createdAt: isoOrNull(row.created_at),+ updatedAt: isoOrNull(row.updated_at),+ deleted: row.deleted === true,+ deletedAt: row.deleted === true ? isoOrNull(row.deleted_at) : null,};};@@ -71,7 +91,7 @@ const projectCard = (row) => {imageRefs: filenames(d.imageRefs),primaryImageRef: trimTo(d.primaryImageRef) || null,render: d.render && typeof d.render === 'object' ? d.render : null,- updatedAt: row.updated_at,+ updatedAt: isoOrNull(row.updated_at),};};@@ -82,9 +102,11 @@ const loadCards = async (client, deckId) => {return rows.map(projectCard);};-export async function listDecks() {+export async function listDecks({ includeDeleted = false } = {}) {await ensureSchema();- const { rows } = await query('SELECT * FROM decks ORDER BY updated_at DESC, id');+ const { rows } = await query(+ `SELECT * FROM decks ${includeDeleted ? '' : 'WHERE deleted IS NOT TRUE'} ORDER BY updated_at DESC, id`,+ );// Completion reads three card fields; project just those instead of every// card's prompt/history so the index page doesn't pull the whole deck.const { rows: cardRows } = await query(`SELECT deck_id, jsonb_build_object(@@ -97,10 +119,10 @@ export async function listDecks() {}));}-export async function getDeck(id) {+export async function getDeck(id, { includeDeleted = false } = {}) {await ensureSchema();const { rows } = await query('SELECT * FROM decks WHERE id = $1', [id]);- if (!rows[0]) throw notFound();+ if (!rows[0] || (!includeDeleted && rows[0].deleted === true)) throw notFound();const cards = await loadCards({ query }, id);return { ...projectDeck(rows[0]), cards, completion: deckCompletion(cards) };}@@ -116,7 +138,7 @@ async function patchDeck(id, mutate) {await ensureSchema();await withTransaction(async (client) => {const { rows } = await client.query('SELECT * FROM decks WHERE id = $1', [id]);- if (!rows[0]) throw notFound();+ if (!rows[0] || rows[0].deleted === true) throw notFound();const d = { ...(rows[0].definition || {}) };const columns = (await mutate(d, rows[0])) || {};await client.query(@@ -124,6 +146,7 @@ async function patchDeck(id, mutate) {[id, columns.name ?? rows[0].name, columns.universeId === undefined ? rows[0].universe_id : columns.universeId, d],);});+ emitRecordUpdated(DECK_KIND, id);return getDeck(id);}@@ -136,6 +159,11 @@ async function patchDeck(id, mutate) {async function patchCard(deckId, cardId, mutate, { missingOk = false, touch = true } = {}) {await ensureSchema();return withTransaction(async (client) => {+ const { rows: deckRows } = await client.query('SELECT deleted FROM decks WHERE id = $1', [deckId]);+ if (!deckRows[0] || deckRows[0].deleted === true) {+ if (missingOk) return null;+ throw notFound();+ }const { rows } = await client.query('SELECT * FROM deck_cards WHERE deck_id = $1 AND id = $2', [deckId, cardId]);if (!rows[0]) {if (missingOk) return null;@@ -204,9 +232,31 @@ export async function createDeck({ name, kind, description = '', universeId = nu);});console.log(`🃏 deck created "${trimTo(name)}" kind=${kind} cards=${roster.length}${universeId ? ` universe=${universeId}` : ''}`);+ // Announce to the per-record push pipeline AND auto-subscribe every+ // decks-enabled peer, so a brand-new deck (and its later tombstone)+ // propagates without waiting for a manual subscribe. Mirrors the music-video+ // / creative-director `announceNewProject` shape.+ emitRecordUpdated(DECK_KIND, id);+ autoSubscribeRecordToAllPeers(DECK_KIND, id).catch(() => {});return getDeck(id);}+/**+ * Apply the authored style-guide fields a patch carries onto a deck definition+ * copy. Absent keys preserve; a present key applies. Shared by `updateDeck` and+ * the conflict-journal `restoreDeck` (whose restorable set is exactly these) so+ * a restore can't drift from a normal edit. The install-capability pins are NOT+ * here — a restore never carries them (they're stripped from the wire).+ */+function applyDefinitionPatch(d, patch) {+ if (patch.description !== undefined) d.description = trimTo(patch.description);+ if (patch.styleNotes !== undefined) d.styleNotes = trimTo(patch.styleNotes);+ if (patch.influences !== undefined) d.influences = universeVisualStyleTokens({ influences: patch.influences });+ if (patch.layoutPrompt !== undefined) d.layoutPrompt = trimTo(patch.layoutPrompt);+ if (patch.samples !== undefined) d.samples = Array.isArray(patch.samples) ? patch.samples.slice(0, DECK_SAMPLES_MAX) : [];+ if (patch.cardSize !== undefined) d.cardSize = { width: patch.cardSize.width, height: patch.cardSize.height };+}+/*** Patch deck-level fields. Absent keys preserve; a present key applies (so* `universeId: null` unlinks and `imageMode: null` clears the pin — the@@ -214,13 +264,9 @@ export async function createDeck({ name, kind, description = '', universeId = nu*/export function updateDeck(id, patch = {}) {return patchDeck(id, (d) => {- if (patch.description !== undefined) d.description = trimTo(patch.description);- if (patch.styleNotes !== undefined) d.styleNotes = trimTo(patch.styleNotes);- if (patch.influences !== undefined) d.influences = universeVisualStyleTokens({ influences: patch.influences });- if (patch.layoutPrompt !== undefined) d.layoutPrompt = trimTo(patch.layoutPrompt);+ applyDefinitionPatch(d, patch);if (patch.imageMode !== undefined) d.imageMode = patch.imageMode || null;if (patch.imageModelId !== undefined) d.imageModelId = patch.imageModelId || null;- if (patch.cardSize !== undefined) d.cardSize = { width: patch.cardSize.width, height: patch.cardSize.height };if (patch.promptLlm !== undefined) d.promptLlm = sanitizeLlmRoutePin(patch.promptLlm);return {...(patch.name !== undefined ? { name: trimTo(patch.name) } : {}),@@ -229,19 +275,30 @@ export function updateDeck(id, patch = {}) {});}+/**+ * Soft-delete a deck. A hard delete never reaches a peer — the tombstone is+ * what converges a subscribed instance, and the GC sweep hard-removes it once+ * every peer has had the grace window to see it (`pruneTombstonedDecks`).+ * Card rows are kept so a conflict-journal restore can un-tombstone the deck+ * with its roster intact; the sweep's ON DELETE CASCADE clears them for good.+ */export async function deleteDeck(id) {await ensureSchema();- const { rowCount } = await query('DELETE FROM decks WHERE id = $1', [id]);+ const { rowCount } = await query(+ 'UPDATE decks SET deleted = TRUE, deleted_at = NOW(), updated_at = NOW() WHERE id = $1 AND deleted IS NOT TRUE',+ [id],+ );if (!rowCount) throw notFound();console.log(`🃏 deck deleted ${id}`);+ emitRecordDeleted(DECK_KIND, id);return { ok: true };}// ── Cards ────────────────────────────────────────────────────────────────────/** Patch one card's authored fields (prompt, negative, name, refs, canon link). */-export function updateCard(deckId, cardId, patch = {}) {- return patchCard(deckId, cardId, (d) => {+export async function updateCard(deckId, cardId, patch = {}) {+ const card = await patchCard(deckId, cardId, (d) => {if (patch.name !== undefined) d.name = trimTo(patch.name);if (patch.prompt !== undefined) { d.prompt = trimTo(patch.prompt); d.promptSource = 'edited'; }if (patch.negativePrompt !== undefined) d.negativePrompt = trimTo(patch.negativePrompt);@@ -251,6 +308,8 @@ export function updateCard(deckId, cardId, patch = {}) {// A primary that no longer exists in the history falls back to the latest.if (d.primaryImageRef && !filenames(d.imageRefs).includes(d.primaryImageRef)) d.primaryImageRef = null;});+ emitRecordUpdated(DECK_KIND, deckId);+ return card;}/**@@ -267,7 +326,10 @@ export async function applyCardGenerations(deckId, entries = []) {}, { missingOk: true, touch: false });if (card) applied += 1;}- if (applied) await query('UPDATE decks SET updated_at = NOW() WHERE id = $1', [deckId]);+ if (applied) {+ await query('UPDATE decks SET updated_at = NOW() WHERE id = $1', [deckId]);+ emitRecordUpdated(DECK_KIND, deckId);+ }return applied;}@@ -308,12 +370,17 @@ export function markCardRenderTerminal(deckId, cardId, { jobId, status, error =* append the gallery filename, promote it to primary, clear the in-flight* record. Returns the card, or null when the card no longer exists.*/-export function attachCardRender({ deckId, cardId, filename, jobId }) {- return patchCard(deckId, cardId, (d) => {+export async function attachCardRender({ deckId, cardId, filename, jobId }) {+ const card = await patchCard(deckId, cardId, (d) => {d.imageRefs = [...filenames(d.imageRefs).filter((f) => f !== filename), filename].slice(-DECK_CARD_IMAGE_REFS_MAX);d.primaryImageRef = filename;d.render = { ...(d.render || {}), jobId, status: 'completed', error: null, filename, updatedAt: new Date().toISOString() };}, { missingOk: true });+ // `imageRefs` / `primaryImageRef` are wire-visible, so a completed render is+ // a real content change peers must receive (the in-flight `render` stamps+ // above are stripped from the wire and deliberately announce nothing).+ if (card) emitRecordUpdated(DECK_KIND, deckId);+ return card;}// ── Samples (style references) ───────────────────────────────────────────────@@ -349,3 +416,240 @@ export function removeSample(id, sampleId) {d.samples = (Array.isArray(d.samples) ? d.samples : []).filter((s) => s?.id !== sampleId);});}++// ── Federation (record kind `deck`, sync category `decks`) ───────────────────+//+// A deck rides ONE push carrying the deck row plus its full card roster, merged+// whole-record LWW on the deck's `updatedAt`. Cards are addressed by their+// stable roster `key` (not by row id) so two machines that minted the same deck+// kind converge on the same 52/78 slots instead of doubling them. Card ids stay+// machine-local for the same reason: the receiver keeps its own row id for a key+// it already holds, and mints one for a key it doesn't.++export const DECK_KIND = 'deck';++// Per-deck write tail: a merge's read-modify-write must not interleave with a+// concurrent REST edit or a second merge for the same deck.+const queueRecordWrite = createRecordWriteQueue();++/**+ * One deck's sanitized record (tombstone surfaced), or null when unknown. Only+ * a genuine miss answers null — a DB fault must NOT read as "absent," or the+ * merge would treat an existing deck as new and skip the LWW compare entirely.+ */+export async function getDeckForSync(id) {+ return getDeck(id, { includeDeleted: true }).catch((error) => {+ if (error?.code === 'DECK_NOT_FOUND') return null;+ throw error;+ });+}++/** Every LIVE deck as `{ id, updatedAt }` — the full-sync coverage compare set. */+export async function listDecksForSync() {+ await ensureSchema();+ const { rows } = await query('SELECT id, updated_at FROM decks WHERE deleted IS NOT TRUE');+ return rows.map((r) => ({ id: r.id, updatedAt: isoOrNull(r.updated_at) }));+}++/** Deck ids — live only by default, or all (incl. tombstones) for the sweep. */+export async function listDeckIdsForSync({ includeDeleted = false } = {}) {+ await ensureSchema();+ const { rows } = await query(+ `SELECT id FROM decks ${includeDeleted ? '' : 'WHERE deleted IS NOT TRUE'}`,+ );+ return rows.map((r) => r.id);+}++// The wire-form card fields the receiver persists. `id` and `render` are+// machine-local (a row id and an in-flight jobId mean nothing on a peer), so a+// remote card never overwrites either.+const cardDefinitionFromRemote = (card) => ({+ name: trimTo(card?.name),+ group: trimTo(card?.group),+ groupLabel: trimTo(card?.groupLabel),+ rank: card?.rank ?? null,+ motif: trimTo(card?.motif) || null,+ prompt: trimTo(card?.prompt),+ negativePrompt: trimTo(card?.negativePrompt),+ canonRef: card?.canonRef && typeof card.canonRef === 'object' ? card.canonRef : null,+ imageRefs: filenames(card?.imageRefs).slice(-DECK_CARD_IMAGE_REFS_MAX),+ primaryImageRef: trimTo(card?.primaryImageRef) || null,+});++// The deck-level definition fields that travel. The install-capability pins+// (`imageMode` / `imageModelId` / `promptLlm`) are absent from the wire, so the+// receiver's own pins are carried forward from its local copy instead of being+// reset to null by a remote win.+const definitionFromRemote = (remote, local) => ({+ description: trimTo(remote?.description),+ styleNotes: trimTo(remote?.styleNotes),+ influences: universeVisualStyleTokens(remote),+ layoutPrompt: trimTo(remote?.layoutPrompt),+ samples: Array.isArray(remote?.samples) ? remote.samples.slice(0, DECK_SAMPLES_MAX) : [],+ cardSize: remote?.cardSize?.width && remote?.cardSize?.height+ ? { width: remote.cardSize.width, height: remote.cardSize.height }+ : undefined,+ imageMode: local?.imageMode ?? null,+ imageModelId: local?.imageModelId ?? null,+ promptLlm: local?.promptLlm ?? null,+});++// Newest ISO timestamp wins; a tie keeps the local copy (no churn on equal clocks).+const remoteWinsOver = (remoteAt, localAt) => {+ if (!isNonBlankStr(remoteAt)) return false;+ if (!isNonBlankStr(localAt)) return true;+ return new Date(remoteAt).getTime() > new Date(localAt).getTime();+};++/**+ * Apply one remote deck inside a transaction: upsert the deck row (tombstone+ * included) and reconcile its cards by roster `key` — upsert what the remote+ * carries, drop the keys it no longer has. A tombstone carries no cards, so it+ * leaves the local roster alone (a restore then has something to restore to).+ */+async function writeRemoteDeck(id, remote, local) {+ const localDefinition = local ? {+ imageMode: local.imageMode, imageModelId: local.imageModelId, promptLlm: local.promptLlm,+ } : null;+ await withTransaction(async (client) => {+ const definition = definitionFromRemote(remote, localDefinition);+ if (definition.cardSize === undefined) {+ definition.cardSize = { ...(DECK_CARD_SIZE_BY_KIND[remote.kind] || DECK_CARD_SIZE) };+ }+ await client.query(+ `INSERT INTO decks (id, name, kind, universe_id, definition, updated_at, deleted, deleted_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)+ ON CONFLICT (id) DO UPDATE SET+ name = EXCLUDED.name, kind = EXCLUDED.kind, universe_id = EXCLUDED.universe_id,+ definition = EXCLUDED.definition, updated_at = EXCLUDED.updated_at,+ deleted = EXCLUDED.deleted, deleted_at = EXCLUDED.deleted_at`,+ [+ id, trimTo(remote.name), remote.kind, remote.universeId || null, definition,+ remote.updatedAt, remote.deleted === true,+ remote.deleted === true ? (remote.deletedAt || new Date().toISOString()) : null,+ ],+ );+ if (remote.deleted === true) return;+ const cards = Array.isArray(remote.cards) ? remote.cards : [];+ if (!cards.length) return;+ await client.query(+ `INSERT INTO deck_cards (id, deck_id, position, key, definition)+ SELECT COALESCE(existing.id, v.new_id), $1, v.position, v.key, v.definition+ FROM unnest($2::uuid[], $3::int[], $4::text[], $5::jsonb[]) AS v(new_id, position, key, definition)+ LEFT JOIN deck_cards existing ON existing.deck_id = $1 AND existing.key = v.key+ ON CONFLICT (deck_id, key) DO UPDATE SET+ position = EXCLUDED.position, definition = EXCLUDED.definition, updated_at = NOW()`,+ [+ id,+ cards.map(() => randomUUID()),+ cards.map((c, i) => (Number.isInteger(c?.position) ? c.position : i)),+ cards.map((c) => String(c.key)),+ cards.map(cardDefinitionFromRemote),+ ],+ );+ await client.query(+ 'DELETE FROM deck_cards WHERE deck_id = $1 AND key <> ALL($2::text[])',+ [id, cards.map((c) => String(c.key))],+ );+ });+}++/**+ * Merge an incoming batch of deck records from a peer (LWW, tombstone-aware).+ * Serialized per-id against the REST writers, journals the about-to-be-+ * overwritten local version when the remote wins, and re-stamps the+ * conflict-journal base hash for the record it just wrote.+ */+export async function mergeDecksFromSync(remoteRecords, { source = { via: 'sync', peerId: null } } = {}) {+ if (!Array.isArray(remoteRecords) || !remoteRecords.length) return { applied: false, count: 0 };+ await ensureSchema();+ let changed = 0;+ for (const remote of remoteRecords) {+ const id = remote?.id;+ // `kind` is a CHECK-constrained column — a record naming an unknown deck+ // kind would fail the INSERT, so drop it on the floor like a missing id.+ if (!isNonBlankStr(id) || !isNonBlankStr(remote?.kind) || !DECK_CARD_SIZE_BY_KIND[remote.kind]) continue;+ const applied = await queueRecordWrite(id, async () => {+ const local = await getDeckForSync(id);+ if (local && !remoteWinsOver(remote.updatedAt, local.updatedAt)) return false;+ // An already-tombstoned local deck re-receiving the same tombstone is a+ // no-op — writing it would restart its GC grace period every cycle.+ if (local?.deleted === true && remote.deleted === true) return false;+ if (local) {+ await maybeJournalBeforeOverwrite({ kind: DECK_KIND, id, local, remote, source });+ }+ await writeRemoteDeck(id, remote, local);+ const merged = await getDeckForSync(id);+ if (merged) await setSyncBaseHash(DECK_KIND, id, contentHashForRecord(DECK_KIND, merged));+ return true;+ });+ if (applied) changed += 1;+ }+ await flushBaseHashes();+ if (changed > 0) console.log(`🃏 deck sync: merged ${changed} deck(s)`);+ return changed === 0 ? { applied: false, count: 0 } : { applied: true, count: changed };+}++/**+ * Hard-remove tombstoned decks deleted before `cutoffEpochMs`; evicts each base+ * hash. `cutoffEpochMs` is an ABSOLUTE epoch-ms instant (what `cutoffForKind`+ * produces), not a duration — matching every other `pruneTombstonedX`.+ */+export async function pruneTombstonedDecks(cutoffEpochMs) {+ if (!Number.isFinite(cutoffEpochMs)) return { pruned: 0, ids: [] };+ await ensureSchema();+ const cutoff = new Date(cutoffEpochMs).toISOString();+ const { rows } = await query(+ 'SELECT id FROM decks WHERE deleted IS TRUE AND deleted_at IS NOT NULL AND deleted_at < $1',+ [cutoff],+ );+ const ids = [];+ await withBaseHashFlushBatch(async () => {+ for (const row of rows) {+ // Re-check the predicate INSIDE the per-id tail: a merge that rewrote+ // this tombstone with a fresher deletedAt mid-sweep restarted its grace+ // period, and hard-deleting it early would let an offline peer+ // resurrect the record. Cards go with it via ON DELETE CASCADE.+ const pruned = await queueRecordWrite(row.id, async () => {+ const { rowCount } = await query(+ 'DELETE FROM decks WHERE id = $1 AND deleted IS TRUE AND deleted_at < $2',+ [row.id, cutoff],+ );+ return rowCount > 0;+ });+ if (!pruned) continue;+ ids.push(row.id);+ await deleteSyncBaseHash(DECK_KIND, row.id).catch(() => {});+ }+ });+ if (ids.length) console.log(`🃏 deck tombstone GC: pruned ${ids.length} deck(s)`);+ return { pruned: ids.length, ids };+}++/**+ * Restore a tombstoned/overwritten deck from a conflict-journal snapshot:+ * apply the restorable fields, un-tombstone, and bump `updatedAt` so the+ * restore wins the next LWW and re-pushes. Returns null for a deck that has+ * already been hard-pruned (→ ERR_TARGET_GONE at the route).+ */+export async function restoreDeck(id, patch = {}) {+ await ensureSchema();+ return queueRecordWrite(id, async () => {+ const { rows } = await query('SELECT * FROM decks WHERE id = $1', [id]);+ if (!rows[0]) return null;+ const d = { ...(rows[0].definition || {}) };+ applyDefinitionPatch(d, patch);+ await query(+ `UPDATE decks SET name = $2, universe_id = $3, definition = $4,+ updated_at = NOW(), deleted = FALSE, deleted_at = NULL WHERE id = $1`,+ [+ id,+ patch.name !== undefined ? trimTo(patch.name) : rows[0].name,+ patch.universeId !== undefined ? (patch.universeId || null) : rows[0].universe_id,+ d,+ ],+ );+ emitRecordUpdated(DECK_KIND, id);+ return getDeck(id);+ });+}diff --git a/server/services/decksSync.db.test.js b/server/services/decksSync.db.test.jsnew file mode 100644index 0000000000..c63ba3090d--- /dev/null+++ b/server/services/decksSync.db.test.js@@ -0,0 +1,179 @@+/**+ * Deck federation over PostgreSQL (#decks): the LWW merge, the tombstone+ * lifecycle, and the machine-local fields a remote win must not reset.+ * Runs only against portos_test.+ */+import { afterAll, describe, expect, it } from 'vitest';+import { checkHealth, ensureSchema, query, close } from '../lib/db.js';+import { requireDbOrSkip } from '../lib/dbTestGate.js';+import { sanitizeRecordForWire } from '../lib/syncWire.js';+import {+ createDeck, getDeck, updateDeck, updateCard, deleteDeck,+ getDeckForSync, listDecksForSync, listDeckIdsForSync,+ mergeDecksFromSync, pruneTombstonedDecks, restoreDeck,+} from './decks.js';++const health = await checkHealth().catch((error) => ({ connected: false, error: error.message }));+const ready = requireDbOrSkip('services/decksSync.db.test', health.connected, health.error);+if (ready) await ensureSchema();+const ids = [];+afterAll(async () => {+ if (ready && ids.length) await query('DELETE FROM decks WHERE id = ANY($1::uuid[])', [ids]);+ await close();+});++const make = async (name) => {+ const deck = await createDeck({ name, kind: 'playing' });+ ids.push(deck.id);+ return deck;+};++// The shape a peer would actually receive: the local record run through the+// wire projection, so these tests exercise the same bytes the push ships.+const asWire = (deck, patch = {}) => ({ ...sanitizeRecordForWire('deck', deck), ...patch });+const later = (iso, ms) => new Date(new Date(iso).getTime() + ms).toISOString();++describe.skipIf(!ready)('deck federation', () => {+ it('merges a newer remote deck and leaves an older one alone', async () => {+ const deck = await make('Merge Base');+ const remote = asWire(deck, {+ name: 'Renamed On Peer',+ styleNotes: 'etched linework',+ updatedAt: later(deck.updatedAt, 60_000),+ });+ expect(await mergeDecksFromSync([remote])).toEqual({ applied: true, count: 1 });+ expect((await getDeck(deck.id)).name).toBe('Renamed On Peer');+ expect((await getDeck(deck.id)).styleNotes).toBe('etched linework');++ const stale = asWire(deck, { name: 'Stale', updatedAt: later(deck.updatedAt, -60_000) });+ expect(await mergeDecksFromSync([stale])).toEqual({ applied: false, count: 0 });+ expect((await getDeck(deck.id)).name).toBe('Renamed On Peer');+ });++ it('inserts a deck it has never seen, with its full card roster keyed by roster key', async () => {+ const source = await make('Roster Source');+ const remoteId = crypto.randomUUID();+ ids.push(remoteId);+ const remote = asWire(source, { id: remoteId, name: 'From Peer', updatedAt: new Date().toISOString() });+ remote.cards[0] = { ...remote.cards[0], prompt: 'a king of coins, woodcut' };++ expect(await mergeDecksFromSync([remote])).toEqual({ applied: true, count: 1 });+ const landed = await getDeck(remoteId);+ expect(landed.name).toBe('From Peer');+ expect(landed.cards).toHaveLength(source.cards.length);+ expect(landed.cards.map((c) => c.key).sort()).toEqual(source.cards.map((c) => c.key).sort());+ const authored = landed.cards.find((c) => c.key === remote.cards[0].key);+ expect(authored.prompt).toBe('a king of coins, woodcut');+ // Row ids are minted locally — a remote never dictates them.+ expect(landed.cards.every((c) => c.id && c.id !== remote.cards[0].id)).toBe(true);+ });++ it('carries the receiver\'s own render/LLM pins forward through a remote win', async () => {+ const deck = await make('Pinned');+ await updateDeck(deck.id, {+ imageMode: 'grok', imageModelId: 'grok-image-1',+ promptLlm: { providerId: 'claude-cli', model: 'claude-opus-5' },+ });+ const pinned = await getDeck(deck.id);+ expect(pinned.promptLlm).toMatchObject({ providerId: 'claude-cli', model: 'claude-opus-5' });+ await mergeDecksFromSync([asWire(pinned, {+ name: 'Remote Wins', updatedAt: later(pinned.updatedAt, 60_000),+ })]);++ const merged = await getDeck(deck.id);+ expect(merged.name).toBe('Remote Wins');+ expect(merged.imageMode).toBe('grok');+ expect(merged.imageModelId).toBe('grok-image-1');+ expect(merged.promptLlm).toEqual(pinned.promptLlm);+ });++ it('keeps a card\'s local render history when the remote carries none for it', async () => {+ const deck = await make('Render History');+ const card = deck.cards[0];+ await updateCard(deck.id, card.id, { imageRefs: ['local-render.png'], primaryImageRef: 'local-render.png' });+ const withRender = await getDeck(deck.id);++ // A remote that HAS the render keeps it; the refs are wire-visible, so+ // this is the round-trip a real peer performs.+ await mergeDecksFromSync([asWire(withRender, { updatedAt: later(withRender.updatedAt, 60_000) })]);+ const merged = await getDeck(deck.id);+ expect(merged.cards.find((c) => c.key === card.key).imageRefs).toEqual(['local-render.png']);+ // The local row id survived the upsert — the receiver matches on roster key.+ expect(merged.cards.find((c) => c.key === card.key).id).toBe(card.id);+ });++ it('tombstones on delete, hides the deck from reads, and keeps it visible to sync', async () => {+ const deck = await make('Doomed');+ await deleteDeck(deck.id);++ await expect(getDeck(deck.id)).rejects.toThrow(/not found/i);+ expect((await listDecksForSync()).some((d) => d.id === deck.id)).toBe(false);+ expect(await listDeckIdsForSync()).not.toContain(deck.id);+ expect(await listDeckIdsForSync({ includeDeleted: true })).toContain(deck.id);++ const tombstone = await getDeckForSync(deck.id);+ expect(tombstone.deleted).toBe(true);+ expect(tombstone.deletedAt).toBeTruthy();+ });++ it('applies a remote tombstone once, then treats a repeat as a no-op (a rewrite would restart the GC grace period)', async () => {+ const deck = await make('Remote Delete');+ const tombstone = asWire(deck, {+ deleted: true,+ deletedAt: new Date().toISOString(),+ updatedAt: later(deck.updatedAt, 60_000),+ });+ expect(await mergeDecksFromSync([tombstone])).toEqual({ applied: true, count: 1 });+ const applied = await getDeckForSync(deck.id);+ expect(applied.deleted).toBe(true);++ expect(await mergeDecksFromSync([{ ...tombstone, updatedAt: later(deck.updatedAt, 120_000) }]))+ .toEqual({ applied: false, count: 0 });+ expect((await getDeckForSync(deck.id)).deletedAt).toBe(applied.deletedAt);+ });++ it('drops a remote record with no id or an unknown deck kind rather than failing the batch', async () => {+ const deck = await make('Batch Survivor');+ const good = asWire(deck, { name: 'Landed', updatedAt: later(deck.updatedAt, 60_000) });+ const result = await mergeDecksFromSync([+ { name: 'no id', kind: 'playing', updatedAt: new Date().toISOString() },+ { id: crypto.randomUUID(), kind: 'hanafuda', updatedAt: new Date().toISOString() },+ good,+ ]);+ expect(result).toEqual({ applied: true, count: 1 });+ expect((await getDeck(deck.id)).name).toBe('Landed');+ });++ it('prunes a tombstone only once its deletedAt precedes the cutoff', async () => {+ const deck = await make('GC Candidate');+ await deleteDeck(deck.id);++ expect(await pruneTombstonedDecks(Date.now() - 86_400_000)).toEqual({ pruned: 0, ids: [] });+ expect(await listDeckIdsForSync({ includeDeleted: true })).toContain(deck.id);++ const swept = await pruneTombstonedDecks(Date.now() + 1000);+ expect(swept.ids).toContain(deck.id);+ expect(await getDeckForSync(deck.id)).toBeNull();+ // The card rows go with it (ON DELETE CASCADE) — no orphan roster left behind.+ const { rows } = await query('SELECT 1 FROM deck_cards WHERE deck_id = $1', [deck.id]);+ expect(rows).toHaveLength(0);+ });++ it('restores a tombstoned deck from a conflict-journal snapshot and re-arms it for the next push', async () => {+ const deck = await make('Restorable');+ await updateDeck(deck.id, { styleNotes: 'the authored guide' });+ const before = await getDeck(deck.id);+ await deleteDeck(deck.id);++ const restored = await restoreDeck(deck.id, { name: 'Restored', styleNotes: before.styleNotes });+ expect(restored.deleted).toBe(false);+ expect(restored.name).toBe('Restored');+ expect(restored.styleNotes).toBe('the authored guide');+ expect(new Date(restored.updatedAt).getTime()).toBeGreaterThan(new Date(before.updatedAt).getTime());+ expect((await getDeck(deck.id)).cards).toHaveLength(before.cards.length);+ });++ it('returns null when restoring a deck the sweep already hard-pruned', async () => {+ expect(await restoreDeck(crypto.randomUUID(), { name: 'ghost' })).toBeNull();+ });+});diff --git a/server/services/instances.js b/server/services/instances.jsindex 927ba7a1aa..a95ad37542 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -264,6 +264,7 @@ const DEFAULT_SYNC_CATEGORIES = {musicVideoProjects: false,commissionFeedback: false,creativeCommissions: false,+ decks: false,catalog: false};@@ -380,6 +381,7 @@ const PER_RECORD_CATEGORY_KINDS = Object.freeze([['musicVideoProjects', 'musicVideoProject'],['commissionFeedback', 'commissionFeedback'],['creativeCommissions', 'creativeCommission'],+ ['decks', 'deck'],]);export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, auth, transport, protocol = 'http' }) {diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex f0b6c13470..c3c50670b6 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -42,6 +42,7 @@ import { listBoards } from '../moodBoard/index.js';import { listLooms } from '../fableLoom/index.js';import { listWorksForSync, listFoldersForSync, listExercisesForSync } from '../writersRoom/sync.js';import { listCommissionFeedbackForSync } from '../creativeCommissions/feedbackStore.js';+import { listDecksForSync } from '../decks.js';import { listCommissionsForSync } from '../creativeCommissions/store.js';import { initCursor } from './peerTombstoneCursors.js';import {@@ -208,6 +209,10 @@ const RECORD_KIND_LISTERS = {// Live commission briefs as { id, updatedAt } (#2686). Body-less on the wire// (schedule/runs/assignment stripped), so no asset manifest backfill.creativeCommission: () => listCommissionsForSync(),+ // Live decks as { id, updatedAt } — the coverage compare keys on the same+ // clock the wire LWW does, so a deck edited since its last confirmed push+ // reads as stale rather than fully mirrored.+ deck: () => listDecksForSync(),};/**diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 7e303892e3..38f422cda4 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -199,6 +199,13 @@ vi.mock('../creativeCommissions/store.js', async (importOriginal) => ({getCommissionForSync: vi.fn(),mergeCommissionsFromSync: vi.fn().mockResolvedValue({ applied: true, count: 1 }),}));+vi.mock('../decks.js', () => ({+ listDecksForSync: vi.fn().mockResolvedValue([]),+ listDeckIdsForSync: vi.fn().mockResolvedValue([]),+ getDeckForSync: vi.fn(),+ mergeDecksFromSync: vi.fn().mockResolvedValue({ applied: true, count: 1 }),+ pruneTombstonedDecks: vi.fn().mockResolvedValue({ pruned: 0, ids: [] }),+}));vi.mock('../../lib/peerHttpClient.js', async () => ({peerFetch: vi.fn(),@@ -297,6 +304,7 @@ import {import { diffWorkBibleManifest } from '../writersRoom/bibleSync.js';import { listCommissionFeedbackForSync, getCommissionFeedbackForSync, mergeCommissionFeedbackFromSync } from '../creativeCommissions/feedbackStore.js';import { listCommissionsForSync, getCommissionForSync, mergeCommissionsFromSync } from '../creativeCommissions/store.js';+import { getDeckForSync, mergeDecksFromSync } from '../decks.js';import { peerFetch } from '../../lib/peerHttpClient.js';import { RESPONSE_TOO_LARGE } from '../../lib/httpClient.js';import { reconcileMediaAssets } from '../mediaAssetIndex/index.js';@@ -490,7 +498,7 @@ describe('peerSync', () => {// caught — this list is canonical and its order can affect iteration// elsewhere (e.g. syncNow's per-kind backfill). Issues piggyback on series// subscriptions; direct issue subs are intentionally rejected (Stage 2).- expect(PEER_SUBSCRIBABLE_KINDS).toEqual(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'fableLoom', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']);+ expect(PEER_SUBSCRIBABLE_KINDS).toEqual(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'fableLoom', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission', 'deck']);});});@@ -5148,6 +5156,7 @@ describe('media-library federation (#1566)', () => {musicVideoProject: { get: getMusicVideoProject, merge: mergeMusicVideoProjectsFromSync },commissionFeedback: { get: getCommissionFeedbackForSync, merge: mergeCommissionFeedbackFromSync },creativeCommission: { get: getCommissionForSync, merge: mergeCommissionsFromSync },+ deck: { get: getDeckForSync, merge: mergeDecksFromSync },};it('every PEER_SUBSCRIBABLE_KINDS entry has a test fixture (guards the parity suite itself against a silently-skipped kind)', () => {diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.jsindex 769694665d..5416d18db9 100644--- a/server/services/sharing/peerSyncAssets.js+++ b/server/services/sharing/peerSyncAssets.js@@ -594,6 +594,34 @@ export async function buildBoardAssetManifest(board) {return [...dedup.values()];}+/**+ * Hash every gallery image a deck (#decks) references so a subscribed peer can+ * pull the bytes and actually SEE the deck: each card's render history+ * (`imageRefs`, which already includes `primaryImageRef`) plus the style+ * samples the vision step analyzed (`samples[].imageRef`). De-duped by+ * filename — the same render can be a card ref and a sample — and each+ * missing-local-file entry is skipped silently (mirrors buildBoardAssetManifest:+ * a null-hash entry would make every receiver re-request bytes the sender+ * cannot fulfil).+ */+export async function buildDeckAssetManifest(deck) {+ const filenames = new Set();+ for (const card of Array.isArray(deck?.cards) ? deck.cards : []) {+ for (const ref of Array.isArray(card?.imageRefs) ? card.imageRefs : []) {+ const safe = sanitizeAssetFilename(ref);+ if (safe) filenames.add(safe);+ }+ const primary = sanitizeAssetFilename(card?.primaryImageRef);+ if (primary) filenames.add(primary);+ }+ for (const sample of Array.isArray(deck?.samples) ? deck.samples : []) {+ const safe = sanitizeAssetFilename(sample?.imageRef);+ if (safe) filenames.add(safe);+ }+ const entries = await Promise.all([...filenames].map((f) => hashImageForManifest(f)));+ return entries.filter(Boolean);+}+export async function buildAssetManifestForSeries(series, issues, linkedCollection = null) {const seriesAssets = await buildAssetManifest(series);const dedup = new Map(seriesAssets.map((a) => [`${a.kind}:${a.filename}`, a]));diff --git a/server/services/sharing/peerSyncShared.js b/server/services/sharing/peerSyncShared.jsindex a316f22a70..9603936d36 100644--- a/server/services/sharing/peerSyncShared.js+++ b/server/services/sharing/peerSyncShared.js@@ -15,7 +15,7 @@ import { EventEmitter } from 'events';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';import { getPeers, resolveEffectiveCategories } from '../instances.js';-export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'fableLoom', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']);+export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'fableLoom', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission', 'deck']);/*** The optional top-level keys a NEWER sender may attach to a push envelope@@ -163,6 +163,7 @@ export const KIND_TO_CATEGORY = Object.freeze({musicVideoProject: 'musicVideoProjects',commissionFeedback: 'commissionFeedback',creativeCommission: 'creativeCommissions',+ deck: 'decks',});// The half every outbound predicate shares: the peer exists, the user has notdiff --git a/server/services/sharing/recordKinds.js b/server/services/sharing/recordKinds.jsindex 48bb05829f..ab67d350e2 100644--- a/server/services/sharing/recordKinds.js+++ b/server/services/sharing/recordKinds.js@@ -1,7 +1,7 @@/*** Federated peer-sync — per-kind record descriptor table.*- * The 16 subscribable record kinds (`PEER_SUBSCRIBABLE_KINDS`,+ * The 17 subscribable record kinds (`PEER_SUBSCRIBABLE_KINDS`,* `peerSyncShared.js`) each need the same four facts — how to load one by* id, how to merge an incoming batch, how to build its asset manifest, and* whether the kind has a local-only "ephemeral" opt-out flag. Before #6843@@ -55,6 +55,7 @@ import {} from '../writersRoom/sync.js';import { getCommissionFeedbackForSync, mergeCommissionFeedbackFromSync } from '../creativeCommissions/feedbackStore.js';import { getCommissionForSync, mergeCommissionsFromSync } from '../creativeCommissions/store.js';+import { getDeckForSync, mergeDecksFromSync } from '../decks.js';import {buildAssetManifest,buildAssetManifestForSeries,@@ -67,6 +68,7 @@ import {buildMusicVideoAssetManifest,buildBoardAssetManifest,buildFableLoomAssetManifest,+ buildDeckAssetManifest,} from './peerSyncAssets.js';import { isNonBlankStr } from '../../lib/textUtils.js';@@ -184,6 +186,15 @@ export const RECORD_KINDS = Object.freeze({buildAssetManifest: null, // body-less brief (#2686)hasEphemeral: false,},+ deck: {+ // The loader surfaces tombstones (a delete must push) and bundles the full+ // card roster on the record itself, so no bundle-aware push hook is needed+ // — the generic manifest builder reads `record.cards[]` directly.+ load: (id) => getDeckForSync(id),+ merge: mergeDecksFromSync,+ buildAssetManifest: buildDeckAssetManifest,+ hasEphemeral: false,+ },});// --- Asset-integrity manifest (moved from peerSyncAssets.js, #6843) -------diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.jsindex 63fe5e9aa7..ac5909152e 100644--- a/server/services/sharing/tombstoneGc.js+++ b/server/services/sharing/tombstoneGc.js@@ -74,6 +74,7 @@ import {import {pruneTombstonedCommissions, listCommissionIdsForSync,} from '../creativeCommissions/store.js';+import { listDeckIdsForSync, pruneTombstonedDecks } from '../decks.js';import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';@@ -115,6 +116,7 @@ const LIVE_ID_LISTERS = Object.freeze({writersRoomExercise: () => listExerciseIdsForSync(),commissionFeedback: () => listCommissionFeedbackIdsForSync(),creativeCommission: () => listCommissionIdsForSync(),+ deck: () => listDeckIdsForSync(),});// Each peer-subscribable kind's UNCAPPED id source INCLUDING tombstones —@@ -149,6 +151,7 @@ const ALL_ID_LISTERS = Object.freeze({writersRoomExercise: () => listExerciseIdsForSync({ includeDeleted: true }),commissionFeedback: () => listCommissionFeedbackIdsForSync({ includeDeleted: true }),creativeCommission: () => listCommissionIdsForSync({ includeDeleted: true }),+ deck: () => listDeckIdsForSync({ includeDeleted: true }),});// Build a kind-aware id-membership resolver for ONE sweep: lazily list each@@ -424,6 +427,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =writersRoomExerciseCutoff,commissionFeedbackCutoff,creativeCommissionCutoff,+ deckCutoff,] = await Promise.all([cutoffForKind('universe', { peers, subs, now, graceMs }),cutoffForKind('series', { peers, subs, now, graceMs }),@@ -441,9 +445,10 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =cutoffForKind('writersRoomExercise', { peers, subs, now, graceMs }),cutoffForKind('commissionFeedback', { peers, subs, now, graceMs }),cutoffForKind('creativeCommission', { peers, subs, now, graceMs }),+ cutoffForKind('deck', { peers, subs, now, graceMs }),]);const issueCutoff = seriesCutoff;- const [u, s, i, c, a, ar, al, t, cd, mv, mb, fl, wr, wrf, wre, cfb, cc] = await Promise.all([+ const [u, s, i, c, a, ar, al, t, cd, mv, mb, fl, wr, wrf, wre, cfb, cc, dk] = 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),@@ -461,6 +466,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =writersRoomExerciseCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedExercises(writersRoomExerciseCutoff),commissionFeedbackCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedCommissionFeedback(commissionFeedbackCutoff),creativeCommissionCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedCommissions(creativeCommissionCutoff),+ deckCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedDecks(deckCutoff),]);// 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@@ -494,9 +500,10 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =writersRoomExercises: wre.pruned,commissionFeedback: cfb.pruned,creativeCommissions: cc.pruned,+ decks: dk.pruned,orphanBaseHashes: orphan.pruned,orphanSubscriptions: orphanSubs.pruned,- refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, mediaCollectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, creativeDirectorProjectCutoff, musicVideoProjectCutoff, moodBoardCutoff, fableLoomCutoff, writersRoomWorkCutoff, writersRoomFolderCutoff, writersRoomExerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff }),+ refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, mediaCollectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, creativeDirectorProjectCutoff, musicVideoProjectCutoff, moodBoardCutoff, fableLoomCutoff, writersRoomWorkCutoff, writersRoomFolderCutoff, writersRoomExerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff, deckCutoff }),};}@@ -505,7 +512,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, mediaCollectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, creativeDirectorProjectCutoff, musicVideoProjectCutoff, moodBoardCutoff, fableLoomCutoff, writersRoomWorkCutoff, writersRoomFolderCutoff, writersRoomExerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff] = await Promise.all([+ const [universeCutoff, seriesCutoff, mediaCollectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, creativeDirectorProjectCutoff, musicVideoProjectCutoff, moodBoardCutoff, fableLoomCutoff, writersRoomWorkCutoff, writersRoomFolderCutoff, writersRoomExerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff, deckCutoff] = await Promise.all([cutoffForKind('universe', { peers, subs, now, graceMs: 0 }),cutoffForKind('series', { peers, subs, now, graceMs: 0 }),cutoffForKind('mediaCollection', { peers, subs, now, graceMs: 0 }),@@ -522,8 +529,9 @@ export async function getSweepStatus({ now = Date.now() } = {}) {cutoffForKind('writersRoomExercise', { peers, subs, now, graceMs: 0 }),cutoffForKind('commissionFeedback', { peers, subs, now, graceMs: 0 }),cutoffForKind('creativeCommission', { peers, subs, now, graceMs: 0 }),+ cutoffForKind('deck', { peers, subs, now, graceMs: 0 }),]);- return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, mediaCollectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, creativeDirectorProjectCutoff, musicVideoProjectCutoff, moodBoardCutoff, fableLoomCutoff, writersRoomWorkCutoff, writersRoomFolderCutoff, writersRoomExerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff }) };+ return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, mediaCollectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, creativeDirectorProjectCutoff, musicVideoProjectCutoff, moodBoardCutoff, fableLoomCutoff, writersRoomWorkCutoff, writersRoomFolderCutoff, writersRoomExerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff, deckCutoff }) };}export const TOMBSTONE_GRACE_MS = GRACE_MS;diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.jsindex bf118b777c..6a9fd215cd 100644--- a/server/services/sharing/tombstoneGc.test.js+++ b/server/services/sharing/tombstoneGc.test.js@@ -77,6 +77,10 @@ vi.mock('../creativeCommissions/store.js', () => ({}));vi.mock('../../lib/conflictJournal.js', () => ({pruneOrphanedBaseHashes: vi.fn().mockResolvedValue({ pruned: 0 }),+ // `pruneTombstonedDecks` (services/decks.js) batches its base-hash evictions,+ // so the deck arm of the sweep reaches these two as well.+ withBaseHashFlushBatch: vi.fn(async (fn) => fn()),+ deleteSyncBaseHash: vi.fn().mockResolvedValue(undefined),}));vi.mock('./peerSync.js', () => ({listPeerSubscriptions: vi.fn(),@@ -554,6 +558,7 @@ describe('sweepTombstones — return shape', () => {writersRoomExercises: 12,commissionFeedback: 0,creativeCommissions: 0,+ decks: 0,orphanBaseHashes: 0,orphanSubscriptions: 0,refused: [],diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex 1007be772f..f85bebecb9 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -44,6 +44,7 @@ export const DB_TEST_INCLUDE = ['routes/catalog.test.js','routes/mindToolRecipes.db.test.js','routes/decks.db.test.js',+ 'services/decksSync.db.test.js','scripts/run-db-migrations.test.js',];