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
fix: preserve share subscriptions and inbox rows during overlapping updates (#6776)
[._.]/ Adam Eivyb64b85dbce18
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex e3c23f0ff2..8d0ffa288d 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -1,3 +1,4 @@+import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';/*** Share Bucket — importer.*@@ -60,6 +61,8 @@ function isSelfAuthored(senderInstanceId, localInstanceId) {export const sharingEvents = new EventEmitter();+const queueInboxWrite = createKeyCachedQueue();+const inboxPath = (bucketId) => join(PATHS.data, 'sharing', 'inbox', `${bucketId}.json`);async function readInbox(bucketId) {@@ -829,83 +832,85 @@ const ROTATION_CULL_MS = 30 * 24 * 60 * 60 * 1000;* with a fresh instance id (factory reset, new device onboarding).*/async function applyInbox(bucket, manifest, manifestFilename, records) {- const inbox = await readInbox(bucket.id);- inbox.items = Array.isArray(inbox.items) ? inbox.items : [];- const sub = manifest.subscription;- // Tracks whether the rotation-orphan cull (or any other pre-write mutation)- // changed `inbox.items` so early-return paths below can still persist the- // pruned list. Without this, a cull followed by an `inbox-has-newer` /- // `already-in-inbox` short-circuit would silently drop the cull removals- // and the orphan rows would survive until the next non-stale arrival.- let inboxMutatedPreWrite = false;- if (sub?.recordKind && sub?.recordId) {- const senderId = manifest.senderInstanceId || null;- const incomingSource = manifest.source || null;- // Cull cross-sender rotation orphans first so the same-sender match- // below operates on the cleaned-up list. Skip when source is missing- // — a row with no display name can't be attributed to a peer identity.- if (incomingSource) {- const cullThresholdMs = Date.now() - ROTATION_CULL_MS;- const beforeLen = inbox.items.length;- inbox.items = inbox.items.filter((it) => {- if (!it.subscription) return true;- if (it.subscription.recordKind !== sub.recordKind) return true;- if (it.subscription.recordId !== sub.recordId) return true;- if (it.source !== incomingSource) return true;- if ((it.senderInstanceId || null) === senderId) return true;- const createdMs = it.createdAt ? Date.parse(it.createdAt) : NaN;- if (!Number.isFinite(createdMs)) return true;- if (createdMs >= cullThresholdMs) return true;- console.log(`🧹 sharing: bucket=${bucket.name} culled rotation-orphan inbox row source="${incomingSource}" recordKind=${sub.recordKind} recordId=${sub.recordId} oldSender=${it.senderInstanceId || 'null'} newSender=${senderId || 'null'}`);- return false;- });- if (inbox.items.length !== beforeLen) inboxMutatedPreWrite = true;- }- const existing = inbox.items.find((it) => it.subscription- && it.subscription.recordKind === sub.recordKind- && it.subscription.recordId === sub.recordId- && (it.senderInstanceId || null) === senderId);- // Freshness gate: during upgrade a bucket may hold both the new- // `sub-<kind>-<id>-<sender>.json` and the pre-v2 legacy- // `sub-<kind>-<id>.json` for the same sender, and lexicographic- // backlog order visits the new file before the legacy one- // (`-` (0x2D) < `.` (0x2E)). Without a createdAt compare, the- // older legacy manifest would replace the newer inbox row. Skip- // when the incoming manifest is older than what we already have.- if (existing && existing.createdAt && manifest.createdAt- && existing.createdAt > manifest.createdAt) {+ return queueInboxWrite(bucket.id, async () => {+ const inbox = await readInbox(bucket.id);+ inbox.items = Array.isArray(inbox.items) ? inbox.items : [];+ const sub = manifest.subscription;+ // Tracks whether the rotation-orphan cull (or any other pre-write mutation)+ // changed `inbox.items` so early-return paths below can still persist the+ // pruned list. Without this, a cull followed by an `inbox-has-newer` /+ // `already-in-inbox` short-circuit would silently drop the cull removals+ // and the orphan rows would survive until the next non-stale arrival.+ let inboxMutatedPreWrite = false;+ if (sub?.recordKind && sub?.recordId) {+ const senderId = manifest.senderInstanceId || null;+ const incomingSource = manifest.source || null;+ // Cull cross-sender rotation orphans first so the same-sender match+ // below operates on the cleaned-up list. Skip when source is missing+ // — a row with no display name can't be attributed to a peer identity.+ if (incomingSource) {+ const cullThresholdMs = Date.now() - ROTATION_CULL_MS;+ const beforeLen = inbox.items.length;+ inbox.items = inbox.items.filter((it) => {+ if (!it.subscription) return true;+ if (it.subscription.recordKind !== sub.recordKind) return true;+ if (it.subscription.recordId !== sub.recordId) return true;+ if (it.source !== incomingSource) return true;+ if ((it.senderInstanceId || null) === senderId) return true;+ const createdMs = it.createdAt ? Date.parse(it.createdAt) : NaN;+ if (!Number.isFinite(createdMs)) return true;+ if (createdMs >= cullThresholdMs) return true;+ console.log(`🧹 sharing: bucket=${bucket.name} culled rotation-orphan inbox row source="${incomingSource}" recordKind=${sub.recordKind} recordId=${sub.recordId} oldSender=${it.senderInstanceId || 'null'} newSender=${senderId || 'null'}`);+ return false;+ });+ if (inbox.items.length !== beforeLen) inboxMutatedPreWrite = true;+ }+ const existing = inbox.items.find((it) => it.subscription+ && it.subscription.recordKind === sub.recordKind+ && it.subscription.recordId === sub.recordId+ && (it.senderInstanceId || null) === senderId);+ // Freshness gate: during upgrade a bucket may hold both the new+ // `sub-<kind>-<id>-<sender>.json` and the pre-v2 legacy+ // `sub-<kind>-<id>.json` for the same sender, and lexicographic+ // backlog order visits the new file before the legacy one+ // (`-` (0x2D) < `.` (0x2E)). Without a createdAt compare, the+ // older legacy manifest would replace the newer inbox row. Skip+ // when the incoming manifest is older than what we already have.+ if (existing && existing.createdAt && manifest.createdAt+ && existing.createdAt > manifest.createdAt) {+ if (inboxMutatedPreWrite) await writeInbox(bucket.id, inbox);+ return { queued: false, reason: 'inbox-has-newer' };+ }+ if (existing) {+ inbox.items = inbox.items.filter((it) => it !== existing);+ }+ } else if (inbox.items.some((it) => it.manifestId === manifest.id)) {if (inboxMutatedPreWrite) await writeInbox(bucket.id, inbox);- return { queued: false, reason: 'inbox-has-newer' };- }- if (existing) {- inbox.items = inbox.items.filter((it) => it !== existing);+ return { queued: false, reason: 'already-in-inbox' };}- } else if (inbox.items.some((it) => it.manifestId === manifest.id)) {- if (inboxMutatedPreWrite) await writeInbox(bucket.id, inbox);- return { queued: false, reason: 'already-in-inbox' };- }- inbox.items.push({- manifestId: manifest.id,- manifestFilename,- kind: manifest.kind,- subscription: sub || null,- source: manifest.source,- sourceBio: manifest.sourceBio,- senderInstanceId: manifest.senderInstanceId || null,- producedByVersion: manifest.producedByVersion || null,- sharingSchemaVersion: manifest.sharingSchemaVersion ?? manifest.schemaVersion ?? null,- createdAt: manifest.createdAt,- receivedAt: new Date().toISOString(),- recordIds: manifest.recordIds,- assetCount: (manifest.assetRefs || []).length,- collectionItemCount: manifest.collection?.items?.length || 0,- collectionName: manifest.collection?.name || null,- note: manifest.note,- summary: summarizeRecords(records),+ inbox.items.push({+ manifestId: manifest.id,+ manifestFilename,+ kind: manifest.kind,+ subscription: sub || null,+ source: manifest.source,+ sourceBio: manifest.sourceBio,+ senderInstanceId: manifest.senderInstanceId || null,+ producedByVersion: manifest.producedByVersion || null,+ sharingSchemaVersion: manifest.sharingSchemaVersion ?? manifest.schemaVersion ?? null,+ createdAt: manifest.createdAt,+ receivedAt: new Date().toISOString(),+ recordIds: manifest.recordIds,+ assetCount: (manifest.assetRefs || []).length,+ collectionItemCount: manifest.collection?.items?.length || 0,+ collectionName: manifest.collection?.name || null,+ note: manifest.note,+ summary: summarizeRecords(records),+ });+ if (inbox.items.length > INBOX_MAX) inbox.items = inbox.items.slice(-INBOX_MAX);+ await writeInbox(bucket.id, inbox);+ return { queued: true };});- if (inbox.items.length > INBOX_MAX) inbox.items = inbox.items.slice(-INBOX_MAX);- await writeInbox(bucket.id, inbox);- return { queued: true };}function summarizeRecords(records) {@@ -1113,46 +1118,48 @@ export async function processManifest(bucketId, manifestFilename) {* stranding zombie rows the user must hand-dismiss.*/async function pruneSelfAuthoredInbox(bucket, localInstanceId) {- const inbox = await readInbox(bucket.id);- const items = Array.isArray(inbox.items) ? inbox.items : [];- if (items.length === 0) return { pruned: 0, orphaned: 0 };+ return queueInboxWrite(bucket.id, async () => {+ const inbox = await readInbox(bucket.id);+ const items = Array.isArray(inbox.items) ? inbox.items : [];+ if (items.length === 0) return { pruned: 0, orphaned: 0 };- let changed = false;- let orphaned = 0;- const kept = [];- for (const it of items) {- const manifestPath = join(bucket.path, 'manifests', it.manifestFilename);- if (!existsSync(manifestPath)) {- orphaned += 1;- changed = true;- continue;- }- let sender = it.senderInstanceId || null;- let backfilled = it;- if (!sender) {- const m = await readManifest(bucket.path, it.manifestFilename).catch(() => null);- sender = m?.senderInstanceId || null;- if (sender) {- backfilled = { ...it, senderInstanceId: sender };+ let changed = false;+ let orphaned = 0;+ const kept = [];+ for (const it of items) {+ const manifestPath = join(bucket.path, 'manifests', it.manifestFilename);+ if (!existsSync(manifestPath)) {+ orphaned += 1;changed = true;+ continue;}+ let sender = it.senderInstanceId || null;+ let backfilled = it;+ if (!sender) {+ const m = await readManifest(bucket.path, it.manifestFilename).catch(() => null);+ sender = m?.senderInstanceId || null;+ if (sender) {+ backfilled = { ...it, senderInstanceId: sender };+ changed = true;+ }+ }+ if (isSelfAuthored(sender, localInstanceId)) {+ changed = true;+ continue;+ }+ kept.push(backfilled);}- if (isSelfAuthored(sender, localInstanceId)) {- changed = true;- continue;- }- kept.push(backfilled);- }- const pruned = items.length - kept.length - orphaned;- if (changed) {- inbox.items = kept;- await writeInbox(bucket.id, inbox);- if (pruned > 0 || orphaned > 0) {- sharingEvents.emit('inbox-updated', { bucketId: bucket.id });- console.log(`🧹 sharing: bucket=${bucket.name} pruned ${pruned} self-authored + ${orphaned} orphan inbox item(s)`);+ const pruned = items.length - kept.length - orphaned;+ if (changed) {+ inbox.items = kept;+ await writeInbox(bucket.id, inbox);+ if (pruned > 0 || orphaned > 0) {+ sharingEvents.emit('inbox-updated', { bucketId: bucket.id });+ console.log(`🧹 sharing: bucket=${bucket.name} pruned ${pruned} self-authored + ${orphaned} orphan inbox item(s)`);+ }}- }- return { pruned, orphaned };+ return { pruned, orphaned };+ });}/** On startup or registration, scan the manifests dir for unprocessed entries. */@@ -1280,8 +1287,13 @@ export async function promoteInboxItem(bucketId, manifestId) {});}// Drop from inbox.- inbox.items.splice(idx, 1);- await writeInbox(bucketId, inbox);+ await queueInboxWrite(bucketId, async () => {+ const live = await readInbox(bucketId);+ const liveIdx = (live.items || []).findIndex((it) => it.manifestId === manifestId);+ if (liveIdx < 0) return;+ live.items.splice(liveIdx, 1);+ await writeInbox(bucketId, live);+ });sharingEvents.emit('inbox-updated', { bucketId });return { promoted: true, outcome };}@@ -1297,31 +1309,33 @@ export async function handleUnshare(bucketId, manifestFilename) {const cursor = await readCursor(bucketId);const wasTracked = manifestFilename in (cursor.processedById || {})|| (Array.isArray(cursor.processed) && cursor.processed.includes(manifestFilename));- const inbox = await readInbox(bucketId);- const inboxHit = (inbox.items || []).some((it) => it.manifestFilename === manifestFilename);- // chokidar fires `unlink` for any file under the watched dir. If we never- // saw the filename as a manifest, treat the unlink as noise — no cursor- // write, no inbox write, no socket emit.+ const inboxHit = await queueInboxWrite(bucketId, async () => {+ const inbox = await readInbox(bucketId);+ const hit = (inbox.items || []).some((it) => it.manifestFilename === manifestFilename);+ if (hit) {+ inbox.items = inbox.items.filter((it) => it.manifestFilename !== manifestFilename);+ await writeInbox(bucketId, inbox);+ }+ return hit;+ });+ // Ignore unlink noise for files we have never imported or queued.if (!wasTracked && !inboxHit) return { handled: true, wasTracked: false };-await forgetProcessed(bucketId, manifestFilename);- if (inboxHit) {- inbox.items = inbox.items.filter((it) => it.manifestFilename !== manifestFilename);- await writeInbox(bucketId, inbox);- }sharingEvents.emit('unshared', { bucketId, manifestFilename });console.log(`📤 sharing: bucket=${bucketId} manifest=${manifestFilename} unshared by peer`);return { handled: true, wasTracked };}export async function dismissInboxItem(bucketId, manifestId) {- const inbox = await readInbox(bucketId);- const before = (inbox.items || []).length;- inbox.items = (inbox.items || []).filter((it) => it.manifestId !== manifestId);- if (inbox.items.length === before) throw Object.assign(new Error(`Inbox item not found: ${manifestId}`), { code: 'SHARING_INBOX_NOT_FOUND' });- await writeInbox(bucketId, inbox);- sharingEvents.emit('inbox-updated', { bucketId });- return { dismissed: true };+ return queueInboxWrite(bucketId, async () => {+ const inbox = await readInbox(bucketId);+ const before = (inbox.items || []).length;+ inbox.items = (inbox.items || []).filter((it) => it.manifestId !== manifestId);+ if (inbox.items.length === before) throw Object.assign(new Error(`Inbox item not found: ${manifestId}`), { code: 'SHARING_INBOX_NOT_FOUND' });+ await writeInbox(bucketId, inbox);+ sharingEvents.emit('inbox-updated', { bucketId });+ return { dismissed: true };+ });}export async function listInbox(bucketId) {diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.jsindex 11ea8c74c8..43ae392561 100644--- a/server/services/sharing/manifest.js+++ b/server/services/sharing/manifest.js@@ -18,6 +18,7 @@ import { randomUUID } from 'crypto';import { join } from 'path';import { readdir, rename } from 'fs/promises';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';+import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';import { isPlainObject } from '../../lib/objects.js';import { SHARING_SCHEMA_VERSION, getProducedByVersion } from './version.js';import { isStr } from '../../lib/storyBible.js';@@ -37,6 +38,8 @@ export function annotationManifestFilename(senderInstanceId) {/** @deprecated Use SHARING_SCHEMA_VERSION from ./version.js. Kept exported for back-compat. */export const MANIFEST_SCHEMA_VERSION = SHARING_SCHEMA_VERSION;+const queueCursorWrite = createKeyCachedQueue();+const cursorPath = (bucketId) => join(PATHS.data, 'sharing', 'cursors', `${bucketId}.json`);/**@@ -74,24 +77,26 @@ export async function writeCursor(bucketId, cursor) {* cursor at 5000 entries so a runaway peer can't grow the file unbounded.*/export async function markProcessed(bucketId, manifestFilename, manifestId = null) {- const cursor = await readCursor(bucketId);- cursor.processedById[manifestFilename] = manifestId || cursor.processedById[manifestFilename] || '';- // Drop legacy entry if it was tracked there; the map is now authoritative.- if (cursor.processed.includes(manifestFilename)) {- cursor.processed = cursor.processed.filter((f) => f !== manifestFilename);- }- const keys = Object.keys(cursor.processedById);- if (keys.length > 5000) {- // Drop the lexicographically-smallest 1000 — for timestamp-prefixed- // one-shot manifests this is the oldest entries. Subscription filenames- // (sub-…) sort after timestamp-prefixed ones, so they survive a prune- // even when the cursor is full of legacy one-shot history.- const drop = new Set(keys.sort().slice(0, keys.length - 5000));- for (const k of drop) delete cursor.processedById[k];- }- cursor.lastProcessedAt = new Date().toISOString();- await writeCursor(bucketId, cursor);- return cursor;+ return queueCursorWrite(bucketId, async () => {+ const cursor = await readCursor(bucketId);+ cursor.processedById[manifestFilename] = manifestId || cursor.processedById[manifestFilename] || '';+ // Drop legacy entry if it was tracked there; the map is now authoritative.+ if (cursor.processed.includes(manifestFilename)) {+ cursor.processed = cursor.processed.filter((f) => f !== manifestFilename);+ }+ const keys = Object.keys(cursor.processedById);+ if (keys.length > 5000) {+ // Drop the lexicographically-smallest 1000 — for timestamp-prefixed+ // one-shot manifests this is the oldest entries. Subscription filenames+ // (sub-…) sort after timestamp-prefixed ones, so they survive a prune+ // even when the cursor is full of legacy one-shot history.+ const drop = new Set(keys.sort().slice(0, keys.length - 5000));+ for (const k of drop) delete cursor.processedById[k];+ }+ cursor.lastProcessedAt = new Date().toISOString();+ await writeCursor(bucketId, cursor);+ return cursor;+ });}/**@@ -101,14 +106,16 @@ export async function markProcessed(bucketId, manifestFilename, manifestId = nul* `unlink` for arbitrary files in the watched dir, not just our manifests.*/export async function forgetProcessed(bucketId, manifestFilename) {- const cursor = await readCursor(bucketId);- const inMap = cursor.processedById && manifestFilename in cursor.processedById;- const inLegacy = cursor.processed.includes(manifestFilename);- if (!inMap && !inLegacy) return cursor;- if (inMap) delete cursor.processedById[manifestFilename];- if (inLegacy) cursor.processed = cursor.processed.filter((f) => f !== manifestFilename);- await writeCursor(bucketId, cursor);- return cursor;+ return queueCursorWrite(bucketId, async () => {+ const cursor = await readCursor(bucketId);+ const inMap = cursor.processedById && manifestFilename in cursor.processedById;+ const inLegacy = cursor.processed.includes(manifestFilename);+ if (!inMap && !inLegacy) return cursor;+ if (inMap) delete cursor.processedById[manifestFilename];+ if (inLegacy) cursor.processed = cursor.processed.filter((f) => f !== manifestFilename);+ await writeCursor(bucketId, cursor);+ return cursor;+ });}/**diff --git a/server/services/sharing/stateConcurrency.test.js b/server/services/sharing/stateConcurrency.test.jsnew file mode 100644index 0000000000..24c29c4fc9--- /dev/null+++ b/server/services/sharing/stateConcurrency.test.js@@ -0,0 +1,83 @@+import { afterAll, beforeEach, expect, it, vi } from 'vitest';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';+import { makePathsProxy, mockNoPeers, mockNoPeerSync } from '../../lib/mockPathsDataRoot.js';++const tempRoot = mkdtempSync(join(tmpdir(), 'sharing-state-concurrency-'));+const bucketPath = join(tempRoot, 'bucket');+const exportRecord = vi.fn();+vi.mock('../../lib/fileUtils.js', async () =>+ makePathsProxy(await vi.importActual('../../lib/fileUtils.js'), { dataRoot: tempRoot }));+vi.mock('./exporter.js', () => ({ exportSeries: exportRecord, exportUniverse: exportRecord }));+vi.mock('../instances.js', () => mockNoPeers({}, {+ getInstanceId: async () => 'local-instance', UNKNOWN_INSTANCE_ID: 'unknown',+}));+vi.mock('./peerSync.js', () => mockNoPeerSync());+vi.mock('../mediaJobQueue/index.js', () => ({ getJob: () => null }));++const buckets = await import('./buckets.js');+const subscriptions = await import('./subscriptions.js');+const importer = await import('./importer.js');+const manifests = await import('./manifest.js');+let bucket;++beforeEach(async () => {+ rmSync(tempRoot, { recursive: true, force: true });+ mkdirSync(bucketPath, { recursive: true });+ exportRecord.mockReset().mockResolvedValue({ manifestId: 'exported' });+ bucket = await buckets.createBucket({ name: 'Concurrent shares', path: bucketPath, mode: 'inbox' });+});+afterAll(() => {+ subscriptions.__resetForTests();+ rmSync(tempRoot, { recursive: true, force: true });+});++it('keeps an unsubscribe while another subscription finishes its slow export', async () => {+ const b = await subscriptions.subscribe({ bucketId: bucket.id, recordKind: 'universe', recordId: 'b' });+ const started = Promise.withResolvers();+ const exported = Promise.withResolvers();+ exportRecord.mockImplementationOnce(() => { started.resolve(); return exported.promise; });+ const subscribing = subscriptions.subscribe({ bucketId: bucket.id, recordKind: 'universe', recordId: 'a' });+ await started.promise;+ await subscriptions.unsubscribe(b.id);+ exported.resolve({ manifestId: 'a-export' });+ await subscribing;+ expect(await subscriptions.listSubscriptions()).toEqual([+ expect.objectContaining({ recordId: 'a', lastManifestId: 'a-export' }),+ ]);+});++it('does not restore a subscription removed during its own export', async () => {+ const started = Promise.withResolvers();+ const exported = Promise.withResolvers();+ exportRecord.mockImplementationOnce(() => { started.resolve(); return exported.promise; });+ const subscribing = subscriptions.subscribe({ bucketId: bucket.id, recordKind: 'universe', recordId: 'a' });+ await started.promise;+ const [sub] = await subscriptions.listSubscriptions();+ await subscriptions.unsubscribe(sub.id);+ exported.resolve({ manifestId: 'a-export' });+ await subscribing;+ expect(await subscriptions.listSubscriptions()).toEqual([]);+});++it('retains both concurrently received inbox manifests and their cursor entries', async () => {+ for (const id of ['a', 'b']) {+ writeFileSync(join(bucketPath, 'manifests', `${id}.json`), JSON.stringify({+ id, senderInstanceId: 'remote-instance', kind: 'universe', recordIds: [], assetRefs: [],+ }));+ }+ const outcomes = await Promise.all(['a', 'b'].map((id) => importer.processManifest(bucket.id, `${id}.json`)));+ expect(outcomes.every((result) => result.outcome.queued)).toBe(true);+ expect((await importer.listInbox(bucket.id)).map((item) => item.manifestId).sort()).toEqual(['a', 'b']);+ expect((await manifests.readCursor(bucket.id)).processedById).toEqual({ 'a.json': 'a', 'b.json': 'b' });+});++it('preserves a concurrent cursor addition when forgetting an old manifest', async () => {+ await manifests.markProcessed(bucket.id, 'old.json', 'old');+ await Promise.all([+ manifests.forgetProcessed(bucket.id, 'old.json'),+ manifests.markProcessed(bucket.id, 'new.json', 'new'),+ ]);+ expect((await manifests.readCursor(bucket.id)).processedById).toEqual({ 'new.json': 'new' });+});diff --git a/server/services/sharing/subscriptions.js b/server/services/sharing/subscriptions.jsindex 1116c5ffed..7dd57a2223 100644--- a/server/services/sharing/subscriptions.js+++ b/server/services/sharing/subscriptions.js@@ -23,6 +23,7 @@ import { join } from 'path';import { unlink } from 'fs/promises';import { existsSync } from 'fs';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';+import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';import { isStr } from '../../lib/storyBible.js';import { getBucket } from './buckets.js';import { exportSeries, exportUniverse } from './exporter.js';@@ -50,6 +51,8 @@ export const ERR_VALIDATION = 'SHARING_SUBSCRIPTION_VALIDATION';export const ERR_DUPLICATE = 'SHARING_SUBSCRIPTION_DUPLICATE';const makeErr = (message, code) => Object.assign(new Error(message), { code });+const queueStateWrite = createFileWriteQueue();+const STATE_PATH = () => join(PATHS.data, 'sharing', 'subscriptions.json');function subId({ bucketId, recordKind, recordId }) {@@ -97,29 +100,31 @@ export async function adoptImportedSubscription({ bucketId, recordKind, recordIdif (!isStr(bucketId) || !isStr(recordId)) return null;await getBucket(bucketId);- const state = await readState();- const id = subId({ bucketId, recordKind, recordId });- const now = new Date().toISOString();- let sub = state.subscriptions.find((s) => s.id === id);- if (!sub) {- sub = {- id,- bucketId,- recordKind,- recordId,- createdAt: now,- updatedAt: now,- lastManifestId,- lastExportedAt: null,- adoptedFromImport: true,- };- state.subscriptions.push(sub);- } else {- sub.updatedAt = now;- sub.lastManifestId = lastManifestId || sub.lastManifestId || null;- }- await writeState(state);- return sub;+ return queueStateWrite(async () => {+ const state = await readState();+ const id = subId({ bucketId, recordKind, recordId });+ const now = new Date().toISOString();+ let sub = state.subscriptions.find((s) => s.id === id);+ if (!sub) {+ sub = {+ id,+ bucketId,+ recordKind,+ recordId,+ createdAt: now,+ updatedAt: now,+ lastManifestId,+ lastExportedAt: null,+ adoptedFromImport: true,+ };+ state.subscriptions.push(sub);+ } else {+ sub.updatedAt = now;+ sub.lastManifestId = lastManifestId || sub.lastManifestId || null;+ }+ await writeState(state);+ return sub;+ });}/**@@ -138,23 +143,22 @@ export async function subscribe({ bucketId, recordKind, recordId }) {// Validate the bucket exists (throws ERR_NOT_FOUND otherwise).await getBucket(bucketId);- const state = await readState();const id = subId({ bucketId, recordKind, recordId });- let sub = state.subscriptions.find((s) => s.id === id);- const now = new Date().toISOString();- if (!sub) {- sub = { id, bucketId, recordKind, recordId, createdAt: now, updatedAt: now, lastManifestId: null, lastExportedAt: null };- state.subscriptions.push(sub);- await writeState(state);- }+ const sub = await queueStateWrite(async () => {+ const state = await readState();+ let live = state.subscriptions.find((s) => s.id === id);+ if (!live) {+ const now = new Date().toISOString();+ live = { id, bucketId, recordKind, recordId, createdAt: now, updatedAt: now, lastManifestId: null, lastExportedAt: null };+ state.subscriptions.push(live);+ await writeState(state);+ }+ return live;+ });+ // Export outside the state queue, then stamp only a still-live row.const exp = await runExport({ bucketId, recordKind, recordId });- if (exp) {- sub.lastManifestId = exp.manifestId;- sub.lastExportedAt = now;- sub.updatedAt = now;- await writeState(state);- }+ if (exp) return (await stampExport(sub, exp)) || sub;return sub;}@@ -168,10 +172,14 @@ async function runExport({ bucketId, recordKind, recordId }) {export async function unsubscribe(id) {if (!isStr(id)) throw makeErr('subscription id required', ERR_VALIDATION);- const state = await readState();- const idx = state.subscriptions.findIndex((s) => s.id === id);- if (idx < 0) throw makeErr(`Subscription not found: ${id}`, ERR_NOT_FOUND);- const sub = state.subscriptions[idx];+ const sub = await queueStateWrite(async () => {+ const state = await readState();+ const idx = state.subscriptions.findIndex((s) => s.id === id);+ if (idx < 0) throw makeErr(`Subscription not found: ${id}`, ERR_NOT_FOUND);+ const [removed] = state.subscriptions.splice(idx, 1);+ await writeState(state);+ return removed;+ });// Cancel any pending debounced re-export — otherwise the timer fires ~3s// later, the sub is gone, and reexportNow no-ops, but the timer + the@@ -218,8 +226,6 @@ export async function unsubscribe(id) {}}- state.subscriptions.splice(idx, 1);- await writeState(state);return { id, removed: true };}@@ -255,13 +261,20 @@ async function reexportNow(sub) {return null;});if (!exp) return;- const state = await readState();- const live = state.subscriptions.find((s) => s.id === sub.id);- if (!live) return; // unsubscribed between the trigger and the write- live.lastManifestId = exp.manifestId;- live.lastExportedAt = new Date().toISOString();- live.updatedAt = live.lastExportedAt;- await writeState(state);+ await stampExport(sub, exp);+}++function stampExport(sub, exp) {+ return queueStateWrite(async () => {+ const state = await readState();+ const live = state.subscriptions.find((s) => s.id === sub.id);+ if (!live) return null; // unsubscribed while the export was running+ live.lastManifestId = exp.manifestId;+ live.lastExportedAt = new Date().toISOString();+ live.updatedAt = live.lastExportedAt;+ await writeState(state);+ return live;+ });}export async function reexportSubscribedRecord(recordKind, recordId) {