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

feat([sharing-inbox-orphans-on-peer-instance-id-rotation]): cull rotation-orphan inbox rows on import

[._.]/ Adam Eivy379e14e5d46c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 326985bdfc..66bca80d7c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -23,6 +23,7 @@
### Sharing
- **Per-sender subscription filenames.** `subscriptionFilename()` now includes the sender's instance id in the bucket-side filename (`sub-<kind>-<recordId>-<senderInstanceId>.json`) so two peers subscribed to the same series/universe don't clobber each other's deterministic share files. Inbox dedup keys on `(recordKind, recordId, senderInstanceId)` so a peer's update no longer wipes the other peer's inbox row. `unsubscribe` best-effort cleans up the pre-v2 sender-less filename when its `senderInstanceId` matches this instance, leaving any other peer's pre-upgrade file intact. New `legacySubscriptionFilename` export for the legacy name. Touched `server/services/sharing/{manifest,subscriptions,importer,exporter}.js` + tests.
+- **Rotation-orphan inbox cull.** Per-sender inbox dedup means a peer that rotates its `instanceId` (factory reset / new device) would otherwise leave its old identity's row stranded forever. `applyInbox` now culls cross-sender orphans on every subscription-manifest arrival when (a) same `(recordKind, recordId, source)`, (b) different `senderInstanceId`, (c) existing row older than 30 days. The conservative window keeps two legitimately distinct peers with the same display name from being incorrectly culled. 3 new integration tests cover the cull/preserve cases.
## Changed
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index 33b4c98fa2..3643198b19 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -426,6 +426,16 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
const INBOX_MAX = 1000;
+/** Time window after which an inbox row with the same `(recordKind, recordId,
+ * source)` but a DIFFERENT `senderInstanceId` is treated as a rotation
+ * orphan and culled. Post-sharing-v2 the inbox dedup keys on senderInstanceId,
+ * so a peer that rotates its identity (factory reset / new device) re-shares
+ * with a fresh id and the old row never re-matches — without this cull, the
+ * stale row would persist forever as an "active" subscription. 30 days is
+ * conservative; legitimate same-source-different-peer rows (e.g. two devices
+ * both named "MacBook") would only be culled after a month of no updates. */
+const ROTATION_CULL_MS = 30 * 24 * 60 * 60 * 1000;
+
/**
* Inbox mode: write the manifest + record refs to the bucket's inbox for review.
*
@@ -435,6 +445,11 @@ const INBOX_MAX = 1000;
* snapshot. Two peers sharing the same record produce two distinct inbox rows
* (the per-sender filenames keep them apart on disk). One-shot manifests
* dedup by manifest id.
+ *
+ * Cross-sender rotation orphans (same `source` name, same record, DIFFERENT
+ * `senderInstanceId`, row older than `ROTATION_CULL_MS`) are culled on every
+ * subscription-manifest arrival — they represent the same peer reincarnated
+ * with a fresh instance id (factory reset, new device onboarding).
*/
async function applyInbox(bucket, manifest, manifestFilename, records) {
const inbox = await readInbox(bucket.id);
@@ -442,6 +457,25 @@ async function applyInbox(bucket, manifest, manifestFilename, records) {
const sub = manifest.subscription;
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;
+ 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;
+ });
+ }
const existing = inbox.items.find((it) => it.subscription
&& it.subscription.recordKind === sub.recordKind
&& it.subscription.recordId === sub.recordId
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index b93d32384e..560afc5519 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -673,6 +673,142 @@ describe('sharing round-trip', () => {
expect(updates).toHaveLength(1);
});
+ // Rotation-orphan cull — peer reincarnates with a new senderInstanceId
+ // (factory reset, new device), and the old identity's inbox row would
+ // otherwise persist forever. Cull when same source + same record, but
+ // different senderInstanceId, AND the existing row is older than 30 days.
+ it('culls a rotation-orphan inbox row when the same source re-shares from a new senderInstanceId after 30+ days', async () => {
+ const bucket = await buckets.createBucket({ name: 'RotateBucket', path: tempBucket, mode: 'inbox' });
+ const universeBuilder = await import('../universeBuilder.js');
+ const u = await universeBuilder.createUniverse({ name: 'Shared Universe' });
+
+ // Pre-seed the inbox with a stale row from peer "Adam's old laptop"
+ // (senderInstanceId inst-OLD) — same source as the incoming manifest,
+ // same record, 60 days old.
+ const sixtyDaysAgo = new Date(Date.now() - 60 * 24 * 60 * 60 * 1000).toISOString();
+ const fs = await import('fs');
+ const inboxFile = join(tempData, 'sharing', 'inbox', `${bucket.id}.json`);
+ mkdirSync(join(tempData, 'sharing', 'inbox'), { recursive: true });
+ fs.writeFileSync(inboxFile, JSON.stringify({ items: [{
+ manifestId: 'stale-mfst',
+ manifestFilename: `sub-universe-${u.id}-inst-OLD.json`,
+ kind: 'universe',
+ subscription: { recordKind: 'universe', recordId: u.id },
+ source: 'remote-peer',
+ sourceBio: null,
+ senderInstanceId: 'inst-OLD',
+ createdAt: sixtyDaysAgo,
+ receivedAt: sixtyDaysAgo,
+ recordIds: [u.id],
+ assetCount: 0,
+ }] }));
+
+ // Now export from the SAME source name but a fresh senderInstanceId.
+ const exp = await exporter.exportUniverse(u.id, bucket.id, {
+ subscription: { recordKind: 'universe', recordId: u.id },
+ });
+ simulateRemoteSender(tempBucket, exp.filename, 'inst-NEW');
+ // The exporter stamps `source` from the bucket's display name resolver;
+ // override on disk to match the pre-seeded row's source so the cull fires.
+ const manifestPath = join(tempBucket, 'manifests', exp.filename);
+ const m = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
+ m.source = 'remote-peer';
+ fs.writeFileSync(manifestPath, JSON.stringify(m));
+
+ await importer.processManifest(bucket.id, exp.filename);
+
+ const after = await importer.listInbox(bucket.id);
+ expect(after).toHaveLength(1);
+ expect(after[0].senderInstanceId).toBe('inst-NEW');
+ expect(after[0].manifestId).not.toBe('stale-mfst');
+ });
+
+ it('preserves a same-source-different-sender row that is younger than the rotation cull window', async () => {
+ const bucket = await buckets.createBucket({ name: 'FreshSourceBucket', path: tempBucket, mode: 'inbox' });
+ const universeBuilder = await import('../universeBuilder.js');
+ const u = await universeBuilder.createUniverse({ name: 'Co-shared Universe' });
+
+ // Same source name, different senderInstanceId, only 2 days old —
+ // could plausibly be a second device of the same user (both named
+ // "MacBook") rather than a rotation orphan. Preserve it.
+ const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString();
+ const fs = await import('fs');
+ const inboxFile = join(tempData, 'sharing', 'inbox', `${bucket.id}.json`);
+ mkdirSync(join(tempData, 'sharing', 'inbox'), { recursive: true });
+ fs.writeFileSync(inboxFile, JSON.stringify({ items: [{
+ manifestId: 'fresh-other',
+ manifestFilename: `sub-universe-${u.id}-inst-OTHER.json`,
+ kind: 'universe',
+ subscription: { recordKind: 'universe', recordId: u.id },
+ source: 'shared-name',
+ sourceBio: null,
+ senderInstanceId: 'inst-OTHER',
+ createdAt: twoDaysAgo,
+ receivedAt: twoDaysAgo,
+ recordIds: [u.id],
+ assetCount: 0,
+ }] }));
+
+ const exp = await exporter.exportUniverse(u.id, bucket.id, {
+ subscription: { recordKind: 'universe', recordId: u.id },
+ });
+ simulateRemoteSender(tempBucket, exp.filename, 'inst-ME');
+ const manifestPath = join(tempBucket, 'manifests', exp.filename);
+ const m = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
+ m.source = 'shared-name';
+ fs.writeFileSync(manifestPath, JSON.stringify(m));
+
+ await importer.processManifest(bucket.id, exp.filename);
+
+ const after = await importer.listInbox(bucket.id);
+ // Both rows should remain — fresh peer + new arrival.
+ expect(after).toHaveLength(2);
+ const senders = after.map((r) => r.senderInstanceId).sort();
+ expect(senders).toEqual(['inst-ME', 'inst-OTHER']);
+ });
+
+ it('preserves a different-source row even when older than the rotation cull window', async () => {
+ const bucket = await buckets.createBucket({ name: 'OtherSourceBucket', path: tempBucket, mode: 'inbox' });
+ const universeBuilder = await import('../universeBuilder.js');
+ const u = await universeBuilder.createUniverse({ name: 'Public Universe' });
+
+ // Different source name, different senderInstanceId — definitely a
+ // different peer, regardless of age. Preserve.
+ const sixtyDaysAgo = new Date(Date.now() - 60 * 24 * 60 * 60 * 1000).toISOString();
+ const fs = await import('fs');
+ const inboxFile = join(tempData, 'sharing', 'inbox', `${bucket.id}.json`);
+ mkdirSync(join(tempData, 'sharing', 'inbox'), { recursive: true });
+ fs.writeFileSync(inboxFile, JSON.stringify({ items: [{
+ manifestId: 'different-peer',
+ manifestFilename: `sub-universe-${u.id}-inst-PEER-B.json`,
+ kind: 'universe',
+ subscription: { recordKind: 'universe', recordId: u.id },
+ source: 'peer-bob',
+ sourceBio: null,
+ senderInstanceId: 'inst-PEER-B',
+ createdAt: sixtyDaysAgo,
+ receivedAt: sixtyDaysAgo,
+ recordIds: [u.id],
+ assetCount: 0,
+ }] }));
+
+ const exp = await exporter.exportUniverse(u.id, bucket.id, {
+ subscription: { recordKind: 'universe', recordId: u.id },
+ });
+ simulateRemoteSender(tempBucket, exp.filename, 'inst-PEER-A');
+ const manifestPath = join(tempBucket, 'manifests', exp.filename);
+ const m = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
+ m.source = 'peer-alice';
+ fs.writeFileSync(manifestPath, JSON.stringify(m));
+
+ await importer.processManifest(bucket.id, exp.filename);
+
+ const after = await importer.listInbox(bucket.id);
+ expect(after).toHaveLength(2);
+ const sources = after.map((r) => r.source).sort();
+ expect(sources).toEqual(['peer-alice', 'peer-bob']);
+ });
+
it('content-addressed blob is shared when two manifests reference identical bytes under different filenames', async () => {
const bucket = await buckets.createBucket({ name: 'DedupBucket', path: tempBucket, mode: 'auto-merge' });
const fs = await import('fs');