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(peer-sync): Stage 5 — tombstone GC sweep (#438)
[._.]/ Adam Eivye21662990284
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex cac113bbfb..b2fdd15a34 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,6 +1,7 @@# Unreleased Changes## Added+- Federated peer-sync tombstone GC (Stage 5 of 5). New `server/services/sharing/tombstoneGc.js` runs once per 60s sync tick and prunes tombstoned universes / series / issues that every subscribed peer has acked + a 24h grace buffer. The cutoff is `min(now, minAckedAcrossPeers) - 24h`, which collapses the "no peers subscribed" and "peers behind" cases into one formula (Infinity from an empty peer list clamps via `Math.min` to `now`). Issue tombstones use the series ack horizon since issues ride series pushes. Three new exports (`pruneTombstonedUniverses`, `pruneTombstonedSeries`, `pruneTombstonedIssues`) on the record services are mechanical-prune helpers — the GC module owns the policy. `syncOrchestrator` dynamically imports `sweepTombstones` to keep the GC's universe / pipeline / sharing graph off the orchestrator's boot path. Logs only when prune count > 0.- Federated peer-sync UI + receiver-side asset pull (Stage 4 of 5). New `SyncToPeerButton` (`client/src/components/sharing/SyncToPeerButton.jsx`) appears next to the existing `ShareToButton` on Universe and Series pages — a dropdown of every enabled peer with a check/circle toggle to subscribe/unsubscribe. New `MediaImage` component (`client/src/components/MediaImage.jsx`) wraps `<img>` and renders a "Syncing" placeholder when the asset 404s (peer-pushed records reference UUIDs that haven't been pulled yet); a `peerSync:asset-arrived` socket event swaps the placeholder for the live bytes the moment the receiver's worker lands them. The Instances page now shows a per-peer "Live-pushed records" section listing every active sync subscription with a one-click unsubscribe and a `↩ reverse` badge for subs that were auto-created by an inbound push. New receiver-side `pullMissingAssetsFromPeer` worker in `server/services/sharing/peerSync.js` background-fetches each missing asset from the sender's `/data/{kind-dir}/<filename>` static mount and writes it locally (capped at 100MB per asset, filenames re-validated against path traversal even after the diff already sanitized them). `peerSyncEvents` is wired through `sharing/index.js` to socket clients so the UI updates in real time.- Federated peer-sync HTTP routes and orchestrator wiring (Stage 3 of 5). New `server/routes/peerSync.js` mounts at `/api/peer-sync` with `POST /push` (receiver-side; wraps `applyIncomingPush` with Zod-validated payload + asset-manifest size cap of 2000), `GET/POST /subscriptions` (list + create local outgoing subs), and `DELETE /subscriptions/:id`. `installPeerSyncListener()` now runs alongside `installSubscriptionListener` in `initSharing` so one `recordEvents 'updated'` fan-out drives both the share-bucket and peer-sync transports. `syncOrchestrator` now consults `listPeerSubscriptions(peerId)` per cycle and skips the snapshot category for any `(peer, kind)` pair where a per-record peer subscription exists (universe-sub → skip 'universe' snapshot; series-sub → skip 'pipeline' snapshot) so the push pipeline owns the wire for subscribed pairs and the 60s loop stops re-applying the same records. Asset static mounts under `/data/{images,image-refs,videos,video-thumbnails}` now pass `acceptRanges: true` explicitly so the receiver's background asset-pull can resume partial downloads over flaky Tailnet links (default of serve-static, now encoded as a contract so it can't accidentally regress).- Federated peer-sync pipeline modules (Stage 2 of 5). New `server/services/sharing/peerSync.js` holds the per-record subscription store (`data/sharing/peer_subscriptions.json`), the asset-manifest builder, the push pipeline that serializes a record + its child issues + the SHA-manifest to a peer's `/api/peer-sync/push` endpoint, and the receiver-side `applyIncomingPush` that merges via the existing `merge*FromSync` LWW path, computes the asset-diff response, and best-effort auto-creates a reverse subscription back to the sender (honoring per-peer `directions: ['inbound']` to skip when explicitly inbound-only). New `server/services/sharing/peerTombstoneCursors.js` holds per-peer `lastAckedDeleteAt` water-marks so a tombstone is only GC'd once every subscribed peer has acked it (with a `subscribedSince` horizon so late-joining peers don't have to ingest every historical deletion). State writes serialize through a module-level `writeTail` so a fire-and-forget push can't clobber a concurrent subscribe write on the same JSON. The actual HTTP routes and orchestrator wiring land in Stage 3.diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex a237a34a09..ea16178e8c 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -952,3 +952,29 @@ export function mergeIssuesFromSync(remoteIssues) {return { applied: true, count: changed };});}++/**+ * Garbage-collect issue tombstones older than `beforeMs`. See+ * `pruneTombstonedUniverses` for the contract — pure mechanical prune; the+ * caller owns the policy. Tombstones with unparseable `deletedAt` are kept.+ *+ * Issue tombstones ride series pushes (the receiver bundles child issues+ * with each series push) so the relevant ack horizon is "peers subscribed+ * to the parent series." The caller resolves that.+ */+export async function pruneTombstonedIssues(beforeMs) {+ if (!Number.isFinite(beforeMs)) return { pruned: 0 };+ return queueIssueWrite(async () => {+ const state = await readState();+ const original = state.issues.length;+ state.issues = state.issues.filter((i) => {+ if (!i?.deleted) return true;+ const t = Date.parse(i.deletedAt || '');+ if (!Number.isFinite(t)) return true;+ return t >= beforeMs;+ });+ const pruned = original - state.issues.length;+ if (pruned > 0) await writeState(state);+ return { pruned };+ });+}diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.jsindex 964394507b..6fd7327208 100644--- a/server/services/pipeline/issues.test.js+++ b/server/services/pipeline/issues.test.js@@ -817,6 +817,51 @@ describe('pipeline issues service', () => {expect(live.map((i) => i.number)).toEqual([1, 2]);});});++ describe('pruneTombstonedIssues', () => {+ it('removes tombstones older than the cutoff and leaves newer ones + live records', async () => {+ const live = await svc.createIssue({ seriesId: 'ser-prune', title: 'Live' });+ const oldT = await svc.createIssue({ seriesId: 'ser-prune', title: 'Old' });+ const newT = await svc.createIssue({ seriesId: 'ser-prune', title: 'New' });+ await svc.deleteIssue(oldT.id);+ await svc.deleteIssue(newT.id);+ // Back-date the old tombstone via merge so the GC sees it as 100s ago.+ const oldDeletedAt = new Date(Date.now() - 100_000).toISOString();+ const oldIssue = await svc.getIssue(oldT.id, { includeDeleted: true });+ await svc.mergeIssuesFromSync([{+ ...oldIssue,+ deletedAt: oldDeletedAt,+ updatedAt: new Date(Date.now() + 10_000).toISOString(),+ }]);+ const cutoff = Date.now() - 50_000;+ const result = await svc.pruneTombstonedIssues(cutoff);+ expect(result.pruned).toBe(1);+ const remaining = await svc.listIssues({ seriesId: 'ser-prune', includeDeleted: true });+ const ids = remaining.map((i) => i.id);+ expect(ids).toContain(live.id);+ expect(ids).toContain(newT.id);+ expect(ids).not.toContain(oldT.id);+ });++ it('keeps tombstones with unparseable deletedAt (conservative — never silently delete)', async () => {+ const issue = await svc.createIssue({ seriesId: 'ser-corrupt', title: 'C' });+ await svc.deleteIssue(issue.id);+ const tomb = await svc.getIssue(issue.id, { includeDeleted: true });+ await svc.mergeIssuesFromSync([{+ ...tomb,+ deletedAt: 'not-a-date',+ updatedAt: new Date(Date.now() + 10_000).toISOString(),+ }]);+ const result = await svc.pruneTombstonedIssues(Date.now() + 60_000_000);+ expect(result.pruned).toBe(0);+ });++ it('returns { pruned: 0 } for a non-finite cutoff (defensive)', async () => {+ expect(await svc.pruneTombstonedIssues(NaN)).toEqual({ pruned: 0 });+ expect(await svc.pruneTombstonedIssues(Infinity)).toEqual({ pruned: 0 });+ expect(await svc.pruneTombstonedIssues('nope')).toEqual({ pruned: 0 });+ });+ });});describe('isStageReady', () => {diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex ef3c47dd41..59648fe154 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -476,3 +476,26 @@ export async function mergeSeriesFromSync(remoteSeries) {}return result;}++/**+ * Garbage-collect series tombstones older than `beforeMs`. See+ * `pruneTombstonedUniverses` in universeBuilder.js for the contract — the+ * caller owns the ack-cursor + grace-period math and just tells us the+ * cutoff timestamp. Tombstones with unparseable `deletedAt` are kept.+ */+export async function pruneTombstonedSeries(beforeMs) {+ if (!Number.isFinite(beforeMs)) return { pruned: 0 };+ return queueSeriesWrite(async () => {+ const state = await readState();+ const original = state.series.length;+ state.series = state.series.filter((s) => {+ if (!s?.deleted) return true;+ const t = Date.parse(s.deletedAt || '');+ if (!Number.isFinite(t)) return true;+ return t >= beforeMs;+ });+ const pruned = original - state.series.length;+ if (pruned > 0) await writeState(state);+ return { pruned };+ });+}diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.jsindex aa377ac815..f87dcdf9a2 100644--- a/server/services/pipeline/series.test.js+++ b/server/services/pipeline/series.test.js@@ -166,6 +166,51 @@ describe('pipeline series service', () => {await expect(svc.getSeries(s.id)).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });});});++ describe('pruneTombstonedSeries', () => {+ it('removes tombstones older than the cutoff and leaves newer ones + live records', async () => {+ const live = await svc.createSeries({ name: 'Live' });+ const oldT = await svc.createSeries({ name: 'Old tombstone' });+ const newT = await svc.createSeries({ name: 'New tombstone' });+ await svc.deleteSeries(oldT.id);+ await svc.deleteSeries(newT.id);+ // Back-date the old tombstone via merge so the GC sees it as 100s ago.+ const oldDeletedAt = new Date(Date.now() - 100_000).toISOString();+ const oldSeries = await svc.getSeries(oldT.id, { includeDeleted: true });+ await svc.mergeSeriesFromSync([{+ ...oldSeries,+ deletedAt: oldDeletedAt,+ updatedAt: new Date(Date.now() + 10_000).toISOString(),+ }]);+ const cutoff = Date.now() - 50_000;+ const result = await svc.pruneTombstonedSeries(cutoff);+ expect(result.pruned).toBe(1);+ const remaining = await svc.listSeries({ includeDeleted: true });+ const ids = remaining.map((s) => s.id);+ expect(ids).toContain(live.id);+ expect(ids).toContain(newT.id);+ expect(ids).not.toContain(oldT.id);+ });++ it('keeps tombstones with unparseable deletedAt (conservative — never silently delete)', async () => {+ const s = await svc.createSeries({ name: 'Corrupt' });+ await svc.deleteSeries(s.id);+ const tomb = await svc.getSeries(s.id, { includeDeleted: true });+ await svc.mergeSeriesFromSync([{+ ...tomb,+ deletedAt: 'not-a-date',+ updatedAt: new Date(Date.now() + 10_000).toISOString(),+ }]);+ const result = await svc.pruneTombstonedSeries(Date.now() + 60_000_000);+ expect(result.pruned).toBe(0);+ });++ it('returns { pruned: 0 } for a non-finite cutoff (defensive)', async () => {+ expect(await svc.pruneTombstonedSeries(NaN)).toEqual({ pruned: 0 });+ expect(await svc.pruneTombstonedSeries(Infinity)).toEqual({ pruned: 0 });+ expect(await svc.pruneTombstonedSeries('nope')).toEqual({ pruned: 0 });+ });+ });});it('listSeries sorts newest updated first', async () => {diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.jsnew file mode 100644index 0000000000..dfd895a629--- /dev/null+++ b/server/services/sharing/tombstoneGc.js@@ -0,0 +1,164 @@+/**+ * Tombstone garbage collection for federated peer sync.+ *+ * The Stage 1 soft-delete refactor turned deletes into tombstone records+ * (`{ deleted: true, deletedAt }`) so the LWW merge can keep them from+ * being resurrected by out-of-date peers. Tombstones cannot be pruned+ * blindly — if peer-A deletes record X and peer-B comes online later,+ * peer-B's snapshot must still see the tombstone so its older "live" copy+ * loses the merge.+ *+ * This sweep prunes a tombstone only when BOTH conditions hold:+ * 1. Every peer currently subscribed to the record's kind has acked a+ * deletedAt at least as recent as the tombstone (so we know every+ * subscriber has received and applied this specific deletion).+ * 2. At least GRACE_MS has elapsed since the tombstone was created — a+ * buffer for transient replay / disconnect cases that haven't shown+ * up in the ack water-mark yet.+ *+ * When a record's kind has NO subscribed peers, condition (1) is trivially+ * satisfied (`getMinAckAcrossPeers([])` returns Infinity), so the sweep+ * falls back to a simple "older than grace" check.+ *+ * Issues piggyback on the series subscription model — an issue tombstone+ * is only pushed alongside its parent series's push, so the relevant ack+ * cohort for issue tombstones is "peers subscribed to series".+ *+ * Wired into the syncOrchestrator interval; runs once per cycle (~60s)+ * since the math is cheap (read 3 small JSONs + cursor map) and prunes+ * in place when there's anything to drop.+ */++import { pruneTombstonedUniverses } from '../universeBuilder.js';+import { pruneTombstonedSeries } from '../pipeline/series.js';+import { pruneTombstonedIssues } from '../pipeline/issues.js';+import { listPeerSubscriptions } from './peerSync.js';+import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';+import { getPeers } from '../instances.js';++const GRACE_MS = 24 * 60 * 60 * 1000; // 24h grace++/**+ * Resolve the set of peer ids currently subscribed to a given record kind.+ * The result feeds `getMinAckAcrossPeers` to compute the GC water-mark.+ *+ * Returns an array of unique instance ids; an empty array means "no+ * subscribers — fall back to time-only grace."+ */+async function peerIdsSubscribedToKind(recordKind) {+ const subs = await listPeerSubscriptions({ recordKind });+ return [...new Set(subs.map((s) => s.peerId).filter(Boolean))];+}++/**+ * Map a record kind to the snapshot-sync category that ships it on the wire.+ * Universe records ride the 'universe' snapshot category; series + issues+ * both ride the 'pipeline' snapshot category (which bundles them together+ * — see `dataSync.getPipelineSnapshot`).+ */+function snapshotCategoryForKind(recordKind) {+ if (recordKind === 'universe') return 'universe';+ if (recordKind === 'series' || recordKind === 'issue') return 'pipeline';+ return null;+}++/**+ * Returns the set of enabled peer instance-ids that can still send us a+ * snapshot of this record kind via the 60s snapshot loop in `dataSync.js`.+ *+ * The snapshot path has NO per-peer ack water-mark — peerTombstoneCursors+ * only tracks acks from the per-record push pipeline. So for every peer in+ * this set that's NOT also covered by a per-record subscription, we have+ * zero proof they've received any deletion we want to prune. An offline+ * peer with an older LIVE copy could come back, push its snapshot, and+ * `merge*FromSync` would INSERT the resurrected record (the merge path+ * inserts records the local file is missing).+ *+ * Legacy peers without an explicit `syncCategories` map fall back to+ * brain+memory only (see syncOrchestrator.getEffectiveCategories), so+ * they can't send universe/pipeline snapshots — excluded from the set.+ */+async function snapshotPeerIdsForKind(recordKind) {+ const category = snapshotCategoryForKind(recordKind);+ if (!category) return [];+ const peers = await getPeers().catch(() => []);+ return peers+ .filter((p) => {+ if (!p?.enabled) return false;+ const cats = p.syncCategories;+ return !!cats && typeof cats === 'object' && cats[category] === true;+ })+ .map((p) => p.instanceId)+ .filter(Boolean);+}++/**+ * Compute the cutoff timestamp: tombstones with `deletedAt < cutoff` are+ * safe to prune. The cutoff is the EARLIER of "now - grace" and+ * "minAck - grace" — i.e. we subtract the grace buffer from whichever+ * water-mark is lower, so we never prune past the laggiest peer's ack.+ *+ * Returns `null` to mean "refuse to prune" — used when ANY snapshot-mode+ * peer for this kind is NOT covered by a per-record subscription. The+ * snapshot path has no ack water-mark, so an uncovered snapshot peer+ * can resurrect a pruned tombstone on its next snapshot push. This+ * applies BOTH to "no per-record subs at all" AND to "mixed deployment+ * where peer-A has per-record subs but peer-B is snapshot-only" — both+ * cases leave at least one peer un-acked, so both must refuse.+ *+ * Otherwise: subtract grace from `min(now, minAckedAcrossPeers)`. The+ * `Math.min` collapses the two safe branches into one formula:+ * - no peers at all (no subs, no snapshot peers) → minAck=Infinity →+ * cutoff = now - grace+ * - every snapshot peer also has a per-record sub → minAck < now →+ * cutoff = minAck - grace+ *+ * @returns {number|null} the cutoff ms-epoch (or null to refuse).+ */+async function cutoffForKind(recordKind, { now = Date.now() } = {}) {+ const peerIds = await peerIdsSubscribedToKind(recordKind);+ const snapshotPeerIds = await snapshotPeerIdsForKind(recordKind);+ // Snapshot-mode peers NOT covered by per-record subscriptions have no+ // ack horizon — refuse to prune until every snapshot peer is covered+ // OR they're disabled (the filter in snapshotPeerIdsForKind drops them).+ const subbed = new Set(peerIds);+ const uncovered = snapshotPeerIds.filter((id) => !subbed.has(id));+ if (uncovered.length > 0) return null;+ const minAck = await getMinAckAcrossPeers(peerIds);+ const threshold = Math.min(minAck, now);+ return threshold - GRACE_MS;+}++/**+ * One sweep cycle. Runs all three kinds in parallel — each prune call is+ * already serialized through its own service's write queue, so concurrent+ * kicks don't race local writers.+ *+ * Returns `{ universes, series, issues }` with the prune count per kind so+ * the orchestrator can log a single-line summary on non-zero cycles and+ * stay quiet otherwise.+ */+export async function sweepTombstones({ now = Date.now() } = {}) {+ const [universeCutoff, seriesCutoff] = await Promise.all([+ cutoffForKind('universe', { now }),+ cutoffForKind('series', { now }),+ ]);+ // Issue tombstones ride series pushes — same ack cohort, same cutoff.+ const issueCutoff = seriesCutoff;+ // Skip the prune entirely when cutoff is null (snapshot-mode peer exists+ // for the kind, no ack horizon → refuse to prune to avoid resurrection).+ const [u, s, i] = await Promise.all([+ universeCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedUniverses(universeCutoff),+ seriesCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedSeries(seriesCutoff),+ issueCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedIssues(issueCutoff),+ ]);+ return {+ universes: u.pruned,+ series: s.pruned,+ issues: i.pruned,+ };+}++// Constants exported for tests; module-level so future tuning doesn't+// require a code search to find the magic number.+export const TOMBSTONE_GRACE_MS = GRACE_MS;diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.jsnew file mode 100644index 0000000000..25d3d488bb--- /dev/null+++ b/server/services/sharing/tombstoneGc.test.js@@ -0,0 +1,247 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// All four downstream surfaces are mocked so we can drive the math without+// touching real state files. The point of these tests is the cutoff policy+// (grace + min-ack), not the pure-mechanical prune helpers — those are+// covered by their own service tests.+vi.mock('../universeBuilder.js', () => ({+ pruneTombstonedUniverses: vi.fn().mockResolvedValue({ pruned: 0 }),+}));+vi.mock('../pipeline/series.js', () => ({+ pruneTombstonedSeries: vi.fn().mockResolvedValue({ pruned: 0 }),+}));+vi.mock('../pipeline/issues.js', () => ({+ pruneTombstonedIssues: vi.fn().mockResolvedValue({ pruned: 0 }),+}));+vi.mock('./peerSync.js', () => ({+ listPeerSubscriptions: vi.fn(),+}));+vi.mock('./peerTombstoneCursors.js', () => ({+ getMinAckAcrossPeers: vi.fn(),+}));+vi.mock('../instances.js', () => ({+ getPeers: vi.fn(),+}));++import {+ sweepTombstones,+ TOMBSTONE_GRACE_MS,+} from './tombstoneGc.js';+import { pruneTombstonedUniverses } from '../universeBuilder.js';+import { pruneTombstonedSeries } from '../pipeline/series.js';+import { pruneTombstonedIssues } from '../pipeline/issues.js';+import { listPeerSubscriptions } from './peerSync.js';+import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';+import { getPeers } from '../instances.js';++const NOW = 1_700_000_000_000; // arbitrary epoch ms anchor++beforeEach(() => {+ vi.clearAllMocks();+ // Default: no peer subscriptions (empty array → getMinAckAcrossPeers+ // returns Infinity in the real implementation; mirror that here).+ listPeerSubscriptions.mockResolvedValue([]);+ getMinAckAcrossPeers.mockResolvedValue(Infinity);+ // Default: no snapshot-mode peers either — clears the resurrection-safety+ // gate so the cutoff defaults to `now - GRACE`.+ getPeers.mockResolvedValue([]);+});++describe('TOMBSTONE_GRACE_MS', () => {+ it('is 24 hours so an off-by-a-magnitude regression fails the test (not silently in prod)', () => {+ expect(TOMBSTONE_GRACE_MS).toBe(24 * 60 * 60 * 1000);+ });+});++describe('sweepTombstones — no peers subscribed', () => {+ it('uses now-GRACE as the cutoff for all three kinds when nobody is subscribed', async () => {+ await sweepTombstones({ now: NOW });+ const expectedCutoff = NOW - TOMBSTONE_GRACE_MS;+ expect(pruneTombstonedUniverses).toHaveBeenCalledWith(expectedCutoff);+ expect(pruneTombstonedSeries).toHaveBeenCalledWith(expectedCutoff);+ expect(pruneTombstonedIssues).toHaveBeenCalledWith(expectedCutoff);+ });+});++describe('sweepTombstones — peers behind', () => {+ it("clamps the universe cutoff to the laggiest universe-subscribed peer (can't prune past min-ack)", async () => {+ // Regression: if we used `now - GRACE` even when peers are subscribed,+ // we'd prune tombstones the laggiest peer hasn't seen yet — and a+ // subsequent push from that peer would resurrect the record under its+ // older `updatedAt`.+ const minAck = NOW - 48 * 60 * 60 * 1000; // 48h behind now+ listPeerSubscriptions.mockImplementation(async ({ recordKind }) => {+ if (recordKind === 'universe') return [{ peerId: 'peer-a' }];+ return [];+ });+ getMinAckAcrossPeers.mockImplementation(async (peerIds) => {+ if (peerIds.includes('peer-a')) return minAck;+ return Infinity;+ });+ await sweepTombstones({ now: NOW });+ expect(pruneTombstonedUniverses).toHaveBeenCalledWith(minAck - TOMBSTONE_GRACE_MS);+ // series + issues still use now-GRACE since no series subs exist.+ expect(pruneTombstonedSeries).toHaveBeenCalledWith(NOW - TOMBSTONE_GRACE_MS);+ expect(pruneTombstonedIssues).toHaveBeenCalledWith(NOW - TOMBSTONE_GRACE_MS);+ });++ it('uses the same cutoff for issues as for series (issue tombstones ride series pushes)', async () => {+ // Regression: if issue cutoff used issues' own subscription cohort,+ // it would always be `now - GRACE` (issues are never directly+ // subscribable) — but issues need to wait for series-subscribed peers+ // to ack their parent series's push.+ const seriesAck = NOW - 72 * 60 * 60 * 1000;+ listPeerSubscriptions.mockImplementation(async ({ recordKind }) => {+ if (recordKind === 'series') return [{ peerId: 'peer-a' }];+ return [];+ });+ getMinAckAcrossPeers.mockImplementation(async (peerIds) => {+ if (peerIds.includes('peer-a')) return seriesAck;+ return Infinity;+ });+ await sweepTombstones({ now: NOW });+ const seriesCutoff = seriesAck - TOMBSTONE_GRACE_MS;+ expect(pruneTombstonedSeries).toHaveBeenCalledWith(seriesCutoff);+ expect(pruneTombstonedIssues).toHaveBeenCalledWith(seriesCutoff);+ });++ it('does NOT clamp past `now` when peers are ahead of wall-clock (defensive)', async () => {+ // Regression: a peer's lastAckedDeleteAt should never legitimately+ // exceed now (it's an ack of OUR deletion timestamps), but if some+ // future replay or clock skew put it there, the cutoff must still+ // not move into the future — otherwise we'd prune tombstones the+ // local user just created.+ const ahead = NOW + 24 * 60 * 60 * 1000;+ listPeerSubscriptions.mockImplementation(async ({ recordKind }) => {+ if (recordKind === 'universe') return [{ peerId: 'peer-a' }];+ return [];+ });+ getMinAckAcrossPeers.mockImplementation(async () => ahead);+ await sweepTombstones({ now: NOW });+ expect(pruneTombstonedUniverses).toHaveBeenCalledWith(NOW - TOMBSTONE_GRACE_MS);+ });++ it('passes the unique peer-id list to getMinAckAcrossPeers (no duplicate ids)', async () => {+ // Subscriptions are per-record, so one peer can appear in many sub+ // rows. Pass the deduped set to the cursor query — otherwise a peer+ // subscribed to 50 universes would over-count itself.+ listPeerSubscriptions.mockImplementation(async ({ recordKind }) => {+ if (recordKind === 'universe') {+ return [+ { peerId: 'peer-a' },+ { peerId: 'peer-a' }, // same peer, different record+ { peerId: 'peer-b' },+ ];+ }+ return [];+ });+ getMinAckAcrossPeers.mockResolvedValue(NOW - 1000);+ await sweepTombstones({ now: NOW });+ expect(getMinAckAcrossPeers).toHaveBeenCalledWith(+ expect.arrayContaining(['peer-a', 'peer-b']),+ );+ const firstCallArgs = getMinAckAcrossPeers.mock.calls[0][0];+ // De-dup invariant.+ expect(new Set(firstCallArgs).size).toBe(firstCallArgs.length);+ });+});++describe('sweepTombstones — return shape', () => {+ it('returns the per-kind prune count so the orchestrator can log a single-line summary', async () => {+ pruneTombstonedUniverses.mockResolvedValueOnce({ pruned: 2 });+ pruneTombstonedSeries.mockResolvedValueOnce({ pruned: 0 });+ pruneTombstonedIssues.mockResolvedValueOnce({ pruned: 5 });+ const result = await sweepTombstones({ now: NOW });+ expect(result).toEqual({ universes: 2, series: 0, issues: 5 });+ });+});++describe('sweepTombstones — resurrection safety against snapshot-mode peers', () => {+ it('refuses to prune universe tombstones when a snapshot-mode peer exists for the universe category', async () => {+ // Regression: with no per-record subs but a snapshot-mode peer enabled+ // for `universe`, an offline peer could come back with an older LIVE+ // copy and force-resurrect via mergeUniversesFromSync's "no local+ // record → insert" branch. We must refuse to prune.+ listPeerSubscriptions.mockResolvedValue([]);+ getPeers.mockResolvedValue([+ { instanceId: 'peer-a', enabled: true, syncCategories: { universe: true, pipeline: false } },+ ]);+ await sweepTombstones({ now: NOW });+ // Universe prune is skipped (no call); series + issues still run+ // because no peer has pipeline=true here.+ expect(pruneTombstonedUniverses).not.toHaveBeenCalled();+ expect(pruneTombstonedSeries).toHaveBeenCalledWith(NOW - TOMBSTONE_GRACE_MS);+ expect(pruneTombstonedIssues).toHaveBeenCalledWith(NOW - TOMBSTONE_GRACE_MS);+ });++ it('refuses to prune series + issue tombstones when a pipeline snapshot-mode peer exists', async () => {+ // Same risk on the pipeline side — and the gate must apply to BOTH+ // series and issues (issues ride pipeline snapshots bundled with+ // series).+ listPeerSubscriptions.mockResolvedValue([]);+ getPeers.mockResolvedValue([+ { instanceId: 'peer-a', enabled: true, syncCategories: { universe: false, pipeline: true } },+ ]);+ await sweepTombstones({ now: NOW });+ expect(pruneTombstonedUniverses).toHaveBeenCalled();+ expect(pruneTombstonedSeries).not.toHaveBeenCalled();+ expect(pruneTombstonedIssues).not.toHaveBeenCalled();+ });++ it('still prunes when per-record subscriptions exist (their min-ack water-mark provides the safety we need)', async () => {+ // Snapshot peers are also subscribed via per-record: the ack cursor+ // tracks every push they receive, so we have a horizon and CAN prune.+ listPeerSubscriptions.mockImplementation(async ({ recordKind }) => {+ if (recordKind === 'universe') return [{ peerId: 'peer-a' }];+ return [];+ });+ getMinAckAcrossPeers.mockResolvedValue(NOW - 1000);+ getPeers.mockResolvedValue([+ { instanceId: 'peer-a', enabled: true, syncCategories: { universe: true, pipeline: true } },+ ]);+ await sweepTombstones({ now: NOW });+ expect(pruneTombstonedUniverses).toHaveBeenCalled();+ });++ it('refuses to prune in mixed deployment (peer-A per-record subscribed, peer-B snapshot-only)', async () => {+ // Regression for the round-3 finding: my round-2 fix only checked the+ // snapshot-mode gate when peerIds.length === 0. But if peer-A has a+ // per-record sub AND peer-B is snapshot-only for the same kind, peer-B+ // has no ack horizon — its next snapshot push could still resurrect+ // a record we pruned based on peer-A's ack alone. The fix now checks+ // for ANY uncovered snapshot peer.+ listPeerSubscriptions.mockImplementation(async ({ recordKind }) => {+ if (recordKind === 'universe') return [{ peerId: 'peer-a' }];+ return [];+ });+ getMinAckAcrossPeers.mockResolvedValue(NOW - 1000);+ getPeers.mockResolvedValue([+ { instanceId: 'peer-a', enabled: true, syncCategories: { universe: true } },+ { instanceId: 'peer-b', enabled: true, syncCategories: { universe: true } }, // snapshot-only+ ]);+ await sweepTombstones({ now: NOW });+ expect(pruneTombstonedUniverses).not.toHaveBeenCalled();+ });++ it("ignores disabled snapshot-mode peers (can't resurrect from a disabled peer)", async () => {+ listPeerSubscriptions.mockResolvedValue([]);+ getPeers.mockResolvedValue([+ { instanceId: 'peer-a', enabled: false, syncCategories: { universe: true } },+ ]);+ await sweepTombstones({ now: NOW });+ expect(pruneTombstonedUniverses).toHaveBeenCalled();+ });++ it("ignores legacy peers with no syncCategories (they can't send universe/pipeline snapshots)", async () => {+ // Legacy peers fall back to brain+memory only in getEffectiveCategories,+ // so they don't participate in the universe/pipeline snapshot loop and+ // can't resurrect those records.+ listPeerSubscriptions.mockResolvedValue([]);+ getPeers.mockResolvedValue([+ { instanceId: 'peer-a', enabled: true /* no syncCategories */ },+ ]);+ await sweepTombstones({ now: NOW });+ expect(pruneTombstonedUniverses).toHaveBeenCalled();+ expect(pruneTombstonedSeries).toHaveBeenCalled();+ });+});diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex d2f82bd23d..39bfb1dd48 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -452,16 +452,47 @@ export function initSyncOrchestrator() {};instanceEvents.on('peer:online', peerOnlineHandler);- // Background safety-net interval+ // Background safety-net interval. The two side-cycle jobs (tombstone GC,+ // future asset-orphan GC) ride the same interval rather than getting their+ // own timer — once-per-minute is plenty given the 24h grace period, and+ // sharing a tick keeps the wake-up cost flat.syncTimer = setInterval(() => {syncAllPeers().catch(err => {console.error(`❌ Periodic sync failed: ${err.message}`);});+ // The outer `.catch` is non-optional — runTombstoneSweep is async and+ // can reject BEFORE its inner .catch fires (e.g. if the dynamic import+ // of tombstoneGc.js itself fails). An unhandled rejection on the+ // interval tick would crash the Node process under default settings.+ runTombstoneSweep().catch(err => {+ console.error(`❌ Tombstone sweep tick failed: ${err.message}`);+ });}, SYNC_INTERVAL_MS);console.log(`🔄 Sync orchestrator started (${SYNC_INTERVAL_MS / 1000}s interval)`);}+/**+ * 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.+ */+async function runTombstoneSweep() {+ const { sweepTombstones } = await import('./sharing/tombstoneGc.js');+ const result = await sweepTombstones().catch((err) => {+ console.error(`❌ Tombstone sweep failed: ${err.message}`);+ return null;+ });+ if (result && (result.universes > 0 || result.series > 0 || result.issues > 0)) {+ // "series" is already its own plural so no s-suffix toggle needed there.+ const universes = `${result.universes} universe${result.universes === 1 ? '' : 's'}`;+ const issues = `${result.issues} issue${result.issues === 1 ? '' : 's'}`;+ console.log(`🪦 Tombstone GC: pruned ${universes}, ${result.series} series, ${issues}`);+ }+}+/*** Stop the sync orchestrator*/diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex c5d60f97e6..45eeb8a73b 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -1255,6 +1255,32 @@ export async function mergeUniversesFromSync(remoteUniverses) {return result;}+/**+ * Garbage-collect universe tombstones older than `beforeMs`. Pure of GC+ * policy — the caller (server/services/sharing/tombstoneGc.js) owns the+ * ack-cursor + grace-period math and just tells us the cutoff timestamp.+ *+ * Tombstones whose `deletedAt` is a non-parseable string are conservatively+ * KEPT — we'd rather leak a few garbled records than silently delete data.+ * Returns `{ pruned }` with the count actually removed.+ */+export async function pruneTombstonedUniverses(beforeMs) {+ if (!Number.isFinite(beforeMs)) return { pruned: 0 };+ return queueUniverseWrite(async () => {+ const state = await readState();+ const original = state.universes.length;+ state.universes = state.universes.filter((u) => {+ if (!u?.deleted) return true;+ const t = Date.parse(u.deletedAt || '');+ if (!Number.isFinite(t)) return true;+ return t >= beforeMs;+ });+ const pruned = original - state.universes.length;+ if (pruned > 0) await writeState(state);+ return { pruned };+ });+}+export async function recordRun(run) {const sanitized = sanitizeRun(run);if (!sanitized) throw makeErr('Invalid run payload', ERR_VALIDATION);diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.jsindex 0a0316b6ce..52f3cfbc94 100644--- a/server/services/universeBuilder.test.js+++ b/server/services/universeBuilder.test.js@@ -696,6 +696,55 @@ describe("universeBuilder service", () => {expect(fresh.universeId).toBeNull();});});++ describe("pruneTombstonedUniverses", () => {+ it("removes tombstones older than the cutoff and leaves newer ones + live records", async () => {+ const live = await seedWorld();+ const oldTombstone = await seedWorld();+ const newTombstone = await seedWorld();+ await svc.deleteUniverse(oldTombstone.id);+ await svc.deleteUniverse(newTombstone.id);+ // Backdate the old tombstone's deletedAt directly via merge.+ const oldDeletedAt = new Date(Date.now() - 100_000).toISOString();+ await svc.mergeUniversesFromSync([{+ ...(await svc.getUniverse(oldTombstone.id, { includeDeleted: true })),+ deletedAt: oldDeletedAt,+ updatedAt: new Date(Date.now() + 10_000).toISOString(),+ }]);++ // Cutoff = now - 50s — old (100s ago) is past, new (just now) is not.+ const cutoff = Date.now() - 50_000;+ const result = await svc.pruneTombstonedUniverses(cutoff);+ expect(result.pruned).toBe(1);+ const remaining = await svc.listUniverses({ includeDeleted: true });+ const ids = remaining.map((u) => u.id);+ expect(ids).toContain(live.id);+ expect(ids).toContain(newTombstone.id);+ expect(ids).not.toContain(oldTombstone.id);+ });++ it("keeps tombstones with unparseable deletedAt (conservative)", async () => {+ const w = await seedWorld();+ await svc.deleteUniverse(w.id);+ // Corrupt the deletedAt via merge — this can happen if a peer ships+ // a malformed record. We refuse to prune anything we can't time-stamp.+ await svc.mergeUniversesFromSync([{+ ...(await svc.getUniverse(w.id, { includeDeleted: true })),+ deletedAt: 'not-a-date',+ updatedAt: new Date(Date.now() + 10_000).toISOString(),+ }]);+ const result = await svc.pruneTombstonedUniverses(Date.now() + 60_000_000);+ expect(result.pruned).toBe(0);+ const remaining = await svc.listUniverses({ includeDeleted: true });+ expect(remaining.find((u) => u.id === w.id)).toBeTruthy();+ });++ it("returns { pruned: 0 } for a non-finite cutoff (defensive)", async () => {+ expect(await svc.pruneTombstonedUniverses(NaN)).toEqual({ pruned: 0 });+ expect(await svc.pruneTombstonedUniverses(Infinity)).toEqual({ pruned: 0 });+ expect(await svc.pruneTombstonedUniverses('not-a-number')).toEqual({ pruned: 0 });+ });+ });});describe("synthesizeCanonPrompt", () => {