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(sharing): one-shot heal for cursor entries stuck on absent records

Ilya Eivy42f504c91abf
diff --git a/data/migrations/009-heal-sharing-cursor-drops.js b/data/migrations/009-heal-sharing-cursor-drops.js
new file mode 100644
index 0000000000..6f67cd3785
--- /dev/null
+++ b/data/migrations/009-heal-sharing-cursor-drops.js
@@ -0,0 +1,120 @@
+/**
+ * One-shot heal for sharing cursor entries that suppressed retry of a
+ * manifest whose record JSON hadn't synced yet at first-import time.
+ *
+ * Background: a pre-fix processManifest marked every manifest as processed
+ * even when readReferencedRecords returned an empty records array (the JSON
+ * file hadn't synced into the bucket yet). The cursor entry then suppressed
+ * every future replay, silently dropping the universe/series until the user
+ * re-shared. The importer now defers markProcessed when a manifest references
+ * records that aren't present, but installs that already accumulated bad
+ * cursor entries stay stuck. This migration scans each bucket's cursor
+ * against the local record stores and forgets entries whose referenced
+ * records are absent locally AND whose manifest is still on disk — the next
+ * backlog pass will retry them through the fixed code path.
+ *
+ * Idempotent: a second run finds nothing to forget (the bad entries were
+ * already cleared, or the records have since been imported successfully).
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+
+const readJson = async (path, fallback) => {
+ const raw = await readFile(path, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) return fallback;
+ try { return JSON.parse(raw); } catch { return fallback; }
+};
+
+const writeJson = (path, value) =>
+ writeFile(path, JSON.stringify(value, null, 2) + '\n');
+
+async function loadLocalIdSets(dataDir) {
+ const universes = await readJson(join(dataDir, 'universe-builder.json'), { universes: [] });
+ const series = await readJson(join(dataDir, 'pipeline-series.json'), { series: [] });
+ const issues = await readJson(join(dataDir, 'pipeline-issues.json'), { issues: [] });
+ const media = await readJson(join(dataDir, 'media-jobs.json'), { jobs: [] });
+ return {
+ universeIds: new Set((universes.universes || []).map((u) => u?.id).filter(Boolean)),
+ seriesIds: new Set((series.series || []).map((s) => s?.id).filter(Boolean)),
+ issueIds: new Set((issues.issues || []).map((i) => i?.id).filter(Boolean)),
+ mediaIds: new Set((media.jobs || []).map((m) => m?.id).filter(Boolean)),
+ };
+}
+
+function manifestHasMissingRecord(manifest, idSets) {
+ for (const id of manifest?.recordIds || []) {
+ if (typeof id !== 'string') continue;
+ if (id.startsWith('ser-')) {
+ if (!idSets.seriesIds.has(id)) return true;
+ } else if (id.startsWith('iss-')) {
+ if (!idSets.issueIds.has(id)) return true;
+ } else if (id.startsWith('chr-') || id.startsWith('set-') || id.startsWith('obj-')) {
+ // Bible entries — never standalone records, skip.
+ continue;
+ } else {
+ // UUID-only — could be universe or media job. Present in either is fine.
+ if (!idSets.universeIds.has(id) && !idSets.mediaIds.has(id)) return true;
+ }
+ }
+ return false;
+}
+
+export async function healSharingCursorDrops({ rootDir }) {
+ const dataDir = join(rootDir, 'data');
+ const sharingDir = join(dataDir, 'sharing');
+ const bucketsPath = join(sharingDir, 'buckets.json');
+ const cursorsDir = join(sharingDir, 'cursors');
+
+ const bucketsDoc = await readJson(bucketsPath, null);
+ if (!bucketsDoc || !Array.isArray(bucketsDoc.buckets) || bucketsDoc.buckets.length === 0) {
+ console.log('📦 sharing.heal: no buckets registered — nothing to do');
+ return { totalForgotten: 0 };
+ }
+
+ const idSets = await loadLocalIdSets(dataDir);
+ let totalForgotten = 0;
+
+ for (const bucket of bucketsDoc.buckets) {
+ if (!bucket?.id || !bucket?.path) continue;
+ const cursorPath = join(cursorsDir, `${bucket.id}.json`);
+ const cursor = await readJson(cursorPath, null);
+ if (!cursor || !cursor.processedById || typeof cursor.processedById !== 'object') continue;
+
+ const manifestsDir = join(bucket.path, 'manifests');
+ const forgotten = [];
+ for (const filename of Object.keys(cursor.processedById)) {
+ const manifestPath = join(manifestsDir, filename);
+ // Peer unshared the record (file gone) — leave the cursor alone so we
+ // don't churn forgetting + re-noticing the same unlink.
+ if (!existsSync(manifestPath)) continue;
+ const manifest = await readJson(manifestPath, null);
+ if (!manifest) continue;
+ if (manifestHasMissingRecord(manifest, idSets)) {
+ forgotten.push(filename);
+ }
+ }
+
+ if (forgotten.length === 0) continue;
+ for (const f of forgotten) delete cursor.processedById[f];
+ cursor.lastProcessedAt = new Date().toISOString();
+ await writeJson(cursorPath, cursor);
+ totalForgotten += forgotten.length;
+ console.log(`🧹 sharing.heal: bucket=${bucket.name || bucket.id} forgot ${forgotten.length} cursor entr${forgotten.length === 1 ? 'y' : 'ies'} pointing at absent records`);
+ }
+
+ if (totalForgotten === 0) {
+ console.log('✅ sharing.heal: no stuck cursor entries found');
+ } else {
+ console.log(`✅ sharing.heal: total ${totalForgotten} entr${totalForgotten === 1 ? 'y' : 'ies'} cleared — next watcher pass will retry`);
+ }
+ return { totalForgotten };
+}
+
+export default {
+ up: healSharingCursorDrops,
+};
diff --git a/server/services/sharing/healCursorMigration.test.js b/server/services/sharing/healCursorMigration.test.js
new file mode 100644
index 0000000000..f64f87dd23
--- /dev/null
+++ b/server/services/sharing/healCursorMigration.test.js
@@ -0,0 +1,141 @@
+/**
+ * Tests for `data/migrations/009-heal-sharing-cursor-drops.js` — the
+ * one-shot heal that clears sharing cursor entries whose manifests are
+ * still on disk but whose records never got inserted locally.
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import { healSharingCursorDrops } from '../../../data/migrations/009-heal-sharing-cursor-drops.js';
+
+const writeJson = (path, value) =>
+ writeFileSync(path, JSON.stringify(value, null, 2) + '\n');
+
+describe('healSharingCursorDrops migration', () => {
+ let rootDir;
+ let dataDir;
+ let bucketPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'portos-heal-migration-root-'));
+ dataDir = join(rootDir, 'data');
+ bucketPath = mkdtempSync(join(tmpdir(), 'portos-heal-migration-bucket-'));
+ mkdirSync(join(dataDir, 'sharing', 'cursors'), { recursive: true });
+ mkdirSync(join(bucketPath, 'manifests'), { recursive: true });
+ });
+
+ afterEach(() => {
+ if (rootDir) rmSync(rootDir, { recursive: true, force: true });
+ if (bucketPath) rmSync(bucketPath, { recursive: true, force: true });
+ });
+
+ function registerBucket(id, name) {
+ writeJson(join(dataDir, 'sharing', 'buckets.json'), {
+ buckets: [{ id, name, path: bucketPath, mode: 'auto-merge' }],
+ });
+ }
+
+ function writeManifest(filename, recordIds, manifestId = 'mfst-test') {
+ writeJson(join(bucketPath, 'manifests', filename), {
+ id: manifestId, kind: 'universe', recordIds, assetRefs: [],
+ });
+ }
+
+ function writeCursor(bucketId, processedById, extra = {}) {
+ writeJson(join(dataDir, 'sharing', 'cursors', `${bucketId}.json`), {
+ processedById, processed: [], lastProcessedAt: null, ...extra,
+ });
+ }
+
+ function readCursor(bucketId) {
+ return JSON.parse(readFileSync(join(dataDir, 'sharing', 'cursors', `${bucketId}.json`), 'utf-8'));
+ }
+
+ it('forgets cursor entries whose universe record is absent locally', async () => {
+ registerBucket('bkt-1', 'TestBucket');
+ writeManifest('sub-universe-uuid-stuck.json', ['uuid-stuck'], 'mfst-stuck');
+ writeCursor('bkt-1', { 'sub-universe-uuid-stuck.json': 'mfst-stuck' });
+ // universe-builder.json absent → uuid-stuck not in any local set.
+
+ const result = await healSharingCursorDrops({ rootDir });
+ expect(result.totalForgotten).toBe(1);
+ const cursor = readCursor('bkt-1');
+ expect(cursor.processedById).toEqual({});
+ expect(cursor.lastProcessedAt).toBeTruthy();
+ });
+
+ it('keeps cursor entries when every referenced record is present locally', async () => {
+ registerBucket('bkt-1', 'TestBucket');
+ writeManifest('sub-universe-uuid-ok.json', ['uuid-ok'], 'mfst-ok');
+ writeJson(join(dataDir, 'universe-builder.json'), {
+ universes: [{ id: 'uuid-ok', name: 'OK Universe' }],
+ });
+ writeCursor('bkt-1', { 'sub-universe-uuid-ok.json': 'mfst-ok' });
+
+ const result = await healSharingCursorDrops({ rootDir });
+ expect(result.totalForgotten).toBe(0);
+ const cursor = readCursor('bkt-1');
+ expect(cursor.processedById).toEqual({ 'sub-universe-uuid-ok.json': 'mfst-ok' });
+ });
+
+ it('leaves cursor alone when manifest is gone from the bucket (peer unshared)', async () => {
+ registerBucket('bkt-1', 'TestBucket');
+ // No manifest file on disk — peer unshared.
+ writeCursor('bkt-1', { 'sub-universe-uuid-gone.json': 'mfst-gone' });
+
+ const result = await healSharingCursorDrops({ rootDir });
+ expect(result.totalForgotten).toBe(0);
+ expect(readCursor('bkt-1').processedById).toEqual({ 'sub-universe-uuid-gone.json': 'mfst-gone' });
+ });
+
+ it('treats series + issue + universe (UUID) recordIds correctly', async () => {
+ registerBucket('bkt-1', 'TestBucket');
+ writeManifest('sub-series-ser-known.json',
+ ['ser-known', 'iss-known', 'uuid-known'], 'mfst-mixed-present');
+ writeManifest('sub-series-ser-partial.json',
+ ['ser-known', 'iss-missing'], 'mfst-mixed-partial');
+ writeJson(join(dataDir, 'pipeline-series.json'), { series: [{ id: 'ser-known' }] });
+ writeJson(join(dataDir, 'pipeline-issues.json'), { issues: [{ id: 'iss-known' }] });
+ writeJson(join(dataDir, 'universe-builder.json'), { universes: [{ id: 'uuid-known' }] });
+ writeCursor('bkt-1', {
+ 'sub-series-ser-known.json': 'mfst-mixed-present',
+ 'sub-series-ser-partial.json': 'mfst-mixed-partial',
+ });
+
+ const result = await healSharingCursorDrops({ rootDir });
+ expect(result.totalForgotten).toBe(1);
+ const cursor = readCursor('bkt-1');
+ expect(cursor.processedById).toEqual({ 'sub-series-ser-known.json': 'mfst-mixed-present' });
+ });
+
+ it('accepts UUID records that resolve via media-jobs instead of universes', async () => {
+ registerBucket('bkt-1', 'TestBucket');
+ writeManifest('sub-media-uuid-job.json', ['uuid-mediajob'], 'mfst-media');
+ writeJson(join(dataDir, 'media-jobs.json'), { jobs: [{ id: 'uuid-mediajob' }] });
+ writeCursor('bkt-1', { 'sub-media-uuid-job.json': 'mfst-media' });
+
+ const result = await healSharingCursorDrops({ rootDir });
+ expect(result.totalForgotten).toBe(0);
+ });
+
+ it('is idempotent on second run', async () => {
+ registerBucket('bkt-1', 'TestBucket');
+ writeManifest('sub-universe-uuid-stuck.json', ['uuid-stuck'], 'mfst-stuck');
+ writeCursor('bkt-1', { 'sub-universe-uuid-stuck.json': 'mfst-stuck' });
+
+ const first = await healSharingCursorDrops({ rootDir });
+ expect(first.totalForgotten).toBe(1);
+ const second = await healSharingCursorDrops({ rootDir });
+ expect(second.totalForgotten).toBe(0);
+ });
+
+ it('no-ops on installs with no sharing buckets registered', async () => {
+ // No buckets.json file at all.
+ const result = await healSharingCursorDrops({ rootDir });
+ expect(result.totalForgotten).toBe(0);
+ expect(existsSync(join(dataDir, 'sharing', 'cursors'))).toBe(true);
+ });
+});