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([issue-727]): gate orphan GC on a dedicated importDraft marker, not ephemeral

[._.]/ Adam Eivyc1acfd96c11f
diff --git a/server/lib/syncWire.js b/server/lib/syncWire.js
index e999048dbe..0b9cb89d14 100644
--- a/server/lib/syncWire.js
+++ b/server/lib/syncWire.js
@@ -87,7 +87,14 @@ export function sanitizeRecordForWire(kind, record) {
// invariant for the tombstone-cross-wire case above: a deleted record
// that carried `ephemeral: true` on disk MUST hash identically against
// a pre-flag peer's tombstone for the same record.
- const { deleted: _deleted, deletedAt: _deletedAt, ephemeral: _ephemeral, ...rest } = record;
+ // `importDraft` (issue #727) is a local-only importer-orphan GC marker,
+ // analogous to `ephemeral` — strip it here too so it never appears in the
+ // serialized wire form and the checksum stays byte-stable against peers
+ // that predate the flag. In practice an import-draft record is always
+ // `ephemeral: true` and already short-circuits at the top, but stripping
+ // unconditionally keeps the invariant robust if the two flags ever
+ // diverge.
+ const { deleted: _deleted, deletedAt: _deletedAt, ephemeral: _ephemeral, importDraft: _importDraft, ...rest } = record;
// EPHEMERAL TOMBSTONES — minimize the payload. If a record was
// created ephemeral and never shared, deleting it would otherwise
// ship the full content to peers that never had it (just because
diff --git a/server/services/importer.js b/server/services/importer.js
index a7aeb9c8a5..780cde4d19 100644
--- a/server/services/importer.js
+++ b/server/services/importer.js
@@ -810,23 +810,25 @@ export async function analyzeImport({
// 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
+ // New shells are created as import drafts (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`)
+ // transport; `importDraft` is the dedicated GC marker that distinguishes an
+ // abandoned analyze from a user's deliberately-private empty record (which
+ // is also `ephemeral`) — so the orphan-shell GC sweep (importerOrphanGc.js)
+ // only ever touches genuine import shells. `commitImport` clears both flags
// so a committed import becomes a normal, syncing record. Pre-existing
- // records are never re-flagged ephemeral here.
+ // records are never re-flagged here.
let universe = isExistingUniverse
? existingUniverse
- : await createUniverse({ name: universeName.trim(), ephemeral: true });
+ : await createUniverse({ name: universeName.trim(), ephemeral: true, importDraft: true });
const universeWasCreated = !isExistingUniverse;
let series;
try {
series = isExistingSeries
? existingSeries
- : await createSeries({ name: seriesName.trim(), universeId: universe.id, ephemeral: true });
+ : await createSeries({ name: seriesName.trim(), universeId: universe.id, ephemeral: true, importDraft: true });
} catch (seriesErr) {
if (universeWasCreated) {
await deleteUniverse(universe.id).catch((delErr) =>
@@ -1374,21 +1376,23 @@ 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.
+ // Promote any import-draft shell now that the commit fully succeeded (issue
+ // #727). analyzeImport creates brand-new universe/series records as import
+ // drafts (`ephemeral` + `importDraft`) so an abandoned analyze leaves no
+ // syncing orphan; a successful commit turns them into normal records by
+ // clearing BOTH flags. Clearing `ephemeral` must go through
+ // updateUniverse/updateSeries (they wire the ephemeral→non-ephemeral peer
+ // re-subscribe), so the same patch clears `importDraft` too. Gate STRICTLY on
+ // `importDraft` — committing an import onto a user's pre-existing private
+ // (`ephemeral`-only) record must NOT silently un-privatize it. Done after the
+ // issue loop so a rolled-back commit leaves the draft shells GC-eligible.
let promotedUniverse = updatedUniverse;
let promotedSeries = updatedSeries;
- if (updatedUniverse.ephemeral === true) {
- promotedUniverse = await updateUniverse(updatedUniverse.id, { ephemeral: false });
+ if (updatedUniverse.importDraft === true) {
+ promotedUniverse = await updateUniverse(updatedUniverse.id, { ephemeral: false, importDraft: false });
}
- if (updatedSeries.ephemeral === true) {
- promotedSeries = await updateSeries(updatedSeries.id, { ephemeral: false });
+ if (updatedSeries.importDraft === true) {
+ promotedSeries = await updateSeries(updatedSeries.id, { ephemeral: false, importDraft: false });
}
return {
diff --git a/server/services/importer.test.js b/server/services/importer.test.js
index 5b5b9f043c..8755756ed6 100644
--- a/server/services/importer.test.js
+++ b/server/services/importer.test.js
@@ -320,10 +320,14 @@ 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.
+ // New shells are created as import drafts (issue #727): `ephemeral` keeps
+ // them out of sync, `importDraft` is the marker the orphan-shell GC keys on
+ // so an abandoned analyze self-cleans (without touching a user's private
+ // `ephemeral`-only records).
expect(result.universe.ephemeral).toBe(true);
expect(result.series.ephemeral).toBe(true);
+ expect(result.universe.importDraft).toBe(true);
+ expect(result.series.importDraft).toBe(true);
expect(result.canonPreview.characters).toHaveLength(1);
expect(result.canonPreview.characters[0].name).toBe('Aria');
expect(result.canonPreview.places).toHaveLength(1);
@@ -815,8 +819,12 @@ async function setupForCommit() {
// PATHS is, and instances.js resolves its own file paths) and fans the
// fixture out to every actual peer, leaving "Commit U" / "Commit S"
// records on the user's null sync machine after every test run.
- const uni = await universeSvc.createUniverse({ name: 'Commit U', ephemeral: true });
- const ser = await seriesSvc.createSeries({ name: 'Commit S', universeId: uni.id, ephemeral: true });
+ //
+ // importDraft:true models what analyzeImport stamps on a brand-new shell, so
+ // commitImport's promotion (which gates strictly on importDraft) clears both
+ // flags — matching the real analyze→commit lifecycle.
+ const uni = await universeSvc.createUniverse({ name: 'Commit U', ephemeral: true, importDraft: true });
+ const ser = await seriesSvc.createSeries({ name: 'Commit S', universeId: uni.id, ephemeral: true, importDraft: true });
return { uni, ser };
}
@@ -866,10 +874,13 @@ 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.
+ // A successful commit promotes both shells out of draft state (issue #727):
+ // ephemeral cleared so they sync to peers, importDraft cleared so the
+ // orphan-shell GC never touches them.
expect(result.universe.ephemeral).not.toBe(true);
expect(result.series.ephemeral).not.toBe(true);
+ expect(result.universe.importDraft).not.toBe(true);
+ expect(result.series.importDraft).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.js
index 3a1e80152f..098f236dc4 100644
--- a/server/services/importerOrphanGc.js
+++ b/server/services/importerOrphanGc.js
@@ -6,17 +6,20 @@
* 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
+ * The primary defense is marking analyze-created shells as import drafts
+ * (`ephemeral` so they stay out of every sync transport, plus a dedicated
+ * `importDraft` marker) and clearing both flags 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,
+ * shells that are STILL import drafts, 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.
+ * - Only `importDraft` records are candidates. `ephemeral` alone is NOT enough
+ * — it's a general user-settable "don't sync / keep local" marker, so a
+ * user's deliberately-private empty universe/series is also `ephemeral` and
+ * must never be swept. `importDraft` is stamped ONLY by analyzeImport and
+ * cleared on commit, so it uniquely identifies an abandoned import shell.
* - 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.
@@ -86,11 +89,11 @@ export async function sweepOrphanShells({ now = Date.now(), maxAgeMs = ORPHAN_SH
survivingSeriesByUniverse.set(key, (survivingSeriesByUniverse.get(key) || 0) + 1);
};
- // True only for an ephemeral, story-work-free, aged-out, zero-issue shell.
+ // True only for an import-draft, story-work-free, aged-out, zero-issue shell.
// Each gate runs cheapest-first (the listIssues read is reached only by a
// series that already passed every in-memory check).
const seriesIsSweepable = async (s) => {
- if (s.ephemeral !== true || seriesHasStoryWork(s)) return false;
+ if (s.importDraft !== true || seriesHasStoryWork(s)) return false;
const age = ageMs(s, now);
if (!Number.isFinite(age) || age < maxAgeMs) return false;
const issues = await listIssues({ seriesId: s.id });
@@ -106,10 +109,10 @@ export async function sweepOrphanShells({ now = Date.now(), maxAgeMs = ORPHAN_SH
}
}
- // --- Pass 2: ephemeral, empty, aged-out universes with no surviving series ---
+ // --- Pass 2: import-draft, empty, aged-out universes with no surviving series ---
const allUniverses = await listUniverses();
for (const u of allUniverses) {
- if (u.ephemeral !== true) continue;
+ if (u.importDraft !== true) continue;
if (universeHasCanon(u)) continue;
const age = ageMs(u, now);
if (!Number.isFinite(age) || age < maxAgeMs) continue;
diff --git a/server/services/importerOrphanGc.test.js b/server/services/importerOrphanGc.test.js
index 35402964b8..83f01804d6 100644
--- a/server/services/importerOrphanGc.test.js
+++ b/server/services/importerOrphanGc.test.js
@@ -45,8 +45,8 @@ 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 uni = await universeSvc.createUniverse({ name: 'Abandoned U', ephemeral: true, importDraft: true });
+ const ser = await seriesSvc.createSeries({ name: 'Abandoned S', universeId: uni.id, ephemeral: true, importDraft: true });
const { deletedSeries, deletedUniverses } = await sweepOrphanShells({ now: FUTURE });
expect(deletedSeries).toContain(ser.id);
@@ -65,9 +65,24 @@ describe('sweepOrphanShells', () => {
expect(deletedUniverses).not.toContain(uni.id);
});
+ it('spares an ephemeral-but-not-importDraft empty record (user-private, not an import shell)', async () => {
+ // `ephemeral` is a general user-settable "keep local / don't sync" marker —
+ // a deliberately-private empty universe/series carries it too. The GC must
+ // key on `importDraft` (stamped only by analyzeImport), never `ephemeral`
+ // alone, or it would silently delete the user's private records.
+ const uni = await universeSvc.createUniverse({ name: 'Private U', ephemeral: true });
+ const ser = await seriesSvc.createSeries({ name: 'Private S', universeId: uni.id, ephemeral: true });
+ expect(uni.importDraft).not.toBe(true);
+ expect(ser.importDraft).not.toBe(true);
+
+ 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 });
+ const uni = await universeSvc.createUniverse({ name: 'Fresh U', ephemeral: true, importDraft: true });
+ const ser = await seriesSvc.createSeries({ name: 'Fresh S', universeId: uni.id, ephemeral: true, importDraft: true });
// Sweep with the real clock — the records were created just now, so the
// age gate must spare them.
@@ -77,8 +92,8 @@ describe('sweepOrphanShells', () => {
});
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 });
+ const uni = await universeSvc.createUniverse({ name: 'WithIssues U', ephemeral: true, importDraft: true });
+ const ser = await seriesSvc.createSeries({ name: 'WithIssues S', universeId: uni.id, ephemeral: true, importDraft: true });
await issuesSvc.createIssue({ seriesId: ser.id, title: 'A', arcPosition: 1 });
const { deletedSeries, deletedUniverses } = await sweepOrphanShells({ now: FUTURE });
@@ -90,7 +105,7 @@ describe('sweepOrphanShells', () => {
it('spares an ephemeral universe that has canon entities', async () => {
const uni = await universeSvc.createUniverse({
name: 'WithCanon U',
- ephemeral: true,
+ ephemeral: true, importDraft: true,
characters: [{ name: 'Aria' }],
});
@@ -99,8 +114,8 @@ describe('sweepOrphanShells', () => {
});
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 uni = await universeSvc.createUniverse({ name: 'Shared U', ephemeral: true, importDraft: true });
+ const orphanSer = await seriesSvc.createSeries({ name: 'Orphan S', universeId: uni.id, ephemeral: true, importDraft: true });
const committedSer = await seriesSvc.createSeries({ name: 'Committed S', universeId: uni.id });
const { deletedSeries, deletedUniverses } = await sweepOrphanShells({ now: FUTURE });
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index 2278989d6e..6006103f8c 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -179,6 +179,12 @@ const sanitizeSeries = (raw) => {
// existing series keep their on-disk + wire-checksum shape. See
// syncWire.sanitizeRecordForWire for the wire-side enforcement.
...(raw.ephemeral === true ? { ephemeral: true } : {}),
+ // Importer-orphan marker (issue #727). Stamped only by analyzeImport on a
+ // brand-new shell so the orphan-shell GC can tell an abandoned analyze from
+ // a user's deliberately-private empty series (also `ephemeral`).
+ // commitImport clears it. Server-set only — never from a route body — and
+ // persisted only when true so every other record's shape stays stable.
+ ...(raw.importDraft === true ? { importDraft: true } : {}),
};
};
@@ -220,6 +226,8 @@ export async function createSeries(input = {}) {
createdAt: now,
updatedAt: now,
ephemeral: input.ephemeral === true,
+ // Importer-orphan marker (issue #727) — see sanitizeSeries.
+ importDraft: input.importDraft === true,
});
await store().saveOne(created.id, created);
// Skip auto-subscribe for ephemeral series — wire-side push would short-
@@ -330,6 +338,9 @@ export async function updateSeries(id, patch = {}) {
// Local-only "don't sync" marker — sanitizer normalizes anything
// non-true back to absent.
...('ephemeral' in patch ? { ephemeral: patch.ephemeral } : {}),
+ // Importer-orphan marker (issue #727) — commitImport clears it via
+ // `{ importDraft: false }`; sanitizer normalizes non-true back to absent.
+ ...('importDraft' in patch ? { importDraft: patch.importDraft } : {}),
llm: mergedLlm,
updatedAt: new Date().toISOString(),
});
@@ -516,6 +527,9 @@ export async function mergeSeriesFromSync(remoteSeries, { source = { via: 'sync'
if (!sanitized) return;
// Strip inbound `ephemeral` — see mergeUniversesFromSync.
if ('ephemeral' in sanitized) delete sanitized.ephemeral;
+ // Strip inbound `importDraft` (issue #727) — local-only GC marker; a peer
+ // must not be able to mark our records GC-eligible.
+ if ('importDraft' in sanitized) delete sanitized.importDraft;
const local = await store().loadOne(sanitized.id);
if (!local) {
// See universeBuilder.mergeUniversesFromSync — no local means no
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index 849c569fae..94cd0147b4 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -802,6 +802,13 @@ const sanitizeTemplate = (raw) => {
// sanitizeRecordForWire). Mark a scratch universe ephemeral to keep it
// off the federation; test fixtures stamp this too.
...(raw.ephemeral === true ? { ephemeral: true } : {}),
+ // Importer-orphan marker (issue #727). Stamped only by analyzeImport on a
+ // brand-new shell so the orphan-shell GC can distinguish an abandoned
+ // analyze from a user's deliberately-private empty universe (which is also
+ // `ephemeral`). commitImport clears it on promotion. Server-set only —
+ // never accepted from a route body — and persisted only when true so the
+ // on-disk shape and wire checksum stay stable for every other record.
+ ...(raw.importDraft === true ? { importDraft: true } : {}),
};
};
@@ -943,6 +950,8 @@ export async function createUniverse(input = {}) {
// (snapshot loop + per-record push) skips this universe (see
// sanitizeRecordForWire) and the auto-subscribe below short-circuits.
ephemeral: input.ephemeral === true,
+ // Importer-orphan marker (issue #727) — see sanitizeTemplate.
+ importDraft: input.importDraft === true,
});
// Write through the store — we're inside the per-id queue so use
// atomicWrite directly to avoid re-queueing on the same id.
@@ -1150,6 +1159,10 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {
// not the goal — protecting "you can't accidentally truthy your way
// into ephemeral and never sync again" is.
'ephemeral',
+ // Importer-orphan marker (issue #727). commitImport clears it on
+ // promotion via `{ importDraft: false }`; the sanitizer drops every
+ // non-`true` value back to absent, mirroring `ephemeral`.
+ 'importDraft',
];
const scalarPatch = Object.fromEntries(
PATCHABLE_SCALARS.filter((k) => k in patch).map((k) => [k, patch[k]]),
@@ -1481,6 +1494,9 @@ export async function mergeUniversesFromSync(remoteUniverses, { source = { via:
// permanently un-syncable. The on-disk-only contract is enforced on
// the receive boundary.
if ('ephemeral' in sanitized) delete sanitized.ephemeral;
+ // `importDraft` (issue #727) is likewise LOCAL-only — never trust an
+ // inbound value, or a peer could mark our records GC-eligible.
+ if ('importDraft' in sanitized) delete sanitized.importDraft;
writeTasks.push(s.queueRecordWrite(sanitized.id, async () => {
const local = await s.loadOne(sanitized.id);
if (!local) {