Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(peer-sync): Stage 1 — soft-delete + syncWire + assetHash foundation (#433)

[._.]/ Adam Eivyb9985feb5520
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 75e964af88..0a0b0e31f6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,6 +1,7 @@
# Unreleased Changes
## Added
+- Foundation for federated peer sync of Universes, Series, and Issues (Stage 1 of 5). Soft-delete (`deleted` + `deletedAt` tombstone fields) is now part of the on-disk record for universes, series, and issues — so a delete propagates to other PortOS instances via the existing LWW snapshot merge instead of vanishing locally and resurrecting from a peer. `listUniverses` / `listSeries` / `listIssues` (and their per-id getters) filter tombstones by default; pass `{ includeDeleted: true }` to see them. `mergeUniversesFromSync` / `mergeSeriesFromSync` / `mergeIssuesFromSync` detect delete-transitions and fire the same orphan-cleanup cascades as a local delete (media-collection unlink, slot-map clear, issue renumber). New `server/lib/syncWire.js` is the single source of truth for what fields cross the peer wire (today it strips `runs[]` from universe state — shared by the 60s snapshot loop and the upcoming per-record push). New `server/lib/assetHash.js` persists SHA-256 hashes in each `data/images/{uuid}.metadata.json` sidecar so both the share-bucket exporter and the upcoming peer-sync push pipeline reuse the same value (no per-bucket recomputation, no per-transport cache). `insertUniverseWithId` / `insertSeriesWithId` / `insertIssueWithId` now overwrite a tombstoned record (re-import undeletes) but still reject DUPLICATE on a live record.
## Changed
diff --git a/server/lib/README.md b/server/lib/README.md
index f3caa2d230..f6c840aeeb 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -86,6 +86,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `multipart.js` | Streaming multipart/form-data parser. |
| `pdfImageEmbed.js` | PDF image embed helpers for comic / volume PDFs. |
| `zipStream.js` | Streaming ZIP parser. |
+| `assetHash.js` | Cross-transport SHA-256 cache for `data/images/*` — persists hashes in the asset's `.metadata.json` sidecar so the share-bucket exporter and the federated peer-sync push pipeline reuse the same value. |
## Process execution
@@ -106,6 +107,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `peerSelfHost.js` | Tailscale-issued hostname this PortOS sends in federation. |
| `peerUrl.js` | Build the base URL for a peer. |
| `sharingOrigin.js` | Origin metadata for records imported from share buckets. |
+| `syncWire.js` | Single source of truth for what fields cross the federated-peer wire (snapshot loop + per-record push agree). |
| `tailscale.js` | Common paths where the Tailscale CLI binary is found. |
| `httpsState.js` | Captures whether PortOS booted with HTTPS active. |
| `networkExposure.js` | Snapshot of scheme + bind + cert mode for the dashboard's Network Exposure widget. |
diff --git a/server/lib/assetHash.js b/server/lib/assetHash.js
new file mode 100644
index 0000000000..fef7a74755
--- /dev/null
+++ b/server/lib/assetHash.js
@@ -0,0 +1,87 @@
+import { stat } from 'fs/promises';
+import { basename, join } from 'path';
+import { atomicWrite, readJSONFile, sha256File, PATHS } from './fileUtils.js';
+
+// Each image at `data/images/{uuid}.png` has a sibling `.metadata.json`
+// sidecar carrying its generation provenance (model, prompt, dimensions, etc).
+// The federated peer-sync system also needs the SHA-256 of the image bytes so
+// the receiver can diff its local set against a sender's manifest without
+// downloading every file. Computing sha256 over a 2–3 MB PNG is cheap on
+// modern hardware but quickly adds up at universe-scale (~200 assets per
+// universe × multiple universes × every sync cycle), so we persist the hash
+// in the sidecar once and reuse it forever — invalidating only when the
+// image's mtime+size change (a re-render replaces the file in place).
+//
+// The sharing-bucket exporter has its own per-bucket cache for the same
+// reason, but that cache lives inside a specific bucket directory and is not
+// reachable by the peer-sync path. The sidecar is the universal source of
+// truth — both transports read from it.
+
+const HEX_64 = /^[a-f0-9]{64}$/;
+
+const isHexHash = (v) => typeof v === 'string' && HEX_64.test(v);
+
+/**
+ * Path to the metadata sidecar for an image filename. Accepts either the bare
+ * filename (`abc.png`) or an absolute path; the sidecar always sits next to
+ * the image in PATHS.images.
+ */
+export function sidecarPathForImage(imageFilenameOrPath) {
+ // Total over all inputs — callers (`getOrComputeImageSha256`, the share-bucket
+ // exporter, the upcoming peer-sync push) treat a null return as "no sidecar
+ // path resolvable for this asset" and fall through. Without the type guard,
+ // `path.basename(null)` would throw TypeError and crash the calling pipeline.
+ if (typeof imageFilenameOrPath !== 'string' || !imageFilenameOrPath) return null;
+ const base = basename(imageFilenameOrPath);
+ if (!base) return null;
+ // Strip extension and append `.metadata.json` (e.g. `abc.png` → `abc.metadata.json`).
+ // Mirrors `imageSidecarName` in services/sharing/buckets.js — kept inline
+ // here to avoid lib/ → services/ import direction.
+ const dot = base.lastIndexOf('.');
+ const stem = dot > 0 ? base.slice(0, dot) : base;
+ return join(PATHS.images, `${stem}.metadata.json`);
+}
+
+/**
+ * Returns sha256 of the image at `imagePath`, reading from the sidecar when
+ * possible and computing fresh (and persisting) when not. The sidecar entry
+ * is keyed on mtimeMs + size so a re-rendered image (same UUID, different
+ * bytes) invalidates the cached hash naturally.
+ *
+ * Returns `{ hash, sidecar }` where `sidecar` is the latest sidecar JSON
+ * (with the sha256 entry merged in) — callers who already need to read the
+ * sidecar for prompt/model metadata save a round-trip by reusing this object.
+ *
+ * Returns null when the image itself is missing or unreadable.
+ */
+export async function getOrComputeImageSha256(imagePath) {
+ const info = await stat(imagePath).catch(() => null);
+ if (!info) return null;
+ const sidecarPath = sidecarPathForImage(imagePath);
+ if (!sidecarPath) return null;
+ const sidecar = await readJSONFile(sidecarPath, null, { logError: false });
+ const cached = sidecar?.sha256;
+ if (
+ cached
+ && isHexHash(cached.value)
+ && cached.mtimeMs === info.mtimeMs
+ && cached.size === info.size
+ ) {
+ return { hash: cached.value, sidecar };
+ }
+ const hash = await sha256File(imagePath);
+ const next = {
+ ...(sidecar || {}),
+ sha256: { value: hash, mtimeMs: info.mtimeMs, size: info.size },
+ };
+ // Atomic so a concurrent reader never sees a half-written file. A race with
+ // a parallel re-render is benign: the loser's hash entry just gets
+ // overwritten on the next read (mtimeMs comparison invalidates it).
+ await atomicWrite(sidecarPath, next).catch((err) => {
+ // Sidecar may be missing entirely (asset has no provenance) and the dir
+ // may not exist — log but don't fail the caller, the hash is still valid
+ // for this call's purposes.
+ console.error(`⚠️ assetHash: sidecar write failed for ${sidecarPath}: ${err?.message || err}`);
+ });
+ return { hash, sidecar: next };
+}
diff --git a/server/lib/assetHash.test.js b/server/lib/assetHash.test.js
new file mode 100644
index 0000000000..aba0210936
--- /dev/null
+++ b/server/lib/assetHash.test.js
@@ -0,0 +1,127 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdir, rm, writeFile, readFile } from 'fs/promises';
+import { join, dirname } from 'path';
+import { tmpdir } from 'os';
+import { sidecarPathForImage, getOrComputeImageSha256 } from './assetHash.js';
+
+// PATHS.images is resolved at module-load from fileUtils. We monkey-patch it
+// per-test by writing a tmpdir-rooted image and pointing the sidecar resolver
+// at it via the same getOrComputeImageSha256 signature.
+
+let imageDir;
+
+beforeEach(async () => {
+ imageDir = join(tmpdir(), `portos-assethash-${Date.now()}-${Math.random()}`);
+ await mkdir(imageDir, { recursive: true });
+});
+
+afterEach(async () => {
+ await rm(imageDir, { recursive: true, force: true });
+});
+
+// The helpers above use PATHS.images from fileUtils. Rather than monkey-patch
+// that, we test the sidecar-key invariant directly with a controlled writePath
+// that lives under PATHS.images (using a unique-name token so cleanup is
+// scoped). This keeps the tests honest about real-world callsites.
+//
+// We re-import PATHS so each test resolves to the real images dir.
+import { PATHS } from './fileUtils.js';
+
+describe('assetHash', () => {
+ describe('sidecarPathForImage', () => {
+ it('replaces extension with .metadata.json under PATHS.images', () => {
+ const p = sidecarPathForImage('abc-123.png');
+ expect(p).toBe(join(PATHS.images, 'abc-123.metadata.json'));
+ });
+
+ it('handles absolute path inputs by taking basename', () => {
+ expect(sidecarPathForImage('/some/where/abc.png')).toBe(
+ join(PATHS.images, 'abc.metadata.json'),
+ );
+ });
+
+ it('null for empty', () => {
+ expect(sidecarPathForImage('')).toBeNull();
+ });
+
+ it('null for non-string inputs (total over all types — no TypeError crash)', () => {
+ // Regression: without the type guard, basename(null) throws TypeError
+ // and crashes the calling exporter / peer-sync pipeline.
+ expect(sidecarPathForImage(null)).toBeNull();
+ expect(sidecarPathForImage(undefined)).toBeNull();
+ expect(sidecarPathForImage(42)).toBeNull();
+ expect(sidecarPathForImage({})).toBeNull();
+ expect(sidecarPathForImage([])).toBeNull();
+ });
+ });
+
+ describe('getOrComputeImageSha256', () => {
+ it('null for missing image', async () => {
+ const result = await getOrComputeImageSha256(join(imageDir, 'nope.png'));
+ expect(result).toBeNull();
+ });
+
+ it('computes + persists sha256 in sidecar on first call', async () => {
+ // Use a name in the real PATHS.images dir so the sidecar write hits a
+ // real location. Token makes cleanup easy.
+ const token = `portos-assethash-test-${Date.now()}-${Math.random()}.png`;
+ const imagePath = join(PATHS.images, token);
+ const sidecarPath = sidecarPathForImage(imagePath);
+ await mkdir(dirname(imagePath), { recursive: true });
+ await writeFile(imagePath, Buffer.from('hello world'));
+ const result = await getOrComputeImageSha256(imagePath);
+ expect(result).not.toBeNull();
+ // "hello world" sha256:
+ expect(result.hash).toBe(
+ 'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9',
+ );
+ const sidecarJson = JSON.parse(await readFile(sidecarPath, 'utf8'));
+ expect(sidecarJson.sha256.value).toBe(result.hash);
+ expect(sidecarJson.sha256.size).toBe(11);
+ // cleanup
+ await rm(imagePath, { force: true });
+ await rm(sidecarPath, { force: true });
+ });
+
+ it('reuses cached sha256 on second call (no recompute)', async () => {
+ const token = `portos-assethash-test-${Date.now()}-${Math.random()}.png`;
+ const imagePath = join(PATHS.images, token);
+ const sidecarPath = sidecarPathForImage(imagePath);
+ await mkdir(dirname(imagePath), { recursive: true });
+ await writeFile(imagePath, Buffer.from('one'));
+ const first = await getOrComputeImageSha256(imagePath);
+ // Tamper with the sidecar to a known-wrong value but matching the size/mtime —
+ // the helper should trust the cached entry (proves it's reading sidecar first).
+ const tampered = JSON.parse(await readFile(sidecarPath, 'utf8'));
+ const fakeHash = 'a'.repeat(64);
+ tampered.sha256.value = fakeHash;
+ await writeFile(sidecarPath, JSON.stringify(tampered));
+ const second = await getOrComputeImageSha256(imagePath);
+ expect(second.hash).toBe(fakeHash);
+ expect(second.hash).not.toBe(first.hash);
+ await rm(imagePath, { force: true });
+ await rm(sidecarPath, { force: true });
+ });
+
+ it('recomputes when file changes (mtime+size invalidate cache)', async () => {
+ const token = `portos-assethash-test-${Date.now()}-${Math.random()}.png`;
+ const imagePath = join(PATHS.images, token);
+ const sidecarPath = sidecarPathForImage(imagePath);
+ await mkdir(dirname(imagePath), { recursive: true });
+ await writeFile(imagePath, Buffer.from('one'));
+ const first = await getOrComputeImageSha256(imagePath);
+ // Ensure mtime advances on slow filesystems where atime granularity
+ // could match — wait a tick before the rewrite.
+ await new Promise((r) => setTimeout(r, 20));
+ await writeFile(imagePath, Buffer.from('two-different-bytes'));
+ const second = await getOrComputeImageSha256(imagePath);
+ expect(second.hash).not.toBe(first.hash);
+ // Sidecar reflects the new hash + size.
+ const sidecarJson = JSON.parse(await readFile(sidecarPath, 'utf8'));
+ expect(sidecarJson.sha256.value).toBe(second.hash);
+ expect(sidecarJson.sha256.size).toBe(19);
+ await rm(imagePath, { force: true });
+ await rm(sidecarPath, { force: true });
+ });
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 08761d1ceb..06f446d84f 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -72,6 +72,7 @@ export * from './fileUtils.js';
export * from './fileWriteQueue.js';
export * from './imageClean.js';
export * from './multipart.js';
+export * from './assetHash.js';
export * from './pdfImageEmbed.js';
export * from './zipStream.js';
@@ -90,6 +91,7 @@ export * from './peerHttpClient.js';
export * from './peerSelfHost.js';
export * from './peerUrl.js';
export * from './sharingOrigin.js';
+export * from './syncWire.js';
export * from './tailscale.js';
// === Search & indexing ===
diff --git a/server/lib/syncWire.js b/server/lib/syncWire.js
new file mode 100644
index 0000000000..dde3cd3b70
--- /dev/null
+++ b/server/lib/syncWire.js
@@ -0,0 +1,118 @@
+const isNonEmptyStr = (v) => typeof v === 'string' && v.trim().length > 0;
+
+/**
+ * Normalize the `deleted` + `deletedAt` tombstone fields on a raw record.
+ * Used by every sanitizer that participates in soft-delete / peer sync
+ * (`sanitizeTemplate` for universes, `sanitizeSeries`, `sanitizeIssue`) so
+ * the shape of a tombstone is identical regardless of which file owns the
+ * record. The invariants are:
+ * 1. when `deleted=false`, `deletedAt` is always `null` — never a stray
+ * timestamp from a corrupted payload.
+ * 2. `deletedAt` is a NON-EMPTY string when present; empty/whitespace
+ * strings normalize to `null` so a malformed payload (`{ deleted: true,
+ * deletedAt: '' }`) doesn't persist a useless tombstone marker.
+ */
+export function sanitizeSoftDeleteFields(raw) {
+ const deleted = raw?.deleted === true;
+ const deletedAt = deleted && isNonEmptyStr(raw?.deletedAt) ? raw.deletedAt : null;
+ return { deleted, deletedAt };
+}
+
+// Single source of truth for what fields cross the federated-peer wire.
+//
+// Two transports carry universe / series / issue records between peers:
+//
+// 1. The 60s snapshot loop in `server/services/dataSync.js` — sends the full
+// per-category state every cycle for LWW reconciliation.
+// 2. The per-record push pipeline in `server/services/sharing/peerSync.js` —
+// sends one record (+ asset manifest) when a subscription fires after a
+// local edit.
+//
+// Both transports MUST agree on which fields are wire-safe and which are
+// peer-local (ephemeral state, transcripts, render history that's too large
+// to round-trip). The helpers here are the single decision point — change
+// them and every transport updates together.
+
+/**
+ * Wire-safe projection of a single record. Normalizes soft-delete fields so
+ * the on-disk shape is irrelevant to the wire hash — a legacy record without
+ * `deleted` / `deletedAt` and a freshly-rewritten record with
+ * `{ deleted: false, deletedAt: null }` carry the same logical content and
+ * MUST produce the same checksum. Without this, the 60s snapshot loop would
+ * see a permanent checksum mismatch between an upgraded peer and a not-yet-
+ * upgraded peer for the same live records (the merge LWW would no-op because
+ * `updatedAt` is equal, so the files never converge and sync churns forever).
+ *
+ * Per-record field stripping (e.g. dropping `runHistory` from issue stages
+ * once it grows too large for sync) goes here when the time comes — the
+ * function exists today so the new push path has the same callsite as the
+ * snapshot path, and so the next "should this field cross the wire?"
+ * decision lands in one place.
+ */
+export function sanitizeRecordForWire(kind, record) {
+ // Reject non-objects, arrays (typeof [] === 'object'), and records missing
+ // a usable id. Receiver-side merge functions (mergeUniversesFromSync etc.)
+ // skip records without an `id`, so including such records here would mean
+ // the snapshot checksum reflects content the receiver can never apply —
+ // 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;
+ 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;
+ return { ...rest, ...sanitizeSoftDeleteFields(record) };
+ }
+ default:
+ return null;
+ }
+}
+
+/**
+ * Wire-safe projection of a top-level state file. The 60s snapshot loop
+ * stripped `runs[]` from `universe-builder.json` here inline; centralising it
+ * means the per-record push uses the same rule when it bootstraps a peer with
+ * the full universe set on first subscribe.
+ *
+ * Returns `{ kind, data }` so callers can pass the result straight to
+ * `computeChecksum` and the receiver-side merge entry points.
+ */
+export function sanitizeStateForWire(kind, state) {
+ if (!state || typeof state !== 'object') return { kind, data: null };
+ switch (kind) {
+ case 'universe': {
+ const universes = Array.isArray(state.universes)
+ ? state.universes
+ .map((u) => sanitizeRecordForWire('universe', u))
+ .filter(Boolean)
+ : [];
+ // `runs[]` is local LLM run history (transcripts, ephemeral). Each peer
+ // keeps its own — never cross the wire.
+ return { kind, data: { universes } };
+ }
+ case 'pipeline': {
+ const series = Array.isArray(state.series)
+ ? state.series
+ .map((s) => sanitizeRecordForWire('series', s))
+ .filter(Boolean)
+ : [];
+ const issues = Array.isArray(state.issues)
+ ? state.issues
+ .map((i) => sanitizeRecordForWire('issue', i))
+ .filter(Boolean)
+ : [];
+ return { kind, data: { series, issues } };
+ }
+ default:
+ return { kind, data: null };
+ }
+}
diff --git a/server/lib/syncWire.test.js b/server/lib/syncWire.test.js
new file mode 100644
index 0000000000..c38ab096fb
--- /dev/null
+++ b/server/lib/syncWire.test.js
@@ -0,0 +1,173 @@
+import { describe, it, expect } from 'vitest';
+import {
+ sanitizeRecordForWire,
+ sanitizeStateForWire,
+ sanitizeSoftDeleteFields,
+} from './syncWire.js';
+
+describe('syncWire', () => {
+ describe('sanitizeSoftDeleteFields', () => {
+ it('returns live shape when deleted is absent or not strictly true', () => {
+ expect(sanitizeSoftDeleteFields({})).toEqual({ deleted: false, deletedAt: null });
+ expect(sanitizeSoftDeleteFields({ deleted: false })).toEqual({ deleted: false, deletedAt: null });
+ // Truthy-but-not-true (string, number, object) is treated as live — guards against
+ // corrupted payloads sneaking a tombstone through.
+ expect(sanitizeSoftDeleteFields({ deleted: 1 })).toEqual({ deleted: false, deletedAt: null });
+ expect(sanitizeSoftDeleteFields({ deleted: 'yes' })).toEqual({ deleted: false, deletedAt: null });
+ });
+
+ it('drops deletedAt when deleted=false, even if the payload has both', () => {
+ expect(sanitizeSoftDeleteFields({ deleted: false, deletedAt: '2026-01-01T00:00:00Z' }))
+ .toEqual({ deleted: false, deletedAt: null });
+ });
+
+ it('preserves deletedAt only when it is a non-empty string and deleted=true', () => {
+ expect(sanitizeSoftDeleteFields({ deleted: true, deletedAt: '2026-01-01T00:00:00Z' }))
+ .toEqual({ deleted: true, deletedAt: '2026-01-01T00:00:00Z' });
+ expect(sanitizeSoftDeleteFields({ deleted: true, deletedAt: 12345 }))
+ .toEqual({ deleted: true, deletedAt: null });
+ expect(sanitizeSoftDeleteFields({ deleted: true }))
+ .toEqual({ deleted: true, deletedAt: null });
+ });
+
+ it('normalizes empty / whitespace deletedAt to null (no useless tombstone markers)', () => {
+ expect(sanitizeSoftDeleteFields({ deleted: true, deletedAt: '' }))
+ .toEqual({ deleted: true, deletedAt: null });
+ expect(sanitizeSoftDeleteFields({ deleted: true, deletedAt: ' ' }))
+ .toEqual({ deleted: true, deletedAt: null });
+ expect(sanitizeSoftDeleteFields({ deleted: true, deletedAt: '\t\n' }))
+ .toEqual({ deleted: true, deletedAt: null });
+ });
+
+ it('null/undefined input returns live shape', () => {
+ expect(sanitizeSoftDeleteFields(null)).toEqual({ deleted: false, deletedAt: null });
+ expect(sanitizeSoftDeleteFields(undefined)).toEqual({ deleted: false, deletedAt: null });
+ });
+ });
+
+ describe('sanitizeRecordForWire', () => {
+ it('returns null for non-objects', () => {
+ expect(sanitizeRecordForWire('universe', null)).toBeNull();
+ expect(sanitizeRecordForWire('universe', undefined)).toBeNull();
+ expect(sanitizeRecordForWire('universe', 'string')).toBeNull();
+ });
+
+ it('returns null for unknown kinds', () => {
+ expect(sanitizeRecordForWire('mystery', { id: 'x' })).toBeNull();
+ });
+
+ it('returns null for arrays (typeof [] is "object" — must be excluded explicitly)', () => {
+ expect(sanitizeRecordForWire('universe', [])).toBeNull();
+ expect(sanitizeRecordForWire('universe', [{ id: 'u1' }])).toBeNull();
+ });
+
+ it('returns null for records missing or having a non-string id (receiver merges drop these)', () => {
+ // Without the id guard, a corrupted entry crosses the wire and the
+ // checksum reflects content the receiver can never merge in — permanent
+ // sync churn until both sides clean up the corrupt record.
+ expect(sanitizeRecordForWire('universe', { name: 'no id' })).toBeNull();
+ expect(sanitizeRecordForWire('universe', { id: '', name: 'empty id' })).toBeNull();
+ expect(sanitizeRecordForWire('universe', { id: ' ', name: 'ws id' })).toBeNull();
+ expect(sanitizeRecordForWire('universe', { id: 42, name: 'num id' })).toBeNull();
+ });
+
+ it('passes through universe/series/issue records with canonical soft-delete fields', () => {
+ const u = { id: 'u1', name: 'Foo' };
+ const canonical = { id: 'u1', name: 'Foo', deleted: false, deletedAt: null };
+ expect(sanitizeRecordForWire('universe', u)).toEqual(canonical);
+ expect(sanitizeRecordForWire('series', u)).toEqual(canonical);
+ expect(sanitizeRecordForWire('issue', u)).toEqual(canonical);
+ });
+
+ it('preserves tombstone records (deleted: true must cross the wire)', () => {
+ const u = { id: 'u1', deleted: true, deletedAt: '2026-01-01T00:00:00Z' };
+ expect(sanitizeRecordForWire('universe', u))
+ .toEqual({ id: 'u1', deleted: true, deletedAt: '2026-01-01T00:00:00Z' });
+ });
+
+ it('canonicalizes a legacy record (no deleted/deletedAt fields) to match a rewritten live record byte-for-byte', () => {
+ // Regression: without this, an upgraded peer that has rewritten its
+ // state to include { deleted: false, deletedAt: null } would compute a
+ // different snapshot checksum than a not-yet-upgraded peer with the
+ // same logical content, and the 60s sync loop would churn forever.
+ // computeChecksum uses JSON.stringify, which is key-order sensitive —
+ // assert STRING equality, not just object equality.
+ const legacy = { id: 'u1', name: 'U' };
+ const rewritten = { id: 'u1', name: 'U', deleted: false, deletedAt: null };
+ const a = sanitizeRecordForWire('universe', legacy);
+ const b = sanitizeRecordForWire('universe', rewritten);
+ expect(a).toEqual(b);
+ expect(JSON.stringify(a)).toBe(JSON.stringify(b));
+ });
+
+ it('canonicalizes records with oddly-ordered keys (deleted in head position) to canonical tail order', () => {
+ // Regression for the Copilot finding: spreading sanitizeSoftDeleteFields
+ // into a record that already has `deleted` in a non-tail position only
+ // OVERWRITES the value — the key keeps its original position. Without
+ // explicitly stripping then re-adding, the JSON.stringify output differs.
+ const odd = { deleted: false, id: 'u1', deletedAt: null, name: 'U' };
+ const canonical = { id: 'u1', name: 'U', deleted: false, deletedAt: null };
+ expect(JSON.stringify(sanitizeRecordForWire('universe', odd)))
+ .toBe(JSON.stringify(sanitizeRecordForWire('universe', canonical)));
+ });
+
+ it('strips stray deletedAt when deleted=false (defensive against corrupted payloads)', () => {
+ const corrupt = { id: 'u1', deleted: false, deletedAt: '2026-01-01T00:00:00Z' };
+ expect(sanitizeRecordForWire('universe', corrupt))
+ .toEqual({ id: 'u1', deleted: false, deletedAt: null });
+ });
+ });
+
+ describe('sanitizeStateForWire', () => {
+ it('strips runs[] from universe state (peer-local LLM history)', () => {
+ const state = {
+ universes: [{ id: 'u1', name: 'U' }],
+ runs: [{ id: 'r1', universeId: 'u1' }],
+ };
+ const result = sanitizeStateForWire('universe', state);
+ expect(result.kind).toBe('universe');
+ // Universes are canonicalized through sanitizeRecordForWire, which adds
+ // the default soft-delete fields so legacy + rewritten records hash the
+ // same on the wire (see the canonicalization regression test above).
+ expect(result.data).toEqual({
+ universes: [{ id: 'u1', name: 'U', deleted: false, deletedAt: null }],
+ });
+ expect(result.data.runs).toBeUndefined();
+ });
+
+ it('handles missing universes array (empty state)', () => {
+ expect(sanitizeStateForWire('universe', {})).toEqual({
+ kind: 'universe',
+ data: { universes: [] },
+ });
+ });
+
+ it('preserves tombstoned records in universe state', () => {
+ const state = {
+ universes: [
+ { id: 'u1' },
+ { id: 'u2', deleted: true, deletedAt: '2026-01-01T00:00:00Z' },
+ ],
+ };
+ const result = sanitizeStateForWire('universe', state);
+ expect(result.data.universes).toHaveLength(2);
+ expect(result.data.universes[1].deleted).toBe(true);
+ });
+
+ it('returns series + issues for pipeline kind', () => {
+ const state = {
+ series: [{ id: 's1' }],
+ issues: [{ id: 'i1' }, { id: 'i2', deleted: true }],
+ };
+ const result = sanitizeStateForWire('pipeline', state);
+ expect(result.kind).toBe('pipeline');
+ expect(result.data.series).toHaveLength(1);
+ expect(result.data.issues).toHaveLength(2);
+ });
+
+ it('null for unknown kind / non-object state', () => {
+ expect(sanitizeStateForWire('mystery', {}).data).toBeNull();
+ expect(sanitizeStateForWire('universe', null).data).toBeNull();
+ });
+ });
+});
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index cdb4091c5a..ec1b8e7cee 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -14,6 +14,7 @@ import { isPlainObject } from '../lib/objects.js';
import { mergeUniversesFromSync } from './universeBuilder.js';
import { mergeSeriesFromSync } from './pipeline/series.js';
import { mergeIssuesFromSync } from './pipeline/issues.js';
+import { sanitizeStateForWire } from '../lib/syncWire.js';
// --- Category Definitions ---
@@ -346,11 +347,12 @@ async function applyMeatspaceRemote(remoteData) {
// --- Category: Universe ---
async function getUniverseSnapshot() {
- const data = await readJSONFile(UNIVERSE_BUILDER_FILE, { universes: [] });
- // Skip `runs[]` — that's local LLM run history (transcripts, ephemeral),
- // not user-edited universe state. Each peer keeps its own history.
- const universesOnly = { universes: data.universes || [] };
- return { data: universesOnly, checksum: computeChecksum(universesOnly) };
+ const raw = await readJSONFile(UNIVERSE_BUILDER_FILE, { universes: [] });
+ // Wire-projection lives in `server/lib/syncWire.js` so the new per-record
+ // peer-sync push agrees on what to strip (currently: top-level `runs[]`,
+ // which is local LLM run history per peer).
+ const { data } = sanitizeStateForWire('universe', raw);
+ return { data, checksum: computeChecksum(data) };
}
async function applyUniverseRemote(remoteData) {
@@ -375,10 +377,11 @@ async function getPipelineSnapshot() {
readJSONFile(PIPELINE_SERIES_FILE, { series: [] }),
readJSONFile(PIPELINE_ISSUES_FILE, { issues: [] }),
]);
- const data = {
- series: seriesFile.series || [],
- issues: issuesFile.issues || [],
- };
+ // Wire-projection lives in `server/lib/syncWire.js` — see getUniverseSnapshot.
+ const { data } = sanitizeStateForWire('pipeline', {
+ series: seriesFile.series,
+ issues: issuesFile.issues,
+ });
return { data, checksum: computeChecksum(data) };
}
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index b62e8736ab..a237a34a09 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -29,6 +29,7 @@ import {
CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,
} from '../../lib/issueLength.js';
import { sanitizeOrigin } from '../../lib/sharingOrigin.js';
+import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
import { ServerError } from '../../lib/errorHandler.js';
import { ARC_ROLES } from '../../lib/storyArc.js';
import { isStr, trimTo } from '../../lib/storyBible.js';
@@ -410,6 +411,8 @@ const sanitizeIssue = (raw) => {
origin: sanitizeOrigin(raw.origin),
createdAt,
updatedAt,
+ // Soft-delete fields — see universeBuilder.sanitizeTemplate.
+ ...sanitizeSoftDeleteFields(raw),
};
};
@@ -430,9 +433,11 @@ export async function listIssues({
limit = ISSUES_PER_RESPONSE_MAX,
paginated = false,
withHistory = true,
+ includeDeleted = false,
} = {}) {
const { issues } = await readState();
- const filtered = seriesId ? issues.filter((i) => i.seriesId === seriesId) : issues;
+ const live = includeDeleted ? issues : issues.filter((i) => !i.deleted);
+ const filtered = seriesId ? live.filter((i) => i.seriesId === seriesId) : live;
const sorted = [...filtered].sort((a, b) => {
if (a.seriesId !== b.seriesId) return a.seriesId.localeCompare(b.seriesId);
return (a.number || 0) - (b.number || 0);
@@ -459,8 +464,9 @@ export async function listIssues({
* beyond 1000, so the sidebar's recent-issues view needs this dedicated
* helper.
*/
-export async function listRecentIssues({ limit = 10, withHistory = true } = {}) {
+export async function listRecentIssues({ limit = 10, withHistory = true, includeDeleted = false } = {}) {
const { issues } = await readState();
+ const live = includeDeleted ? issues : issues.filter((i) => !i.deleted);
// Coerce in two passes so non-finite inputs ('abc', undefined) fall to
// the default rather than letting JS's `0 || 10` short-circuit return
// 10 for an explicit limit=0.
@@ -468,16 +474,17 @@ export async function listRecentIssues({ limit = 10, withHistory = true } = {})
const fallback = Number.isFinite(raw) ? Math.floor(raw) : 10;
const clamped = Math.max(1, Math.min(50, fallback));
const project = withHistory ? (i) => i : stripRunHistoryFromIssue;
- return [...issues]
+ return [...live]
.sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''))
.slice(0, clamped)
.map(project);
}
-export async function getIssue(id) {
+export async function getIssue(id, { includeDeleted = false } = {}) {
const { issues } = await readState();
const found = issues.find((i) => i.id === id);
if (!found) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
+ if (found.deleted && !includeDeleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
return found;
}
@@ -487,40 +494,44 @@ export function createIssue(input = {}) {
const title = trimTo(input.title, TITLE_MAX);
if (!title) return Promise.reject(makeErr(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION));
return queueIssueWrite(async () => {
- const state = await readState();
- const next = sanitizeIssue({
- id: `iss-${randomUUID()}`,
- seriesId,
- // Placeholder — `renumberInline` below derives the canonical number.
- number: 0,
- title,
- status: 'draft',
- // Phase 2: optional arc pointers passed by the season-episodes generator
- // (and any future caller wiring an issue to a season at create time).
- seasonId: 'seasonId' in input ? input.seasonId : null,
- arcPosition: 'arcPosition' in input ? input.arcPosition : null,
- arcRole: 'arcRole' in input ? input.arcRole : null,
- lengthProfile: 'lengthProfile' in input ? input.lengthProfile : undefined,
- pageTarget: 'pageTarget' in input ? input.pageTarget : null,
- minutesTarget: 'minutesTarget' in input ? input.minutesTarget : null,
- stages: input.stages || {},
- createdAt: new Date().toISOString(),
- updatedAt: new Date().toISOString(),
- });
- if (!next) throw makeErr('Invalid issue payload', ERR_VALIDATION);
- state.issues.push(next);
- await renumberInline(state, seriesId, next.seasonId || UNSCOPED_ANCHOR);
- await writeState(state);
- // New issue = series-level change for any active share subscription.
- emitRecordUpdated('series', next.seriesId);
- return next;
+ const state = await readState();
+ const next = sanitizeIssue({
+ id: `iss-${randomUUID()}`,
+ seriesId,
+ // Placeholder — `renumberInline` below derives the canonical number.
+ number: 0,
+ title,
+ status: 'draft',
+ // Phase 2: optional arc pointers passed by the season-episodes generator
+ // (and any future caller wiring an issue to a season at create time).
+ seasonId: 'seasonId' in input ? input.seasonId : null,
+ arcPosition: 'arcPosition' in input ? input.arcPosition : null,
+ arcRole: 'arcRole' in input ? input.arcRole : null,
+ lengthProfile: 'lengthProfile' in input ? input.lengthProfile : undefined,
+ pageTarget: 'pageTarget' in input ? input.pageTarget : null,
+ minutesTarget: 'minutesTarget' in input ? input.minutesTarget : null,
+ stages: input.stages || {},
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ });
+ if (!next) throw makeErr('Invalid issue payload', ERR_VALIDATION);
+ state.issues.push(next);
+ await renumberInline(state, seriesId, next.seasonId || UNSCOPED_ANCHOR);
+ await writeState(state);
+ // New issue = series-level change for any active share subscription.
+ emitRecordUpdated('series', next.seriesId);
+ return next;
}); // end queueIssueWrite
}
async function renumberInline(state, seriesId, fromSeasonId = null) {
const series = await seriesSvc.getSeries(seriesId).catch(() => null);
+ // Exclude tombstones from numbering — surviving issues should keep a
+ // contiguous sequence regardless of how many deletes happened.
+ // applyVolumeOrderedNumbers mutates each issue's `number` in place, so the
+ // filtered array still aliases the same objects in state.issues.
return applyVolumeOrderedNumbers({
- issues: state.issues,
+ issues: state.issues.filter((i) => !i.deleted),
seriesId,
seasons: series?.seasons || [],
fromSeasonId,
@@ -578,6 +589,10 @@ export function bulkReassignSeason(seriesId, fromSeasonId, toSeasonId = null, {
for (let i = 0; i < state.issues.length; i += 1) {
const iss = state.issues[i];
if (iss.seriesId !== seriesId) continue;
+ // Skip tombstones — moving a soft-deleted issue would bump its
+ // `updatedAt`, which then loses LWW races with the originator's
+ // tombstone and can resurrect the record on every peer.
+ if (iss.deleted) continue;
if ((iss.seasonId || null) !== (fromSeasonId || null)) continue;
// Re-sanitize through the same pipeline updateIssue uses so the
// in-memory rewrite gets the same shape guarantees as a route PATCH.
@@ -615,12 +630,19 @@ export function insertIssueWithId(input = {}) {
if (!title) return Promise.reject(makeErr(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION));
return queueIssueWrite(async () => {
const state = await readState();
- if (state.issues.some((i) => i.id === input.id)) {
+ // Tombstone-overwrite: same contract as universeBuilder.insertUniverseWithId.
+ const existingIdx = state.issues.findIndex((i) => i.id === input.id);
+ if (existingIdx >= 0 && !state.issues[existingIdx].deleted) {
throw makeErr(`Issue id already exists: ${input.id}`, ERR_DUPLICATE);
}
const next = sanitizeIssue({ ...input, seriesId, title });
if (!next) throw makeErr('Invalid issue payload', ERR_VALIDATION);
- state.issues.push(next);
+ if (existingIdx >= 0) {
+ console.warn(`♻️ insertIssueWithId: overwriting tombstone for ${input.id}`);
+ state.issues[existingIdx] = next;
+ } else {
+ state.issues.push(next);
+ }
// Imported `number` is a starting hint — local canonical numbering still
// comes from (volume order, arcPosition) of the local state.
await renumberInline(state, seriesId, next.seasonId || UNSCOPED_ANCHOR);
@@ -631,97 +653,98 @@ export function insertIssueWithId(input = {}) {
export function updateIssue(id, patch = {}, { skipRenumber = false } = {}) {
return queueIssueWrite(async () => {
- const state = await readState();
- const idx = state.issues.findIndex((i) => i.id === id);
- if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
- const cur = state.issues[idx];
-
- // Per-stage merge: a stage patch carries only the fields the caller is
- // changing (e.g. `{ genConfig }` or `{ cover }`). Without this, the top-level
- // spread would replace the entire stage object and silently drop sibling
- // fields like `scenes` / `pages` / `genConfig`. Sanitization then defaults
- // those back to empty arrays/null, erasing work the user (or LLM) just did.
- // Callers that need stage-level changes without touching issue-level fields
- // should use `updateStage`, which does a shallow merge of the patch over the
- // existing stage (`{ ...cur.stages[stageId], ...patch }`) before sanitizing.
- // Note: `updateStage` still merges — omitted sibling stage fields are
- // preserved. To clear a field explicitly, pass it as `null` or `""` in the
- // patch.
- //
- // `cover` and `genConfig` are treated as deep-merge sub-objects: a partial
- // `{ cover: { script } }` patch from a textarea-blur save must not wipe the
- // sibling `imageJobId` / `prompt` that a parallel "Render cover" mutation
- // just persisted. Passing `null` explicitly still clears the sub-object
- // (intentional-clear semantics).
- const NESTED_DEEP_MERGE_KEYS = ['cover', 'genConfig'];
- let mergedStages = cur.stages;
- if ('stages' in patch && patch.stages && typeof patch.stages === 'object') {
- mergedStages = { ...cur.stages };
- for (const [stageId, stagePatch] of Object.entries(patch.stages)) {
- const prev = cur.stages?.[stageId];
- if (prev && stagePatch && typeof prev === 'object' && typeof stagePatch === 'object') {
- const merged = { ...prev, ...stagePatch };
- // Mirror the snapshot trigger from updateStageWithLatest so a
- // route-level PATCH that swaps lastRunId (e.g. the restore endpoint)
- // also produces a runHistory entry. No-op when the patch is a plain
- // save-edit without lastRunId.
- merged.runHistory = snapshotRunHistory(prev, stagePatch, stageId);
- for (const key of NESTED_DEEP_MERGE_KEYS) {
- if (key in stagePatch
- && stagePatch[key] && typeof stagePatch[key] === 'object'
- && prev[key] && typeof prev[key] === 'object') {
- merged[key] = { ...prev[key], ...stagePatch[key] };
+ const state = await readState();
+ const idx = state.issues.findIndex((i) => i.id === id);
+ if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
+ const cur = state.issues[idx];
+ if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
+
+ // Per-stage merge: a stage patch carries only the fields the caller is
+ // changing (e.g. `{ genConfig }` or `{ cover }`). Without this, the top-level
+ // spread would replace the entire stage object and silently drop sibling
+ // fields like `scenes` / `pages` / `genConfig`. Sanitization then defaults
+ // those back to empty arrays/null, erasing work the user (or LLM) just did.
+ // Callers that need stage-level changes without touching issue-level fields
+ // should use `updateStage`, which does a shallow merge of the patch over the
+ // existing stage (`{ ...cur.stages[stageId], ...patch }`) before sanitizing.
+ // Note: `updateStage` still merges — omitted sibling stage fields are
+ // preserved. To clear a field explicitly, pass it as `null` or `""` in the
+ // patch.
+ //
+ // `cover` and `genConfig` are treated as deep-merge sub-objects: a partial
+ // `{ cover: { script } }` patch from a textarea-blur save must not wipe the
+ // sibling `imageJobId` / `prompt` that a parallel "Render cover" mutation
+ // just persisted. Passing `null` explicitly still clears the sub-object
+ // (intentional-clear semantics).
+ const NESTED_DEEP_MERGE_KEYS = ['cover', 'genConfig'];
+ let mergedStages = cur.stages;
+ if ('stages' in patch && patch.stages && typeof patch.stages === 'object') {
+ mergedStages = { ...cur.stages };
+ for (const [stageId, stagePatch] of Object.entries(patch.stages)) {
+ const prev = cur.stages?.[stageId];
+ if (prev && stagePatch && typeof prev === 'object' && typeof stagePatch === 'object') {
+ const merged = { ...prev, ...stagePatch };
+ // Mirror the snapshot trigger from updateStageWithLatest so a
+ // route-level PATCH that swaps lastRunId (e.g. the restore endpoint)
+ // also produces a runHistory entry. No-op when the patch is a plain
+ // save-edit without lastRunId.
+ merged.runHistory = snapshotRunHistory(prev, stagePatch, stageId);
+ for (const key of NESTED_DEEP_MERGE_KEYS) {
+ if (key in stagePatch
+ && stagePatch[key] && typeof stagePatch[key] === 'object'
+ && prev[key] && typeof prev[key] === 'object') {
+ merged[key] = { ...prev[key], ...stagePatch[key] };
+ }
}
+ // Clear transient error fields when a content/status change implies
+ // the previous failure is no longer the active state. Mirrors the
+ // pre-per-stage-merge behavior, where a `{ status, input, output }`
+ // patch replaced the whole stage and implicitly wiped errorMessage.
+ if ('status' in stagePatch && stagePatch.status !== 'error'
+ && stagePatch.status !== 'generating'
+ && !('errorMessage' in stagePatch)) {
+ merged.errorMessage = '';
+ }
+ mergedStages[stageId] = merged;
+ } else {
+ mergedStages[stageId] = stagePatch;
}
- // Clear transient error fields when a content/status change implies
- // the previous failure is no longer the active state. Mirrors the
- // pre-per-stage-merge behavior, where a `{ status, input, output }`
- // patch replaced the whole stage and implicitly wiped errorMessage.
- if ('status' in stagePatch && stagePatch.status !== 'error'
- && stagePatch.status !== 'generating'
- && !('errorMessage' in stagePatch)) {
- merged.errorMessage = '';
- }
- mergedStages[stageId] = merged;
- } else {
- mergedStages[stageId] = stagePatch;
}
}
- }
- const merged = sanitizeIssue({
- ...cur,
- ...('title' in patch ? { title: patch.title } : {}),
- ...('number' in patch ? { number: patch.number } : {}),
- ...('status' in patch ? { status: patch.status } : {}),
- ...('seasonId' in patch ? { seasonId: patch.seasonId } : {}),
- ...('arcPosition' in patch ? { arcPosition: patch.arcPosition } : {}),
- ...('arcRole' in patch ? { arcRole: patch.arcRole } : {}),
- ...('lengthProfile' in patch ? { lengthProfile: patch.lengthProfile } : {}),
- ...('pageTarget' in patch ? { pageTarget: patch.pageTarget } : {}),
- ...('minutesTarget' in patch ? { minutesTarget: patch.minutesTarget } : {}),
- ...('origin' in patch ? { origin: patch.origin } : {}),
- stages: mergedStages,
- updatedAt: new Date().toISOString(),
- });
- if (!merged) throw makeErr('Invalid issue payload', ERR_VALIDATION);
- state.issues[idx] = merged;
- // A seasonId move affects both source and destination volumes, so full
- // renumber. An arcPosition change only reorders within the current volume.
- // `skipRenumber` lets bulk callers (e.g. deleteSeason) collapse N per-update
- // renumbers into one final pass.
- if (!skipRenumber) {
- if ('seasonId' in patch && cur.seasonId !== merged.seasonId) {
- await renumberInline(state, merged.seriesId, null);
- } else if ('arcPosition' in patch && cur.arcPosition !== merged.arcPosition) {
- await renumberInline(state, merged.seriesId, merged.seasonId || UNSCOPED_ANCHOR);
+ const merged = sanitizeIssue({
+ ...cur,
+ ...('title' in patch ? { title: patch.title } : {}),
+ ...('number' in patch ? { number: patch.number } : {}),
+ ...('status' in patch ? { status: patch.status } : {}),
+ ...('seasonId' in patch ? { seasonId: patch.seasonId } : {}),
+ ...('arcPosition' in patch ? { arcPosition: patch.arcPosition } : {}),
+ ...('arcRole' in patch ? { arcRole: patch.arcRole } : {}),
+ ...('lengthProfile' in patch ? { lengthProfile: patch.lengthProfile } : {}),
+ ...('pageTarget' in patch ? { pageTarget: patch.pageTarget } : {}),
+ ...('minutesTarget' in patch ? { minutesTarget: patch.minutesTarget } : {}),
+ ...('origin' in patch ? { origin: patch.origin } : {}),
+ stages: mergedStages,
+ updatedAt: new Date().toISOString(),
+ });
+ if (!merged) throw makeErr('Invalid issue payload', ERR_VALIDATION);
+ state.issues[idx] = merged;
+ // A seasonId move affects both source and destination volumes, so full
+ // renumber. An arcPosition change only reorders within the current volume.
+ // `skipRenumber` lets bulk callers (e.g. deleteSeason) collapse N per-update
+ // renumbers into one final pass.
+ if (!skipRenumber) {
+ if ('seasonId' in patch && cur.seasonId !== merged.seasonId) {
+ await renumberInline(state, merged.seriesId, null);
+ } else if ('arcPosition' in patch && cur.arcPosition !== merged.arcPosition) {
+ await renumberInline(state, merged.seriesId, merged.seasonId || UNSCOPED_ANCHOR);
+ }
}
- }
- await writeState(state);
- // Issues are exported as part of their parent series — re-export the
- // series so any active subscription picks up the issue change.
- emitRecordUpdated('series', merged.seriesId);
- return merged;
+ await writeState(state);
+ // Issues are exported as part of their parent series — re-export the
+ // series so any active subscription picks up the issue change.
+ emitRecordUpdated('series', merged.seriesId);
+ return merged;
}); // end queueIssueWrite
}
@@ -771,19 +794,25 @@ export function restoreStageFromHistory(issueId, stageId, runId) {
}
export function deleteIssue(id) {
+ // Soft-delete — same tombstone-in-record pattern as universes/series. The
+ // record stays on disk with `deleted: true` so the next sync propagates the
+ // delete to peers; the orchestrator's GC sweep prunes it once all peers ack.
+ // `renumberInline` filters tombstones, so surviving issues stay contiguous.
return queueIssueWrite(async () => {
- const state = await readState();
- const idx = state.issues.findIndex((i) => i.id === id);
- if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
- const removed = state.issues[idx];
- const seriesId = removed.seriesId;
- state.issues.splice(idx, 1);
- await renumberInline(state, seriesId, removed.seasonId || UNSCOPED_ANCHOR);
- await writeState(state);
- // Series export bundles every issue, so a deletion is an update on the
- // parent series for any active share-bucket subscription.
- emitRecordUpdated('series', seriesId);
- return { id };
+ const state = await readState();
+ const idx = state.issues.findIndex((i) => i.id === id);
+ if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
+ const cur = state.issues[idx];
+ if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
+ const seriesId = cur.seriesId;
+ const now = new Date().toISOString();
+ state.issues[idx] = { ...cur, deleted: true, deletedAt: now, updatedAt: now };
+ await renumberInline(state, seriesId, cur.seasonId || UNSCOPED_ANCHOR);
+ await writeState(state);
+ // Series export bundles every issue, so a deletion is an update on the
+ // parent series for any active share-bucket subscription.
+ emitRecordUpdated('series', seriesId);
+ return { id };
}); // end queueIssueWrite
}
@@ -805,44 +834,45 @@ export function updateStageWithLatest(issueId, stageId, computeFn) {
return Promise.reject(makeErr(`Unknown stage: ${stageId}`, ERR_VALIDATION));
}
return queueIssueWrite(async () => {
- const state = await readState();
- const idx = state.issues.findIndex((i) => i.id === issueId);
- if (idx < 0) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);
- const cur = state.issues[idx];
- const isVisual = VISUAL_STAGE_IDS.includes(stageId);
- const isAudio = AUDIO_STAGE_IDS.includes(stageId);
- const currentStage = cur.stages[stageId];
- const patch = computeFn(currentStage);
- // Empty-patch fast path: a computeFn that returns `{}` is a "decided not
- // to write" signal (e.g. stale media-job completion against a re-rendered
- // page). Skip the disk write + emitRecordUpdated so it doesn't trigger
- // a re-export storm in share subscriptions for late no-op events.
- if (isPlainObject(patch) && Object.keys(patch).length === 0) {
- return { issue: cur, stage: currentStage };
- }
- // Snapshot the prior `{ runId, input, output }` into runHistory when this
- // patch carries a fresh lastRunId (i.e. a generate just replaced prior
- // content). Computed BEFORE the spread so it reads pre-merge state.
- const nextRunHistory = snapshotRunHistory(currentStage, patch, stageId);
- const merged = {
- ...currentStage,
- ...patch,
- runHistory: nextRunHistory,
- updatedAt: new Date().toISOString(),
- };
- let next;
- if (isVisual) next = sanitizeVisualStage(merged, stageId);
- else if (isAudio) next = sanitizeAudioStage(merged);
- else next = sanitizeStage(merged);
- const mergedIssue = sanitizeIssue({
- ...cur,
- stages: { ...cur.stages, [stageId]: next },
- updatedAt: new Date().toISOString(),
- });
- state.issues[idx] = mergedIssue;
- await writeState(state);
- emitRecordUpdated('series', mergedIssue.seriesId);
- return { issue: mergedIssue, stage: mergedIssue.stages[stageId] };
+ const state = await readState();
+ const idx = state.issues.findIndex((i) => i.id === issueId);
+ if (idx < 0) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);
+ const cur = state.issues[idx];
+ if (cur.deleted) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);
+ const isVisual = VISUAL_STAGE_IDS.includes(stageId);
+ const isAudio = AUDIO_STAGE_IDS.includes(stageId);
+ const currentStage = cur.stages[stageId];
+ const patch = computeFn(currentStage);
+ // Empty-patch fast path: a computeFn that returns `{}` is a "decided not
+ // to write" signal (e.g. stale media-job completion against a re-rendered
+ // page). Skip the disk write + emitRecordUpdated so it doesn't trigger
+ // a re-export storm in share subscriptions for late no-op events.
+ if (isPlainObject(patch) && Object.keys(patch).length === 0) {
+ return { issue: cur, stage: currentStage };
+ }
+ // Snapshot the prior `{ runId, input, output }` into runHistory when this
+ // patch carries a fresh lastRunId (i.e. a generate just replaced prior
+ // content). Computed BEFORE the spread so it reads pre-merge state.
+ const nextRunHistory = snapshotRunHistory(currentStage, patch, stageId);
+ const merged = {
+ ...currentStage,
+ ...patch,
+ runHistory: nextRunHistory,
+ updatedAt: new Date().toISOString(),
+ };
+ let next;
+ if (isVisual) next = sanitizeVisualStage(merged, stageId);
+ else if (isAudio) next = sanitizeAudioStage(merged);
+ else next = sanitizeStage(merged);
+ const mergedIssue = sanitizeIssue({
+ ...cur,
+ stages: { ...cur.stages, [stageId]: next },
+ updatedAt: new Date().toISOString(),
+ });
+ state.issues[idx] = mergedIssue;
+ await writeState(state);
+ emitRecordUpdated('series', mergedIssue.seriesId);
+ return { issue: mergedIssue, stage: mergedIssue.stages[stageId] };
}); // end queueIssueWrite
}
@@ -858,6 +888,15 @@ export function updateStageWithLatest(issueId, stageId, computeFn) {
*/
export function mergeIssuesFromSync(remoteIssues) {
if (!Array.isArray(remoteIssues)) return Promise.resolve({ applied: false, count: 0 });
+ // Series IDs whose issue set saw at least one delete-transition — drives a
+ // post-write renumber so the receiver's issue numbering catches up with the
+ // sender's (otherwise a synced tombstone would leave a gap).
+ //
+ // Edit-only merges (no delete-transitions) do NOT emit `recordUpdated` for
+ // the parent series — see `mergeUniversesFromSync` for the rationale (the
+ // Stage 2 per-record peer-sync push owns sync-time edit emits). Delete-
+ // transitions DO emit per series so subscribers know to drop the issue.
+ const seriesNeedingRenumber = new Set();
return queueIssueWrite(async () => {
const state = await readState();
const localById = new Map(state.issues.map((i) => [i.id, i]));
@@ -868,6 +907,10 @@ export function mergeIssuesFromSync(remoteIssues) {
if (!sanitized) continue;
const local = localById.get(sanitized.id);
if (!local) {
+ // No local counterpart — accept the record but don't trigger a
+ // renumber pass. A tombstone for an issue we never had has nothing
+ // to compact; firing `emitRecordUpdated('series', …)` for a series
+ // we may not even own would spuriously re-export.
localById.set(sanitized.id, sanitized);
changed++;
} else {
@@ -875,13 +918,37 @@ export function mergeIssuesFromSync(remoteIssues) {
const remoteTs = sanitized.updatedAt || '';
if (remoteTs > localTs) {
localById.set(sanitized.id, sanitized);
+ // Renumber on EITHER direction of the transition: a delete leaves
+ // a gap, a resurrection (deleted→live) reintroduces a previously-
+ // compacted number and can collide with live siblings until some
+ // unrelated edit triggers a renumber. Cover both here.
+ if (sanitized.deleted !== local.deleted) {
+ seriesNeedingRenumber.add(sanitized.seriesId);
+ // A resurrection may move from the OLD seriesId to a different
+ // one in the inbound record (rare, but possible) — renumber both.
+ if (local.seriesId && local.seriesId !== sanitized.seriesId) {
+ seriesNeedingRenumber.add(local.seriesId);
+ }
+ }
changed++;
}
}
}
if (changed === 0) return { applied: false, count: 0 };
state.issues = Array.from(localById.values());
+ // Compact issue numbers for each affected series — the merge may have
+ // tombstoned (gap) or resurrected (collision) an issue. renumberInline
+ // skips tombstones, so the resulting numbering is always contiguous
+ // across live issues. Single renumber per series, all inside the queue.
+ for (const seriesId of seriesNeedingRenumber) {
+ await renumberInline(state, seriesId, null);
+ }
await writeState(state);
+ // Re-emit a series-updated for each touched series so any active share
+ // subscription re-exports the post-merge issue set.
+ for (const seriesId of seriesNeedingRenumber) {
+ emitRecordUpdated('series', seriesId);
+ }
return { applied: true, count: changed };
});
}
diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.js
index ef4edbe76a..964394507b 100644
--- a/server/services/pipeline/issues.test.js
+++ b/server/services/pipeline/issues.test.js
@@ -682,6 +682,143 @@ describe('pipeline issues service', () => {
await expect(svc.deleteIssue(i.id)).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
});
+ describe('soft-delete (tombstones for peer sync)', () => {
+ it('deleteIssue soft-deletes (record stays on disk with deleted=true)', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'First' });
+ await svc.deleteIssue(i.id);
+ expect((await svc.listIssues({ seriesId: 'ser-1' })).map((x) => x.id)).not.toContain(i.id);
+ const all = await svc.listIssues({ seriesId: 'ser-1', includeDeleted: true });
+ const tomb = all.find((x) => x.id === i.id);
+ expect(tomb).toMatchObject({ deleted: true });
+ expect(tomb.deletedAt).toBeTruthy();
+ });
+
+ it('getIssue 404s for tombstoned; includeDeleted exposes it', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'Hidden' });
+ await svc.deleteIssue(i.id);
+ await expect(svc.getIssue(i.id)).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
+ const tomb = await svc.getIssue(i.id, { includeDeleted: true });
+ expect(tomb).toMatchObject({ id: i.id, deleted: true });
+ });
+
+ it('updateIssue 404s on a tombstone (no zombie edits)', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'Locked' });
+ await svc.deleteIssue(i.id);
+ await expect(svc.updateIssue(i.id, { title: 'Zombie' })).rejects.toMatchObject({
+ code: svc.ERR_NOT_FOUND,
+ });
+ });
+
+ it('insertIssueWithId overwrites a tombstoned record (re-import undeletes)', async () => {
+ const id = 'iss-550e8400-e29b-41d4-a716-44665544abce';
+ await svc.insertIssueWithId({ id, seriesId: 'ser-1', title: 'First' });
+ await svc.deleteIssue(id);
+ const restored = await svc.insertIssueWithId({ id, seriesId: 'ser-1', title: 'Restored' });
+ expect(restored).toMatchObject({ id, title: 'Restored', deleted: false });
+ });
+
+ it('insertIssueWithId still rejects DUPLICATE on a LIVE record', async () => {
+ const id = 'iss-550e8400-e29b-41d4-a716-44665544abcf';
+ await svc.insertIssueWithId({ id, seriesId: 'ser-1', title: 'First' });
+ await expect(svc.insertIssueWithId({ id, seriesId: 'ser-1', title: 'Second' }))
+ .rejects.toMatchObject({ code: svc.ERR_DUPLICATE });
+ });
+
+ it('renumberInline skips tombstones — surviving issues stay contiguous', async () => {
+ const a = await svc.createIssue({ seriesId: 'ser-renum', title: 'A' });
+ const b = await svc.createIssue({ seriesId: 'ser-renum', title: 'B' });
+ const c = await svc.createIssue({ seriesId: 'ser-renum', title: 'C' });
+ await svc.deleteIssue(b.id);
+ const live = await svc.listIssues({ seriesId: 'ser-renum' });
+ expect(live.map((i) => i.title)).toEqual(['A', 'C']);
+ expect(live.map((i) => i.number)).toEqual([1, 2]);
+ // Tombstone keeps its old number but is hidden from listIssues.
+ const all = await svc.listIssues({ seriesId: 'ser-renum', includeDeleted: true });
+ expect(all.find((i) => i.id === b.id).deleted).toBe(true);
+ // Adding a new issue picks up after the live tail (3), not 4 from the tombstone.
+ const d = await svc.createIssue({ seriesId: 'ser-renum', title: 'D' });
+ expect(d.number).toBe(3);
+ });
+
+ describe('mergeIssuesFromSync', () => {
+ it('applies an inbound soft-delete from a peer', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'Synced' });
+ const ts = new Date(Date.now() + 60_000).toISOString();
+ const r = await svc.mergeIssuesFromSync([{
+ ...i,
+ deleted: true,
+ deletedAt: ts,
+ updatedAt: ts,
+ }]);
+ expect(r).toEqual({ applied: true, count: 1 });
+ await expect(svc.getIssue(i.id)).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
+ });
+
+ it('LWW: an inbound edit with later updatedAt resurrects over a local tombstone', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'Original' });
+ await svc.deleteIssue(i.id);
+ const editTs = new Date(Date.now() + 60_000).toISOString();
+ const r = await svc.mergeIssuesFromSync([{
+ ...i,
+ title: 'Edited After Delete',
+ deleted: false,
+ deletedAt: null,
+ updatedAt: editTs,
+ }]);
+ expect(r.applied).toBe(true);
+ const live = await svc.getIssue(i.id);
+ expect(live).toMatchObject({ title: 'Edited After Delete', deleted: false });
+ });
+
+ it('synced RESURRECTION compacts collisions — issue restored mid-series gets a unique number', async () => {
+ // Regression: local delete already compacts numbering (A=1, C=2 after
+ // deleting B). When B's tombstone is overridden by a later remote edit
+ // (B comes back to life), B re-enters with its OLD number (2) and
+ // collides with C. mergeIssuesFromSync must trigger a renumber on
+ // both delete-transitions AND resurrection-transitions.
+ const a = await svc.createIssue({ seriesId: 'ser-resurrect', title: 'A' });
+ const b = await svc.createIssue({ seriesId: 'ser-resurrect', title: 'B' });
+ const c = await svc.createIssue({ seriesId: 'ser-resurrect', title: 'C' });
+ expect([a.number, b.number, c.number]).toEqual([1, 2, 3]);
+ await svc.deleteIssue(b.id);
+ // Local compacts to A=1, C=2.
+ const afterDelete = await svc.listIssues({ seriesId: 'ser-resurrect' });
+ expect(afterDelete.map((i) => i.number)).toEqual([1, 2]);
+ // Remote sends B with a later updatedAt — resurrection.
+ const editTs = new Date(Date.now() + 60_000).toISOString();
+ await svc.mergeIssuesFromSync([{
+ ...b,
+ deleted: false,
+ deletedAt: null,
+ updatedAt: editTs,
+ }]);
+ const live = await svc.listIssues({ seriesId: 'ser-resurrect' });
+ // All three live, contiguous numbering, no duplicates.
+ expect(live.map((i) => i.title).sort()).toEqual(['A', 'B', 'C']);
+ const numbers = live.map((i) => i.number).sort((x, y) => x - y);
+ expect(numbers).toEqual([1, 2, 3]);
+ expect(new Set(numbers).size).toBe(3);
+ });
+
+ it('synced delete-transition compacts surviving issues for that series', async () => {
+ const a = await svc.createIssue({ seriesId: 'ser-sync-renum', title: 'A' });
+ const b = await svc.createIssue({ seriesId: 'ser-sync-renum', title: 'B' });
+ const c = await svc.createIssue({ seriesId: 'ser-sync-renum', title: 'C' });
+ expect([a.number, b.number, c.number]).toEqual([1, 2, 3]);
+ const ts = new Date(Date.now() + 60_000).toISOString();
+ await svc.mergeIssuesFromSync([{
+ ...b,
+ deleted: true,
+ deletedAt: ts,
+ updatedAt: ts,
+ }]);
+ const live = await svc.listIssues({ seriesId: 'ser-sync-renum' });
+ expect(live.map((i) => i.title)).toEqual(['A', 'C']);
+ expect(live.map((i) => i.number)).toEqual([1, 2]);
+ });
+ });
+ });
+
describe('isStageReady', () => {
it('returns true for ready/edited stages with non-empty output', () => {
expect(svc.isStageReady({ status: 'ready', output: 'beats' })).toBe(true);
@@ -844,6 +981,29 @@ describe('pipeline issues service', () => {
expect(result.reassigned).toBe(0);
});
+ it('skips tombstoned issues — soft-deleted records keep their seasonId + updatedAt', async () => {
+ // Regression test: bulkReassignSeason must NOT bump a tombstone's
+ // `updatedAt`, otherwise the receiver's tombstone wins the LWW race
+ // against the originator's tombstone and the deleted issue can
+ // resurrect on every peer.
+ const { series, a, b } = await setup();
+ const list = await svc.listIssues({ seriesId: series.id });
+ const victim = list.find((i) => i.seasonId === a.id);
+ await svc.deleteIssue(victim.id);
+ const tombBefore = await svc.getIssue(victim.id, { includeDeleted: true });
+ const result = await svc.bulkReassignSeason(series.id, a.id, b.id);
+ // Live issues in season A moved (originally 3, one tombstoned → 2 live moved).
+ expect(result.reassigned).toBe(2);
+ // Tombstone preserved verbatim — seasonId unchanged, updatedAt unchanged,
+ // still tombstoned.
+ const tombAfter = await svc.getIssue(victim.id, { includeDeleted: true });
+ expect(tombAfter).toMatchObject({
+ seasonId: a.id,
+ deleted: true,
+ updatedAt: tombBefore.updatedAt,
+ });
+ });
+
it('only touches issues in the matching series — other series untouched', async () => {
const { series, a, b } = await setup();
const other = await seriesSvc.createSeries({ name: 'Other' });
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index 433dd3b355..ef3c47dd41 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -18,6 +18,7 @@ import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';
import { isStr, trimTo } from '../../lib/storyBible.js';
import { sanitizeArc, sanitizeSeasonList } from '../../lib/storyArc.js';
import { sanitizeOrigin } from '../../lib/sharingOrigin.js';
+import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
import { emitRecordUpdated, emitRecordDeleted } from '../sharing/recordEvents.js';
import { renameCollectionForSeries, unlinkCollectionsForSeries } from '../mediaCollections.js';
@@ -144,6 +145,9 @@ const sanitizeSeries = (raw) => {
origin: sanitizeOrigin(raw.origin),
createdAt,
updatedAt,
+ // 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),
};
};
@@ -158,15 +162,17 @@ async function writeState(state) {
await atomicWrite(statePath(), state);
}
-export async function listSeries() {
+export async function listSeries({ includeDeleted = false } = {}) {
const { series } = await readState();
- return [...series].sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));
+ const filtered = includeDeleted ? series : series.filter((s) => !s.deleted);
+ return [...filtered].sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));
}
-export async function getSeries(id) {
+export async function getSeries(id, { includeDeleted = false } = {}) {
const { series } = await readState();
const found = series.find((s) => s.id === id);
if (!found) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
+ if (found.deleted && !includeDeleted) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
return found;
}
@@ -218,12 +224,21 @@ export async function insertSeriesWithId(input = {}) {
if (!name) throw makeErr(`Series name is required (1..${NAME_MAX} chars)`, ERR_VALIDATION);
return queueSeriesWrite(async () => {
const state = await readState();
- if (state.series.some((s) => s.id === input.id)) {
+ // Tombstone-overwrite: same contract as universeBuilder.insertUniverseWithId —
+ // re-import undeletes; peer-sync resurrection is prevented at the merge
+ // path via LWW, not here.
+ const existingIdx = state.series.findIndex((s) => s.id === input.id);
+ if (existingIdx >= 0 && !state.series[existingIdx].deleted) {
throw makeErr(`Series id already exists: ${input.id}`, ERR_DUPLICATE);
}
const next = sanitizeSeries({ ...input, name });
if (!next) throw makeErr('Invalid series payload', ERR_VALIDATION);
- state.series.push(next);
+ if (existingIdx >= 0) {
+ console.warn(`♻️ insertSeriesWithId: overwriting tombstone for ${input.id}`);
+ state.series[existingIdx] = next;
+ } else {
+ state.series.push(next);
+ }
await writeState(state);
return next;
});
@@ -243,6 +258,7 @@ export async function updateSeries(id, patch = {}) {
const idx = state.series.findIndex((s) => s.id === id);
if (idx < 0) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
const cur = state.series[idx];
+ if (cur.deleted) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
// Per-field merge so `{ provider: 'codex' }` doesn't clobber an existing `model`.
const mergedLlm = 'llm' in patch
? { ...(cur.llm || {}), ...(patch.llm || {}) }
@@ -297,6 +313,7 @@ export async function setArcFieldLock(id, field, locked) {
const idx = state.series.findIndex((s) => s.id === id);
if (idx < 0) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
const cur = state.series[idx];
+ if (cur.deleted) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
const arcFields = { ...(cur.locked?.arcFields || {}) };
if (locked === true) arcFields[field] = true;
else delete arcFields[field];
@@ -333,6 +350,7 @@ export async function updateSeasonOnSeries(seriesId, seasonId, patchFn) {
const idx = state.series.findIndex((s) => s.id === seriesId);
if (idx < 0) throw makeErr(`Series not found: ${seriesId}`, ERR_NOT_FOUND);
const cur = state.series[idx];
+ if (cur.deleted) throw makeErr(`Series not found: ${seriesId}`, ERR_NOT_FOUND);
const seasons = Array.isArray(cur.seasons) ? cur.seasons : [];
const seasonIdx = seasons.findIndex((s) => s.id === seasonId);
if (seasonIdx < 0) {
@@ -367,11 +385,18 @@ export async function updateSeasonOnSeries(seriesId, seasonId, patchFn) {
}
export async function deleteSeries(id) {
+ // Soft-delete: flip `deleted` + stamp `deletedAt`, bump `updatedAt` so the
+ // tombstone propagates via the existing LWW merge. Side effects (media-
+ // collection unlink + recordDeleted emit) still run locally and also fire
+ // on the receiving peer via mergeSeriesFromSync's transition detection.
const result = await queueSeriesWrite(async () => {
const state = await readState();
- const before = state.series.length;
- state.series = state.series.filter((s) => s.id !== id);
- if (state.series.length === before) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
+ const idx = state.series.findIndex((s) => s.id === id);
+ if (idx < 0) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
+ const cur = state.series[idx];
+ if (cur.deleted) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
+ const now = new Date().toISOString();
+ state.series[idx] = { ...cur, deleted: true, deletedAt: now, updatedAt: now };
await writeState(state);
// Any live share-bucket subscription for this series tears itself down via
// the recordEvents listener instead of orphaning.
@@ -387,6 +412,18 @@ export async function deleteSeries(id) {
return result;
}
+/**
+ * Cascade orphan cleanup for a series whose soft-delete arrived via peer
+ * sync. Mirrors the post-queue cleanup in deleteSeries so a synced delete on
+ * the receiver leaves the same orphan-free state as a local delete.
+ */
+async function cascadeDeleteSideEffects(id) {
+ await unlinkCollectionsForSeries(id).catch((err) => {
+ console.error(`❌ unlink media collections for synced-delete series ${id} failed: ${err?.message || err}`);
+ });
+ emitRecordDeleted('series', id);
+}
+
/**
* Sync-orchestrator entry point. Merges a remote peer's series array into
* local state INSIDE `queueSeriesWrite`, so the read-modify-write window
@@ -398,7 +435,14 @@ export async function deleteSeries(id) {
*/
export async function mergeSeriesFromSync(remoteSeries) {
if (!Array.isArray(remoteSeries)) return { applied: false, count: 0 };
- return queueSeriesWrite(async () => {
+ // Series IDs that transitioned to deleted via this merge — cascade fires
+ // after the write queue releases (mirrors local-delete contract).
+ //
+ // Edit-merges (no delete-transition) DO NOT call `emitRecordUpdated` here —
+ // see `mergeUniversesFromSync` for the rationale (the Stage 2 per-record
+ // peer-sync push owns sync-time edit emits).
+ const transitionedToDeleted = [];
+ const result = await queueSeriesWrite(async () => {
const state = await readState();
const localById = new Map(state.series.map((s) => [s.id, s]));
let changed = 0;
@@ -408,6 +452,8 @@ export async function mergeSeriesFromSync(remoteSeries) {
if (!sanitized) continue;
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 {
@@ -415,6 +461,7 @@ export async function mergeSeriesFromSync(remoteSeries) {
const remoteTs = sanitized.updatedAt || '';
if (remoteTs > localTs) {
localById.set(sanitized.id, sanitized);
+ if (sanitized.deleted && !local.deleted) transitionedToDeleted.push(sanitized.id);
changed++;
}
}
@@ -424,4 +471,8 @@ export async function mergeSeriesFromSync(remoteSeries) {
await writeState(state);
return { applied: true, count: changed };
});
+ for (const id of transitionedToDeleted) {
+ await cascadeDeleteSideEffects(id);
+ }
+ return result;
}
diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.js
index 1f6f2cb353..aa377ac815 100644
--- a/server/services/pipeline/series.test.js
+++ b/server/services/pipeline/series.test.js
@@ -80,6 +80,94 @@ describe('pipeline series service', () => {
expect(await svc.listSeries()).toEqual([]);
});
+ describe('soft-delete (tombstones for peer sync)', () => {
+ it('deleteSeries soft-deletes (record stays on disk with deleted=true)', async () => {
+ const s = await svc.createSeries({ name: 'Salt Run' });
+ await svc.deleteSeries(s.id);
+ expect(await svc.listSeries()).toEqual([]);
+ const all = await svc.listSeries({ includeDeleted: true });
+ expect(all).toHaveLength(1);
+ expect(all[0]).toMatchObject({ id: s.id, deleted: true });
+ expect(all[0].deletedAt).toBeTruthy();
+ expect(all[0].updatedAt).toBe(all[0].deletedAt);
+ });
+
+ it('getSeries 404s for tombstoned; includeDeleted exposes it', async () => {
+ const s = await svc.createSeries({ name: 'Hidden' });
+ await svc.deleteSeries(s.id);
+ await expect(svc.getSeries(s.id)).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
+ const tomb = await svc.getSeries(s.id, { includeDeleted: true });
+ expect(tomb).toMatchObject({ id: s.id, deleted: true });
+ });
+
+ it('updateSeries 404s on a tombstone (no zombie edits)', async () => {
+ const s = await svc.createSeries({ name: 'Locked' });
+ await svc.deleteSeries(s.id);
+ await expect(svc.updateSeries(s.id, { name: 'Zombie' })).rejects.toMatchObject({
+ code: svc.ERR_NOT_FOUND,
+ });
+ });
+
+ it('insertSeriesWithId overwrites a tombstoned record (re-import undeletes)', async () => {
+ const id = 'ser-550e8400-e29b-41d4-a716-44665544abcd';
+ await svc.insertSeriesWithId({ id, name: 'First' });
+ await svc.deleteSeries(id);
+ const restored = await svc.insertSeriesWithId({ id, name: 'Restored' });
+ expect(restored).toMatchObject({ id, name: 'Restored', deleted: false });
+ expect((await svc.listSeries()).map((s) => s.id)).toContain(id);
+ });
+
+ it('insertSeriesWithId still rejects DUPLICATE on a LIVE record', async () => {
+ const id = 'ser-550e8400-e29b-41d4-a716-44665544abce';
+ await svc.insertSeriesWithId({ id, name: 'First' });
+ await expect(svc.insertSeriesWithId({ id, name: 'Second' }))
+ .rejects.toMatchObject({ code: svc.ERR_DUPLICATE });
+ });
+
+ describe('mergeSeriesFromSync', () => {
+ it('applies an inbound soft-delete from a peer', async () => {
+ const s = await svc.createSeries({ name: 'Synced' });
+ const ts = new Date(Date.now() + 60_000).toISOString();
+ const r = await svc.mergeSeriesFromSync([{
+ ...s,
+ deleted: true,
+ deletedAt: ts,
+ updatedAt: ts,
+ }]);
+ expect(r).toEqual({ applied: true, count: 1 });
+ await expect(svc.getSeries(s.id)).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
+ });
+
+ it('LWW: an inbound edit with later updatedAt wins over a local tombstone', async () => {
+ const s = await svc.createSeries({ name: 'Original' });
+ await svc.deleteSeries(s.id);
+ const editTs = new Date(Date.now() + 60_000).toISOString();
+ const r = await svc.mergeSeriesFromSync([{
+ ...s,
+ name: 'Edited After Delete',
+ deleted: false,
+ deletedAt: null,
+ updatedAt: editTs,
+ }]);
+ expect(r.applied).toBe(true);
+ const live = await svc.getSeries(s.id);
+ expect(live).toMatchObject({ name: 'Edited After Delete', deleted: false });
+ });
+
+ it('LWW: an inbound tombstone with later updatedAt wins over a local edit', async () => {
+ const s = await svc.createSeries({ name: 'Edited Locally' });
+ const ts = new Date(Date.now() + 60_000).toISOString();
+ await svc.mergeSeriesFromSync([{
+ ...s,
+ deleted: true,
+ deletedAt: ts,
+ updatedAt: ts,
+ }]);
+ await expect(svc.getSeries(s.id)).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
+ });
+ });
+ });
+
it('listSeries sorts newest updated first', async () => {
const a = await svc.createSeries({ name: 'A' });
await new Promise((r) => setTimeout(r, 5));
diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.js
index 05d3e33826..d5203eddbc 100644
--- a/server/services/sharing/exporter.js
+++ b/server/services/sharing/exporter.js
@@ -19,6 +19,7 @@ import { join, basename } from 'path';
import { copyFile, readFile, writeFile, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { PATHS, ensureDir, atomicWrite, readJSONFile, sha256File } from '../../lib/fileUtils.js';
+import { getOrComputeImageSha256 } from '../../lib/assetHash.js';
import { isPlainObject } from '../../lib/objects.js';
import { getBucket, ensureBucketLayout, bucketBlobsDir, bucketBlobPath, bucketBlobSidecarPath, bucketBlobIndexPath, imageSidecarName, isHexHash } from './buckets.js';
import { buildManifest, writeManifest, pruneBucketManifests } from './manifest.js';
@@ -129,7 +130,18 @@ async function copyAssetIfPresent(filename, kind, bucketPath, cache) {
const cacheKey = `${sourcePath}:${info.mtimeMs}:${info.size}`;
let hash = cache && isHexHash(cache[cacheKey]) ? cache[cacheKey] : null;
if (!hash || !existsSync(bucketBlobPath(bucketPath, hash))) {
- hash = await sha256File(sourcePath);
+ // For images, prefer the cross-transport sidecar cache (lib/assetHash) —
+ // it persists the hash next to the asset so the peer-sync push pipeline
+ // (which has no bucket context) can read the same value. The bucket
+ // cache is still populated so future exports inside this bucket take
+ // the fast path. For non-image kinds (videos), no sidecar exists yet so
+ // fall through to direct sha256File.
+ if (kind === 'image') {
+ const sidecarResult = await getOrComputeImageSha256(sourcePath);
+ hash = sidecarResult?.hash || (await sha256File(sourcePath));
+ } else {
+ hash = await sha256File(sourcePath);
+ }
if (cache) cache[cacheKey] = hash;
}
const blobPath = bucketBlobPath(bucketPath, hash);
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index ad5ead7561..c7602e0ff4 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -1097,7 +1097,14 @@ describe('sharing round-trip', () => {
// Both manifests point at the same blob path; only one on-disk blob file exists
// (the dotfile `.index.json` is the per-bucket source→hash cache, not a blob).
expect(fs.existsSync(join(tempBucket, 'assets', 'blobs', hash))).toBe(true);
- expect(fs.readdirSync(join(tempBucket, 'assets', 'blobs')).filter((f) => !f.startsWith('.'))).toEqual([hash]);
+ // Filter out: dotfiles (.index.json source-hash cache) AND .metadata.json
+ // sidecars (which mirror the source-side sidecars created by the new
+ // cross-transport SHA-256 cache in lib/assetHash.js). The point of the
+ // assertion is "only ONE actual blob exists for two manifests that share
+ // bytes" — the sidecar is provenance metadata, not a duplicate blob.
+ const blobs = fs.readdirSync(join(tempBucket, 'assets', 'blobs'))
+ .filter((f) => !f.startsWith('.') && !f.endsWith('.metadata.json'));
+ expect(blobs).toEqual([hash]);
// Each manifest's assetRef carries the hash + its own original filename.
const mA = JSON.parse(fs.readFileSync(join(tempBucket, 'manifests', expA.filename), 'utf-8'));
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index f8abfe7cff..c5d60f97e6 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -37,6 +37,7 @@ import {
normalizeBibleName, isStr, trimTo,
} from '../lib/storyBible.js';
import { sanitizeOrigin } from '../lib/sharingOrigin.js';
+import { sanitizeSoftDeleteFields } from '../lib/syncWire.js';
import { emitRecordUpdated, emitRecordDeleted } from './sharing/recordEvents.js';
import { renameCollectionForUniverse, unlinkCollectionsForUniverse } from './mediaCollections.js';
import {
@@ -728,6 +729,10 @@ const sanitizeTemplate = (raw) => {
: { provider: null, model: null };
const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();
const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;
+ // Soft-delete fields — peer sync needs the tombstone in the record itself
+ // so LWW merge can resolve delete-vs-edit races by `updatedAt`. Existing
+ // records without these fields read as live (deleted=false, deletedAt=null).
+ const { deleted, deletedAt } = sanitizeSoftDeleteFields(raw);
return {
id: raw.id,
name,
@@ -748,6 +753,8 @@ const sanitizeTemplate = (raw) => {
origin: sanitizeOrigin(raw.origin),
createdAt,
updatedAt,
+ deleted,
+ deletedAt,
};
};
@@ -795,16 +802,18 @@ async function writeState(state) {
await atomicWrite(statePath(), state);
}
-export async function listUniverses() {
+export async function listUniverses({ includeDeleted = false } = {}) {
const { universes } = await readState();
+ const filtered = includeDeleted ? universes : universes.filter((u) => !u.deleted);
// Newest first — matches user expectation for a "your universes" list.
- return [...universes].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
+ return [...filtered].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
}
-export async function getUniverse(id) {
+export async function getUniverse(id, { includeDeleted = false } = {}) {
const { universes } = await readState();
const w = universes.find((x) => x.id === id);
if (!w) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);
+ if (w.deleted && !includeDeleted) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);
return w;
}
@@ -821,7 +830,7 @@ export async function needsEntryIdPersist(id) {
await ensureDir(PATHS.data);
const raw = await readJSONFile(statePath(), DEFAULT_STATE, { logError: false });
const rec = Array.isArray(raw.universes) ? raw.universes.find((u) => u?.id === id) : null;
- if (!rec) return false;
+ if (!rec || rec.deleted) return false;
const cats = rec.categories && typeof rec.categories === 'object' ? rec.categories : {};
for (const cat of Object.values(cats)) {
const vars = Array.isArray(cat?.variations) ? cat.variations : [];
@@ -892,12 +901,24 @@ export async function insertUniverseWithId(input = {}) {
if (!name) throw makeErr(`Universe name is required (1..${NAME_MAX_LENGTH} chars)`, ERR_VALIDATION);
return queueUniverseWrite(async () => {
const state = await readState();
- if (state.universes.some((u) => u.id === input.id)) {
+ // Tombstone-overwrite: a previously-deleted record with the same id is
+ // overwritten (effectively undeleted) — this keeps the share-bucket
+ // re-import flow idempotent (deleting then re-importing the same manifest
+ // restores the universe rather than 409ing). The peer-sync resurrection
+ // hazard is already prevented by `mergeUniversesFromSync`'s LWW check,
+ // which is the transport the federation uses.
+ const existingIdx = state.universes.findIndex((u) => u.id === input.id);
+ if (existingIdx >= 0 && !state.universes[existingIdx].deleted) {
throw makeErr(`Universe id already exists: ${input.id}`, ERR_DUPLICATE);
}
const next = sanitizeTemplate({ ...input, name });
if (!next) throw makeErr('Invalid universe payload', ERR_VALIDATION);
- state.universes.push(next);
+ if (existingIdx >= 0) {
+ console.warn(`♻️ insertUniverseWithId: overwriting tombstone for ${input.id}`);
+ state.universes[existingIdx] = next;
+ } else {
+ state.universes.push(next);
+ }
await writeState(state);
return next;
});
@@ -923,6 +944,7 @@ export async function updateUniverse(id, patchOrMutator = {}) {
const idx = state.universes.findIndex((w) => w.id === id);
if (idx < 0) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);
const cur = state.universes[idx];
+ if (cur.deleted) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);
let patch;
if (isMutator) {
@@ -1107,14 +1129,23 @@ export async function updateUniverse(id, patchOrMutator = {}) {
}
export async function deleteUniverse(id) {
- // Queue covers only the universe-builder write; cross-file unlink runs
- // after the queue releases so a slow media-collections write can't block
- // subsequent universe mutators.
+ // Soft-delete: mark the record with `deleted: true` + `deletedAt` and bump
+ // `updatedAt` so federated peers learn about the deletion via the existing
+ // LWW merge (tombstone-as-state). The orchestrator's tombstone-cleanup
+ // sweep prunes the record entirely once every subscribed peer has acked.
+ //
+ // Cross-file side effects still run on the local delete: drop runs,
+ // unlink media collections, clear sheet slots. These cascades also run on
+ // the receiving peer when a soft-delete arrives via mergeUniversesFromSync
+ // so a synced delete doesn't leave orphan media-collection locks.
await queueUniverseWrite(async () => {
const state = await readState();
- const before = state.universes.length;
- state.universes = state.universes.filter((w) => w.id !== id);
- if (state.universes.length === before) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);
+ const idx = state.universes.findIndex((w) => w.id === id);
+ if (idx < 0) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);
+ const cur = state.universes[idx];
+ if (cur.deleted) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);
+ const now = new Date().toISOString();
+ state.universes[idx] = { ...cur, deleted: true, deletedAt: now, updatedAt: now };
// Drop runs referencing the deleted universe — they're useless without it.
state.runs = state.runs.filter((r) => r.universeId !== id);
await writeState(state);
@@ -1123,7 +1154,7 @@ export async function deleteUniverse(id) {
// the orphan collection's `universeId` stays stamped and the lock in
// updateCollection blocks renames forever even though the universe is gone.
// Best-effort: a failure here mustn't fail the delete (the universe is
- // already gone from state). Runs OUTSIDE the universe-builder queue.
+ // already tombstoned). Runs OUTSIDE the universe-builder queue.
await unlinkCollectionsForUniverse(id).catch((err) => {
console.error(`❌ unlink media collections for deleted universe ${id} failed: ${err?.message || err}`);
});
@@ -1133,6 +1164,21 @@ export async function deleteUniverse(id) {
return { id };
}
+/**
+ * Cascade orphan cleanup for a universe whose soft-delete arrived via peer
+ * sync (mergeUniversesFromSync detected a deleted=false → deleted=true
+ * transition). Mirrors the post-queue cleanup in deleteUniverse so a synced
+ * delete on the receiver leaves the same orphan-free state as a local delete.
+ * Runs outside the universe-builder write queue.
+ */
+async function cascadeDeleteSideEffects(id) {
+ await unlinkCollectionsForUniverse(id).catch((err) => {
+ console.error(`❌ unlink media collections for synced-delete universe ${id} failed: ${err?.message || err}`);
+ });
+ clearPendingSheetSlotsForUniverse(id);
+ emitRecordDeleted('universe', id);
+}
+
/**
* Sync-orchestrator entry point. Merges a remote peer's universe array into
* local state INSIDE `queueUniverseWrite`, so the read-modify-write window
@@ -1152,7 +1198,18 @@ export async function deleteUniverse(id) {
*/
export async function mergeUniversesFromSync(remoteUniverses) {
if (!Array.isArray(remoteUniverses)) return { applied: false, count: 0 };
- return queueUniverseWrite(async () => {
+ // Records that transitioned to deleted via this merge get their orphan
+ // cascade fired after the write queue releases — matches the side-effect
+ // contract of locally-initiated `deleteUniverse`.
+ //
+ // Edit-merges (no delete-transition) DO NOT call `emitRecordUpdated` here.
+ // Unlike `updateUniverse`, the snapshot sync is meant to be silent — every
+ // 60s cycle would otherwise trigger a re-export storm in share-bucket
+ // subscriptions even when nothing user-visible changed. The Stage 2
+ // per-record peer-sync push pipeline will own the "edit arrived from
+ // peer" emit so subscribers fire exactly once per actual edit.
+ const transitionedToDeleted = [];
+ const result = await queueUniverseWrite(async () => {
const state = await readState();
const localById = new Map(state.universes.map((u) => [u.id, u]));
let changed = 0;
@@ -1162,6 +1219,11 @@ export async function mergeUniversesFromSync(remoteUniverses) {
if (!sanitized) continue;
const local = localById.get(sanitized.id);
if (!local) {
+ // No local counterpart — accept the record (live OR tombstone) but
+ // do NOT cascade orphan-cleanup. A tombstone for a record we never
+ // had has nothing to clean up; firing `emitRecordDeleted` would spuriously
+ // tear down share-bucket subscriptions looking for a manifest that
+ // never existed.
localById.set(sanitized.id, sanitized);
changed++;
} else {
@@ -1169,15 +1231,28 @@ export async function mergeUniversesFromSync(remoteUniverses) {
const remoteTs = sanitized.updatedAt || '';
if (remoteTs > localTs) {
localById.set(sanitized.id, sanitized);
+ if (sanitized.deleted && !local.deleted) transitionedToDeleted.push(sanitized.id);
changed++;
}
}
}
if (changed === 0) return { applied: false, count: 0 };
+ // Drop runs for any record that just transitioned to deleted — matches
+ // the local-delete contract that ditches now-orphan runs.
+ if (transitionedToDeleted.length) {
+ const tombstoned = new Set(transitionedToDeleted);
+ state.runs = state.runs.filter((r) => !tombstoned.has(r.universeId));
+ }
state.universes = Array.from(localById.values());
await writeState(state);
return { applied: true, count: changed };
});
+ // Fire cascades after the queue releases (mirrors deleteUniverse ordering)
+ // so a slow media-collections write can't block other universe mutators.
+ for (const id of transitionedToDeleted) {
+ await cascadeDeleteSideEffects(id);
+ }
+ return result;
}
export async function recordRun(run) {
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index 26449fc780..0a0316b6ce 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -536,6 +536,168 @@ describe("universeBuilder service", () => {
).resolves.toMatchObject({ name: "User-Renamed" });
});
+ describe("soft-delete (tombstones for peer sync)", () => {
+ it("deleteUniverse soft-deletes (record stays on disk with deleted=true)", async () => {
+ const w = await seedWorld();
+ await svc.deleteUniverse(w.id);
+ // listUniverses hides it.
+ expect(await svc.listUniverses()).toEqual([]);
+ // includeDeleted exposes the tombstone with deletedAt + bumped updatedAt.
+ const all = await svc.listUniverses({ includeDeleted: true });
+ expect(all).toHaveLength(1);
+ expect(all[0]).toMatchObject({ id: w.id, deleted: true });
+ expect(all[0].deletedAt).toBeTruthy();
+ expect(all[0].updatedAt).toBe(all[0].deletedAt);
+ });
+
+ it("getUniverse returns 404 for tombstoned, includeDeleted exposes it", async () => {
+ const w = await seedWorld();
+ await svc.deleteUniverse(w.id);
+ await expect(svc.getUniverse(w.id)).rejects.toMatchObject({ code: "NOT_FOUND" });
+ const tombstone = await svc.getUniverse(w.id, { includeDeleted: true });
+ expect(tombstone).toMatchObject({ id: w.id, deleted: true });
+ });
+
+ it("updateUniverse on a tombstoned record throws 404 (no zombie edits)", async () => {
+ const w = await seedWorld();
+ await svc.deleteUniverse(w.id);
+ await expect(svc.updateUniverse(w.id, { name: "Zombie" })).rejects.toMatchObject({
+ code: "NOT_FOUND",
+ });
+ });
+
+ it("deleteUniverse on an already-tombstoned record throws 404", async () => {
+ const w = await seedWorld();
+ await svc.deleteUniverse(w.id);
+ await expect(svc.deleteUniverse(w.id)).rejects.toMatchObject({ code: "NOT_FOUND" });
+ });
+
+ it("insertUniverseWithId overwrites a tombstoned record (re-import undeletes)", async () => {
+ const id = "550e8400-e29b-41d4-a716-44665544abcd";
+ await svc.insertUniverseWithId({ id, name: "First" });
+ await svc.deleteUniverse(id);
+ const restored = await svc.insertUniverseWithId({ id, name: "Restored" });
+ expect(restored).toMatchObject({ id, name: "Restored", deleted: false });
+ // listUniverses shows it (no longer hidden).
+ expect((await svc.listUniverses()).map((u) => u.id)).toContain(id);
+ });
+
+ it("insertUniverseWithId still rejects DUPLICATE on a LIVE record", async () => {
+ const id = "550e8400-e29b-41d4-a716-44665544abce";
+ await svc.insertUniverseWithId({ id, name: "First" });
+ await expect(
+ svc.insertUniverseWithId({ id, name: "Second" }),
+ ).rejects.toMatchObject({ code: svc.ERR_DUPLICATE });
+ });
+
+ describe("mergeUniversesFromSync", () => {
+ it("applies an inbound soft-delete from a peer", async () => {
+ const w = await seedWorld();
+ const tombstoneTs = new Date(Date.now() + 60_000).toISOString();
+ const r = await svc.mergeUniversesFromSync([{
+ ...w,
+ deleted: true,
+ deletedAt: tombstoneTs,
+ updatedAt: tombstoneTs,
+ }]);
+ expect(r).toEqual({ applied: true, count: 1 });
+ await expect(svc.getUniverse(w.id)).rejects.toMatchObject({ code: "NOT_FOUND" });
+ const tombstone = await svc.getUniverse(w.id, { includeDeleted: true });
+ expect(tombstone.deleted).toBe(true);
+ });
+
+ it("LWW: an inbound edit with later updatedAt wins over a local tombstone", async () => {
+ const w = await seedWorld();
+ await svc.deleteUniverse(w.id);
+ const editTs = new Date(Date.now() + 60_000).toISOString();
+ const r = await svc.mergeUniversesFromSync([{
+ ...w,
+ name: "Edited After Delete",
+ deleted: false,
+ deletedAt: null,
+ updatedAt: editTs,
+ }]);
+ expect(r.applied).toBe(true);
+ // Edit wins — record is live again with the new name.
+ const live = await svc.getUniverse(w.id);
+ expect(live).toMatchObject({ name: "Edited After Delete", deleted: false });
+ });
+
+ it("LWW: an inbound tombstone with later updatedAt wins over a local edit", async () => {
+ const w = await seedWorld();
+ const tombstoneTs = new Date(Date.now() + 60_000).toISOString();
+ const r = await svc.mergeUniversesFromSync([{
+ ...w,
+ deleted: true,
+ deletedAt: tombstoneTs,
+ updatedAt: tombstoneTs,
+ }]);
+ expect(r.applied).toBe(true);
+ await expect(svc.getUniverse(w.id)).rejects.toMatchObject({ code: "NOT_FOUND" });
+ });
+
+ it("delete transition via sync drops orphan runs (mirrors local-delete contract)", async () => {
+ const w = await seedWorld();
+ await svc.recordRun({
+ id: "run-sync-1",
+ universeId: w.id,
+ collectionId: "col-x",
+ jobIds: ["j1"],
+ promptCount: 1,
+ });
+ expect(await svc.listRuns(w.id)).toHaveLength(1);
+ const tombstoneTs = new Date(Date.now() + 60_000).toISOString();
+ await svc.mergeUniversesFromSync([{
+ ...w,
+ deleted: true,
+ deletedAt: tombstoneTs,
+ updatedAt: tombstoneTs,
+ }]);
+ expect(await svc.listRuns(w.id)).toEqual([]);
+ });
+
+ it("inbound tombstone for a NEVER-SEEN universe is accepted without firing the cascade (no orphan teardown for nothing)", async () => {
+ // Regression: the no-local branch previously included tombstones in
+ // `transitionedToDeleted`, firing `emitRecordDeleted` + the orphan
+ // cascade for a record we never had. Now the no-local branch accepts
+ // the record silently — the cascade only fires on real local
+ // transitions (deleted=false → deleted=true).
+ const ghostId = "550e8400-0000-0000-0000-000000000999";
+ const ts = new Date().toISOString();
+ const r = await svc.mergeUniversesFromSync([{
+ id: ghostId,
+ name: "Ghost",
+ deleted: true,
+ deletedAt: ts,
+ updatedAt: ts,
+ }]);
+ expect(r).toEqual({ applied: true, count: 1 });
+ // Tombstone is on disk via includeDeleted.
+ const all = await svc.listUniverses({ includeDeleted: true });
+ expect(all.find((u) => u.id === ghostId)).toMatchObject({ deleted: true });
+ });
+
+ it("delete transition via sync runs cascade — unlinks media collections", async () => {
+ const collections = await import("./mediaCollections.js");
+ const w = await seedWorld();
+ const linked = await collections.findOrCreateCollectionByName({
+ name: collections.universeCollectionNameFor(w.name),
+ universeId: w.id,
+ });
+ expect(linked.universeId).toBe(w.id);
+ const tombstoneTs = new Date(Date.now() + 60_000).toISOString();
+ await svc.mergeUniversesFromSync([{
+ ...w,
+ deleted: true,
+ deletedAt: tombstoneTs,
+ updatedAt: tombstoneTs,
+ }]);
+ const fresh = await collections.getCollection(linked.id);
+ expect(fresh.universeId).toBeNull();
+ });
+ });
+ });
+
describe("synthesizeCanonPrompt", () => {
it("hand-authored prompt wins over field synthesis", () => {
expect(svc.synthesizeCanonPrompt("characters", {