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
stop the tombstone sweep from hydrating every universe/series/loom each tick
[._.]/ Adam Eivyc7059d153940
diff --git a/server/services/fableLoom/db.js b/server/services/fableLoom/db.jsindex 5a4a3b8489..a29efc6e0f 100644--- a/server/services/fableLoom/db.js+++ b/server/services/fableLoom/db.js@@ -17,6 +17,38 @@ export async function listRaw() {return rows.map((row) => row.data);}+/** Every loom id (live AND tombstones) — the service filters. */+export async function listIds() {+ const { rows } = await query('SELECT id FROM fableloom_stories');+ return rows.map((row) => row.id);+}++/**+ * Live (non-deleted) loom ids only — id-only projection hitting+ * idx_fableloom_live. Backs tombstoneGc's LIVE_ID_LISTERS (the base-hash+ * orphan sweep), so a record stops protecting its base hash the moment it's+ * tombstoned without the sweep ever reading a loom's JSONB body.+ */+export async function listLiveIds() {+ const { rows } = await query('SELECT id FROM fableloom_stories WHERE deleted = FALSE');+ return rows.map((row) => row.id);+}++/**+ * Tombstoned loom ids whose deletedAt is older than `beforeMs` (epoch ms) —+ * the GC candidate scan for `pruneTombstonedLooms`. An id-only projection:+ * the sweep almost never finds a tombstone, so the common case must not pay+ * for a single loom's JSONB body, let alone every one of them.+ */+export async function listTombstoneIdsBefore(beforeMs) {+ const cutoffIso = new Date(beforeMs).toISOString();+ const { rows } = await query(+ 'SELECT id FROM fableloom_stories WHERE deleted = TRUE AND deleted_at IS NOT NULL AND deleted_at < $1',+ [cutoffIso],+ );+ return rows.map((row) => row.id);+}+export async function writeRaw(id, record) {const now = new Date().toISOString();const createdAt = mirrorTimestamp(record?.createdAt, now);diff --git a/server/services/fableLoom/db.test.js b/server/services/fableLoom/db.test.jsnew file mode 100644index 0000000000..fc44d8dc26--- /dev/null+++ b/server/services/fableLoom/db.test.js@@ -0,0 +1,124 @@+/**+ * Postgres-backed round-trip for the FableLoom DB adapter.+ *+ * Like universeBuilder/db.test.js and pipeline/seriesStore/db.test.js, needs a+ * live PostgreSQL with the schema applied; SKIPS cleanly when no DB is+ * reachable. Snapshots + restores the table so a developer's real looms+ * survive the run. This file didn't exist before #6851 — fableLoom/db.js had+ * no direct PG-adapter coverage (only exercised indirectly through the file+ * backend in records.test.js), so it covers the pre-existing leaf I/O+ * alongside the new id projections added for the tombstone-sweep hydration fix.+ */++import { describe, it, expect, afterAll, beforeAll, beforeEach } from 'vitest';+import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';+import { requireDbOrSkip } from '../../lib/dbTestGate.js';++let dbReady = false;+let skipReason = '';+{+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));+ if (!health.connected) {+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;+ } else {+ await ensureSchema().catch(() => {});+ const probe = await query(+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'fableloom_stories') AS ok`,+ ).catch(() => ({ rows: [{ ok: false }] }));+ if (probe.rows?.[0]?.ok) dbReady = true;+ else skipReason = 'fableloom_stories table not present';+ }+}++const runDb = requireDbOrSkip('services/fableLoom/db.test', dbReady, skipReason);++const L = (id, extra = {}) => ({+ id, name: id, universeId: null, seriesId: null,+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-02T00:00:00.000Z',+ deleted: false, deletedAt: null, ...extra,+});++describe.skipIf(!runDb)('fableLoom DB adapter round-trip', () => {+ let db;+ let snap = [];+ beforeAll(async () => {+ db = await import('./db.js');+ snap = (await query(`SELECT * FROM fableloom_stories`)).rows;+ });++ beforeEach(async () => { await query(`DELETE FROM fableloom_stories`); });++ afterAll(async () => {+ await query(`DELETE FROM fableloom_stories`).catch(() => {});+ for (const r of snap) {+ await query(+ `INSERT INTO fableloom_stories (id, name, universe_id, series_id, data, created_at, updated_at, deleted, deleted_at)+ VALUES ($1,$2,$3,$4,$5::jsonb,$6,$7,$8,$9) ON CONFLICT (id) DO NOTHING`,+ [r.id, r.name, r.universe_id, r.series_id, JSON.stringify(r.data), r.created_at, r.updated_at, r.deleted, r.deleted_at],+ ).catch(() => {});+ }+ await close();+ });++ it('writes a record and reads it back verbatim', async () => {+ const rec = L('loom-1', { universeId: 'u-1', episodes: [{ id: 'ep-1', nodes: [] }] });+ await db.writeRaw('loom-1', rec);+ expect(await db.readRaw('loom-1')).toEqual(rec);+ });++ it('upsert updates the record and the mirror columns', async () => {+ await db.writeRaw('loom-1', L('loom-1', { name: 'First', universeId: 'u-1' }));+ await db.writeRaw('loom-1', L('loom-1', { name: 'Renamed', universeId: 'u-2', updatedAt: '2026-03-03T00:00:00.000Z' }));+ const col = (await query(`SELECT name, universe_id, updated_at FROM fableloom_stories WHERE id = 'loom-1'`)).rows[0];+ expect(col.name).toBe('Renamed');+ expect(col.universe_id).toBe('u-2');+ expect(new Date(col.updated_at).toISOString()).toBe('2026-03-03T00:00:00.000Z');+ });++ it('listRaw returns every record body verbatim, newest-updated first', async () => {+ await db.writeRaw('loom-a', L('loom-a', { updatedAt: '2026-01-01T00:00:00.000Z' }));+ await db.writeRaw('loom-b', L('loom-b', { updatedAt: '2026-02-01T00:00:00.000Z' }));+ const all = await db.listRaw();+ expect(all.map((r) => r.id)).toEqual(['loom-b', 'loom-a']);+ });++ it('listIds returns live and tombstoned ids alike', async () => {+ await db.writeRaw('loom-live', L('loom-live'));+ await db.writeRaw('loom-dead', L('loom-dead', { deleted: true, deletedAt: '2026-02-02T00:00:00.000Z' }));+ expect((await db.listIds()).sort()).toEqual(['loom-dead', 'loom-live']);+ });++ it('listLiveIds returns only non-deleted ids', async () => {+ await db.writeRaw('loom-live', L('loom-live'));+ await db.writeRaw('loom-dead', L('loom-dead', { deleted: true, deletedAt: '2026-02-02T00:00:00.000Z' }));+ expect(await db.listLiveIds()).toEqual(['loom-live']);+ });++ it('listTombstoneIdsBefore returns only tombstones older than the cutoff, keeping a NULL deleted_at', async () => {+ await db.writeRaw('loom-live', L('loom-live'));+ await db.writeRaw('loom-old', L('loom-old', { deleted: true, deletedAt: '2026-01-01T00:00:00.000Z' }));+ await db.writeRaw('loom-new', L('loom-new', { deleted: true, deletedAt: '2026-06-01T00:00:00.000Z' }));+ // mirrorTimestamp(deletedAt, null) leaves deleted_at NULL for an+ // unparseable value — `deleted_at < $1` is never true against NULL, so+ // the row is conservatively excluded from every cutoff.+ await db.writeRaw('loom-bad', L('loom-bad', { deleted: true, deletedAt: 'not-a-date' }));+ const cutoff = Date.parse('2026-03-01T00:00:00.000Z');+ expect(await db.listTombstoneIdsBefore(cutoff)).toEqual(['loom-old']);+ });++ it('tolerates a malformed timestamp without throwing (falls back)', async () => {+ await db.writeRaw('loom-bad', L('loom-bad', { updatedAt: 'not-a-date', createdAt: 'nope' }));+ const back = await db.readRaw('loom-bad');+ expect(back.id).toBe('loom-bad'); // data stored verbatim+ const col = (await query(`SELECT created_at, updated_at FROM fableloom_stories WHERE id = 'loom-bad'`)).rows[0];+ expect(col.created_at).toBeInstanceOf(Date); // fell back to NOW(), not null/throw+ expect(col.updated_at).toBeInstanceOf(Date);+ });++ it('deleteRaw removes the row (idempotent)', async () => {+ await db.writeRaw('loom-1', L('loom-1'));+ await db.deleteRaw('loom-1');+ expect(await db.readRaw('loom-1')).toBeNull();+ await db.deleteRaw('loom-1'); // no throw on missing+ });+});diff --git a/server/services/fableLoom/index.js b/server/services/fableLoom/index.jsindex b72644c5d4..e66e92bb68 100644--- a/server/services/fableLoom/index.js+++ b/server/services/fableLoom/index.js@@ -71,6 +71,8 @@ export {export {_resetFableLoomBackend,isValidLoomId,+ listIds,+ listLiveIds,verifySchemaVersion,} from './store.js';export {diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.jsindex 701fb83566..152ac7d145 100644--- a/server/services/fableLoom/records.js+++ b/server/services/fableLoom/records.js@@ -37,6 +37,7 @@ import {deleteRaw,isValidLoomId,listRaw,+ listTombstoneIdsBefore,queueLoomWrite,readRaw,writeRaw,@@ -892,18 +893,21 @@ export async function mergeLoomsFromSync(/** Hard-prune tombstones only after the shared federation GC computes a safe cutoff. */export async function pruneTombstonedLooms(olderThanMs) {if (!Number.isFinite(olderThanMs)) return { pruned: 0 };- const candidates = (await listLooms({ includeDeleted: true }))- .filter((loom) => loom.deleted && Number.isFinite(Date.parse(loom.deletedAt))- && Date.parse(loom.deletedAt) < olderThanMs);+ // Id-only candidate scan — SQL projection on Postgres, hydrate+filter on the+ // file escape hatch. The sweep almost never finds a tombstone, so this must+ // not pay for every loom's JSONB body (episode graphs included) just to+ // find zero candidates. The authoritative re-check inside each per-id queue+ // below still re-reads and re-sanitizes the record.+ const candidateIds = await listTombstoneIdsBefore(olderThanMs);let pruned = 0;await withBaseHashFlushBatch(async () => {- for (const candidate of candidates) {- const removed = await queueLoomWrite(candidate.id, async () => {- const current = sanitizeLoom(await readRaw(candidate.id));+ for (const id of candidateIds) {+ const removed = await queueLoomWrite(id, async () => {+ const current = sanitizeLoom(await readRaw(id));const deletedAtMs = Date.parse(current?.deletedAt || '');if (!current?.deleted || !Number.isFinite(deletedAtMs) || deletedAtMs >= olderThanMs) return false;- await deleteRaw(candidate.id);- await deleteSyncBaseHash('fableLoom', candidate.id);+ await deleteRaw(id);+ await deleteSyncBaseHash('fableLoom', id);return true;});if (removed) pruned += 1;diff --git a/server/services/fableLoom/store.js b/server/services/fableLoom/store.jsindex 66289607f1..6e4d6e8348 100644--- a/server/services/fableLoom/store.js+++ b/server/services/fableLoom/store.js@@ -38,6 +38,27 @@ function makeFileBackend() {name: 'file',readRaw: (id) => collection.loadOneRaw(id),listRaw: () => collection.loadAll(),+ listIds: () => collection.listIds(),+ // The file layout can't project — `deleted` lives inside each record, so+ // a live-only or tombstone-cutoff id list means reading them all (no+ // sanitizeRecord is configured on this collection, so loadAll() is+ // already raw — same as listRaw above). Mirrors the JS filter+ // pruneTombstonedLooms used to run over listLooms({includeDeleted:true})+ // directly — same conservative "unparseable deletedAt is kept" rule.+ listLiveIds: async () => {+ const records = await collection.loadAll();+ return records.filter((r) => r?.deleted !== true).map((r) => r.id);+ },+ listTombstoneIdsBefore: async (beforeMs) => {+ const records = await collection.loadAll();+ const out = [];+ for (const r of records) {+ if (!r?.deleted || typeof r.id !== 'string' || !r.id) continue;+ const t = Date.parse(r.deletedAt || '');+ if (Number.isFinite(t) && t < beforeMs) out.push(r.id);+ }+ return out;+ },writeRaw: (id, record) => collection.saveOneNow(id, record),deleteRaw: (id) => collection.deleteOneNow(id),verify: () => collection.verifySchemaVersion(),@@ -49,6 +70,9 @@ function makePgBackend(db) {name: 'postgres',readRaw: db.readRaw,listRaw: db.listRaw,+ listIds: db.listIds,+ listLiveIds: db.listLiveIds,+ listTombstoneIdsBefore: db.listTombstoneIdsBefore,writeRaw: db.writeRaw,deleteRaw: db.deleteRaw,verify: async () => ({@@ -79,6 +103,15 @@ export const readRaw = async (id) => {export const listRaw = async () => (await facade.getBackend()).listRaw();+/** Every loom id (live AND tombstones) — used by tombstoneGc's ALL_ID_LISTERS. */+export const listIds = async () => (await facade.getBackend()).listIds();++/** Live loom ids only — used by tombstoneGc's LIVE_ID_LISTERS. */+export const listLiveIds = async () => (await facade.getBackend()).listLiveIds();++/** Tombstoned loom ids older than `beforeMs` — the GC candidate scan. */+export const listTombstoneIdsBefore = async (beforeMs) => (await facade.getBackend()).listTombstoneIdsBefore(beforeMs);+export const writeRaw = async (id, record) => {assertId(id);return (await facade.getBackend()).writeRaw(id, record);diff --git a/server/services/fableLoom/store.test.js b/server/services/fableLoom/store.test.jsnew file mode 100644index 0000000000..af3d598327--- /dev/null+++ b/server/services/fableLoom/store.test.js@@ -0,0 +1,58 @@+/**+ * FableLoom store facade — file-backend id projections (#6851).+ *+ * NODE_ENV=test selects the file backend (collectionStore over a real+ * tmpdir). Focused on the id-only projections added for the tombstone-sweep+ * hydration fix — `listIds`/`listLiveIds` (tombstoneGc's orphan-sweep+ * listers, re-exported through fableLoom/index.js) and+ * `listTombstoneIdsBefore` (the candidate scan `pruneTombstonedLooms` uses in+ * records.js). The pre-existing readRaw/listRaw/writeRaw/deleteRaw surface is+ * already exercised end-to-end through the service layer in records.test.js.+ */++import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'fableloom-store-test-'));++vi.mock('../../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };+});++const {+ listIds, listLiveIds, listTombstoneIdsBefore, writeRaw, _resetFableLoomBackend,+} = await import('./store.js');++describe('fableLoom store facade — file backend id projections', () => {+ beforeEach(() => {+ rmSync(join(TEST_DATA_ROOT, 'fableloom'), { recursive: true, force: true });+ _resetFableLoomBackend();+ });+ afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));++ it('listIds returns live and tombstoned ids alike', async () => {+ await writeRaw('loom-live', { id: 'loom-live', name: 'Live' });+ await writeRaw('loom-dead', { id: 'loom-dead', name: 'Dead', deleted: true, deletedAt: '2026-01-01T00:00:00.000Z' });+ expect((await listIds()).sort()).toEqual(['loom-dead', 'loom-live']);+ });++ it('listLiveIds returns only non-deleted ids', async () => {+ await writeRaw('loom-live', { id: 'loom-live', name: 'Live' });+ await writeRaw('loom-dead', { id: 'loom-dead', name: 'Dead', deleted: true, deletedAt: '2026-01-01T00:00:00.000Z' });+ expect(await listLiveIds()).toEqual(['loom-live']);+ });++ it('listTombstoneIdsBefore returns only tombstones older than the cutoff, keeping unparseable deletedAt', async () => {+ await writeRaw('loom-live', { id: 'loom-live', name: 'Live' });+ await writeRaw('loom-old', { id: 'loom-old', name: 'Old', deleted: true, deletedAt: '2026-01-01T00:00:00.000Z' });+ await writeRaw('loom-new', { id: 'loom-new', name: 'New', deleted: true, deletedAt: '2026-06-01T00:00:00.000Z' });+ // Non-parseable deletedAt is conservatively KEPT — never a candidate,+ // regardless of cutoff (mirrors the JS filter this projection replaces).+ await writeRaw('loom-bad', { id: 'loom-bad', name: 'Bad', deleted: true, deletedAt: 'not-a-date' });+ const cutoff = Date.parse('2026-03-01T00:00:00.000Z');+ expect(await listTombstoneIdsBefore(cutoff)).toEqual(['loom-old']);+ });+});diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.jsindex 53c8632fb8..d22f5a1989 100644--- a/server/services/mediaCollections.js+++ b/server/services/mediaCollections.js@@ -239,6 +239,17 @@ export async function listCollections({ includeDeleted = false } = {}) {return all.filter((c) => c.deleted !== true);}+/**+ * Every collection id on disk (live AND tombstoned) — a directory listing, no+ * record hydration. Backs tombstoneGc's ALL_ID_LISTERS.mediaCollection (the+ * orphan peer-subscription sweep); LIVE_ID_LISTERS keeps `listCollections()`+ * because `deleted` lives inside the record file, so there is no cheaper live+ * projection for this file-backed store the way the DB-backed kinds have one.+ */+export async function listCollectionIds() {+ return store().listIds();+}+export async function getCollection(id, { includeDeleted = false } = {}) {const c = await store().loadOne(id);if (!c) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.jsindex f60f549f15..edd0958e9e 100644--- a/server/services/mediaCollections.test.js+++ b/server/services/mediaCollections.test.js@@ -103,6 +103,15 @@ describe('mediaCollections service', () => {expect(all).toHaveLength(1);});+ it('listCollectionIds returns every collection id, including tombstoned ones', async () => {+ const a = await svc.createCollection({ name: 'A' });+ const b = await svc.createCollection({ name: 'B' });+ await svc.deleteCollection(b.id);+ // A directory listing, not a hydrate+filter — tombstoneGc's+ // ALL_ID_LISTERS.mediaCollection needs every id, live or not.+ expect((await svc.listCollectionIds()).sort()).toEqual([a.id, b.id].sort());+ });+it('addItem rejects duplicate (same kind+ref)', async () => {const c = await svc.createCollection({ name: 'A' });await svc.addItem(c.id, { kind: 'image', ref: 'foo.png' });diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 77a47a7fae..ae63ffc12e 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -1288,6 +1288,24 @@ export async function mergeSeriesFromSync(remoteSeries, { source = { via: 'sync'return result;}+/**+ * Series id listers for the tombstone-sweep's orphan resolvers+ * (server/services/sharing/tombstoneGc.js). Both are id-only projections — no+ * record hydration, no sanitize — so a sweep that only checks set membership+ * never pays for a series' JSONB body, let alone every one of them.+ *+ * `listLiveIds` excludes tombstones (LIVE_ID_LISTERS — a record stops+ * protecting its base hash once tombstoned); `listIds` includes them+ * (ALL_ID_LISTERS — a tombstone still owns its peer subscription until the+ * record is hard-deleted).+ */+export async function listLiveIds() {+ return store().listLiveIds();+}+export async function listIds() {+ return store().listIds();+}+/*** Garbage-collect series tombstones older than `beforeMs`. See* `pruneTombstonedUniverses` in universeBuilder.js for the contract — the@@ -1297,14 +1315,10 @@ export async function mergeSeriesFromSync(remoteSeries, { source = { via: 'sync'export async function pruneTombstonedSeries(beforeMs) {if (!Number.isFinite(beforeMs)) return { pruned: 0 };const s = store();- const series = await s.loadAll();- const candidates = [];- for (const rec of series) {- if (!rec?.deleted) continue;- const t = Date.parse(rec.deletedAt || '');- if (!Number.isFinite(t)) continue;- if (t < beforeMs) candidates.push(rec.id);- }+ // Id-only candidate scan — SQL projection on Postgres, hydrate+filter on the+ // file escape hatch. The sweep almost never finds a tombstone, so this must+ // not pay for every series' JSONB body just to find zero candidates.+ const candidates = await s.listTombstoneIdsBefore(beforeMs);// Re-check the tombstone status INSIDE each per-id queue. A concurrent// mergeSeriesFromSync could have un-deleted the record (newer remote// `updatedAt`, `deleted: false`) between our out-of-queue snapshot and thediff --git a/server/services/pipeline/seriesStore/db.js b/server/services/pipeline/seriesStore/db.jsindex a5166f9b4f..398fa21cbe 100644--- a/server/services/pipeline/seriesStore/db.js+++ b/server/services/pipeline/seriesStore/db.js@@ -34,6 +34,32 @@ export async function listIds() {return rows.map((r) => r.id);}+/**+ * Live (non-deleted) series ids only — id-only projection. Backs+ * tombstoneGc's LIVE_ID_LISTERS (the base-hash orphan sweep), so a record+ * stops protecting its base hash the moment it's tombstoned without the+ * sweep ever reading a series' JSONB body.+ */+export async function listLiveIds() {+ const { rows } = await query(`SELECT id FROM pipeline_series WHERE deleted = FALSE`);+ return rows.map((r) => r.id);+}++/**+ * Tombstoned series ids whose deletedAt is older than `beforeMs` (epoch ms) —+ * the GC candidate scan for `pruneTombstonedSeries`. An id-only projection:+ * the sweep almost never finds a tombstone, so the common case must not pay+ * for a single series' JSONB body, let alone every one of them.+ */+export async function listTombstoneIdsBefore(beforeMs) {+ const cutoffIso = new Date(beforeMs).toISOString();+ const { rows } = await query(+ `SELECT id FROM pipeline_series WHERE deleted = TRUE AND deleted_at IS NOT NULL AND deleted_at < $1`,+ [cutoffIso],+ );+ return rows.map((r) => r.id);+}+/** Every record's raw `data` JSONB in one query (live/ephemeral/tombstones). */export async function listRaw() {const { rows } = await query(`SELECT data FROM pipeline_series`);diff --git a/server/services/pipeline/seriesStore/db.test.js b/server/services/pipeline/seriesStore/db.test.jsindex bcb620f6bc..4ef098503c 100644--- a/server/services/pipeline/seriesStore/db.test.js+++ b/server/services/pipeline/seriesStore/db.test.js@@ -86,6 +86,25 @@ describe.skipIf(!runDb)('pipeline series DB adapter round-trip', () => {expect((await db.listIds()).sort()).toEqual(['ser-dead', 'ser-ghost', 'ser-live']);});+ it('listLiveIds returns only non-deleted ids', async () => {+ await db.writeRaw('ser-live', S('ser-live'));+ await db.writeRaw('ser-dead', S('ser-dead', { deleted: true, deletedAt: '2026-02-02T00:00:00.000Z' }));+ await db.writeRaw('ser-ghost', S('ser-ghost', { ephemeral: true }));+ expect((await db.listLiveIds()).sort()).toEqual(['ser-ghost', 'ser-live']);+ });++ it('listTombstoneIdsBefore returns only tombstones older than the cutoff, keeping a NULL deleted_at', async () => {+ await db.writeRaw('ser-live', S('ser-live'));+ await db.writeRaw('ser-old', S('ser-old', { deleted: true, deletedAt: '2026-01-01T00:00:00.000Z' }));+ await db.writeRaw('ser-new', S('ser-new', { deleted: true, deletedAt: '2026-06-01T00:00:00.000Z' }));+ // mirrorTimestamp(deletedAt, null) leaves deleted_at NULL for an+ // unparseable value — `deleted_at < $1` is never true against NULL, so+ // the row is conservatively excluded from every cutoff.+ await db.writeRaw('ser-bad', S('ser-bad', { deleted: true, deletedAt: 'not-a-date' }));+ const cutoff = Date.parse('2026-03-01T00:00:00.000Z');+ expect(await db.listTombstoneIdsBefore(cutoff)).toEqual(['ser-old']);+ });+it('tolerates a malformed timestamp without throwing (falls back)', async () => {await db.writeRaw('ser-bad', S('ser-bad', { updatedAt: 'not-a-date', createdAt: 'nope' }));const col = (await query(`SELECT created_at, updated_at FROM pipeline_series WHERE id = 'ser-bad'`)).rows[0];diff --git a/server/services/pipeline/seriesStore/store.js b/server/services/pipeline/seriesStore/store.jsindex 8b5379f2fb..ef7e3020b1 100644--- a/server/services/pipeline/seriesStore/store.js+++ b/server/services/pipeline/seriesStore/store.js@@ -72,6 +72,26 @@ function makeFileBackend(dir, sanitizeRecord) {const records = await Promise.all(ids.map((id) => cs.loadOneRaw(id)));return records.filter((r) => r != null);},+ // The file layout can't project — `deleted` lives inside each record, so+ // a live-only or tombstone-cutoff id list means reading them all. Mirrors+ // the JS filter series.js used to run over loadAll() directly — same+ // conservative "unparseable deletedAt is kept" rule.+ listLiveIds: async () => {+ const ids = await cs.listIds();+ const records = await Promise.all(ids.map((id) => cs.loadOneRaw(id)));+ return records.filter((r) => r && r.deleted !== true).map((r) => r.id);+ },+ listTombstoneIdsBefore: async (beforeMs) => {+ const ids = await cs.listIds();+ const records = await Promise.all(ids.map((id) => cs.loadOneRaw(id)));+ const out = [];+ for (const r of records) {+ if (!r?.deleted || typeof r.id !== 'string' || !r.id) continue;+ const t = Date.parse(r.deletedAt || '');+ if (Number.isFinite(t) && t < beforeMs) out.push(r.id);+ }+ return out;+ },writeRaw: (id, record) => cs.saveOneNow(id, record),deleteRaw: (id) => cs.deleteOneNow(id),verify: () => cs.verifySchemaVersion(),@@ -88,6 +108,8 @@ function makePgBackend(db, sanitizeRecord) {return raw ? sanitizeRecord(raw) : null;},listIds: db.listIds,+ listLiveIds: db.listLiveIds,+ listTombstoneIdsBefore: db.listTombstoneIdsBefore,listRaw: db.listRaw,writeRaw: db.writeRaw,deleteRaw: db.deleteRaw,@@ -146,6 +168,8 @@ function createFacade({ dir, sanitizeRecord }) {// Reads (sanitized, matching collectionStore.loadOne/loadAll)listIds: async () => (await getBackend()).listIds(),+ listLiveIds: async () => (await getBackend()).listLiveIds(),+ listTombstoneIdsBefore: async (beforeMs) => (await getBackend()).listTombstoneIdsBefore(beforeMs),loadOne,loadOneRaw: async (id) => {if (typeof id !== 'string' || !ID_PATTERN.test(id)) return null;diff --git a/server/services/pipeline/seriesStore/store.test.js b/server/services/pipeline/seriesStore/store.test.jsindex 91c1f7d211..6e90648917 100644--- a/server/services/pipeline/seriesStore/store.test.js+++ b/server/services/pipeline/seriesStore/store.test.js@@ -57,6 +57,23 @@ describe('pipeline series store facade — file backend', () => {expect(all.every((r) => r._sanitized)).toBe(true);});+ it('listLiveIds returns only non-deleted ids', async () => {+ const s = getSeriesStore(passthroughSanitize);+ await s.saveOneNow('ser-1', { id: 'ser-1', name: 'Live' });+ await s.saveOneNow('ser-2', { id: 'ser-2', name: 'Dead', deleted: true, deletedAt: '2026-01-01T00:00:00.000Z' });+ expect(await s.listLiveIds()).toEqual(['ser-1']);+ });++ it('listTombstoneIdsBefore returns only tombstones older than the cutoff, keeping unparseable deletedAt', async () => {+ const s = getSeriesStore(passthroughSanitize);+ await s.saveOneNow('ser-live', { id: 'ser-live', name: 'Live' });+ await s.saveOneNow('ser-old', { id: 'ser-old', name: 'Old', deleted: true, deletedAt: '2026-01-01T00:00:00.000Z' });+ await s.saveOneNow('ser-new', { id: 'ser-new', name: 'New', deleted: true, deletedAt: '2026-06-01T00:00:00.000Z' });+ await s.saveOneNow('ser-bad', { id: 'ser-bad', name: 'Bad', deleted: true, deletedAt: 'not-a-date' });+ const cutoff = Date.parse('2026-03-01T00:00:00.000Z');+ expect(await s.listTombstoneIdsBefore(cutoff)).toEqual(['ser-old']);+ });+it('deleteOneNow removes the record', async () => {const s = getSeriesStore(passthroughSanitize);await s.saveOneNow('ser-1', { id: 'ser-1', name: 'X' });diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.jsindex 9c4e0e1d33..bf45b54dae 100644--- a/server/services/sharing/tombstoneGc.js+++ b/server/services/sharing/tombstoneGc.js@@ -36,10 +36,18 @@* failed). See `TRACK_COHORT_KINDS` / `confirmedFloorForSub` below.*/-import { pruneTombstonedUniverses, listUniverses } from '../universeBuilder.js';-import { pruneTombstonedSeries, listSeries } from '../pipeline/series.js';+import {+ pruneTombstonedUniverses,+ listLiveIds as listLiveUniverseIds,+ listIds as listUniverseIds,+} from '../universeBuilder.js';+import {+ pruneTombstonedSeries,+ listLiveIds as listLiveSeriesIds,+ listIds as listSeriesIds,+} from '../pipeline/series.js';import { pruneTombstonedIssues, listIssueIds } from '../pipeline/issues.js';-import { pruneTombstonedCollections, listCollections } from '../mediaCollections.js';+import { pruneTombstonedCollections, listCollections, listCollectionIds } from '../mediaCollections.js';import { pruneTombstonedAuthors, listAuthorIds } from '../authors/index.js';import { pruneTombstonedArtists, listArtistIds } from '../artists/index.js';import { pruneTombstonedAlbums, listAlbumIds } from '../albums/index.js';@@ -50,7 +58,11 @@ import {listProjectIds as listMusicVideoProjectIds,} from '../musicVideo/projects.js';import { pruneTombstonedBoards, listBoardIds } from '../moodBoard/index.js';-import { pruneTombstonedLooms, listLooms } from '../fableLoom/index.js';+import {+ pruneTombstonedLooms,+ listLiveIds as listLiveLoomIds,+ listIds as listLoomIds,+} from '../fableLoom/index.js';import {pruneTombstonedWorks, listWorkIdsForSync,pruneTombstonedFolders, listFolderIdsForSync,@@ -78,9 +90,16 @@ import { PEER_SUBSCRIBABLE_KINDS } from './peerSyncShared.js';// `listIssueIds` (not `listIssues`) because the latter caps at 1000 — a capped// source would report a live record beyond the cap as missing and the sweep// would strip its base hash, silently disabling conflict detection for it.+//+// universe/series/fableLoom read id-only projections (`listLiveIds` — a SQL+// `WHERE deleted = FALSE`, or the file-backend hydrate+filter twin) instead of+// the full-record listers: this sweep runs every tick and almost never finds+// anything to strip, so it must not pay for every universe/series/loom body+// (#6851). mediaCollection is file-backed with `deleted` living inside the+// record, so there's no cheaper live projection — it still hydrates.const LIVE_ID_LISTERS = Object.freeze({- universe: async () => (await listUniverses()).map((r) => r.id),- series: async () => (await listSeries()).map((r) => r.id),+ universe: () => listLiveUniverseIds(),+ series: () => listLiveSeriesIds(),issue: () => listIssueIds(),mediaCollection: async () => (await listCollections()).map((r) => r.id),author: () => listAuthorIds(),@@ -90,7 +109,7 @@ const LIVE_ID_LISTERS = Object.freeze({creativeDirectorProject: () => listProjectIds(),musicVideoProject: () => listMusicVideoProjectIds(),moodBoard: () => listBoardIds(),- fableLoom: async () => (await listLooms()).map((r) => r.id),+ fableLoom: () => listLiveLoomIds(),writersRoomWork: () => listWorkIdsForSync(),writersRoomFolder: () => listFolderIdsForSync(),writersRoomExercise: () => listExerciseIdsForSync(),@@ -105,10 +124,18 @@ const LIVE_ID_LISTERS = Object.freeze({// directory is actually gone (hard-deleted by the tombstone prune above).// Issues are absent — they're never directly subscribed (issue tombstones// ride their parent series's push, so PEER_SUBSCRIBABLE_KINDS has no 'issue').+//+// universe/series/fableLoom/mediaCollection read id-only projections here too+// (`listIds`/`listCollectionIds` — every row, no JSONB body) instead of the+// full-record `{ includeDeleted: true }` listers, same hydration-avoidance+// reasoning as LIVE_ID_LISTERS above. mediaCollection's projection is a+// directory listing (collectionStore.listIds()), not a SQL query — the file+// layout has no `deleted` column to filter live vs. tombstoned rows on, but a+// plain id listing needs no hydration either way.const ALL_ID_LISTERS = Object.freeze({- universe: async () => (await listUniverses({ includeDeleted: true })).map((r) => r.id),- series: async () => (await listSeries({ includeDeleted: true })).map((r) => r.id),- mediaCollection: async () => (await listCollections({ includeDeleted: true })).map((r) => r.id),+ universe: () => listUniverseIds(),+ series: () => listSeriesIds(),+ mediaCollection: () => listCollectionIds(),author: () => listAuthorIds({ includeDeleted: true }),artist: () => listArtistIds({ includeDeleted: true }),album: () => listAlbumIds({ includeDeleted: true }),@@ -116,7 +143,7 @@ const ALL_ID_LISTERS = Object.freeze({creativeDirectorProject: () => listProjectIds({ includeDeleted: true }),musicVideoProject: () => listMusicVideoProjectIds({ includeDeleted: true }),moodBoard: () => listBoardIds({ includeDeleted: true }),- fableLoom: async () => (await listLooms({ includeDeleted: true })).map((r) => r.id),+ fableLoom: () => listLoomIds(),writersRoomWork: () => listWorkIdsForSync({ includeDeleted: true }),writersRoomFolder: () => listFolderIdsForSync({ includeDeleted: true }),writersRoomExercise: () => listExerciseIdsForSync({ includeDeleted: true }),diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.jsindex bef7dd90d8..ba2fe01423 100644--- a/server/services/sharing/tombstoneGc.test.js+++ b/server/services/sharing/tombstoneGc.test.js@@ -7,10 +7,14 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';vi.mock('../universeBuilder.js', () => ({pruneTombstonedUniverses: vi.fn().mockResolvedValue({ pruned: 0 }),listUniverses: vi.fn().mockResolvedValue([]),+ listLiveIds: vi.fn().mockResolvedValue([]),+ listIds: vi.fn().mockResolvedValue([]),}));vi.mock('../pipeline/series.js', () => ({pruneTombstonedSeries: vi.fn().mockResolvedValue({ pruned: 0 }),listSeries: vi.fn().mockResolvedValue([]),+ listLiveIds: vi.fn().mockResolvedValue([]),+ listIds: vi.fn().mockResolvedValue([]),}));vi.mock('../pipeline/issues.js', () => ({pruneTombstonedIssues: vi.fn().mockResolvedValue({ pruned: 0 }),@@ -19,6 +23,7 @@ vi.mock('../pipeline/issues.js', () => ({vi.mock('../mediaCollections.js', () => ({pruneTombstonedCollections: vi.fn().mockResolvedValue({ pruned: 0 }),listCollections: vi.fn().mockResolvedValue([]),+ listCollectionIds: vi.fn().mockResolvedValue([]),}));vi.mock('../authors/index.js', () => ({pruneTombstonedAuthors: vi.fn().mockResolvedValue({ pruned: 0 }),@@ -51,6 +56,8 @@ vi.mock('../moodBoard/index.js', () => ({vi.mock('../fableLoom/index.js', () => ({pruneTombstonedLooms: vi.fn().mockResolvedValue({ pruned: 0 }),listLooms: vi.fn().mockResolvedValue([]),+ listLiveIds: vi.fn().mockResolvedValue([]),+ listIds: vi.fn().mockResolvedValue([]),}));vi.mock('../writersRoom/sync.js', () => ({pruneTombstonedWorks: vi.fn().mockResolvedValue({ pruned: 0 }),@@ -87,10 +94,16 @@ import {getSweepStatus,TOMBSTONE_GRACE_MS,} from './tombstoneGc.js';-import { pruneTombstonedUniverses, listUniverses } from '../universeBuilder.js';-import { pruneTombstonedSeries, listSeries } from '../pipeline/series.js';+import {+ pruneTombstonedUniverses, listUniverses,+ listLiveIds as listLiveUniverseIds, listIds as listUniverseIds,+} from '../universeBuilder.js';+import {+ pruneTombstonedSeries, listSeries,+ listLiveIds as listLiveSeriesIds, listIds as listSeriesIds,+} from '../pipeline/series.js';import { pruneTombstonedIssues, listIssueIds } from '../pipeline/issues.js';-import { pruneTombstonedCollections, listCollections } from '../mediaCollections.js';+import { pruneTombstonedCollections, listCollections, listCollectionIds } from '../mediaCollections.js';import { pruneTombstonedAuthors, listAuthorIds } from '../authors/index.js';import { pruneTombstonedArtists, listArtistIds } from '../artists/index.js';import { pruneTombstonedAlbums, listAlbumIds } from '../albums/index.js';@@ -98,7 +111,10 @@ import { pruneTombstonedTracks, listTrackIds } from '../tracks/index.js';import { pruneTombstonedProjects } from '../creativeDirector/local.js';import { pruneTombstonedProjects as pruneTombstonedMusicVideoProjects } from '../musicVideo/projects.js';import { pruneTombstonedBoards } from '../moodBoard/index.js';-import { pruneTombstonedLooms } from '../fableLoom/index.js';+import {+ pruneTombstonedLooms, listLooms,+ listLiveIds as listLiveLoomIds, listIds as listLoomIds,+} from '../fableLoom/index.js';import { pruneTombstonedWorks, pruneTombstonedFolders, pruneTombstonedExercises } from '../writersRoom/sync.js';import { pruneTombstonedCommissionFeedback } from '../creativeCommissions/feedbackStore.js';import { pruneTombstonedCommissions } from '../creativeCommissions/store.js';@@ -235,8 +251,13 @@ describe('sweepTombstones — orphaned base-hash sweep', () => {});it('passes a resolver that keeps live records, drops dead ones, keeps unknown kinds, and lists each kind once', async () => {- listUniverses.mockResolvedValue([{ id: 'u-live' }]);- listSeries.mockResolvedValue([{ id: 's-live' }]);+ // universe/series/fableLoom resolve through id-only projections+ // (listLiveIds), NOT the full-record listers — #6851, this sweep runs+ // every tick and must not hydrate a universe/series/loom body just to+ // find nothing to prune.+ listLiveUniverseIds.mockResolvedValue(['u-live']);+ listLiveSeriesIds.mockResolvedValue(['s-live']);+ listLiveLoomIds.mockResolvedValue(['fl-live']);listIssueIds.mockResolvedValue(['i-live']); // already ids, uncappedlistCollections.mockResolvedValue([{ id: 'c-live' }]);listAuthorIds.mockResolvedValue(['auth-live']);@@ -265,18 +286,26 @@ describe('sweepTombstones — orphaned base-hash sweep', () => {expect(await resolver('album', 'album-gone')).toBe(false);expect(await resolver('track', 'track-live')).toBe(true);expect(await resolver('track', 'track-gone')).toBe(false);+ expect(await resolver('fableLoom', 'fl-live')).toBe(true);+ expect(await resolver('fableLoom', 'fl-gone')).toBe(false);// Unknown kind is always kept and never triggers a listing.expect(await resolver('brain', 'whatever')).toBe(true);// A second probe of an already-listed kind reuses the cached id-set —- // listUniverses is called exactly once across both universe probes.- expect(listUniverses).toHaveBeenCalledTimes(1);- expect(listSeries).toHaveBeenCalledTimes(1);+ // listLiveUniverseIds is called exactly once across both universe probes.+ expect(listLiveUniverseIds).toHaveBeenCalledTimes(1);+ expect(listLiveSeriesIds).toHaveBeenCalledTimes(1);+ expect(listLiveLoomIds).toHaveBeenCalledTimes(1);expect(listIssueIds).toHaveBeenCalledTimes(1);expect(listCollections).toHaveBeenCalledTimes(1);expect(listAuthorIds).toHaveBeenCalledTimes(1);expect(listArtistIds).toHaveBeenCalledTimes(1);expect(listAlbumIds).toHaveBeenCalledTimes(1);expect(listTrackIds).toHaveBeenCalledTimes(1);+ // The hydration this issue removes: a scheduled sweep must never call the+ // full-record listers for these three kinds.+ expect(listUniverses).not.toHaveBeenCalled();+ expect(listSeries).not.toHaveBeenCalled();+ expect(listLooms).not.toHaveBeenCalled();});});@@ -314,12 +343,15 @@ describe('sweepTombstones — orphaned peer-subscription sweep', () => {});it('passes a tombstone-inclusive resolver: keeps live + tombstoned records, drops dir-gone ones, keeps unknown kinds, lists once', async () => {- // includeDeleted:true listers — a tombstoned record (u-tomb) is STILL in the- // list, so its sub must survive (it pushes the delete to peers). Only a- // record whose dir is truly gone (u-gone) resolves false.- listUniverses.mockResolvedValue([{ id: 'u-live' }, { id: 'u-tomb', deleted: true }]);- listSeries.mockResolvedValue([{ id: 's-live' }]);- listCollections.mockResolvedValue([{ id: 'c-live' }]);+ // universe/series/fableLoom/mediaCollection resolve through id-only+ // projections that already include tombstones (listIds /+ // listCollectionIds) — #6851, no full-record hydration. A tombstoned id+ // (u-tomb) is STILL in the list, so its sub must survive (it pushes the+ // delete to peers). Only an id truly absent (u-gone) resolves false.+ listUniverseIds.mockResolvedValue(['u-live', 'u-tomb']);+ listSeriesIds.mockResolvedValue(['s-live']);+ listLoomIds.mockResolvedValue(['fl-live']);+ listCollectionIds.mockResolvedValue(['c-live']);listAuthorIds.mockResolvedValue(['auth-live']);listArtistIds.mockResolvedValue(['artist-live']);listAlbumIds.mockResolvedValue(['album-live']);@@ -343,14 +375,23 @@ describe('sweepTombstones — orphaned peer-subscription sweep', () => {expect(await resolver('album', 'album-gone')).toBe(false);expect(await resolver('track', 'track-live')).toBe(true);expect(await resolver('track', 'track-gone')).toBe(false);+ expect(await resolver('fableLoom', 'fl-live')).toBe(true);+ expect(await resolver('fableLoom', 'fl-gone')).toBe(false);// Unknown kind (issues are never directly subscribed) is always kept and// never triggers a listing.expect(await resolver('issue', 'i-whatever')).toBe(true);expect(await resolver('brain', 'whatever')).toBe(true);- // The resolver lists with includeDeleted so tombstones are visible.- expect(listUniverses).toHaveBeenCalledWith({ includeDeleted: true });// Cached id-set — a second universe probe reuses the listing.- expect(listUniverses).toHaveBeenCalledTimes(1);+ expect(listUniverseIds).toHaveBeenCalledTimes(1);+ expect(listSeriesIds).toHaveBeenCalledTimes(1);+ expect(listLoomIds).toHaveBeenCalledTimes(1);+ expect(listCollectionIds).toHaveBeenCalledTimes(1);+ // The hydration this issue removes: the orphan-subscription sweep must+ // never call the full-record `{ includeDeleted: true }` listers either.+ expect(listUniverses).not.toHaveBeenCalled();+ expect(listSeries).not.toHaveBeenCalled();+ expect(listLooms).not.toHaveBeenCalled();+ expect(listCollections).not.toHaveBeenCalled();});});diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex 8ffe789087..013f47c70e 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -30,11 +30,24 @@ import { isNonBlankStr } from '../lib/textUtils.js';const CURSORS_FILE = dataPath('instances_sync_cursors.json');const SYNC_INTERVAL_MS = 60000;const FETCH_TIMEOUT_MS = 15000;+// The tombstone sweep rides the 60s tick but doesn't need the tick's cadence —+// GRACE_MS (tombstoneGc.js) is 24h, so an hour of extra GC latency is invisible+// to users, and every sweep that finds nothing to prune still id-lists every+// federated kind (#6851). runTombstoneSweep() below gates on this instead of+// firing every tick; the manual `POST /tombstones/sweep` route stays unthrottled+// (it calls sweepTombstones() directly, never through this gate).+const TOMBSTONE_SWEEP_INTERVAL_MS = 60 * 60 * 1000;const withLock = createMutex();let syncTimer = null;let peerOnlineHandler = null;const syncingPeers = new Set();+// 0 = "never swept this process" — runTombstoneSweep() always runs the FIRST+// tick after boot (or after a restart) regardless of this value, then waits+// out the full interval before the next one. Reset alongside the timer in+// initSyncOrchestrator/stopSyncOrchestrator so a restart (and each test) starts+// from "first tick runs".+let lastTombstoneSweepAt = 0;// --- Realtime sync progress ---//@@ -946,6 +959,9 @@ export async function syncAllPeers() {* Initialize the sync orchestrator*/export function initSyncOrchestrator() {+ // Fresh start (boot, or a test's init after a prior stop) always runs the+ // tombstone sweep on the first tick — see TOMBSTONE_SWEEP_INTERVAL_MS above.+ lastTombstoneSweepAt = 0;// Sync immediately when a peer comes onlinepeerOnlineHandler = (peer) => {if (!hasAnySyncEnabled(peer)) return;@@ -981,13 +997,19 @@ export function initSyncOrchestrator() {}/**- * Run a single tombstone GC sweep, fire-and-forget. Dynamic import keeps- * the GC module's universe / pipeline / sharing dependency graph off the- * orchestrator's module-load path (same reason as `categoriesCoveredByPeerSync`- * above). Logs a single-line summary only when something was actually- * pruned — quiet on no-op cycles.+ * Run a single tombstone GC sweep, fire-and-forget — but only once per+ * TOMBSTONE_SWEEP_INTERVAL_MS, not on every 60s tick. Runs on the first tick+ * after boot (`lastTombstoneSweepAt === 0`) so a fresh process doesn't wait a+ * full hour for its first GC pass. Dynamic import keeps the GC module's+ * universe / pipeline / sharing dependency graph off the orchestrator's+ * module-load path (same reason as `categoriesCoveredByPeerSync` above). Logs+ * a single-line summary only when something was actually pruned — quiet on+ * no-op cycles.*/async function runTombstoneSweep() {+ const now = Date.now();+ if (lastTombstoneSweepAt !== 0 && now - lastTombstoneSweepAt < TOMBSTONE_SWEEP_INTERVAL_MS) return;+ lastTombstoneSweepAt = now;const { sweepTombstones } = await import('./sharing/tombstoneGc.js');const result = await sweepTombstones().catch((err) => {console.error(`❌ Tombstone sweep failed: ${err.message}`);@@ -1029,6 +1051,7 @@ async function runBrainTombstoneSweep() {* Stop the sync orchestrator*/export function stopSyncOrchestrator() {+ lastTombstoneSweepAt = 0;if (peerOnlineHandler) {instanceEvents.removeListener('peer:online', peerOnlineHandler);peerOnlineHandler = null;diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.jsindex 59a8aab0f4..297e1efa96 100644--- a/server/services/syncOrchestrator.test.js+++ b/server/services/syncOrchestrator.test.js@@ -104,8 +104,24 @@ vi.mock('fs/promises', () => ({writeFile: vi.fn().mockResolvedValue(),rename: vi.fn().mockResolvedValue()}));+// runTombstoneSweep/runBrainTombstoneSweep each `await import(...)` this+// module lazily (keeps the GC dependency graphs off the orchestrator's own+// module-load path) — vitest's mock registry covers a dynamic import the same+// as a static one, so this intercepts it. Zero-valued results so the+// no-op-cycle logging branches in both functions stay quiet.+vi.mock('./sharing/tombstoneGc.js', () => ({+ sweepTombstones: vi.fn().mockResolvedValue({+ universes: 0, series: 0, issues: 0, collections: 0,+ orphanBaseHashes: 0, orphanSubscriptions: 0, refused: [],+ }),+}));+vi.mock('./brainTombstoneGc.js', () => ({+ sweepBrainTombstones: vi.fn().mockResolvedValue({ pruned: 0 }),+}));import { readJSONFile } from '../lib/fileUtils.js';+import { sweepTombstones } from './sharing/tombstoneGc.js';+import { sweepBrainTombstones } from './brainTombstoneGc.js';import { getPeers } from './instances.js';import { applyRemoteChanges as applyBrainChanges } from './brainSync.js';import { BRAIN_ENTITY_TYPES } from './brainStorage.js';@@ -1110,6 +1126,42 @@ describe('syncOrchestrator', () => {// syncAllPeers should have been triggeredexpect(getPeers).toHaveBeenCalled();});++ // #6851 — the tombstone sweep no longer rides every 60s tick; it's gated+ // to once per TOMBSTONE_SWEEP_INTERVAL_MS (1h), except the very first tick+ // after boot always runs it so a fresh process doesn't wait an hour.+ it('runs the tombstone sweep on the first tick after boot', async () => {+ initSyncOrchestrator();+ getPeers.mockResolvedValue([]);+ await vi.advanceTimersByTimeAsync(60000);+ expect(sweepTombstones).toHaveBeenCalledTimes(1);+ });++ it('does not run the tombstone sweep again on the very next tick (60s later)', async () => {+ initSyncOrchestrator();+ getPeers.mockResolvedValue([]);+ await vi.advanceTimersByTimeAsync(60000); // first tick — sweeps+ await vi.advanceTimersByTimeAsync(60000); // second tick, 60s later — gated+ expect(sweepTombstones).toHaveBeenCalledTimes(1);+ });++ it('runs the tombstone sweep again once a full hour has elapsed', async () => {+ initSyncOrchestrator();+ getPeers.mockResolvedValue([]);+ await vi.advanceTimersByTimeAsync(60000); // first tick (t=60s) — sweeps+ await vi.advanceTimersByTimeAsync(60 * 60 * 1000); // t=1h60s — due again+ expect(sweepTombstones).toHaveBeenCalledTimes(2);+ });++ it('runs syncAllPeers and the brain tombstone sweep on every tick regardless of the tombstone-sweep gate', async () => {+ initSyncOrchestrator();+ getPeers.mockResolvedValue([]);+ await vi.advanceTimersByTimeAsync(60000); // t=60s — tombstone sweep runs (first tick)+ await vi.advanceTimersByTimeAsync(60000); // t=120s — tombstone sweep gated+ expect(getPeers).toHaveBeenCalledTimes(2); // syncAllPeers fires every tick+ expect(sweepBrainTombstones).toHaveBeenCalledTimes(2); // brain sweep is untouched by this gate+ expect(sweepTombstones).toHaveBeenCalledTimes(1); // gated on the second tick+ });});describe('stopSyncOrchestrator', () => {diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.jsindex 6f25905f08..e2b71e31cf 100644--- a/server/services/universeBuilder.test.js+++ b/server/services/universeBuilder.test.js@@ -1421,6 +1421,53 @@ describe("universeBuilder service", () => {expect(await svc.pruneTombstonedUniverses(Infinity)).toEqual({ pruned: 0 });expect(await svc.pruneTombstonedUniverses('not-a-number')).toEqual({ pruned: 0 });});++ it("rescues a record un-deleted between the id-only candidate scan and the queued delete (race safety, #6851)", async () => {+ // The candidate scan now comes from listTombstoneIdsBefore (a store+ // projection) instead of an out-of-queue listRaw()+filter, but the+ // race it must still lose to is the same one pruneTombstonedUniverses+ // has always guarded against: a concurrent sync un-deleting the record+ // between that scan and the per-id queued re-check.+ const w = await seedWorld();+ await svc.deleteUniverse(w.id);+ const oldDeletedAt = new Date(Date.now() - 100_000).toISOString();+ await svc.mergeUniversesFromSync([{+ ...(await svc.getUniverse(w.id, { includeDeleted: true })),+ deletedAt: oldDeletedAt,+ updatedAt: new Date(Date.now() + 10_000).toISOString(),+ }]);+ const cutoff = Date.now() - 50_000;++ // Hold the record's per-id write queue open BEFORE calling prune, so+ // prune's own queueRecordWrite(w.id, recheck) — issued only after its+ // async candidate scan resolves — is forced to queue BEHIND this held+ // task. Writes directly through the facade (not mergeUniversesFromSync,+ // which would itself re-enter queueRecordWrite for the same id and+ // deadlock against the very task it's called from).+ const s = svc.store();+ let releaseHold;+ const holdGate = new Promise((resolve) => { releaseHold = resolve; });+ const held = s.queueRecordWrite(w.id, async () => {+ await holdGate;+ const current = await s.loadOne(w.id);+ await s.writeRecord(w.id, {+ ...current,+ deleted: false,+ deletedAt: null,+ updatedAt: new Date(Date.now() + 20_000).toISOString(),+ });+ });++ const prunePromise = svc.pruneTombstonedUniverses(cutoff);+ releaseHold();+ await held;+ const result = await prunePromise;++ expect(result.pruned).toBe(0);+ const remaining = await svc.listUniverses({ includeDeleted: true });+ const rescued = remaining.find((u) => u.id === w.id);+ expect(rescued?.deleted).toBe(false);+ });});});diff --git a/server/services/universeBuilder/db.js b/server/services/universeBuilder/db.jsindex 7fcdcf27e7..8a5117a494 100644--- a/server/services/universeBuilder/db.js+++ b/server/services/universeBuilder/db.js@@ -41,6 +41,32 @@ export async function listIds() {return rows.map((r) => r.id);}+/**+ * Live (non-deleted) universe ids only — id-only projection hitting+ * idx_universes_live. Backs tombstoneGc's LIVE_ID_LISTERS (the base-hash+ * orphan sweep), so a record stops protecting its base hash the moment it's+ * tombstoned without the sweep ever reading a universe's JSONB body.+ */+export async function listLiveIds() {+ const { rows } = await query(`SELECT id FROM universes WHERE deleted = FALSE`);+ return rows.map((r) => r.id);+}++/**+ * Tombstoned universe ids whose deletedAt is older than `beforeMs` (epoch ms) —+ * the GC candidate scan for `pruneTombstonedUniverses`. An id-only projection:+ * the sweep almost never finds a tombstone, so the common case must not pay+ * for a single universe's JSONB body, let alone every one of them.+ */+export async function listTombstoneIdsBefore(beforeMs) {+ const cutoffIso = new Date(beforeMs).toISOString();+ const { rows } = await query(+ `SELECT id FROM universes WHERE deleted = TRUE AND deleted_at IS NOT NULL AND deleted_at < $1`,+ [cutoffIso],+ );+ return rows.map((r) => r.id);+}+/*** Every record's raw `data` JSONB in one query (live/ephemeral/tombstones).* The bulk read behind listUniverses — one SELECT instead of N per-id reads.diff --git a/server/services/universeBuilder/db.test.js b/server/services/universeBuilder/db.test.jsindex 0feeb3bec6..2c8ee6410d 100644--- a/server/services/universeBuilder/db.test.js+++ b/server/services/universeBuilder/db.test.js@@ -97,6 +97,26 @@ describe.skipIf(!runDb)('universeBuilder DB adapter round-trip', () => {expect(ids).toEqual(['dead', 'ghost', 'live']);});+ it('listLiveIds returns only non-deleted ids', async () => {+ await db.writeRaw('live', U('live'));+ await db.writeRaw('dead', U('dead', { deleted: true, deletedAt: '2026-02-02T00:00:00.000Z' }));+ await db.writeRaw('ghost', U('ghost', { ephemeral: true }));+ expect((await db.listLiveIds()).sort()).toEqual(['ghost', 'live']);+ });++ it('listTombstoneIdsBefore returns only tombstones older than the cutoff, keeping a NULL deleted_at', async () => {+ await db.writeRaw('live', U('live'));+ await db.writeRaw('old', U('old', { deleted: true, deletedAt: '2026-01-01T00:00:00.000Z' }));+ await db.writeRaw('new', U('new', { deleted: true, deletedAt: '2026-06-01T00:00:00.000Z' }));+ // writeRaw's mirrorTimestamp(record.deletedAt, null) falls back to NULL+ // (not NOW()) for an unparseable deletedAt — `deleted_at < $1` is never+ // true against NULL, so this row is conservatively excluded from every+ // cutoff, matching the JS filter's "unparseable → kept" rule.+ await db.writeRaw('bad', U('bad', { deleted: true, deletedAt: 'not-a-date' }));+ const cutoff = Date.parse('2026-03-01T00:00:00.000Z');+ expect(await db.listTombstoneIdsBefore(cutoff)).toEqual(['old']);+ });+it('listRaw returns every record body verbatim in one query', async () => {await db.writeRaw('u-1', U('u-1', { logline: 'x' }));await db.writeRaw('u-2', U('u-2'));diff --git a/server/services/universeBuilder/store.js b/server/services/universeBuilder/store.jsindex 95e7ba5e4d..472109054a 100644--- a/server/services/universeBuilder/store.js+++ b/server/services/universeBuilder/store.js@@ -90,6 +90,25 @@ function makeFileBackend(dir) {name: 'file',readRaw: (id) => cs.loadOneRaw(id),listIds: () => cs.listIds(),+ // The file layout can't project either — `deleted` lives inside each+ // record, so a live-only or tombstone-cutoff id list means reading them+ // all (same constraint as countUniverses below). Mirrors the JS filters+ // the service used to run over listRaw() directly — same conservative+ // "unparseable deletedAt is kept" rule.+ listLiveIds: async () => {+ const records = await listRaw();+ return records.filter((r) => r?.deleted !== true).map((r) => r.id);+ },+ listTombstoneIdsBefore: async (beforeMs) => {+ const records = await listRaw();+ const out = [];+ for (const r of records) {+ if (!r?.deleted || typeof r.id !== 'string' || !r.id) continue;+ const t = Date.parse(r.deletedAt || '');+ if (Number.isFinite(t) && t < beforeMs) out.push(r.id);+ }+ return out;+ },listRaw,// There is no cheap count on the file layout — `deleted` lives INSIDE each// record, so knowing which ids are live means reading them all (listIds()@@ -164,6 +183,8 @@ function makePgBackend(db) {name: 'postgres',readRaw: db.readRaw,listIds: db.listIds,+ listLiveIds: db.listLiveIds,+ listTombstoneIdsBefore: db.listTombstoneIdsBefore,listRaw: db.listRaw,countUniverses: db.countUniverses,listNames: db.listNames,@@ -223,6 +244,8 @@ function createFacade({ dir, sanitizeRecord }) {// ReadslistIds: async () => (await getBackend()).listIds(),+ listLiveIds: async () => (await getBackend()).listLiveIds(),+ listTombstoneIdsBefore: async (beforeMs) => (await getBackend()).listTombstoneIdsBefore(beforeMs),listRaw: async () => (await getBackend()).listRaw(),countUniverses: async (opts) => (await getBackend()).countUniverses(opts),listNames: async () => (await getBackend()).listNames(),diff --git a/server/services/universeBuilder/store.test.js b/server/services/universeBuilder/store.test.jsindex 5b4a15439f..e372135aab 100644--- a/server/services/universeBuilder/store.test.js+++ b/server/services/universeBuilder/store.test.js@@ -59,6 +59,28 @@ describe('universe store facade — file backend', () => {expect(all.every((r) => !('_sanitized' in r))).toBe(true); // raw, not sanitized});+ it('listLiveIds returns only non-deleted ids', async () => {+ const s = getUniverseStore(passthroughSanitize);+ await s.writeRecord('u-1', { id: 'u-1', name: 'Live' });+ await s.writeRecord('u-2', { id: 'u-2', name: 'Dead', deleted: true, deletedAt: '2026-01-01T00:00:00.000Z' });+ await s.writeRecord('u-3', { id: 'u-3', name: 'Ghost', ephemeral: true });+ // Ephemeral (but not deleted) counts as live — matches db.listLiveIds'+ // `WHERE deleted = FALSE` (it doesn't filter on ephemeral either).+ expect((await s.listLiveIds()).sort()).toEqual(['u-1', 'u-3']);+ });++ it('listTombstoneIdsBefore returns only tombstones older than the cutoff, keeping unparseable deletedAt', async () => {+ const s = getUniverseStore(passthroughSanitize);+ await s.writeRecord('u-live', { id: 'u-live', name: 'Live' });+ await s.writeRecord('u-old', { id: 'u-old', name: 'Old', deleted: true, deletedAt: '2026-01-01T00:00:00.000Z' });+ await s.writeRecord('u-new', { id: 'u-new', name: 'New', deleted: true, deletedAt: '2026-06-01T00:00:00.000Z' });+ // Non-parseable deletedAt is conservatively KEPT — never a candidate,+ // regardless of cutoff (mirrors the JS filter this projection replaces).+ await s.writeRecord('u-bad', { id: 'u-bad', name: 'Bad', deleted: true, deletedAt: 'not-a-date' });+ const cutoff = Date.parse('2026-03-01T00:00:00.000Z');+ expect(await s.listTombstoneIdsBefore(cutoff)).toEqual(['u-old']);+ });+it('listStyles projects to the style fields and drops tombstones', async () => {const s = getUniverseStore(passthroughSanitize);await s.writeRecord('u-1', {diff --git a/server/services/universeBuilder/sync.js b/server/services/universeBuilder/sync.jsindex 7c52a34abf..37d22bb734 100644--- a/server/services/universeBuilder/sync.js+++ b/server/services/universeBuilder/sync.js@@ -187,6 +187,24 @@ export async function mergeUniversesFromSync(remoteUniverses, { source = { via:return result;}+/**+ * Universe id listers for the tombstone-sweep's orphan resolvers+ * (server/services/sharing/tombstoneGc.js). Both are id-only projections — no+ * record hydration, no sanitize — so a sweep that only checks set membership+ * never pays for a universe's JSONB body, let alone every one of them.+ *+ * `listLiveIds` excludes tombstones (LIVE_ID_LISTERS — a record stops+ * protecting its base hash once tombstoned); `listIds` includes them+ * (ALL_ID_LISTERS — a tombstone still owns its peer subscription until the+ * record is hard-deleted).+ */+export async function listLiveIds() {+ return store().listLiveIds();+}+export async function listIds() {+ return store().listIds();+}+/*** Garbage-collect universe tombstones older than `beforeMs`. Pure of GC* policy — the caller (server/services/sharing/tombstoneGc.js) owns the@@ -199,17 +217,13 @@ export async function mergeUniversesFromSync(remoteUniverses, { source = { via:export async function pruneTombstonedUniverses(beforeMs) {if (!Number.isFinite(beforeMs)) return { pruned: 0 };const s = store();- // Bulk raw read for the out-of-queue candidate scan — we only need- // id/deleted/deletedAt, so skip the per-record sanitize. The authoritative- // re-check inside each per-id queue below still uses loadOne (sanitized).- const records = await s.listRaw();- const candidates = [];- for (const u of records) {- if (!u?.deleted || !isStr(u.id)) continue;- const t = Date.parse(u.deletedAt || '');- if (!Number.isFinite(t)) continue;- if (t < beforeMs) candidates.push(u.id);- }+ // Id-only candidate scan for the out-of-queue pass — a SQL projection on+ // Postgres (`WHERE deleted = TRUE AND deleted_at < $1`), hydrate+filter on+ // the file escape hatch. The sweep almost never finds a tombstone, so this+ // must not pay for every universe's JSONB body just to find zero candidates.+ // The authoritative re-check inside each per-id queue below still uses+ // loadOne (sanitized).+ const candidates = await s.listTombstoneIdsBefore(beforeMs);// Per-id deletes fan out, but we re-check the tombstone status INSIDE each// per-id queue. A concurrent mergeUniversesFromSync could have un-deleted// the record (newer remote `updatedAt`, `deleted: false`) between our