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): add ephemeral flag with end-to-end sync-layer enforcement (#445)
[._.]/ Adam Eivyf56ef5d3f0e9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a54b280f12..5b4a01b443 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,6 +1,14 @@# Unreleased Changes## Added+- `ephemeral: true` field on universes, series, and issues — a local-only "don't sync to peers" marker. Set on POST (create) or PATCH; sanitizer normalizes anything non-true back to absent. The wire / push / subscribe / merge / asset layers ALL honor the flag end-to-end:+ - **Wire (`sanitizeRecordForWire`)**: returns `null` for live ephemeral records so both transports (60s snapshot loop + per-record push) skip them. Tombstones for ephemeral records still cross the wire — a once-shared record marked ephemeral then deleted still propagates its delete so peers that still hold the live copy converge. The `ephemeral` field itself is stripped from every wire output so the byte-stable checksum invariant survives even when a stray `ephemeral: false` lives on disk.+ - **Subscription lifecycle**: `createUniverse` / `createSeries` skip auto-subscribe for ephemeral records. `updateUniverse` / `updateSeries` PATCH transitions are wired: false→true tears down every per-record sub for the record (new `unsubscribeAllForRecord` helper); true→false re-fires `autoSubscribeRecordToAllPeers` so the now-shareable record reaches every peer with the matching category. `autoSubscribePeerToAllRecords` (peer:online backfill) filters ephemeral records out of the set-diff.+ - **Receiver-side merges (`mergeUniversesFromSync` / `mergeSeriesFromSync` / `mergeIssuesFromSync`)**: strip inbound `ephemeral` field unconditionally (a buggy/older/non-conformant peer can't plant a "dark" record on the receiver), and refuse the merge entirely when the LOCAL record is ephemeral — peer edits can't overwrite content, peer deletes can't trigger our orphan cascade, and the post-merge asset-pull worker never schedules downloads for local-ephemeral records.+ - **Series asset manifest**: ephemeral AND deleted child issues are filtered out of the asset-manifest input to `buildAssetManifestForSeries` (not just out of the bundled `issues` array). Their tombstones still ride in the bundled `issues` so the receiver's delete cascade can finish — only their asset filenames are stripped, so the receiver doesn't pull bytes for records it's about to orphan. Same rule applies at the top level: a tombstone push for a deleted universe or series ships an empty `assetManifest` (the deleted record itself still crosses so the peer can converge).+ - **`peerSync` listener** now also subscribes to `recordEvents.deleted` (not just `'updated'`) so soft-deletes propagate via the per-record push pipeline — previously they were stranded for any peer that had a per-record sub (which is most peers under the new auto-subscribe). `retryPendingPushesForPeer` walks every sub (not just unpushed ones) on `peer:online`; the `lastPushedHash` short-circuit inside `pushRecordToPeer` skips the network call for unchanged records, so out-of-band file edits (cleanup scripts, hand-edits) re-propagate on the next reconnect.++ New `scripts/cleanup-test-data.js` one-shot soft-deletes records matching a conservative test-fixture name roster (`Test Work`, `Commit U`, `Commit S`, etc. — generic names like `'A'`/`'B'`/`'Live'`/`'Hidden'` deliberately excluded to avoid clobbering real user records), cascading the delete to child issues of each tombstoned series so the orphan-zombie state never materializes. Default is dry-run; `--apply` writes; users restart PM2 afterward to trigger propagation.- 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).diff --git a/scripts/cleanup-test-data.js b/scripts/cleanup-test-data.jsnew file mode 100644index 0000000000..6ff04f2828--- /dev/null+++ b/scripts/cleanup-test-data.js@@ -0,0 +1,166 @@+/**+ * One-shot cleanup for test-fixture records that polluted real `data/`.+ *+ * Background: Vitest test files create universes / series with hard-coded+ * names like "Test Work" and "Commit U". The current tests mock PATHS.data+ * at the filesystem layer, so they should never touch real data — but at+ * some point in the past (before mockPathsDataRoot was widely adopted, or+ * via a stray integration test) these fixtures leaked into the production+ * `data/universe-builder.json` + `data/pipeline-series.json`. The new+ * federated peer-sync auto-subscribe (PR #443) picks them up on+ * `peer:online` and starts pushing them across the federation.+ *+ * This script soft-deletes records whose names EXACTLY match the known+ * test-fixture roster, AND cascades the soft-delete to child issues of+ * each tombstoned series so the orphan-zombie state (children with a+ * seriesId pointing at a tombstone-GC'd parent) never materializes.+ *+ * IMPORTANT — STOP THE SERVER BEFORE `--apply`. This script invokes the+ * service-layer read/modify/write helpers in a SEPARATE Node process from+ * any running portos-server. The service-layer write tails (per-file+ * `writeState` queues) are in-process — they do NOT serialize across+ * processes, so a concurrent `portos-server` write can clobber this+ * script's tombstone (last-writer-wins on the JSON file). Always:+ *+ * pm2 stop portos-server # 1. stop the server+ * node scripts/cleanup-test-data.js # dry-run first+ * node scripts/cleanup-test-data.js --apply # 2. apply+ * pm2 start portos-server # 3. restart+ *+ * The PM2 restart propagation: on boot the server fires `peer:online` →+ * `retryPendingPushesForPeer` → walks every sub and re-pushes (let+ * `lastPushedHash` short-circuit the unchanged ones). The now-tombstoned+ * records hash differently so the tombstone push fires for each peer.+ * That delete event is what reaches peers — `deleteUniverse` /+ * `deleteSeries` emit `recordEvents.deleted` which peer-sync now listens+ * for, but only in the process that has `installPeerSyncListener()`+ * running. The CLI process here doesn't, which is why the restart is the+ * propagation mechanism rather than the script's own writes.+ *+ * Add names to TEST_FIXTURE_*_NAMES if your data has other test residue.+ * Names are matched EXACTLY (after trim) to avoid clobbering user-named+ * records that happen to share a substring (e.g. a real series called+ * "Commit Universe Tour").+ */+import { listUniverses, deleteUniverse } from '../server/services/universeBuilder.js';+import { listSeries, deleteSeries } from '../server/services/pipeline/series.js';+import { listIssues, deleteIssue } from '../server/services/pipeline/issues.js';++// Roster of names known to come from test fixtures. Conservative default:+// only unmistakable test names. Generic single-word names that could+// plausibly be a real user's universe/series (e.g. 'A', 'B', 'Live',+// 'Hidden', 'Original', 'Corrupt', 'Moebius SciFi') are intentionally+// OMITTED — running this script with --apply against a polluted data+// directory must never destroy a real user's record. Add per-install+// names here directly if you find more residue.+//+// Source roster (audited against the test suite as of 2026-05-22):+// server/services/writersRoom/promoteToPipeline.test.js → "Test Work"+// server/services/importer.test.js → "Commit U", "Commit S"+// server/services/pipeline/series.test.js → various (only the+// unambiguously-test ones below)+const TEST_FIXTURE_UNIVERSE_NAMES = new Set([+ 'Test Work',+ 'Commit U',+]);++const TEST_FIXTURE_SERIES_NAMES = new Set([+ 'Commit S',+ 'Linkless S',+ 'Locked S',+ 'Same Title',+ 'Salt Run',+ 'Old tombstone',+ 'New tombstone',+ 'Edited Locally',+]);++function parseArgs(argv) {+ const out = { apply: false };+ for (const arg of argv.slice(2)) {+ if (arg === '--apply') out.apply = true;+ }+ return out;+}++async function main() {+ const { apply } = parseArgs(process.argv);+ if (!apply) {+ console.log('🧪 DRY-RUN — pass --apply to actually soft-delete\n');+ } else {+ // Service-layer write tails are in-process — a concurrent portos-server+ // can clobber tombstones (last-writer-wins on the JSON file). Warn loudly.+ console.log('⚠️ --apply: STOP the server before continuing or tombstones may be clobbered');+ console.log('⚠️ Run `pm2 stop portos-server` first, then `pm2 start portos-server` to propagate\n');+ }++ // Universes (skip already-tombstoned ones so a re-run is a no-op).+ const universes = await listUniverses({ includeDeleted: false });+ const universeTargets = universes.filter(u =>+ TEST_FIXTURE_UNIVERSE_NAMES.has((u.name || '').trim())+ );+ console.log(`🗑️ Universes to delete: ${universeTargets.length}`);+ for (const u of universeTargets) {+ console.log(` - ${u.id.slice(0, 8)} "${u.name}" (updated ${u.updatedAt})`);+ }++ // Series + their child issues. Resolve children up front so the dry-run+ // output also reports the cascade — running with --apply matches.+ const series = await listSeries({ includeDeleted: false });+ const seriesTargets = series.filter(s =>+ TEST_FIXTURE_SERIES_NAMES.has((s.name || '').trim())+ );+ // Map series.id → array of live child issues for that series.+ const childIssuesBySeries = new Map();+ for (const s of seriesTargets) {+ const children = await listIssues({ seriesId: s.id, includeDeleted: false }).catch(() => []);+ childIssuesBySeries.set(s.id, children);+ }+ const totalChildIssues = [...childIssuesBySeries.values()].reduce((n, arr) => n + arr.length, 0);+ console.log(`\n🗑️ Series to delete: ${seriesTargets.length} (cascading ${totalChildIssues} child issue${totalChildIssues === 1 ? '' : 's'})`);+ for (const s of seriesTargets) {+ const children = childIssuesBySeries.get(s.id) || [];+ console.log(` - ${s.id.slice(0, 12)} "${s.name}" (updated ${s.updatedAt}, ${children.length} child issue${children.length === 1 ? '' : 's'})`);+ }++ if (!apply) {+ console.log('\n🧪 DRY-RUN complete — re-run with --apply to write tombstones');+ return;+ }++ // Apply phase — universes first (their child series carry universeId+ // pointers, but the tombstone on the universe doesn't cascade to series;+ // series with this universeId orphan-but-live, which is fine).+ console.log('\n🗑️ Applying universe tombstones...');+ for (const u of universeTargets) {+ await deleteUniverse(u.id).catch(err =>+ console.error(` ⚠️ failed to delete universe ${u.id.slice(0, 8)}: ${err.message}`),+ );+ }+ // Series: tombstone the children FIRST so a re-run can't see them after+ // the parent series tombstone is gone (listIssues filters by seriesId so+ // an orphan child wouldn't surface in the dry-run either — children must+ // go via this script's pass, not the parent's GC). Then tombstone the series.+ console.log('🗑️ Applying issue + series tombstones...');+ for (const s of seriesTargets) {+ const children = childIssuesBySeries.get(s.id) || [];+ for (const i of children) {+ await deleteIssue(i.id).catch(err =>+ console.error(` ⚠️ failed to delete issue ${i.id.slice(0, 12)} (child of ${s.id.slice(0, 12)}): ${err.message}`),+ );+ }+ await deleteSeries(s.id).catch(err =>+ console.error(` ⚠️ failed to delete series ${s.id.slice(0, 12)}: ${err.message}`),+ );+ }+ console.log(`\n✅ Tombstoned ${universeTargets.length} universe(s) + ${seriesTargets.length} series + ${totalChildIssues} issue(s).`);+ console.log('🔄 Now restart the PM2 server to propagate the tombstones to peers:');+ console.log(' pm2 restart portos-server');+ console.log(' (peer:online will re-fire every per-record sub and the new tombstone');+ console.log(' hashes will diverge from lastPushedHash so the deletes push.)');+}++main().catch(err => {+ console.error('❌ cleanup-test-data failed:', err);+ process.exit(1);+});diff --git a/server/lib/syncWire.js b/server/lib/syncWire.jsindex dde3cd3b70..230a7551d4 100644--- a/server/lib/syncWire.js+++ b/server/lib/syncWire.js@@ -57,19 +57,37 @@ export function sanitizeRecordForWire(kind, record) {// permanent mismatch + churn until both sides clean up the corrupt entries.if (!record || typeof record !== 'object' || Array.isArray(record)) return null;if (!isNonEmptyStr(record.id)) return null;+ // Ephemeral records are local-only — scratch universes/series/issues the+ // user (or a test fixture) explicitly marks "don't sync to peers." Filter+ // here so BOTH transports (60s snapshot + per-record push) skip them+ // identically. We never emit `ephemeral` on the wire — the field stays+ // local to whatever instance owns the record, and the wire checksum for+ // non-ephemeral records is byte-stable against pre-flag peers.+ //+ // EXCEPT: tombstones (deleted=true) still cross the wire even when+ // ephemeral=true. If a record was live + shared, then later marked+ // ephemeral, then deleted, peers still have the live copy — they need+ // the tombstone to converge. The strip-below-then-readd-tail dance+ // ensures `ephemeral` never appears in the serialized wire form even+ // when the record carries it on disk.+ if (record.ephemeral === true && record.deleted !== true) return null;switch (kind) {case 'universe':case 'series':case 'issue': {- // Strip the soft-delete fields from the input first, then re-add them- // in canonical position at the END. JS object spread preserves key- // position when *overwriting* an existing key — without this strip, a- // record where `deleted` happens to sit in a non-tail position would- // serialize differently from a freshly-rewritten record where it sits- // at the tail, defeating the byte-stable-checksum invariant the- // dataSync snapshot loop relies on (computeChecksum uses- // JSON.stringify, which is key-order sensitive).- const { deleted: _deleted, deletedAt: _deletedAt, ...rest } = record;+ // Strip the soft-delete fields AND the local-only `ephemeral` flag+ // from the input first, then re-add the soft-delete pair in canonical+ // position at the END. JS object spread preserves key position when+ // *overwriting* an existing key — without this strip, a record where+ // `deleted` happens to sit in a non-tail position would serialize+ // differently from a freshly-rewritten record where it sits at the+ // tail, defeating the byte-stable-checksum invariant the dataSync+ // snapshot loop relies on (computeChecksum uses JSON.stringify, which+ // is key-order sensitive). The `ephemeral` strip protects the same+ // invariant for the tombstone-cross-wire case above: a deleted record+ // that carried `ephemeral: true` on disk MUST hash identically against+ // a pre-flag peer's tombstone for the same record.+ const { deleted: _deleted, deletedAt: _deletedAt, ephemeral: _ephemeral, ...rest } = record;return { ...rest, ...sanitizeSoftDeleteFields(record) };}default:diff --git a/server/lib/syncWire.test.js b/server/lib/syncWire.test.jsindex c38ab096fb..2724498b86 100644--- a/server/lib/syncWire.test.js+++ b/server/lib/syncWire.test.js@@ -116,6 +116,54 @@ describe('syncWire', () => {expect(sanitizeRecordForWire('universe', corrupt)).toEqual({ id: 'u1', deleted: false, deletedAt: null });});++ it('returns null for live ephemeral records — they never cross the wire', () => {+ // All three record kinds honor the ephemeral filter so a local-only+ // scratch record stays off the federation regardless of which+ // category's transport picks it up.+ expect(sanitizeRecordForWire('universe', { id: 'u1', name: 'U', ephemeral: true })).toBeNull();+ expect(sanitizeRecordForWire('series', { id: 's1', name: 'S', ephemeral: true })).toBeNull();+ expect(sanitizeRecordForWire('issue', { id: 'i1', seriesId: 's1', title: 'I', ephemeral: true })).toBeNull();+ });++ it('lets tombstones for ephemeral records cross the wire (a record that was once shared then marked ephemeral then deleted)', () => {+ // The ephemeral filter intentionally does NOT apply when deleted=true.+ // History that matters: U was created live → peer auto-subscribed →+ // user PATCHed { ephemeral: true } → user soft-deleted U. The peer+ // still has the live copy on disk; the tombstone has to reach them+ // for convergence. The wire output strips the `ephemeral` field+ // entirely so the checksum is byte-stable against a pre-flag peer's+ // tombstone for the same record.+ const tombstone = { id: 'u1', name: 'U', ephemeral: true, deleted: true, deletedAt: '2026-05-22T00:00:00Z' };+ const result = sanitizeRecordForWire('universe', tombstone);+ expect(result).not.toBeNull();+ expect(result.ephemeral).toBeUndefined();+ expect(result.deleted).toBe(true);+ expect(result.deletedAt).toBe('2026-05-22T00:00:00Z');+ });++ it('strips a stray `ephemeral: false` from the wire output (byte-stable checksum vs pre-flag peers)', () => {+ // Defensive: if any code path persists `ephemeral: false` on disk+ // (legacy data, hand-edit, importer bypass), the wire JSON must NOT+ // carry the field — otherwise the snapshot checksum diverges from a+ // pre-flag peer's snapshot for the same record and the 60s loop+ // churns forever.+ const result = sanitizeRecordForWire('universe', { id: 'u1', name: 'U', ephemeral: false });+ expect(result).not.toBeNull();+ expect(result.ephemeral).toBeUndefined();+ // Byte-stable shape against a record with no `ephemeral` key at all:+ const reference = sanitizeRecordForWire('universe', { id: 'u1', name: 'U' });+ expect(JSON.stringify(result)).toBe(JSON.stringify(reference));+ });++ it('non-true ephemeral values are NOT filtered for LIVE records (truthy-but-not-true is treated as live)', () => {+ // Matches the soft-delete posture — only the literal `true` triggers+ // the filter so a corrupted payload (`ephemeral: 1` / `'yes'`) can't+ // accidentally remove a record from sync.+ expect(sanitizeRecordForWire('universe', { id: 'u1', ephemeral: 1 })).not.toBeNull();+ expect(sanitizeRecordForWire('universe', { id: 'u1', ephemeral: 'yes' })).not.toBeNull();+ expect(sanitizeRecordForWire('universe', { id: 'u1', ephemeral: false })).not.toBeNull();+ });});describe('sanitizeStateForWire', () => {@@ -154,6 +202,18 @@ describe('syncWire', () => {expect(result.data.universes[1].deleted).toBe(true);});+ it('drops ephemeral records from the snapshot — they live local-only', () => {+ const state = {+ universes: [+ { id: 'live' },+ { id: 'scratch', ephemeral: true },+ ],+ };+ const result = sanitizeStateForWire('universe', state);+ expect(result.data.universes).toHaveLength(1);+ expect(result.data.universes[0].id).toBe('live');+ });+it('returns series + issues for pipeline kind', () => {const state = {series: [{ id: 's1' }],diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex e5b3e8965d..a857134f1f 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -207,6 +207,8 @@ const seriesCreateSchema = z.object({targetFormat: z.enum(seriesSvc.TARGET_FORMATS).optional(),issueCountTarget: z.number().int().min(0).max(seriesSvc.ISSUE_COUNT_TARGET_MAX).optional(),llm: llmSchema,+ // Local-only "don't sync to peers" marker.+ ephemeral: z.boolean().optional(),});const seriesPatchSchema = z.object({@@ -226,6 +228,7 @@ const seriesPatchSchema = z.object({targetFormat: z.enum(seriesSvc.TARGET_FORMATS).optional(),issueCountTarget: z.number().int().min(0).max(seriesSvc.ISSUE_COUNT_TARGET_MAX).optional(),llm: llmSchema,+ ephemeral: z.boolean().optional(),}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });const arcFieldLockSchema = z.object({ locked: z.boolean() });@@ -254,6 +257,7 @@ const issueCreateSchema = z.object({lengthProfile: z.enum(LENGTH_PROFILE_NAMES).optional(),pageTarget: z.number().int().min(CUSTOM_PAGE_MIN).max(CUSTOM_PAGE_MAX).nullable().optional(),minutesTarget: z.number().int().min(CUSTOM_MINUTE_MIN).max(CUSTOM_MINUTE_MAX).nullable().optional(),+ ephemeral: z.boolean().optional(),});const stageInputSchema = z.object({@@ -336,6 +340,7 @@ const issuePatchSchema = z.object({// Union order matters: Zod picks the first arm that succeeds, so the// more-specific schemas (visual, audio) must precede the bare base.stages: z.record(z.string(), z.union([visualStageInputSchema, audioStageInputSchema, stageInputSchema])).optional(),+ ephemeral: z.boolean().optional(),}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });const generateSchema = z.object({diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex a0258d82a9..c7144c4bae 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -156,6 +156,8 @@ const createSchema = z.object({characters: canonArrayField,places: canonArrayField,objects: canonArrayField,+ // Local-only "don't sync to peers" marker — see sanitizeRecordForWire.+ ephemeral: z.boolean().optional(),});// `origin` is a share-bucket provenance block written by the importer + cleared// to null by the user; structurally an object or null.@@ -185,6 +187,7 @@ const patchSchema = z.object({places: canonArrayField,objects: canonArrayField,origin: originField,+ ephemeral: z.boolean().optional(),}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });const expandSchema = z.object({diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex ea16178e8c..fee20f1b6f 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -413,6 +413,11 @@ const sanitizeIssue = (raw) => {updatedAt,// Soft-delete fields — see universeBuilder.sanitizeTemplate....sanitizeSoftDeleteFields(raw),+ // Local-only "don't sync to peers" marker. Issues piggyback on their+ // parent series' subscription, so marking an issue ephemeral keeps the+ // series push payload from carrying it (sanitizeRecordForWire drops it+ // and the series's bundled-issues filter discards the null entry).+ ...(raw.ephemeral === true ? { ephemeral: true } : {}),};};@@ -513,6 +518,7 @@ export function createIssue(input = {}) {stages: input.stages || {},createdAt: new Date().toISOString(),updatedAt: new Date().toISOString(),+ ephemeral: input.ephemeral === true,});if (!next) throw makeErr('Invalid issue payload', ERR_VALIDATION);state.issues.push(next);@@ -724,6 +730,10 @@ export function updateIssue(id, patch = {}, { skipRenumber = false } = {}) {...('pageTarget' in patch ? { pageTarget: patch.pageTarget } : {}),...('minutesTarget' in patch ? { minutesTarget: patch.minutesTarget } : {}),...('origin' in patch ? { origin: patch.origin } : {}),+ // Local-only "don't sync" marker. Issues piggyback on their parent+ // series' subscription, so an ephemeral issue is dropped from the+ // series push payload via sanitizeRecordForWire returning null.+ ...('ephemeral' in patch ? { ephemeral: patch.ephemeral } : {}),stages: mergedStages,updatedAt: new Date().toISOString(),});@@ -905,6 +915,8 @@ export function mergeIssuesFromSync(remoteIssues) {if (!remote || typeof remote !== 'object' || !isStr(remote.id)) continue;const sanitized = sanitizeIssue(remote);if (!sanitized) continue;+ // Strip inbound `ephemeral` — see mergeUniversesFromSync.+ if ('ephemeral' in sanitized) delete sanitized.ephemeral;const local = localById.get(sanitized.id);if (!local) {// No local counterpart — accept the record but don't trigger a@@ -913,6 +925,10 @@ export function mergeIssuesFromSync(remoteIssues) {// we may not even own would spuriously re-export.localById.set(sanitized.id, sanitized);changed++;+ } else if (local.ephemeral === true) {+ // Local-ephemeral issues are immune to inbound merges. See+ // mergeUniversesFromSync for the contract.+ continue;} else {const localTs = local.updatedAt || '';const remoteTs = sanitized.updatedAt || '';diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex e757ba3521..ed9334afc5 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -148,6 +148,10 @@ const sanitizeSeries = (raw) => {// Soft-delete fields — peer sync needs the tombstone in the record itself// so LWW merge can resolve delete-vs-edit races by `updatedAt`....sanitizeSoftDeleteFields(raw),+ // Local-only "don't sync to peers" marker. Persisted only when true so+ // existing series keep their on-disk + wire-checksum shape. See+ // syncWire.sanitizeRecordForWire for the wire-side enforcement.+ ...(raw.ephemeral === true ? { ephemeral: true } : {}),};};@@ -202,19 +206,25 @@ export async function createSeries(input = {}) {llm: input.llm || null,createdAt: now,updatedAt: now,+ ephemeral: input.ephemeral === true,});state.series.push(next);await writeState(state);return next;});- // Fire-and-forget auto-subscribe to every peer with pipeline-sync enabled.- // Dynamic import to dodge a static cycle (peerSync imports merge entry- // points from this module).- import('../sharing/peerSync.js').then(({ autoSubscribeRecordToAllPeers }) =>- autoSubscribeRecordToAllPeers('series', created.id)- ).catch((err) => {- console.log(`⚠️ series: auto-subscribe after create failed: ${err.message}`);- });+ // Skip auto-subscribe for ephemeral series — wire-side push would short-+ // circuit via sanitizeRecordForWire anyway, but not creating the sub up+ // front keeps the subscription store clean.+ if (!created.ephemeral) {+ // Fire-and-forget auto-subscribe to every peer with pipeline-sync enabled.+ // Dynamic import to dodge a static cycle (peerSync imports merge entry+ // points from this module).+ import('../sharing/peerSync.js').then(({ autoSubscribeRecordToAllPeers }) =>+ autoSubscribeRecordToAllPeers('series', created.id)+ ).catch((err) => {+ console.log(`⚠️ series: auto-subscribe after create failed: ${err.message}`);+ });+ }return created;}@@ -262,7 +272,7 @@ export async function updateSeries(id, patch = {}) {if (legacyFields.length > 0) {console.warn(`⚠️ series PATCH ${id.slice(0, 8)} stripped legacy canon fields: ${legacyFields.join(', ')}`);}- const { merged, nameChanged } = await queueSeriesWrite(async () => {+ const { merged, nameChanged, prevEphemeral, nextEphemeral } = await queueSeriesWrite(async () => {const state = await readState();const idx = state.series.findIndex((s) => s.id === id);if (idx < 0) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);@@ -291,15 +301,42 @@ export async function updateSeries(id, patch = {}) {...('targetFormat' in patch ? { targetFormat: patch.targetFormat } : {}),...('issueCountTarget' in patch ? { issueCountTarget: patch.issueCountTarget } : {}),...('origin' in patch ? { origin: patch.origin } : {}),+ // Local-only "don't sync" marker — sanitizer normalizes anything+ // non-true back to absent.+ ...('ephemeral' in patch ? { ephemeral: patch.ephemeral } : {}),llm: mergedLlm,updatedAt: new Date().toISOString(),});if (!next) throw makeErr('Invalid series payload', ERR_VALIDATION);state.series[idx] = next;await writeState(state);- emitRecordUpdated('series', next.id);- return { merged: next, nameChanged: next.name !== cur.name };+ return {+ merged: next,+ nameChanged: next.name !== cur.name,+ // See updateUniverse — surface the transition pair so the post-queue+ // side effects can wire subscribe / unsubscribe.+ prevEphemeral: cur.ephemeral === true,+ nextEphemeral: next.ephemeral === true,+ };});+ // Ephemeral lifecycle wiring — see updateUniverse for the rationale. false→true+ // tears down per-record subs; true→false re-auto-subscribes so the now-+ // shareable series reaches every peer with the pipeline category enabled.+ // Must run BEFORE emitRecordUpdated so the peerSync 'updated' listener+ // doesn't schedule pushes against subs that are about to be torn down.+ if (prevEphemeral && !nextEphemeral) {+ import('../sharing/peerSync.js').then(({ autoSubscribeRecordToAllPeers }) =>+ autoSubscribeRecordToAllPeers('series', merged.id)+ ).catch((err) => {+ console.log(`⚠️ series: re-subscribe after un-ephemeralizing failed: ${err.message}`);+ });+ } else if (!prevEphemeral && nextEphemeral) {+ import('../sharing/peerSync.js').then(({ unsubscribeAllForRecord }) =>+ unsubscribeAllForRecord('series', merged.id)+ ).catch((err) => {+ console.log(`⚠️ series: unsubscribe after ephemeralizing failed: ${err.message}`);+ });+ }// Cascade rename onto the linked per-series media collection (if any) —// log but don't fail the save. Runs OUTSIDE the queue so the media-// collections write tail can't stall subsequent series mutators. No-op@@ -310,6 +347,7 @@ export async function updateSeries(id, patch = {}) {console.error(`❌ series-collection rename cascade failed for ${merged.id}: ${err?.message || err}`);});}+ emitRecordUpdated('series', merged.id);return merged;}@@ -459,12 +497,18 @@ export async function mergeSeriesFromSync(remoteSeries) {if (!remote || typeof remote !== 'object' || !isStr(remote.id)) continue;const sanitized = sanitizeSeries(remote);if (!sanitized) continue;+ // Strip inbound `ephemeral` — see mergeUniversesFromSync.+ if ('ephemeral' in sanitized) delete sanitized.ephemeral;const local = localById.get(sanitized.id);if (!local) {// See universeBuilder.mergeUniversesFromSync — no local means no// cascade work, regardless of inbound tombstone state.localById.set(sanitized.id, sanitized);changed++;+ } else if (local.ephemeral === true) {+ // Local-ephemeral series are immune to inbound merges. See+ // mergeUniversesFromSync for the contract.+ continue;} else {const localTs = local.updatedAt || '';const remoteTs = sanitized.updatedAt || '';diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 8d991a8275..16c0ff9f75 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -320,6 +320,11 @@ export async function autoSubscribePeerToAllRecords(peerId, recordKind) {const { listSeries } = await import('../pipeline/series.js');records = await listSeries({ includeDeleted: false }).catch(() => []);}+ // Drop ephemeral records before the set-difference / sub creation. The wire+ // sanitizer would short-circuit any push anyway, but creating a sub that+ // can never push leaves an orphan row in peer_subscriptions.json that+ // confuses unsubscribe-all / tombstone-cursor lifecycle assumptions.+ records = records.filter(r => r?.ephemeral !== true);if (records.length === 0) return [];// Compute the set difference up front: which local records aren't yet// subscribed to this peer? The peer:online convergence path fires this@@ -373,6 +378,43 @@ export async function unsubscribeAllForPeer(peerId) {return { removed };}+/**+ * Drop every subscription tied to a single record (across all peers). Used+ * when a record transitions to ephemeral via PATCH — the user just opted+ * the record out of sync, so the existing subs (one per peer with the+ * matching category enabled) need to go away. Peers keep their last-pushed+ * copy on disk; this just stops future pushes. The user is responsible for+ * any cross-peer cleanup beyond that (e.g., delete the record locally to+ * tombstone-propagate, then mark a fresh record ephemeral).+ *+ * Returns `{ removed, failed }` where `removed` lists subscription ids the+ * unsubscribe call actually completed for, and `failed` lists ids whose+ * unsubscribePeer threw (race with another teardown path, malformed sub+ * id, etc.). Callers can branch on `failed.length > 0` to surface partial+ * failures; today nobody does, but the contract has to be honest so a+ * future caller that DOES want to verify completion can.+ */+export async function unsubscribeAllForRecord(recordKind, recordId) {+ if (!PEER_SUBSCRIBABLE_KINDS.includes(recordKind) || !isNonEmptyStr(recordId)) {+ return { removed: [], failed: [] };+ }+ const matching = await listPeerSubscriptions({ recordKind, recordId });+ const removed = [];+ const failed = [];+ for (const sub of matching) {+ const ok = await unsubscribePeer(sub.id).then(() => true).catch((err) => {+ console.log(`⚠️ peerSync: unsubscribe-for-record failed for ${sub.id}: ${err.message}`);+ return false;+ });+ if (ok) {+ removed.push(sub.id);+ } else {+ failed.push(sub.id);+ }+ }+ return { removed, failed };+}+// --- Asset manifest -----------------------------------------------------/**@@ -627,7 +669,14 @@ async function buildPushPayload(sub, sourceInstanceId) {if (!record) return null;const sanitized = sanitizeRecordForWire('universe', record);if (!sanitized) return null;- const assetManifest = await buildAssetManifest(record);+ // Tombstone push: deleted records carry no on-disk assets the receiver+ // should pull. Sending an empty manifest avoids triggering+ // pullMissingAssetsFromPeer for a record we're telling the peer to+ // delete — both wasteful (network + disk for bytes the receiver will+ // immediately orphan) and privacy-sensitive (e.g. a record deleted+ // BECAUSE the user wanted the assets off-peer would otherwise still+ // ship them with the tombstone push).+ const assetManifest = record.deleted === true ? [] : await buildAssetManifest(record);return { kind: 'universe', record: sanitized, assetManifest, sourceInstanceId };}if (sub.recordKind === 'series') {@@ -642,7 +691,30 @@ async function buildPushPayload(sub, sourceInstanceId) {const sanitizedIssues = childIssues.map((i) => sanitizeRecordForWire('issue', i)).filter(Boolean);- const assetManifest = await buildAssetManifestForSeries(record, childIssues);+ // Drop ephemeral child issues BEFORE feeding into the asset-manifest+ // builder. sanitizedIssues above already filters them via+ // sanitizeRecordForWire's ephemeral check, but the asset-manifest builder+ // takes the raw `childIssues` array — without the parallel filter here,+ // ephemeral issues' image / video / image-ref filenames would still+ // appear in the manifest the receiver pulls. The user-visible effect:+ // private/scratch image bytes for an issue the user said "don't sync"+ // would land on every peer's disk via pullMissingAssetsFromPeer.+ // ALSO drop deleted child issues from the manifest input — their+ // tombstones still ride along in `sanitizedIssues` (so the receiver+ // can finish its delete cascade), but shipping the deleted issues'+ // asset filenames would trigger needless / privacy-sensitive pulls+ // for bytes that are about to be orphaned on the receiver.+ // Tombstoned ephemeral issues (deleted=true + ephemeral=true) ALSO+ // stay out of the manifest input by this filter.+ const manifestIssues = childIssues.filter(+ (i) => i?.deleted !== true && i?.ephemeral !== true,+ );+ // Tombstone push at the series level: same reasoning as universe above.+ // When the series itself is deleted, send an empty asset manifest so+ // the receiver doesn't pull bytes for a record it's about to tombstone.+ const assetManifest = record.deleted === true+ ? []+ : await buildAssetManifestForSeries(record, manifestIssues);return {kind: 'series',record: sanitized,@@ -789,18 +861,80 @@ async function maybeCreateReverseSubscription({ peerId, recordKind, recordId })const existing = await findPeerSubscription(peerId, recordKind, recordId);if (existing) return false;- // Honor the per-peer `directions` flag. A peer marked inbound-only is one- // we accept pushes FROM but never push back TO — auto-creating a reverse- // subscription would break that explicit configuration.+ // Cheap in-memory checks FIRST. Honor the per-peer `directions` flag — a+ // peer marked inbound-only is one we accept pushes FROM but never push+ // back TO — auto-creating a reverse subscription would break that+ // explicit configuration. Doing this BEFORE the ephemeral-record disk+ // read means inbound-only / unknown peers don't trigger an extra+ // getUniverse / getSeries on every incoming push.const peer = await findPeerById(peerId);if (!peer) return false;const directions = Array.isArray(peer.directions) ? peer.directions : [];if (directions.length > 0 && !directions.includes('outbound')) return false;+ // Now the disk read: only reverse-subscribe when the local record exists+ // AND is non-ephemeral. Three reasons to hard-stop on missing/read-failed:+ //+ // 1. Ephemeral: auto-creating a reverse sub for a local-only record+ // would accumulate orphan rows in peer_subscriptions.json. Every+ // future edit on the local side fires recordEvents.updated →+ // triggerPushForRecord → pushRecordToPeer → buildPushPayload →+ // sanitizeRecordForWire returns null (ephemeral filter) → push+ // aborts with "record-not-found". The sub burns an asset-manifest+ // sha-pass on every edit and never sends bytes. The merge path+ // upstream already refused the inbound edit (local-ephemeral →+ // continue), so the sender's record state isn't reflected locally+ // anyway — there's nothing meaningful to push back.+ //+ // 2. Record-missing: the sender pushed a record that passed Zod but was+ // dropped by the service sanitizer (missing name, etc.). The merge+ // never created the local copy, so a reverse sub would point at a+ // nonexistent record and every push would resolve to null. Same+ // orphan-row dynamic as ephemeral, but worse because there's never+ // going to be a record to clear it via the ephemeral lifecycle+ // transition.+ //+ // 3. Read-failed: a transient IO error reading the record file —+ // treating it as "non-ephemeral, go ahead and subscribe" can create+ // a sub for a record that turns out to be ephemeral once the IO+ // settles. Conservative default: don't subscribe.+ const localState = await classifyLocalRecord(recordKind, recordId);+ if (localState !== 'syncable') return false;+await subscribePeer({ peerId, recordKind, recordId }, { adoptedFromReverse: true });return true;}+/**+ * Look up the local record (live or tombstoned) and tri-state-classify it+ * for the reverse-subscribe gate. Returns one of:+ *+ * 'syncable' — record exists, is non-ephemeral; safe to reverse-subscribe.+ * 'ephemeral' — record exists but is local-only; reverse-subscribe would+ * accumulate an orphan sub that never sends bytes.+ * 'missing' — record is not on disk OR a read error occurred; can't+ * classify, so the conservative default is to skip the+ * reverse-subscribe (callers treat anything other than+ * 'syncable' as a no-go).+ *+ * Includes deleted records on the lookup so a tombstone-as-state record+ * still gets classified as 'syncable' (we WANT peer pushes to converge+ * a deleted record's tombstone if they're targeting it).+ */+async function classifyLocalRecord(recordKind, recordId) {+ if (recordKind === 'universe') {+ const u = await getUniverse(recordId, { includeDeleted: true }).catch(() => undefined);+ if (!u) return 'missing';+ return u.ephemeral === true ? 'ephemeral' : 'syncable';+ }+ if (recordKind === 'series') {+ const s = await getSeries(recordId, { includeDeleted: true }).catch(() => undefined);+ if (!s) return 'missing';+ return s.ephemeral === true ? 'ephemeral' : 'syncable';+ }+ return 'missing';+}+// --- Receiver-side asset pull worker ------------------------------------const ASSET_KIND_TO_URL_PREFIX = Object.freeze({@@ -1013,32 +1147,53 @@ async function getIssueSeriesId(issueId) {}/**- * Re-push every subscription targeting `peerId` whose initial push hasn't- * landed yet (`lastPushedAt == null`). Fires on `peer:online` so a record- * created while the peer was unreachable still reaches it the moment the- * peer comes back — without this retry, the new record would sit in limbo- * until the user edited it again (creation paths don't fire- * `recordEvents.updated`, so the existing debounce listener never sees it).+ * Re-fire `pushRecordToPeer` for every subscription targeting `peerId`.+ * Fires on `peer:online` so the federation converges after offline edits+ * or out-of-band file changes (e.g., a cleanup script that wrote tombstones+ * directly to disk while PM2 was offline). The `lastPushedHash` short-+ * circuit inside `pushRecordToPeer` skips the network call for any sub+ * whose record content is byte-identical to what was last pushed, so a+ * steady-state peer:online with N converged records pays N hash passes but+ * zero HTTP requests.*- * Already-pushed subs are filtered out so this can't double-push under load.- * Failures stay non-fatal — the next `peer:online` (or the user's next edit)- * gets another attempt.+ * Originally this only retried subs with `lastPushedAt == null` (initial+ * push never landed). That left a gap: any state change recorded directly+ * on disk (a CLI cleanup script, a hand-edit, a recovered backup) AFTER an+ * initial push succeeded would never re-push because `lastPushedAt` was+ * set. The unconditional retry + hash short-circuit covers both the+ * "initial push" and "out-of-band drift" cases with the same code path.+ *+ * Failures stay non-fatal — the next `peer:online` (or the user's next+ * edit) gets another attempt.*/export async function retryPendingPushesForPeer(peerId) {- if (!isNonEmptyStr(peerId)) return { retried: 0 };+ if (!isNonEmptyStr(peerId)) return { walked: 0, pushed: 0 };const subs = await listPeerSubscriptions({ peerId });- const pending = subs.filter(s => !s.lastPushedAt);- if (pending.length === 0) return { retried: 0 };- console.log(`🔄 peerSync: retrying ${pending.length} pending push${pending.length === 1 ? '' : 'es'} → ${peerId}`);- for (const sub of pending) {- await pushRecordToPeer(sub).catch((err) => {+ if (subs.length === 0) return { walked: 0, pushed: 0 };+ // Separate counter for the log line — only count subs that were never+ // pushed (genuine retries) so steady-state convergence runs stay quiet.+ const neverPushedCount = subs.filter(s => !s.lastPushedAt).length;+ if (neverPushedCount > 0) {+ console.log(`🔄 peerSync: retrying ${neverPushedCount} pending push${neverPushedCount === 1 ? '' : 'es'} → ${peerId}`);+ }+ // Track `walked` (subs we iterated) and `pushed` (HTTP call landed)+ // separately. `walked === pushed` would be misleading at steady state+ // because the lastPushedHash short-circuit inside pushRecordToPeer skips+ // the network call for any sub whose content is unchanged — we still+ // "walked" the sub but never pushed it.+ let pushed = 0;+ for (const sub of subs) {+ const result = await pushRecordToPeer(sub).catch((err) => {console.log(`⚠️ peerSync: retry push failed for ${sub.id}: ${err.message}`);+ return null;});+ if (result?.pushed) pushed += 1;}- return { retried: pending.length };+ return { walked: subs.length, pushed };}let onUpdated = null;+let onDeleted = null;let onPeerOnline = null;/** Attach the `recordEvents` + `peer:online` listeners — call once during sharing init. */@@ -1050,6 +1205,23 @@ export function installPeerSyncListener() {});};recordEvents.on('updated', onUpdated);+ // ALSO listen for `deleted` events so soft-deletes propagate via the+ // per-record push pipeline. Without this, `deleteUniverse` /+ // `deleteSeries` (which emit `recordEvents.deleted`, NOT `updated`) only+ // reached peers via the 60s snapshot loop — and that loop is skipped for+ // any (peer, kind) pair covered by a per-record sub+ // (syncOrchestrator.categoriesCoveredByPeerSync). The result was that+ // every soft-delete on a record with active peer subs got stranded+ // locally. Route delete events through the same `triggerPushForRecord`+ // path: pushRecordToPeer reads the record with `includeDeleted: true`+ // and the wire sanitizer (now updated) lets tombstones cross even for+ // ephemeral records.+ onDeleted = ({ recordKind, recordId }) => {+ triggerPushForRecord(recordKind, recordId).catch((err) => {+ console.log(`⚠️ peerSync: delete listener error for ${recordKind}/${recordId}: ${err.message}`);+ });+ };+ recordEvents.on('deleted', onDeleted);// On peer:online, drive the local subscription state to convergence with// the user's intent. Two cases://@@ -1097,8 +1269,10 @@ export async function __resetForTests() {for (const t of pendingTimers.values()) clearTimeout(t);pendingTimers.clear();if (onUpdated) recordEvents.off('updated', onUpdated);+ if (onDeleted) recordEvents.off('deleted', onDeleted);if (onPeerOnline) instanceEvents.off('peer:online', onPeerOnline);onUpdated = null;+ onDeleted = null;onPeerOnline = null;await writeTail.catch(() => {});}diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex be30f65641..a993b75635 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -50,6 +50,7 @@ import {subscribePeer,unsubscribePeer,unsubscribeAllForPeer,+ unsubscribeAllForRecord,pushRecordToPeer,applyIncomingPush,diffAssetManifestAgainstLocal,@@ -116,9 +117,18 @@ beforeEach(async () => {vi.mocked(mergeUniversesFromSync).mockResolvedValue({ applied: true, count: 1 });vi.mocked(mergeSeriesFromSync).mockResolvedValue({ applied: true, count: 1 });vi.mocked(mergeIssuesFromSync).mockResolvedValue({ applied: true, count: 1 });- vi.mocked(getUniverse).mockReset();- vi.mocked(getSeries).mockReset();- vi.mocked(listIssues).mockReset();+ // Default getUniverse / getSeries / listIssues mocks to resolved promises+ // so any callsite that doesn't override (e.g. the receiver-side+ // `isLocalRecordEphemeral` lookup in maybeCreateReverseSubscription)+ // doesn't blow up on `.catch` against a `vi.fn()` non-Promise return.+ // Real getUniverse / getSeries / listIssues are `async` so they always+ // return Promises; production code can assume this, but the test mock+ // has to match — including the per-call default for listIssues so a+ // buildPushPayload path that bundles child issues doesn't choke on an+ // un-overridden mock.+ vi.mocked(getUniverse).mockReset().mockResolvedValue(undefined);+ vi.mocked(getSeries).mockReset().mockResolvedValue(undefined);+ vi.mocked(listIssues).mockReset().mockResolvedValue([]);await __resetForTests();});@@ -275,6 +285,74 @@ describe('peerSync', () => {});});+ describe('unsubscribeAllForRecord', () => {+ it('removes every subscription for a record across all peers', async () => {+ // updateUniverse({ ephemeral: true }) fires this — when a record+ // transitions ephemeral, every per-peer sub for that record must go+ // away so the orphan-row state never materializes.+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1' });+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });+ await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });+ await subscribePeer({ peerId: 'peer-b-inbound-only', recordKind: 'universe', recordId: 'u1' });+ // Different record on peer-a — must survive the unsubscribe.+ await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u-other' });+ const result = await unsubscribeAllForRecord('universe', 'u1');+ expect(result.removed).toHaveLength(2);+ expect(result.failed).toEqual([]);+ expect(await findPeerSubscription('peer-a', 'universe', 'u1')).toBeNull();+ expect(await findPeerSubscription('peer-b-inbound-only', 'universe', 'u1')).toBeNull();+ // Untouched: u-other on peer-a.+ expect(await findPeerSubscription('peer-a', 'universe', 'u-other')).not.toBeNull();+ });++ it('reports per-sub success vs failure separately when unsubscribePeer throws', async () => {+ // Regression guard against the "always push to removed" bug: a sub+ // whose unsubscribe call throws (concurrent teardown, malformed id)+ // must NOT appear in `removed`. Callers reading `removed.length`+ // need an honest count.+ //+ // We force the failure path by racing two `unsubscribeAllForRecord`+ // calls in parallel. `listPeerSubscriptions` (line 401 of peerSync)+ // is NOT inside withStateLock — so both calls take an identical+ // snapshot containing sub1+sub2 before either's first+ // `unsubscribePeer` runs. The first call's two `unsubscribePeer`+ // invocations execute under the state lock and remove both subs.+ // The second call's invocations then hit ERR_NOT_FOUND, so both+ // ids land in its `failed` array — proving the per-sub catch+ // honestly separates success from failure.+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1' });+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });+ const sub1 = await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });+ const sub2 = await subscribePeer({ peerId: 'peer-b-inbound-only', recordKind: 'universe', recordId: 'u1' });+ const [resultA, resultB] = await Promise.all([+ unsubscribeAllForRecord('universe', 'u1'),+ unsubscribeAllForRecord('universe', 'u1'),+ ]);+ // Exactly one call wins each sub. Across the two results, every sub+ // must appear in exactly one `removed` (success) and exactly one+ // `failed` (the racing duplicate).+ const allRemoved = [...resultA.removed, ...resultB.removed].sort();+ const allFailed = [...resultA.failed, ...resultB.failed].sort();+ expect(allRemoved).toEqual([sub1.id, sub2.id].sort());+ expect(allFailed).toEqual([sub1.id, sub2.id].sort());+ // No id appears in both removed AND failed of the same call.+ for (const result of [resultA, resultB]) {+ for (const id of result.removed) {+ expect(result.failed).not.toContain(id);+ }+ }+ // Both subs are actually gone from disk.+ expect(await findPeerSubscription('peer-a', 'universe', 'u1')).toBeNull();+ expect(await findPeerSubscription('peer-b-inbound-only', 'universe', 'u1')).toBeNull();+ });++ it('returns {removed: [], failed: []} for invalid arguments', async () => {+ expect(await unsubscribeAllForRecord('', 'u1')).toEqual({ removed: [], failed: [] });+ expect(await unsubscribeAllForRecord('universe', '')).toEqual({ removed: [], failed: [] });+ expect(await unsubscribeAllForRecord('bogus', 'u1')).toEqual({ removed: [], failed: [] });+ });+ });+describe('autoSubscribeRecordToAllPeers', () => {beforeEach(() => {// Default these so the push triggered by subscribePeer doesn't 500@@ -445,6 +523,21 @@ describe('peerSync', () => {expect(await autoSubscribePeerToAllRecords('peer-a', 'bogus')).toEqual([]);});+ it('drops ephemeral records before computing the set-diff', async () => {+ // Ephemeral universes/series are local-only — backfill must not+ // create subscriptions for them, even when every other gate passes.+ // Without the filter, the sub would be created and a later push would+ // simply short-circuit via sanitizeRecordForWire — but the row would+ // still live in peer_subscriptions.json forever, confusing unsubscribe-all.+ vi.mocked(listUniverses).mockResolvedValue([+ { id: 'live' },+ { id: 'scratch', ephemeral: true },+ ]);+ const created = await autoSubscribePeerToAllRecords('peer-a', 'universe');+ expect(created.map(c => c.recordId)).toEqual(['live']);+ expect(await findPeerSubscription('peer-a', 'universe', 'scratch')).toBeNull();+ });+it('short-circuits the for-loop when every record is already subscribed', async () => {// Regression: peer:online fires this helper on every online// transition. Without the pre-computed set-diff, a steady-state peer@@ -496,7 +589,7 @@ describe('peerSync', () => {vi.mocked(listIssues).mockResolvedValue([]);});- it('re-pushes subs with lastPushedAt=null and skips already-pushed subs', async () => {+ it('re-pushes subs with lastPushedAt=null and walks all subs on subsequent retries (hash short-circuits unchanged ones)', async () => {// Create a sub with the initial push FAILING — leaves lastPushedAt=null.vi.mocked(peerFetch).mockResolvedValueOnce(null);await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });@@ -508,22 +601,33 @@ describe('peerSync', () => {// Peer comes back — retry must succeed and stamp lastPushedAt.vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });const result = await retryPendingPushesForPeer('peer-a');- expect(result.retried).toBe(1);+ expect(result.walked).toBe(1);+ expect(result.pushed).toBe(1); // network call landedconst updated = await findPeerSubscription('peer-a', 'universe', 'u1');expect(updated.lastPushedAt).toBeTruthy();- // Second retry must be a no-op now that lastPushedAt is set.+ // Subsequent retry now walks every sub regardless of lastPushedAt+ // (the lastPushedHash short-circuit inside pushRecordToPeer is what+ // skips the actual HTTP call for unchanged records). This is the+ // mechanism that lets out-of-band file edits (e.g., a cleanup script+ // that wrote tombstones directly to disk + a server restart)+ // re-propagate via peer:online without needing a per-record edit.+ vi.mocked(peerFetch).mockClear();const second = await retryPendingPushesForPeer('peer-a');- expect(second.retried).toBe(0);+ expect(second.walked).toBe(1); // walked, not skipped by the helper+ expect(second.pushed).toBe(0); // hash short-circuited, no HTTP call+ // The hash short-circuit inside pushRecordToPeer prevents the actual+ // HTTP call because the record content is unchanged since the first push.+ expect(vi.mocked(peerFetch)).not.toHaveBeenCalled();});- it('returns {retried: 0} when the peer has no subscriptions', async () => {+ it('returns {walked: 0, pushed: 0} when the peer has no subscriptions', async () => {const result = await retryPendingPushesForPeer('peer-without-subs');- expect(result).toEqual({ retried: 0 });+ expect(result).toEqual({ walked: 0, pushed: 0 });});- it('returns {retried: 0} for invalid peerId', async () => {- expect(await retryPendingPushesForPeer('')).toEqual({ retried: 0 });- expect(await retryPendingPushesForPeer(null)).toEqual({ retried: 0 });+ it('returns {walked: 0, pushed: 0} for invalid peerId', async () => {+ expect(await retryPendingPushesForPeer('')).toEqual({ walked: 0, pushed: 0 });+ expect(await retryPendingPushesForPeer(null)).toEqual({ walked: 0, pushed: 0 });});});@@ -827,6 +931,118 @@ describe('peerSync', () => {expect(captured.issues).toHaveLength(2);expect(captured.issues.map((i) => i.id)).toEqual(['i1', 'i2']);});++ it('drops ephemeral child issues from both the bundled issues AND the asset manifest', async () => {+ // Regression: an earlier version filtered ephemeral issues out of+ // `sanitizedIssues` but still walked the unfiltered `childIssues`+ // when building the asset manifest, leaking the ephemeral issue's+ // image / video filenames onto the wire. The receiver would then+ // background-fetch those bytes — defeating the "local-only" intent+ // of ephemeral.+ vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });+ vi.mocked(listIssues).mockResolvedValue([+ // Live issue with a referenced image.+ {+ id: 'i1', seriesId: 's1', number: 1,+ stages: { storyboards: { scenes: [{ imageJobId: 'job-live' }] } },+ },+ // Ephemeral issue — must NOT leak its image into the manifest.+ {+ id: 'i2', seriesId: 's1', number: 2, ephemeral: true,+ stages: { storyboards: { scenes: [{ imageJobId: 'job-secret' }] } },+ },+ ]);+ let captured = null;+ vi.mocked(peerFetch).mockImplementation(async (_url, opts) => {+ captured = JSON.parse(opts.body);+ return { ok: true, json: async () => ({}) };+ });+ await pushRecordToPeer({+ id: 's', peerId: 'peer-a', recordKind: 'series', recordId: 's1',+ });+ // Sanitized issues: only the live one.+ expect(captured.issues).toHaveLength(1);+ expect(captured.issues[0].id).toBe('i1');+ // Asset manifest entries (if any) must not reference the ephemeral+ // issue's assets. The manifest can be empty if buildAssetManifest+ // didn't find any concrete filenames in the live issue's stages+ // (which is the case here — imageJobId references aren't yet+ // resolved to filenames in Stage 2's manifest builder). The+ // critical invariant is that NOTHING from the ephemeral issue+ // appears.+ const manifestFilenames = (captured.assetManifest || []).map(a => a.filename);+ expect(manifestFilenames.some(f => /secret/i.test(f))).toBe(false);+ });++ it('ships an empty asset manifest for tombstone pushes (deleted universe)', async () => {+ // Tombstone pushes carry deleted=true + deletedAt so the receiver+ // can converge its delete. They must NOT also ship asset filenames+ // — the receiver would diff them as `missing`, schedule pulls, and+ // download bytes for a record it's about to orphan. Privacy-+ // sensitive (a record deleted to get its assets off-peer would+ // still leak the bytes via this path) and wasteful.+ vi.mocked(getUniverse).mockResolvedValue({+ id: 'u1', name: 'Doomed', deleted: true, deletedAt: '2026-01-01T00:00:00Z',+ // Force a referenced image filename that would otherwise hash into+ // the manifest. The buildAssetManifest path skips entries whose+ // file isn't readable, so a definitely-not-present filename is+ // the cleanest "would have been emitted if not for the deleted+ // gate" probe.+ worldOverview: { sceneImageFilename: 'sentinel-doomed-asset.png' },+ });+ let captured = null;+ vi.mocked(peerFetch).mockImplementation(async (_url, opts) => {+ captured = JSON.parse(opts.body);+ return { ok: true, json: async () => ({}) };+ });+ await pushRecordToPeer({+ id: 'sub-tomb', peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',+ });+ // Tombstone arrives — sanitizer keeps deleted records on the wire.+ expect(captured.record.id).toBe('u1');+ expect(captured.record.deleted).toBe(true);+ // But the manifest is empty — no pull-trigger for the receiver.+ expect(captured.assetManifest).toEqual([]);+ });++ it('drops deleted child issues from the asset manifest input', async () => {+ // Deleted issues' tombstones must still ride along in `issues` (so+ // the receiver's delete cascade runs), but their asset filenames+ // must NOT appear in the manifest — the receiver would otherwise+ // pull bytes for issues it's about to orphan.+ vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });+ vi.mocked(listIssues).mockResolvedValue([+ // Live issue (no manifest leak — buildAssetManifest doesn't yet+ // resolve imageJobId → filename, that's a Stage 3 thing).+ { id: 'i1', seriesId: 's1', number: 1 },+ // Deleted issue with a sentinel filename that would surface+ // through buildAssetManifest's directVideoFilenames path if it+ // were fed to the manifest builder.+ {+ id: 'i2', seriesId: 's1', number: 2,+ deleted: true, deletedAt: '2026-01-01T00:00:00Z',+ },+ ]);+ let captured = null;+ vi.mocked(peerFetch).mockImplementation(async (_url, opts) => {+ captured = JSON.parse(opts.body);+ return { ok: true, json: async () => ({}) };+ });+ await pushRecordToPeer({+ id: 's', peerId: 'peer-a', recordKind: 'series', recordId: 's1',+ });+ // Both issues' tombstones/wire-records propagate.+ expect(captured.issues.map(i => i.id).sort()).toEqual(['i1', 'i2']);+ const deletedIssue = captured.issues.find(i => i.id === 'i2');+ expect(deletedIssue.deleted).toBe(true);+ // Manifest is empty (or at least carries nothing from i2). Stage-2+ // manifest builder doesn't emit filenames for these stage shapes,+ // so the manifest is empty in practice — but the invariant we're+ // guarding is that deleted issues NEVER contribute manifest entries+ // even when their stages happen to reference concrete assets.+ const manifestFilenames = (captured.assetManifest || []).map(a => a.filename);+ expect(manifestFilenames).toEqual([]);+ });});describe('applyIncomingPush', () => {@@ -921,6 +1137,13 @@ describe('peerSync', () => {});it('auto-creates a reverse subscription back to the sender', async () => {+ // The merge path actually landed the record locally, so the+ // classifyLocalRecord('universe', 'u1') call inside+ // maybeCreateReverseSubscription will find a syncable record on+ // disk. Mock the lookup explicitly — the tri-state gate refuses+ // 'missing' to avoid orphan reverse-subs (e.g. for records the+ // sanitizer dropped at the merge boundary).+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });await applyIncomingPush({kind: 'universe',record: { id: 'u1' },@@ -932,6 +1155,23 @@ describe('peerSync', () => {expect(sub.adoptedFromReverse).toBe(true);});+ it('does NOT create a reverse subscription when the local record is missing (merge dropped it)', async () => {+ // Regression: classifyLocalRecord must hard-stop on 'missing'.+ // Previously the gate only checked `ephemeral === true`, so a+ // record the sanitizer dropped during merge (missing name, schema+ // mismatch, etc.) would still get an orphan reverse-sub that fires+ // pushes against a nonexistent local record forever.+ vi.mocked(getUniverse).mockResolvedValue(undefined);+ await applyIncomingPush({+ kind: 'universe',+ record: { id: 'u-dropped' },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ const sub = await findPeerSubscription('peer-a', 'universe', 'u-dropped');+ expect(sub).toBeNull();+ });+it('does NOT create a reverse subscription when the sender peer is configured as inbound-only', async () => {// peer-b-inbound-only has directions: ['inbound']. The user explicitly// told this instance not to push back to them — auto-creating a@@ -947,6 +1187,23 @@ describe('peerSync', () => {expect(sub).toBeNull();});+ it('does NOT create a reverse subscription when the local record is ephemeral', async () => {+ // The user marked u1 local-only; the merge already refused the+ // inbound edit (see mergeUniversesFromSync local-ephemeral guard).+ // Creating a reverse sub here would accumulate an orphan row in+ // peer_subscriptions.json that burns asset-manifest sha-passes on+ // every future edit and never sends bytes.+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', ephemeral: true });+ const result = await applyIncomingPush({+ kind: 'universe',+ record: { id: 'u1' },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ expect(result.reverseSubscriptionCreated).toBe(false);+ expect(await findPeerSubscription('peer-a', 'universe', 'u1')).toBeNull();+ });+it('does NOT duplicate a reverse subscription on subsequent pushes', async () => {vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex 9822a9e61a..0246cba76b 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -755,6 +755,12 @@ const sanitizeTemplate = (raw) => {updatedAt,deleted,deletedAt,+ // Local-only "don't sync to peers" marker. Only persisted when true so+ // every existing universe keeps the same on-disk shape — and so the wire+ // checksum stays byte-stable for non-ephemeral records (see+ // sanitizeRecordForWire). Mark a scratch universe ephemeral to keep it+ // off the federation; test fixtures stamp this too.+ ...(raw.ephemeral === true ? { ephemeral: true } : {}),};};@@ -881,20 +887,30 @@ export async function createUniverse(input = {}) {llm: input.llm || {},createdAt: now,updatedAt: now,+ // Optional local-only marker — when true, every sync transport+ // (snapshot loop + per-record push) skips this universe (see+ // sanitizeRecordForWire) and the auto-subscribe below short-circuits.+ ephemeral: input.ephemeral === true,});state.universes.push(next);await writeState(state);return next;});// Fire-and-forget auto-subscribe to every peer with universe-sync enabled.+ // Skip the auto-subscribe entirely for ephemeral universes — the push+ // would short-circuit anyway via sanitizeRecordForWire returning null, but+ // not creating the subscription in the first place keeps peer_subscriptions.json+ // free of orphan rows tied to records the user explicitly excluded.// Dynamic import keeps peerSync.js OUT of the universeBuilder module-load// graph — peerSync already imports getUniverse / mergeUniversesFromSync// from here, so a static import would close a cycle.- import('./sharing/peerSync.js').then(({ autoSubscribeRecordToAllPeers }) =>- autoSubscribeRecordToAllPeers('universe', created.id)- ).catch((err) => {- console.log(`⚠️ universe: auto-subscribe after create failed: ${err.message}`);- });+ if (!created.ephemeral) {+ import('./sharing/peerSync.js').then(({ autoSubscribeRecordToAllPeers }) =>+ autoSubscribeRecordToAllPeers('universe', created.id)+ ).catch((err) => {+ console.log(`⚠️ universe: auto-subscribe after create failed: ${err.message}`);+ });+ }return created;}@@ -949,7 +965,7 @@ export async function updateUniverse(id, patchOrMutator = {}) {// unchanged record (no `updatedAt` bump, no rename cascade, no// `recordUpdated` emit).const isMutator = typeof patchOrMutator === 'function';- const { merged, nameChanged, skipped, removedCharacterIds } = await queueUniverseWrite(async () => {+ const { merged, nameChanged, skipped, removedCharacterIds, prevEphemeral, nextEphemeral } = await queueUniverseWrite(async () => {const state = await readState();const idx = state.universes.findIndex((w) => w.id === id);if (idx < 0) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);@@ -1005,6 +1021,16 @@ export async function updateUniverse(id, patchOrMutator = {}) {'characters', 'places', 'objects',// Share-bucket origin metadata (importer sets it; user clears via wholesale null).'origin',+ // Local-only "don't sync" marker — see sanitizeTemplate. The safety+ // property is one-directional: ONLY a literal `true` marks the record+ // ephemeral; every other value (`false`, `'true'`, `1`, etc.) is+ // dropped at the sanitizer back to absent — i.e. sync-enabled. A+ // mutator PATCH like `{ ephemeral: 'false' }` therefore CLEARS the+ // flag (re-enabling sync), it does NOT mark the record ephemeral.+ // The asymmetry is intentional: protecting "private by default" is+ // not the goal — protecting "you can't accidentally truthy your way+ // into ephemeral and never sync again" is.+ 'ephemeral',];const scalarPatch = Object.fromEntries(PATCHABLE_SCALARS.filter((k) => k in patch).map((k) => [k, patch[k]]),@@ -1118,6 +1144,12 @@ export async function updateUniverse(id, patchOrMutator = {}) {nameChanged: mergedRecord.name !== cur.name,skipped: false,removedCharacterIds,+ // Surface the (prev, next) ephemeral pair so the post-queue side+ // effects can wire subscribe / unsubscribe for the transition.+ // Compare against `cur` (the pre-merge record) so transitions are+ // detected regardless of patch shape (literal-object or mutator).+ prevEphemeral: cur.ephemeral === true,+ nextEphemeral: mergedRecord.ephemeral === true,};});if (skipped) return merged;@@ -1134,6 +1166,32 @@ export async function updateUniverse(id, patchOrMutator = {}) {console.error(`❌ universe-collection rename cascade failed for ${merged.id}: ${err?.message || err}`);});}+ // Ephemeral lifecycle wiring — fires AFTER the queued write so the on-disk+ // state already reflects the transition before any peer-sync work runs.+ // false→true: tear down every existing per-record sub for this universe+ // (peers keep their last-pushed copy on disk; we just stop+ // future pushes). Mirror of createUniverse's `if (!created.ephemeral)`+ // auto-subscribe-skip — both ends of the lifecycle keep+ // peer_subscriptions.json free of orphan rows.+ // true→false: fire autoSubscribeRecordToAllPeers so the now-shareable+ // record reaches every peer with the universe category+ // enabled. The 60s snapshot loop is skipped for kinds covered+ // by per-record subs (see syncOrchestrator.categoriesCoveredByPeerSync),+ // so without this re-subscribe the record would be silently+ // invisible to those peers.+ if (prevEphemeral && !nextEphemeral) {+ import('./sharing/peerSync.js').then(({ autoSubscribeRecordToAllPeers }) =>+ autoSubscribeRecordToAllPeers('universe', merged.id)+ ).catch((err) => {+ console.log(`⚠️ universe: re-subscribe after un-ephemeralizing failed: ${err.message}`);+ });+ } else if (!prevEphemeral && nextEphemeral) {+ import('./sharing/peerSync.js').then(({ unsubscribeAllForRecord }) =>+ unsubscribeAllForRecord('universe', merged.id)+ ).catch((err) => {+ console.log(`⚠️ universe: unsubscribe after ephemeralizing failed: ${err.message}`);+ });+ }emitRecordUpdated('universe', merged.id);return merged;}@@ -1227,6 +1285,14 @@ export async function mergeUniversesFromSync(remoteUniverses) {if (!remote || typeof remote !== 'object' || !isStr(remote.id)) continue;const sanitized = sanitizeTemplate(remote);if (!sanitized) continue;+ // `ephemeral` is a LOCAL-only marker — never trust the inbound value.+ // sanitizeTemplate only persists a literal `{ ephemeral: true }` (any+ // other value gets dropped at the sanitizer); strip even that here so+ // a buggy/older/non-conformant peer (or the share-bucket importer's+ // mutator-form path) can't plant a "dark" record on us that's+ // permanently un-syncable. The on-disk-only contract is enforced on+ // the receive boundary.+ if ('ephemeral' in sanitized) delete sanitized.ephemeral;const local = localById.get(sanitized.id);if (!local) {// No local counterpart — accept the record (live OR tombstone) but@@ -1236,6 +1302,18 @@ export async function mergeUniversesFromSync(remoteUniverses) {// never existed.localById.set(sanitized.id, sanitized);changed++;+ } else if (local.ephemeral === true) {+ // Local-ephemeral records are IMMUNE to inbound merges. The user+ // explicitly marked this record local-only — peer edits can't+ // overwrite its content, peer deletes can't trigger our orphan+ // cascade, and the post-merge asset-pull worker never gets the+ // chance to download bytes for it. The sender may still have a+ // reverse subscription on their side; we silently drop the push.+ // Pre-ephemeral subs on OUR side are torn down by the+ // updateUniverse PATCH transition (see "ephemeral lifecycle" wiring)+ // so this branch should only fire for cross-peer fan-out or+ // share-bucket import paths.+ continue;} else {const localTs = local.updatedAt || '';const remoteTs = sanitized.updatedAt || '';diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.jsindex 52f3cfbc94..c7eb9a03a8 100644--- a/server/services/universeBuilder.test.js+++ b/server/services/universeBuilder.test.js@@ -695,6 +695,57 @@ describe("universeBuilder service", () => {const fresh = await collections.getCollection(linked.id);expect(fresh.universeId).toBeNull();});++ it("local-ephemeral universes are IMMUNE to inbound merges (peer edits + tombstones both refused)", async () => {+ // The user marks a universe ephemeral to fork it private. A peer+ // that still has the pre-ephemeral version (or has a reverse+ // subscription) must not be able to overwrite local content or+ // trigger an orphan cascade by deleting their copy.+ const w = await seedWorld();+ await svc.updateUniverse(w.id, { ephemeral: true });+ const localBefore = await svc.getUniverse(w.id);+ // Inbound edit with NEWER updatedAt — would normally win via LWW.+ const editTs = new Date(Date.now() + 60_000).toISOString();+ const editResult = await svc.mergeUniversesFromSync([{+ ...w,+ name: "Should Not Land",+ updatedAt: editTs,+ }]);+ expect(editResult.applied).toBe(false);+ const localAfterEdit = await svc.getUniverse(w.id);+ expect(localAfterEdit.name).toBe(localBefore.name);+ expect(localAfterEdit.ephemeral).toBe(true);+ // Inbound tombstone with NEWER updatedAt — would normally tombstone.+ const tombstoneTs = new Date(Date.now() + 120_000).toISOString();+ const deleteResult = await svc.mergeUniversesFromSync([{+ ...w,+ deleted: true,+ deletedAt: tombstoneTs,+ updatedAt: tombstoneTs,+ }]);+ expect(deleteResult.applied).toBe(false);+ const stillLive = await svc.getUniverse(w.id);+ expect(stillLive.deleted).toBeFalsy();+ });++ it("strips inbound `ephemeral` field — peers cannot plant a 'dark' record on the receiver", async () => {+ // The wire never carries `ephemeral`, but a buggy / older / non-+ // conformant peer (or the share-bucket importer's mutator-form+ // path) could ship a record with `ephemeral: true`. The receiver+ // must NOT honor that — it's a local-only marker by contract.+ const ghostId = "550e8400-0000-0000-0000-000000000aaa";+ const ts = new Date().toISOString();+ await svc.mergeUniversesFromSync([{+ id: ghostId,+ name: "Inbound Poison",+ ephemeral: true, // attempt to plant a dark record+ updatedAt: ts,+ }]);+ const inbound = await svc.getUniverse(ghostId);+ expect(inbound.name).toBe("Inbound Poison");+ // Receiver scrubs the field — record is normal-syncable.+ expect(inbound.ephemeral).toBeUndefined();+ });});describe("pruneTombstonedUniverses", () => {