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

refactor: extract createKeyCachedQueue and dedupe the scene-image attach hooks

[._.]/ Adam Eivy87fffaea23c4
diff --git a/server/lib/README.md b/server/lib/README.md
index b8163183f0..04c807f67e 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -109,6 +109,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |
| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |
+| `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. |
| `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |
| `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer`. |
| `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. |
diff --git a/server/lib/createKeyCachedQueue.js b/server/lib/createKeyCachedQueue.js
new file mode 100644
index 0000000000..ff67d6206c
--- /dev/null
+++ b/server/lib/createKeyCachedQueue.js
@@ -0,0 +1,40 @@
+/**
+ * createKeyCachedQueue — per-key serialized async work queue.
+ *
+ * Returns a `queue(key, work)` function that chains each `work` thunk onto the
+ * prior in-flight promise for that `key`, so two operations on the SAME key run
+ * one-after-another (the later one sees the earlier one's committed result)
+ * while different keys still run concurrently. The classic use is the media-job
+ * completion hooks (writers-room / catalog / music-video scene-image attach):
+ * two renders for the same record completing close together would otherwise both
+ * load→modify→save that record and the later write would clobber the earlier.
+ *
+ * The in-memory tail Map is self-pruning: each chained promise registers an
+ * eviction that removes its key only if nothing newer has chained on, so the Map
+ * never grows unbounded. Eviction errors are swallowed (the caller attaches its
+ * own `.catch` to the returned promise), and `work` runs on both fulfil AND
+ * reject of the prior link so one failure can't stall the whole chain.
+ *
+ * Lost on restart, which is fine for the best-effort bookkeeping it serializes.
+ *
+ * The returned function carries a `.clear()` for test reset (drop all tails).
+ */
+export function createKeyCachedQueue() {
+ const tails = new Map();
+
+ function queue(key, work) {
+ const prev = tails.get(key) || Promise.resolve();
+ // Run `work` on both fulfil AND reject so a prior failure doesn't stall the chain.
+ const next = prev.then(work, work);
+ tails.set(key, next);
+ // Evict once settled, but only if nothing newer has chained on. Swallow here
+ // so eviction can't surface as an unhandled rejection — the caller attaches
+ // its own `.catch` to the returned promise.
+ const evict = () => { if (tails.get(key) === next) tails.delete(key); };
+ next.then(evict, evict);
+ return next;
+ }
+
+ queue.clear = () => tails.clear();
+ return queue;
+}
diff --git a/server/lib/createKeyCachedQueue.test.js b/server/lib/createKeyCachedQueue.test.js
new file mode 100644
index 0000000000..f4bb0e89dd
--- /dev/null
+++ b/server/lib/createKeyCachedQueue.test.js
@@ -0,0 +1,71 @@
+import { describe, it, expect } from 'vitest';
+import { createKeyCachedQueue } from './createKeyCachedQueue.js';
+
+const tick = () => new Promise((r) => setTimeout(r, 0));
+
+describe('createKeyCachedQueue', () => {
+ it('serializes work for the same key (later sees earlier result)', async () => {
+ const queue = createKeyCachedQueue();
+ const order = [];
+ let releaseFirst;
+ const first = queue('k', () => new Promise((resolve) => {
+ order.push('start-1');
+ releaseFirst = () => { order.push('end-1'); resolve(); };
+ }));
+ const second = queue('k', async () => { order.push('start-2'); });
+
+ await tick();
+ // The second must NOT start while the first is still pending.
+ expect(order).toEqual(['start-1']);
+ releaseFirst();
+ await Promise.all([first, second]);
+ expect(order).toEqual(['start-1', 'end-1', 'start-2']);
+ });
+
+ it('runs different keys concurrently', async () => {
+ const queue = createKeyCachedQueue();
+ const order = [];
+ let releaseA;
+ const a = queue('a', () => new Promise((resolve) => { order.push('start-a'); releaseA = resolve; }));
+ const b = queue('b', async () => { order.push('start-b'); });
+
+ await tick();
+ // Key 'b' starts without waiting on the still-pending key 'a'.
+ expect(order).toEqual(['start-a', 'start-b']);
+ releaseA();
+ await Promise.all([a, b]);
+ });
+
+ it('continues the chain after a rejected link', async () => {
+ const queue = createKeyCachedQueue();
+ const ran = [];
+ const first = queue('k', async () => { ran.push(1); throw new Error('boom'); }).catch(() => 'handled');
+ const second = queue('k', async () => { ran.push(2); return 'ok'; });
+ expect(await first).toBe('handled');
+ expect(await second).toBe('ok');
+ expect(ran).toEqual([1, 2]);
+ });
+
+ it('evicts settled tails so the Map does not grow unbounded', async () => {
+ const queue = createKeyCachedQueue();
+ await queue('k', async () => 'done');
+ await tick();
+ // After settling with nothing newer chained on, re-queuing starts fresh
+ // (no pending predecessor) — observable as immediate execution.
+ const order = [];
+ const next = queue('k', async () => { order.push('ran'); });
+ await next;
+ expect(order).toEqual(['ran']);
+ });
+
+ it('clear() drops all tails', async () => {
+ const queue = createKeyCachedQueue();
+ // A pending link in flight; clear() must not throw and lets fresh work run.
+ queue('k', () => new Promise(() => {})); // never resolves
+ queue.clear();
+ const order = [];
+ const fresh = queue('k', async () => { order.push('fresh'); });
+ await fresh;
+ expect(order).toEqual(['fresh']);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 31c4ece8b7..232e82e0e0 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -101,6 +101,7 @@ export * from './tuiPromptRunner.js';
// === File & I/O ===
export * from './collectionStore.js';
export * from './conflictJournal.js';
+export * from './createKeyCachedQueue.js';
export * from './fileUtils.js';
export * from './fileWriteQueue.js';
export * from './schemaVersions.js';
diff --git a/server/services/catalogImageAttachHook.js b/server/services/catalogImageAttachHook.js
index 6e4171563c..8f8a98006c 100644
--- a/server/services/catalogImageAttachHook.js
+++ b/server/services/catalogImageAttachHook.js
@@ -23,6 +23,7 @@
import { mediaJobEvents } from './mediaJobQueue/index.js';
import { attachMedia, setPortraitMedia, listMediaForIngredient, getIngredient } from './catalogDB.js';
+import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
// Resolve the render onto the ingredient. Returns the kind attached
// ('portrait' | 'reference'), 'duplicate' when the client already filed it,
@@ -62,21 +63,9 @@ async function attachGeneratedImage({ ingredientId, kind, filename }) {
// so it correctly falls through to 'reference'. Keyed by ingredientId, so
// different ingredients still attach concurrently (their Postgres rows don't
// conflict). In-memory tail, evicted once settled; lost on restart, which is
-// fine — the whole hook is best-effort.
-const attachTails = new Map();
-
-function serializePerIngredient(ingredientId, work) {
- const prev = attachTails.get(ingredientId) || Promise.resolve();
- // `work` on both fulfil AND reject so a prior failure doesn't stall the chain.
- const next = prev.then(work, work);
- attachTails.set(ingredientId, next);
- // Evict once settled, but only if nothing newer has chained on. Swallow here
- // (the eviction branch never rethrows) so it can't surface as an unhandled
- // rejection — the caller attaches its own `.catch` to the returned promise.
- const evict = () => { if (attachTails.get(ingredientId) === next) attachTails.delete(ingredientId); };
- next.then(evict, evict);
- return next;
-}
+// fine — the whole hook is best-effort. (Shared per-key queue — writers-room +
+// music-video scene-image hooks use the same primitive.)
+const serializePerIngredient = createKeyCachedQueue();
let completedHandler = null;
@@ -125,6 +114,6 @@ export const __testing = {
mediaJobEvents.off('completed', completedHandler);
completedHandler = null;
}
- attachTails.clear();
+ serializePerIngredient.clear();
},
};
diff --git a/server/services/writersRoomSceneImageHook.js b/server/services/writersRoomSceneImageHook.js
index ed315c08d6..06dc120d15 100644
--- a/server/services/writersRoomSceneImageHook.js
+++ b/server/services/writersRoomSceneImageHook.js
@@ -26,28 +26,16 @@
import { mediaJobEvents } from './mediaJobQueue/index.js';
import { persistSceneImage } from './writersRoom/evaluator.js';
import { writersRoomEvents } from './writersRoomEvents.js';
+import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
// Serialize attaches per analysis FILE (workId:analysisId). Two scene renders
// for the same analysis completing close together would otherwise both
// load→modify→save the one `sceneImages` map and the later write would clobber
// the earlier scene's entry. Chaining each attach onto the prior one for that
// analysis makes the later job merge against the freshest persisted snapshot.
-// Different analyses (and different works) still attach concurrently. In-memory
-// tail, evicted once settled; lost on restart, which is fine — best-effort.
-const attachTails = new Map();
-
-function serializePerAnalysis(key, work) {
- const prev = attachTails.get(key) || Promise.resolve();
- // Run `work` on both fulfil AND reject so a prior failure doesn't stall the chain.
- const next = prev.then(work, work);
- attachTails.set(key, next);
- // Evict once settled, but only if nothing newer has chained on. Swallow here
- // so eviction can't surface as an unhandled rejection — the caller attaches
- // its own `.catch` to the returned promise.
- const evict = () => { if (attachTails.get(key) === next) attachTails.delete(key); };
- next.then(evict, evict);
- return next;
-}
+// Different analyses (and different works) still attach concurrently. (Shared
+// per-key queue — catalog + music-video scene-image hooks use the same primitive.)
+const serializePerAnalysis = createKeyCachedQueue();
let completedHandler = null;
@@ -113,6 +101,6 @@ export const __testing = {
mediaJobEvents.off('completed', completedHandler);
completedHandler = null;
}
- attachTails.clear();
+ serializePerAnalysis.clear();
},
};