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(peer-sync): importer reads tombstoned records with includeDeleted so they stop mis-reporting as missingUniverse
Adam Eivy09a0101f6075
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex add874b134..a7ca26c741 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -94,10 +94,16 @@ async function mergeCollectionPayload(payload, availableAssetKeys = null) {// merge applies as soon as the owner record lands.let collection;if (payload.universeId) {- const localUniverse = await getUniverse(payload.universeId).catch(() => null);+ const localUniverse = await getUniverse(payload.universeId, { includeDeleted: true }).catch(() => null);if (!localUniverse) {return { itemsAdded: 0, itemsDeferred: payload.items.length, missingUniverse: true };}+ if (localUniverse.deleted) {+ // Universe exists on disk but is tombstoned — not a transient missing-record+ // situation. Return a distinct sentinel (the universe id) so the caller does+ // NOT loop pending forever (the bug: tombstone looks like missing → never resolves).+ return { itemsAdded: 0, itemsDeferred: payload.items.length, tombstonedUniverse: localUniverse.id };+ }// Use the LOCAL owner's name (authoritative for the linked collection's// locked name) over the manifest's `payload.name`. A peer exporting a// stale or tampered collection payload must not be able to mint a@@ -129,13 +135,19 @@ async function mergeCollectionPayload(payload, availableAssetKeys = null) {// Minting a fresh seriesId-stamped collection here would leave a// rename-locked stale per-series bucket attached to a linked series.if (localSeries.universeId) {- const localUniverse = await getUniverse(localSeries.universeId).catch(() => null);+ const localUniverse = await getUniverse(localSeries.universeId, { includeDeleted: true }).catch(() => null);if (!localUniverse) {// Dangling universe link — defer so a later sync of the universe// record unblocks the merge under the universe contract. Treat as// missingSeries (same defer semantics) so the manifest stays pending.return { itemsAdded: 0, itemsDeferred: payload.items.length, missingSeries: true };}+ if (localUniverse.deleted) {+ // Universe is tombstoned — same as the direct-universeId tombstone case.+ // Return the universe id so the caller can surface it without needing to+ // re-resolve the series→universe link.+ return { itemsAdded: 0, itemsDeferred: payload.items.length, tombstonedUniverse: localUniverse.id };+ }collection = await findOrCreateUniverseCollection({universeId: localUniverse.id,universeName: localUniverse.name,@@ -521,6 +533,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =let itemsDeferred = 0;let collectionPendingUniverse = null;let collectionPendingSeries = null;+ let collectionTombstonedUniverse = null;if (manifest.collection) {// Suppress re-export of the owner record while the collection items// land — the items themselves drive recordEvents, which would loop@@ -540,6 +553,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =// later (independent) sync.if (r.missingUniverse) collectionPendingUniverse = manifest.collection.universeId;if (r.missingSeries) collectionPendingSeries = manifest.collection.seriesId;+ if (r.tombstonedUniverse) collectionTombstonedUniverse = r.tombstonedUniverse;}let adoptedSubscription = null;@@ -560,6 +574,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =collectionItemsDeferred: itemsDeferred,collectionPendingUniverse,collectionPendingSeries,+ collectionTombstonedUniverse,legacyCanonPendingUniverses: legacyCanonPendingUniverses.length > 0 ? legacyCanonPendingUniverses : null,legacyCanonPendingFailures: legacyCanonPendingFailures.length > 0 ? legacyCanonPendingFailures : null,adoptedSubscription: adoptedSubscription@@ -814,8 +829,19 @@ export async function processManifest(bucketId, manifestFilename) {// `recordIds`.const collectionPendingUniverse = outcome?.collectionPendingUniverse || null;const collectionPendingSeries = outcome?.collectionPendingSeries || null;+ const collectionTombstonedUniverse = outcome?.collectionTombstonedUniverse || null;const legacyCanonPendingUniverses = outcome?.legacyCanonPendingUniverses || null;const legacyCanonPendingFailures = outcome?.legacyCanonPendingFailures || null;+ // Tombstoned universe: the collection owner IS on disk but locally deleted.+ // Unlike the truly-missing case this will never self-resolve via sync, so we+ // advance the cursor (no infinite pending loop) and emit a clear signal. The+ // user must restore the deleted universe to import the N deferred items.+ if (collectionTombstonedUniverse) {+ await markProcessed(bucketId, manifestFilename, manifest.id);+ sharingEvents.emit('manifest-processed', { bucketId, manifestId: manifest.id, manifestFilename, outcome });+ console.log(`⚠️ sharing: bucket=${bucket.name} manifest=${manifest.id} kind=${manifest.kind} collectionUniverse=${collectionTombstonedUniverse} is deleted locally — ${outcome.collectionItemsDeferred ?? 0} item(s) skipped; restore universe to import`);+ return { processed: true, manifest, outcome };+ }if (assetCopy.missing.length > 0 || missingRecords.length > 0 || collectionPendingUniverse || collectionPendingSeries || legacyCanonPendingUniverses || legacyCanonPendingFailures) {if (assetCopy.missing.length > 0) outcome.pendingAssets = assetCopy.missing;if (missingRecords.length > 0) outcome.pendingRecords = missingRecords;@@ -941,6 +967,12 @@ export async function promoteInboxItem(bucketId, manifestId) {// present locally yet, throw a pending error instead of silently// dropping the inbox item. Otherwise the user's "promote" click// would consume the inbox row while the collection items never landed.+ if (outcome.collectionTombstonedUniverse) {+ throw Object.assign(new Error(`Universe ${outcome.collectionTombstonedUniverse} was deleted locally; restore it to import ${outcome.collectionItemsDeferred ?? 0} collection item(s)`), {+ code: 'SHARING_UNIVERSE_TOMBSTONED',+ collectionTombstonedUniverse: outcome.collectionTombstonedUniverse,+ });+ }if (outcome.collectionPendingUniverse) {throw Object.assign(new Error(`Collection payload waiting on universe ${outcome.collectionPendingUniverse} to be imported first`), {code: 'SHARING_UNIVERSE_PENDING',diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex 45d6d11401..f2ddb7a316 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -1592,6 +1592,166 @@ describe('sharing round-trip', () => {expect(restoredUni.characters.map((c) => c.name)).toContain('Ghost');});+ it('tombstoned collection universe: manifest advances cursor with collectionTombstonedUniverse (not pending forever)', async () => {+ // Regression: before the fix, getUniverse(id) on a tombstoned record threw+ // ERR_NOT_FOUND (same as absent), which resolved to null via .catch(()=>null),+ // returning { missingUniverse: true }. The manifest stayed pending indefinitely+ // because the universe IS on disk — just soft-deleted. The fix uses+ // includeDeleted:true to distinguish tombstoned from truly absent, and+ // advances the cursor immediately with a clear collectionTombstonedUniverse signal.+ const { hasBeenProcessed, readCursor } = await import('./manifest.js');+ const bucket = await buckets.createBucket({ name: 'TombstonedUniBucket', path: tempBucket, mode: 'auto-merge' });++ // Create a universe, then delete it — leaves a tombstone on disk.+ const uni = await universeSvc.createUniverse({ name: 'Deleted Universe' });+ await universeSvc.deleteUniverse(uni.id);+ // Confirm it's tombstoned (not truly absent).+ const tombstoned = await universeSvc.getUniverse(uni.id, { includeDeleted: true });+ expect(tombstoned.deleted).toBe(true);++ // Hand-write a collection-only manifest that references the tombstoned universe.+ mkdirSync(join(tempBucket, 'manifests'), { recursive: true });+ const collectionManifest = {+ id: 'mfst-tombstoned-uni-collection',+ schemaVersion: 1,+ sharingSchemaVersion: 1,+ producedByVersion: '1.0.0',+ createdAt: new Date().toISOString(),+ kind: 'universe',+ senderInstanceId: 'tombstone-peer',+ source: 'Tombstone Peer',+ sourceBio: null,+ bucketId: bucket.id,+ bucketName: bucket.name,+ recordIds: [],+ assetRefs: [],+ collection: {+ universeId: uni.id,+ name: `Universe: Deleted Universe`,+ description: '',+ items: [+ { kind: 'image', ref: 'fakeasset.png' },+ { kind: 'image', ref: 'other.png' },+ ],+ },+ note: null,+ };+ const filename = `2026-05-01T00-00-00-000Z-tombstone-peer-${collectionManifest.id}.json`;+ writeFileSync(join(tempBucket, 'manifests', filename), JSON.stringify(collectionManifest));++ const result = await importer.processManifest(bucket.id, filename);++ // Must be processed (cursor advanced), NOT stuck pending.+ expect(result.processed).toBe(true);+ expect(result.pending).toBeFalsy();+ // Outcome carries the distinct tombstoned sentinel, not missingUniverse.+ expect(result.outcome.collectionTombstonedUniverse).toBe(uni.id);+ // Cursor was advanced — a replay is a no-op (not re-attempted endlessly).+ const cursor = await readCursor(bucket.id);+ expect(hasBeenProcessed(cursor, filename, collectionManifest.id)).toBe(true);+ });++ it('tombstoned collection universe via series link: manifest advances cursor (not pending)', async () => {+ // Same fix applied to the series→universe re-route path: when a local series+ // links to a tombstoned universe, the importer must NOT return missingSeries+ // (which would loop pending forever). It returns tombstonedUniverse and the+ // manifest cursor advances.+ const { hasBeenProcessed, readCursor } = await import('./manifest.js');+ const bucket = await buckets.createBucket({ name: 'TombstonedUniViaSeriesBucket', path: tempBucket, mode: 'auto-merge' });++ // Create universe + linked series, then delete the universe.+ const uni = await universeSvc.createUniverse({ name: 'Gone Universe' });+ const s = await series.createSeries({ name: 'Linked Series', logline: 'x', universeId: uni.id });+ await universeSvc.deleteUniverse(uni.id);++ // Hand-write a collection manifest referencing the series id (the exporter+ // normally resolves series→universe, but a legacy peer may emit seriesId).+ mkdirSync(join(tempBucket, 'manifests'), { recursive: true });+ const collectionManifest = {+ id: 'mfst-tombstoned-uni-via-series',+ schemaVersion: 1,+ sharingSchemaVersion: 1,+ producedByVersion: '1.0.0',+ createdAt: new Date().toISOString(),+ kind: 'series',+ senderInstanceId: 'tombstone-via-series-peer',+ source: 'Tombstone Via Series Peer',+ sourceBio: null,+ bucketId: bucket.id,+ bucketName: bucket.name,+ recordIds: [],+ assetRefs: [],+ collection: {+ seriesId: s.id,+ name: `Series: Linked Series`,+ description: '',+ items: [{ kind: 'image', ref: 'fakeasset.png' }],+ },+ note: null,+ };+ const filename = `2026-05-01T00-00-00-000Z-tombstone-via-series-peer-${collectionManifest.id}.json`;+ writeFileSync(join(tempBucket, 'manifests', filename), JSON.stringify(collectionManifest));++ const result = await importer.processManifest(bucket.id, filename);++ // Cursor must advance — no infinite pending loop.+ expect(result.processed).toBe(true);+ expect(result.pending).toBeFalsy();+ expect(result.outcome.collectionTombstonedUniverse).toBe(uni.id);+ const cursor = await readCursor(bucket.id);+ expect(hasBeenProcessed(cursor, filename, collectionManifest.id)).toBe(true);+ });++ it('promoteInboxItem throws SHARING_UNIVERSE_TOMBSTONED when collection universe is deleted locally', async () => {+ const bucket = await buckets.createBucket({ name: 'TombstonedUniInboxBucket', path: tempBucket, mode: 'inbox' });++ // Create universe, export a collection manifest, then delete the universe.+ const uni = await universeSvc.createUniverse({ name: 'Soon Deleted Universe' });+ mkdirSync(join(tempBucket, 'manifests'), { recursive: true });+ mkdirSync(join(tempBucket, 'records'), { recursive: true });+ const collectionManifest = {+ id: 'mfst-tombstone-promote',+ schemaVersion: 1,+ sharingSchemaVersion: 1,+ producedByVersion: '1.0.0',+ createdAt: new Date().toISOString(),+ kind: 'universe',+ senderInstanceId: 'tombstone-inbox-peer',+ source: 'Tombstone Inbox Peer',+ sourceBio: null,+ bucketId: bucket.id,+ bucketName: bucket.name,+ recordIds: [],+ assetRefs: [],+ collection: {+ universeId: uni.id,+ name: `Universe: Soon Deleted Universe`,+ description: '',+ items: [],+ },+ note: null,+ };+ const filename = `2026-05-01T00-00-00-000Z-tombstone-inbox-peer-${collectionManifest.id}.json`;+ writeFileSync(join(tempBucket, 'manifests', filename), JSON.stringify(collectionManifest));++ // First import into inbox while universe is live.+ const result = await importer.processManifest(bucket.id, filename);+ expect(result.processed).toBe(true);+ expect(result.outcome.queued).toBe(true);++ // Now delete the universe locally (soft-delete / tombstone).+ await universeSvc.deleteUniverse(uni.id);++ // Attempt to promote — must throw with the distinct tombstoned code.+ const promoteErr = await importer.promoteInboxItem(bucket.id, collectionManifest.id).catch((e) => e);+ expect(promoteErr).toBeInstanceOf(Error);+ expect(promoteErr.code).toBe('SHARING_UNIVERSE_TOMBSTONED');+ expect(promoteErr.collectionTombstonedUniverse).toBe(uni.id);+ // Inbox item must NOT be consumed — user can retry after restoring the universe.+ const inbox = await importer.listInbox(bucket.id);+ expect(inbox.some((it) => it.manifestId === collectionManifest.id)).toBe(true);+ });+it('refuses a manifest with a sharingSchemaVersion newer than local + emits incompatible event', async () => {const { SHARING_SCHEMA_VERSION } = await import('./version.js');const { sharingEvents } = await import('./importer.js');