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
feat([issue-727]): GC orphan importer shells from abandoned analyze
[._.]/ Adam Eivye75d6ba1a20f
diff --git a/server/index.js b/server/index.jsindex 95015aee1e..ce5e8140f7 100644--- a/server/index.js+++ b/server/index.js@@ -145,6 +145,7 @@ import { startBrainScheduler } from './services/brainScheduler.js';import { recoverStuckClassifications } from './services/brain.js';import { recoverStuckAnalyses } from './services/writersRoom/evaluator.js';import { recoverStuckAutoRuns } from './services/pipeline/autoRunner.js';+import { startOrphanShellGc } from './services/importerOrphanGc.js';import { initBridge as initBrainMemoryBridge } from './services/brainMemoryBridge.js';import { initDrillCache } from './services/meatspacePostDrillCache.js';import { createAIToolkit } from './lib/aiToolkit/index.js';@@ -515,6 +516,9 @@ initBrainMemoryBridge();initDrillCache().catch(err => console.error(`❌ POST drill cache init failed: ${err.message}`));// Initialize backup scheduler for daily data backupsstartBackupScheduler().catch(err => console.error(`❌ Backup scheduler init failed: ${err.message}`));+// Periodically GC orphan zero-issue/zero-canon importer shells left by an+// abandoned analyze (issue #727).+startOrphanShellGc();// Warm the catalog user-type registry from settings before any catalog request// can land, so user-defined types validate + mint ids immediately on boot.// Refresh on every settings write (the Settings → Catalog tab persists throughdiff --git a/server/services/importer.js b/server/services/importer.jsindex e39ac218f3..a7aeb9c8a5 100644--- a/server/services/importer.js+++ b/server/services/importer.js@@ -809,16 +809,24 @@ export async function analyzeImport({// failure doesn't leave an orphaned universe on disk. We only delete the// universe if we created it in this call — a pre-existing universe must// never be removed as a side-effect of a series-create failure.+ //+ // New shells are created `ephemeral` (issue #727): an analyze the user+ // abandons before commit otherwise leaves a zero-issue/zero-canon universe+ // + series lingering on disk. `ephemeral` keeps them out of every sync+ // transport and tags them for the orphan-shell GC sweep+ // (importerOrphanGc.js). `commitImport` promotes them (clears `ephemeral`)+ // so a committed import becomes a normal, syncing record. Pre-existing+ // records are never re-flagged ephemeral here.let universe = isExistingUniverse? existingUniverse- : await createUniverse({ name: universeName.trim() });+ : await createUniverse({ name: universeName.trim(), ephemeral: true });const universeWasCreated = !isExistingUniverse;let series;try {series = isExistingSeries? existingSeries- : await createSeries({ name: seriesName.trim(), universeId: universe.id });+ : await createSeries({ name: seriesName.trim(), universeId: universe.id, ephemeral: true });} catch (seriesErr) {if (universeWasCreated) {await deleteUniverse(universe.id).catch((delErr) =>@@ -1366,9 +1374,26 @@ export async function commitImport({throw partial;}+ // Promote any ephemeral shell now that the commit fully succeeded (issue+ // #727). analyzeImport creates brand-new universe/series records `ephemeral`+ // so an abandoned analyze leaves no syncing orphan; a successful commit turns+ // them into normal records. Only patch records still flagged ephemeral —+ // updateUniverse/updateSeries handle the ephemeral→non-ephemeral peer+ // re-subscribe wiring, so the clear must go through them (not a raw write).+ // Done after the issue loop so a rolled-back commit leaves the shells+ // ephemeral and still GC-eligible.+ let promotedUniverse = updatedUniverse;+ let promotedSeries = updatedSeries;+ if (updatedUniverse.ephemeral === true) {+ promotedUniverse = await updateUniverse(updatedUniverse.id, { ephemeral: false });+ }+ if (updatedSeries.ephemeral === true) {+ promotedSeries = await updateSeries(updatedSeries.id, { ephemeral: false });+ }+return {- universe: updatedUniverse,- series: updatedSeries,+ universe: promotedUniverse,+ series: promotedSeries,createdIssueIds,remappedIssues,};diff --git a/server/services/importer.test.js b/server/services/importer.test.jsindex afada15c1d..5b5b9f043c 100644--- a/server/services/importer.test.js+++ b/server/services/importer.test.js@@ -320,6 +320,10 @@ describe('analyzeImport', () => {expect(result.universe.id).toBeDefined();expect(result.series.id).toMatch(/^ser-/);expect(result.series.universeId).toBe(result.universe.id);+ // New shells are created ephemeral (issue #727) so an abandoned analyze+ // leaves no syncing orphan — the orphan-shell GC sweeps them later.+ expect(result.universe.ephemeral).toBe(true);+ expect(result.series.ephemeral).toBe(true);expect(result.canonPreview.characters).toHaveLength(1);expect(result.canonPreview.characters[0].name).toBe('Aria');expect(result.canonPreview.places).toHaveLength(1);@@ -862,6 +866,10 @@ describe('commitImport', () => {expect(result.series.logline).toBe('A reluctant heir.');expect(result.series.premise).toBe('Big story.');expect(result.series.issueCountTarget).toBe(1);+ // A successful commit promotes both shells out of ephemeral (issue #727)+ // so the now-real records sync to peers instead of staying GC-eligible.+ expect(result.universe.ephemeral).not.toBe(true);+ expect(result.series.ephemeral).not.toBe(true);// One issue created with prose + idea seeded.expect(result.createdIssueIds).toHaveLength(1);const issue = await issuesSvc.getIssue(result.createdIssueIds[0]);diff --git a/server/services/importerOrphanGc.js b/server/services/importerOrphanGc.jsnew file mode 100644index 0000000000..74411f9ebf--- /dev/null+++ b/server/services/importerOrphanGc.js@@ -0,0 +1,150 @@+/**+ * Importer Orphan-Shell GC (issue #727)+ *+ * `analyzeImport` creates a brand-new universe + series shell so the analyze+ * preview has stable ids the client can commit/retry against. When the user+ * abandons the import before committing (e.g. an issue-split failure on a+ * fresh universe/series), those shells linger on disk forever.+ *+ * The primary defense is marking analyze-created shells `ephemeral` (kept out+ * of every sync transport) and clearing the flag in `commitImport` once the+ * import lands. This sweep is the belt-and-suspenders second half: it deletes+ * shells that are STILL ephemeral, hold no committed work (zero issues,+ * zero canon entities, no arc/seasons), and are older than a grace window —+ * so an abandoned analyze self-cleans instead of accreting orphan data.+ *+ * Conservative by construction:+ * - Only `ephemeral` records are candidates. A committed import promotes both+ * records out of ephemeral, so a real universe/series is never a candidate+ * regardless of how empty it looks.+ * - A universe is only swept once its ephemeral series are gone AND it has no+ * OTHER live (non-deleted) series — so a shared universe is never removed as+ * a side-effect. `deleteUniverse` also enforces this block-until-empty rule.+ * - The age gate is measured from `updatedAt` (the most recent touch), so a+ * user mid-flight on a fresh analyze is never swept out from under them.+ *+ * Runs OUTSIDE the Express request lifecycle (a `setInterval` from index.js),+ * so this module wraps its sweep in try/catch and logs single-line per the+ * repo logging convention — an uncaught throw here would crash the process.+ */++import { listUniverses, deleteUniverse } from './universeBuilder.js';+import { listSeries, deleteSeries } from './pipeline/series.js';+import { listIssues } from './pipeline/issues.js';++// Grace window before an abandoned, never-committed shell is eligible for GC.+// Measured against `updatedAt`. Generous on purpose — the cost of an orphan+// shell lingering an extra day is trivial next to deleting work a user is+// still actively shaping.+export const ORPHAN_SHELL_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days++// How often the sweep runs once started. The shells are cheap to leave around,+// so a slow cadence is fine — daily keeps `data/` tidy without churn.+const SWEEP_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours++let sweepTimer = null;++const ageMs = (record, now) => {+ const ts = Date.parse(record?.updatedAt || record?.createdAt || '');+ return Number.isFinite(ts) ? now - ts : NaN;+};++// A universe carries no committed canon when every entity registry is empty.+const universeHasCanon = (u) =>+ (Array.isArray(u?.characters) && u.characters.length > 0)+ || (Array.isArray(u?.places) && u.places.length > 0)+ || (Array.isArray(u?.objects) && u.objects.length > 0);++// A series carries committed story work when it has an arc or any seasons.+// (Issues are checked separately via listIssues since they live in their own+// store keyed by seriesId.)+const seriesHasStoryWork = (s) =>+ (s?.arc != null) || (Array.isArray(s?.seasons) && s.seasons.length > 0);++/**+ * One GC pass. Pure-ish: takes `now` so tests can pin the clock. Returns a+ * summary `{ deletedSeries, deletedUniverses }` of ids removed.+ *+ * Order matters: series are swept first because `deleteUniverse` refuses to+ * delete a universe that still has live series (hierarchy invariant). A+ * universe only becomes eligible once its own ephemeral shells are gone.+ */+export async function sweepOrphanShells({ now = Date.now(), maxAgeMs = ORPHAN_SHELL_MAX_AGE_MS } = {}) {+ const deletedSeries = [];+ const deletedUniverses = [];++ // --- Pass 1: ephemeral, empty, aged-out series ---+ const allSeries = await listSeries();+ // Track which series survive so the universe pass can tell whether a+ // universe still has live series WITHOUT a second listSeries() read that+ // wouldn't reflect the deletes we just did (the store soft-deletes, so a+ // re-list would still return them within the same tick on some backends).+ const survivingSeriesByUniverse = new Map();+ const noteSurvivor = (s) => {+ const key = s.universeId || '';+ survivingSeriesByUniverse.set(key, (survivingSeriesByUniverse.get(key) || 0) + 1);+ };++ for (const s of allSeries) {+ if (s.ephemeral !== true) { noteSurvivor(s); continue; }+ if (seriesHasStoryWork(s)) { noteSurvivor(s); continue; }+ const age = ageMs(s, now);+ if (!Number.isFinite(age) || age < maxAgeMs) { noteSurvivor(s); continue; }+ const issues = await listIssues({ seriesId: s.id });+ if (issues.length > 0) { noteSurvivor(s); continue; }+ // Empty, ephemeral, aged-out, zero-issue series — sweep it.+ await deleteSeries(s.id);+ deletedSeries.push(s.id);+ }++ // --- Pass 2: ephemeral, empty, aged-out universes with no surviving series ---+ const allUniverses = await listUniverses();+ for (const u of allUniverses) {+ if (u.ephemeral !== true) continue;+ if (universeHasCanon(u)) continue;+ const age = ageMs(u, now);+ if (!Number.isFinite(age) || age < maxAgeMs) continue;+ // A universe with any surviving (live, non-deleted) series — whether we+ // just spared an ephemeral one above or a committed one shares it — must+ // not be removed. deleteUniverse enforces this too, but checking here+ // keeps us from a noisy throw on the expected case.+ if ((survivingSeriesByUniverse.get(u.id) || 0) > 0) continue;+ await deleteUniverse(u.id);+ deletedUniverses.push(u.id);+ }++ return { deletedSeries, deletedUniverses };+}++/**+ * Start the periodic sweep. Fires once on a short delay after boot (so a long+ * grace window doesn't mean orphans wait a full day after a restart) then on+ * SWEEP_INTERVAL_MS. Idempotent — a second call is a no-op.+ */+export function startOrphanShellGc() {+ if (sweepTimer) return;++ const runSweep = () => {+ sweepOrphanShells()+ .then(({ deletedSeries, deletedUniverses }) => {+ if (deletedSeries.length > 0 || deletedUniverses.length > 0) {+ console.log(`🧹 Importer orphan GC: removed ${deletedSeries.length} series + ${deletedUniverses.length} universe shells`);+ }+ })+ .catch((err) => console.error(`❌ Importer orphan GC sweep failed: ${err.message}`));+ };++ // Initial pass ~5 min after boot — outside the startup hot path, but soon+ // enough that a restart doesn't reset the cleanup clock.+ setTimeout(runSweep, 5 * 60 * 1000).unref?.();+ sweepTimer = setInterval(runSweep, SWEEP_INTERVAL_MS);+ sweepTimer.unref?.();+}++/** Stop the periodic sweep (used by tests / graceful shutdown). */+export function stopOrphanShellGc() {+ if (sweepTimer) {+ clearInterval(sweepTimer);+ sweepTimer = null;+ }+}diff --git a/server/services/importerOrphanGc.test.js b/server/services/importerOrphanGc.test.jsnew file mode 100644index 0000000000..35402964b8--- /dev/null+++ b/server/services/importerOrphanGc.test.js@@ -0,0 +1,113 @@+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { mockNoPeerSync, mockNoPeers } from '../lib/mockPathsDataRoot.js';++// Redirect every PATHS member under a per-worker temp root before the+// universe/series/issues stores capture PATHS.data at module init. Same+// pattern as importer.test.js.+const tempRoot = mkdtempSync(join(tmpdir(), 'orphan-gc-test-'));+vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ const redirectedPaths = Object.fromEntries(+ Object.keys(actual.PATHS).map((k) => [k, join(tempRoot, k)]),+ );+ return { ...actual, PATHS: redirectedPaths };+});++// Suppress live peer fan-out — createUniverse/createSeries can background+// auto-subscribe even for ephemeral fixtures (defense-in-depth).+vi.mock('./instances.js', () => mockNoPeers());+vi.mock('./sharing/peerSync.js', () => mockNoPeerSync());++const { sweepOrphanShells, ORPHAN_SHELL_MAX_AGE_MS } = await import('./importerOrphanGc.js');+const universeSvc = await import('./universeBuilder.js');+const seriesSvc = await import('./pipeline/series.js');+const issuesSvc = await import('./pipeline/issues.js');++// The update mutators forcibly re-stamp `updatedAt = now`, so backdating a+// record isn't reliable. Instead we pin the sweep's clock to the future, well+// past the grace window from the records' real (just-now) timestamps.+const FUTURE = Date.now() + ORPHAN_SHELL_MAX_AGE_MS + 60_000;++beforeEach(async () => {+ // Hard-delete any records left by a prior test so counts are deterministic.+ for (const s of await seriesSvc.listSeries({ includeDeleted: true })) {+ await seriesSvc.deleteSeries(s.id).catch(() => {});+ }+ for (const u of await universeSvc.listUniverses({ includeDeleted: true })) {+ await universeSvc.deleteUniverse(u.id).catch(() => {});+ }+});++afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));++describe('sweepOrphanShells', () => {+ it('removes an aged-out, ephemeral, zero-issue/zero-canon universe + series', async () => {+ const uni = await universeSvc.createUniverse({ name: 'Abandoned U', ephemeral: true });+ const ser = await seriesSvc.createSeries({ name: 'Abandoned S', universeId: uni.id, ephemeral: true });++ const { deletedSeries, deletedUniverses } = await sweepOrphanShells({ now: FUTURE });+ expect(deletedSeries).toContain(ser.id);+ expect(deletedUniverses).toContain(uni.id);++ await expect(seriesSvc.getSeries(ser.id)).rejects.toThrow();+ await expect(universeSvc.getUniverse(uni.id)).rejects.toThrow();+ });++ it('spares a NON-ephemeral (committed) universe + series even when empty', async () => {+ const uni = await universeSvc.createUniverse({ name: 'Real U' });+ const ser = await seriesSvc.createSeries({ name: 'Real S', universeId: uni.id });++ const { deletedSeries, deletedUniverses } = await sweepOrphanShells({ now: FUTURE });+ expect(deletedSeries).not.toContain(ser.id);+ expect(deletedUniverses).not.toContain(uni.id);+ });++ it('spares an ephemeral shell that is younger than the grace window', async () => {+ const uni = await universeSvc.createUniverse({ name: 'Fresh U', ephemeral: true });+ const ser = await seriesSvc.createSeries({ name: 'Fresh S', universeId: uni.id, ephemeral: true });++ // Sweep with the real clock — the records were created just now, so the+ // age gate must spare them.+ const { deletedSeries, deletedUniverses } = await sweepOrphanShells();+ expect(deletedSeries).not.toContain(ser.id);+ expect(deletedUniverses).not.toContain(uni.id);+ });++ it('spares an ephemeral series that still has issues, and its universe', async () => {+ const uni = await universeSvc.createUniverse({ name: 'WithIssues U', ephemeral: true });+ const ser = await seriesSvc.createSeries({ name: 'WithIssues S', universeId: uni.id, ephemeral: true });+ await issuesSvc.createIssue({ seriesId: ser.id, title: 'A', arcPosition: 1 });++ const { deletedSeries, deletedUniverses } = await sweepOrphanShells({ now: FUTURE });+ expect(deletedSeries).not.toContain(ser.id);+ // Universe must be spared too — it still has a live series.+ expect(deletedUniverses).not.toContain(uni.id);+ });++ it('spares an ephemeral universe that has canon entities', async () => {+ const uni = await universeSvc.createUniverse({+ name: 'WithCanon U',+ ephemeral: true,+ characters: [{ name: 'Aria' }],+ });++ const { deletedUniverses } = await sweepOrphanShells({ now: FUTURE });+ expect(deletedUniverses).not.toContain(uni.id);+ });++ it('does not remove a shared universe when one of its ephemeral series is GC-able but a committed one survives', async () => {+ const uni = await universeSvc.createUniverse({ name: 'Shared U', ephemeral: true });+ const orphanSer = await seriesSvc.createSeries({ name: 'Orphan S', universeId: uni.id, ephemeral: true });+ const committedSer = await seriesSvc.createSeries({ name: 'Committed S', universeId: uni.id });++ const { deletedSeries, deletedUniverses } = await sweepOrphanShells({ now: FUTURE });+ // The orphan ephemeral series is swept...+ expect(deletedSeries).toContain(orphanSer.id);+ // ...but the universe stays because a committed series still lives in it.+ expect(deletedUniverses).not.toContain(uni.id);+ expect(deletedSeries).not.toContain(committedSer.id);+ });+});