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

Fix three deck-federation defects found in local review

Adam Eivyb746c71a5db7
diff --git a/server/lib/syncWire.js b/server/lib/syncWire.js
index 97b059ea56..4ae7cb54d0 100644
--- a/server/lib/syncWire.js
+++ b/server/lib/syncWire.js
@@ -367,11 +367,20 @@ export function sanitizeRecordForWire(kind, record) {
// regardless of local row ordering.
const { deleted: _d, deletedAt: _da, imageMode: _im, imageModelId: _imi,
promptLlm: _pl, completion: _c, cards, ...rest } = record;
+ const soft = sanitizeSoftDeleteFields(record);
+ // A TOMBSTONE carries no roster at all. The sender still holds its cards
+ // locally (they survive until the GC sweep so a conflict-journal restore
+ // has something to restore), and the receiver's merge deliberately leaves
+ // its own roster untouched on a delete — so shipping them would make the
+ // deleted deck's content hash depend on whether a given peer ever held
+ // the live record, permanently diverging the base hashes of a sender that
+ // has cards and a receiver that inserted the tombstone cold.
+ if (soft.deleted) return { ...rest, ...soft };
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) };
+ return { ...rest, cards: wireCards, ...soft };
}
case 'musicVideoProject': {
// Music Video projects are whole-record LWW, but their image render pin
diff --git a/server/lib/syncWire.test.js b/server/lib/syncWire.test.js
index bc6727572b..f616755501 100644
--- a/server/lib/syncWire.test.js
+++ b/server/lib/syncWire.test.js
@@ -134,10 +134,21 @@ describe('syncWire', () => {
expect(sanitizeRecordForWire('deck', record).cards).toHaveLength(2);
});
- it('normalizes the soft-delete pair on a tombstone', () => {
+ it('normalizes the soft-delete pair on a tombstone and ships no roster with it', () => {
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');
+ // The receiver's merge leaves its own roster alone on a delete, so a
+ // tombstone that carried cards would hash differently on a peer that
+ // once held the live deck than on one inserting the tombstone cold.
+ expect(wire).not.toHaveProperty('cards');
+ });
+
+ it('hashes a tombstone identically whether or not the local copy still has its cards', () => {
+ const withCards = { ...deck(), deleted: true, deletedAt: '2026-05-01T00:00:00Z' };
+ const { cards: _dropped, ...withoutCards } = withCards;
+ expect(JSON.stringify(sanitizeRecordForWire('deck', withCards)))
+ .toBe(JSON.stringify(sanitizeRecordForWire('deck', withoutCards)));
});
});
diff --git a/server/services/decks.js b/server/services/decks.js
index 8497efd7dd..9d15ad824e 100644
--- a/server/services/decks.js
+++ b/server/services/decks.js
@@ -42,6 +42,20 @@ const notFound = (what = 'Deck') => new ServerError(`${what} not found`, {
const isoOrNull = (v) => (v instanceof Date ? v.toISOString() : (v || null));
+// The peer-sync record kind for a deck (see the Federation section below).
+export const DECK_KIND = 'deck';
+
+// Per-DECK write tail. EVERY writer goes through it — the REST patches, the
+// render-completion hook, the delete, the peer merge and the tombstone sweep —
+// because the merge's read-modify-write spans two awaits (read local, then
+// upsert) and a REST PATCH landing between them would be silently overwritten.
+// Serializing only the merge side would leave exactly that gap open. Card
+// writes key on their DECK id, not the card id: a card patch also touches the
+// deck row, and the merge rewrites the whole roster, so they contend.
+// Nothing inside a queued function may call another queued function — the tail
+// is not re-entrant and a nested same-key call would deadlock.
+const queueRecordWrite = createRecordWriteQueue();
+
const filenames = (values) => (Array.isArray(values) ? values : []).map((v) => trimTo(v)).filter(Boolean);
// ── Projections ──────────────────────────────────────────────────────────────
@@ -109,9 +123,12 @@ export async function listDecks({ includeDeleted = false } = {}) {
);
// 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.
+ // Scoped to the decks actually being returned — a tombstone keeps its roster
+ // until the GC sweep, so an unscoped scan drags every pending-deletion deck's
+ // cards through this query for a `byDeck` entry nothing ever looks up.
const { rows: cardRows } = await query(`SELECT deck_id, jsonb_build_object(
'prompt', left(definition->>'prompt', 1), 'imageRefs', COALESCE(definition->'imageRefs', '[]'::jsonb), 'render', definition->'render'
- ) AS definition FROM deck_cards`);
+ ) AS definition FROM deck_cards WHERE deck_id = ANY($1::uuid[])`, [rows.map((r) => r.id)]);
const byDeck = Map.groupBy(cardRows, (r) => r.deck_id);
return rows.map((row) => ({
...projectDeck(row),
@@ -136,7 +153,7 @@ export async function getDeck(id, { includeDeleted = false } = {}) {
*/
async function patchDeck(id, mutate) {
await ensureSchema();
- await withTransaction(async (client) => {
+ await queueRecordWrite(id, () => withTransaction(async (client) => {
const { rows } = await client.query('SELECT * FROM decks WHERE id = $1', [id]);
if (!rows[0] || rows[0].deleted === true) throw notFound();
const d = { ...(rows[0].definition || {}) };
@@ -145,7 +162,7 @@ async function patchDeck(id, mutate) {
'UPDATE decks SET name = $2, universe_id = $3, definition = $4, updated_at = NOW() WHERE id = $1',
[id, columns.name ?? rows[0].name, columns.universeId === undefined ? rows[0].universe_id : columns.universeId, d],
);
- });
+ }));
emitRecordUpdated(DECK_KIND, id);
return getDeck(id);
}
@@ -158,7 +175,7 @@ async function patchDeck(id, mutate) {
*/
async function patchCard(deckId, cardId, mutate, { missingOk = false, touch = true } = {}) {
await ensureSchema();
- return withTransaction(async (client) => {
+ return queueRecordWrite(deckId, () => 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;
@@ -176,7 +193,7 @@ async function patchCard(deckId, cardId, mutate, { missingOk = false, touch = tr
);
if (touch) await client.query('UPDATE decks SET updated_at = NOW() WHERE id = $1', [deckId]);
return projectCard(written[0]);
- });
+ }));
}
// ── Deck CRUD ────────────────────────────────────────────────────────────────
@@ -284,10 +301,10 @@ export function updateDeck(id, patch = {}) {
*/
export async function deleteDeck(id) {
await ensureSchema();
- const { rowCount } = await query(
+ const rowCount = await queueRecordWrite(id, async () => (await query(
'UPDATE decks SET deleted = TRUE, deleted_at = NOW(), updated_at = NOW() WHERE id = $1 AND deleted IS NOT TRUE',
[id],
- );
+ )).rowCount);
if (!rowCount) throw notFound();
console.log(`🃏 deck deleted ${id}`);
emitRecordDeleted(DECK_KIND, id);
@@ -327,7 +344,7 @@ export async function applyCardGenerations(deckId, entries = []) {
if (card) applied += 1;
}
if (applied) {
- await query('UPDATE decks SET updated_at = NOW() WHERE id = $1', [deckId]);
+ await queueRecordWrite(deckId, () => query('UPDATE decks SET updated_at = NOW() WHERE id = $1', [deckId]));
emitRecordUpdated(DECK_KIND, deckId);
}
return applied;
@@ -343,14 +360,14 @@ export async function markCardsRenderQueued(deckId, entries = []) {
if (!entries.length) return;
await ensureSchema();
const stampedAt = new Date().toISOString();
- await query(
+ await queueRecordWrite(deckId, () => query(
`UPDATE deck_cards c
SET definition = c.definition || jsonb_build_object('render', v.render), updated_at = NOW()
FROM unnest($2::uuid[], $3::jsonb[]) AS v(id, render)
WHERE c.deck_id = $1 AND c.id = v.id
AND COALESCE(c.definition->'render'->>'jobId', '') <> v.render->>'jobId'`,
[deckId, entries.map((e) => e.cardId), entries.map((e) => ({ ...e.render, updatedAt: stampedAt }))],
- );
+ ));
}
/**
@@ -426,12 +443,6 @@ export function removeSample(id, sampleId) {
// 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
diff --git a/server/services/decksSync.db.test.js b/server/services/decksSync.db.test.js
index c63ba3090d..c45c4e541a 100644
--- a/server/services/decksSync.db.test.js
+++ b/server/services/decksSync.db.test.js
@@ -173,6 +173,28 @@ describe.skipIf(!ready)('deck federation', () => {
expect((await getDeck(deck.id)).cards).toHaveLength(before.cards.length);
});
+ it('serializes a peer merge against a concurrent REST edit instead of silently dropping one', async () => {
+ // The merge's read-modify-write spans two awaits (read the local copy, then
+ // upsert). Without a shared per-deck write tail an interleaved PATCH lands
+ // between them and the upsert overwrites it with a definition built from the
+ // pre-PATCH read — the edit vanishes with no error anywhere.
+ const deck = await make('Contended');
+ const remote = asWire(deck, { name: 'From Peer', updatedAt: later(deck.updatedAt, 60_000) });
+
+ await Promise.all([
+ mergeDecksFromSync([remote]),
+ updateDeck(deck.id, { styleNotes: 'edited locally mid-merge' }),
+ ]);
+
+ // Whichever ran second wins the name/notes, but NEITHER write may be lost:
+ // the merge's name must be present, or the local edit's notes must be —
+ // and the loser's field must still hold its own pre-write value rather than
+ // a torn mix. The invariant that actually catches the bug is that the local
+ // edit is never silently discarded while reporting success.
+ const after = await getDeck(deck.id);
+ expect([after.name, after.styleNotes]).toContain('edited locally mid-merge');
+ });
+
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/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.js
index 5416d18db9..1e4fd8665e 100644
--- a/server/services/sharing/peerSyncAssets.js
+++ b/server/services/sharing/peerSyncAssets.js
@@ -37,6 +37,12 @@ import { getWorkForSync } from '../writersRoom/sync.js';
import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
import { peerSyncEvents, findPeerById } from './peerSyncShared.js';
import { isStr } from '../../lib/textUtils.js';
+import { mapWithConcurrency } from '../../lib/mapWithConcurrency.js';
+
+// In-flight gallery-image hashes while building one deck's manifest. Sized to
+// libuv's default 4-thread fs pool with a little headroom, so a deck push can't
+// starve unrelated fs work in the process.
+const DECK_HASH_CONCURRENCY = 8;
// --- Asset manifest -----------------------------------------------------
@@ -603,6 +609,15 @@ export async function buildBoardAssetManifest(board) {
* missing-local-file entry is skipped silently (mirrors buildBoardAssetManifest:
* a null-hash entry would make every receiver re-request bytes the sender
* cannot fulfil).
+ *
+ * Hashing is bounded rather than a bare `Promise.all`: a deck is by far the
+ * widest asset fan-out in the system — 78 tarot cards x DECK_CARD_IMAGE_REFS_MAX
+ * (24) render-history refs is ~1.9k gallery files, and each hash stats and may
+ * stream-read the file. Firing those at once exhausts libuv's 4-thread fs pool
+ * (and the fd table), which stalls every other fs call in the process including
+ * the one serving the UI bundle. The other builders here need no cap because
+ * their fan-out is bounded by construction (one headshot, one cover, two refs
+ * per mood-board item).
*/
export async function buildDeckAssetManifest(deck) {
const filenames = new Set();
@@ -618,7 +633,7 @@ export async function buildDeckAssetManifest(deck) {
const safe = sanitizeAssetFilename(sample?.imageRef);
if (safe) filenames.add(safe);
}
- const entries = await Promise.all([...filenames].map((f) => hashImageForManifest(f)));
+ const entries = await mapWithConcurrency([...filenames], DECK_HASH_CONCURRENCY, hashImageForManifest);
return entries.filter(Boolean);
}